Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
7e6536ea57 | ||
|
|
4db655d4f9 | ||
|
|
1cf6c2f806 | ||
|
|
c6beb650c4 | ||
|
|
1b0f1c627a | ||
|
|
3690a7f568 | ||
|
|
870f64d8a9 | ||
|
|
48bc66b42f | ||
|
|
6bb438de6e | ||
|
|
b1bef9024f |
@@ -0,0 +1,48 @@
|
|||||||
|
# Deploy Agent Zero Zulip Adapter
|
||||||
|
|
||||||
|
## Prerequisites
|
||||||
|
- Agent Zero running in Docker on the target CT
|
||||||
|
- A Zulip bot created for the agent (kagentz-bot, scottdenya-bot, etc.)
|
||||||
|
- Python 3.11+ with httpx
|
||||||
|
|
||||||
|
## Steps
|
||||||
|
|
||||||
|
### 1. Create Zulip Bot
|
||||||
|
Go to Zulip admin → Bot management → Add a new bot:
|
||||||
|
- Name after the agent
|
||||||
|
- Copy the API key
|
||||||
|
|
||||||
|
### 2. Install Adapter
|
||||||
|
```bash
|
||||||
|
# On the target CT
|
||||||
|
pip install httpx
|
||||||
|
|
||||||
|
# Copy adapter files
|
||||||
|
scp -r agent-zero-zulip/ root@<ct-ip>:/opt/agent-zero-zulip/
|
||||||
|
|
||||||
|
# Create config
|
||||||
|
cp config.yaml.example config.yaml
|
||||||
|
# Edit config.yaml with Zulip credentials
|
||||||
|
```
|
||||||
|
|
||||||
|
### 3. Start A2A Server on Agent Zero
|
||||||
|
```bash
|
||||||
|
# Inside Agent Zero container
|
||||||
|
docker exec agent-zero /opt/venv-a0/bin/python3 /a0/usr/start_a2a_direct.py &
|
||||||
|
|
||||||
|
# Verify A2A is running
|
||||||
|
curl http://localhost:8001/.well-known/agent.json
|
||||||
|
```
|
||||||
|
|
||||||
|
### 4. Start Zulip Adapter
|
||||||
|
```bash
|
||||||
|
# On the host
|
||||||
|
cd /opt/agent-zero-zulip
|
||||||
|
python3 -m agent_zero_zulip.adapter &
|
||||||
|
|
||||||
|
# Verify
|
||||||
|
tail -f adapter.log
|
||||||
|
```
|
||||||
|
|
||||||
|
### 5. Test
|
||||||
|
Send a DM to kagentz-bot in Zulip. Expect "Processing..." → response.
|
||||||
@@ -0,0 +1,30 @@
|
|||||||
|
# Agent Zero Zulip Adapter
|
||||||
|
|
||||||
|
Direct Zulip integration for Agent Zero agents (kagentz, scottdenya, etc.).
|
||||||
|
Each agent gets its own Zulip bot. Uses A2A protocol internally to
|
||||||
|
communicate with Agent Zero's native A2A server.
|
||||||
|
|
||||||
|
## Architecture
|
||||||
|
|
||||||
|
```
|
||||||
|
┌─────────────────────────────────────────┐
|
||||||
|
│ kagentz (CT 105) │
|
||||||
|
│ │
|
||||||
|
│ ┌──────────────┐ ┌──────────────┐ │
|
||||||
|
│ │ Agent Zero │◄──►│ Zulip A2A │ │
|
||||||
|
│ │ (Docker) │A2A │ Adapter │ │
|
||||||
|
│ │ │ │ │ │
|
||||||
|
│ │ port 8001 │ │ polls Zulip │ │
|
||||||
|
│ └──────────────┘ └──────┬───────┘ │
|
||||||
|
│ │ │
|
||||||
|
└─────────────────────────────┼───────────┘
|
||||||
|
│ Zulip API
|
||||||
|
▼
|
||||||
|
chat.sysloggh.net
|
||||||
|
```
|
||||||
|
|
||||||
|
## Components
|
||||||
|
|
||||||
|
- `adapter.py` — Zulip event queue poller + A2A client
|
||||||
|
- `agent_card.py` — Agent Card for A2A discovery
|
||||||
|
- `Dockerfile` or `requirements.txt` for dependencies
|
||||||
@@ -0,0 +1,13 @@
|
|||||||
|
# Agent Zero Zulip Adapter Configuration
|
||||||
|
# Copy to config.yaml and fill in credentials
|
||||||
|
|
||||||
|
zulip:
|
||||||
|
site: https://chat.sysloggh.net
|
||||||
|
email: kagentz-bot@chat.sysloggh.net
|
||||||
|
api_key: "<your-api-key>"
|
||||||
|
stream: agent-hub
|
||||||
|
|
||||||
|
agent:
|
||||||
|
name: kagentz
|
||||||
|
a2a_url: http://localhost:8001/a2a
|
||||||
|
a2a_token: 8zNgdOEXzYxjQvTl
|
||||||
@@ -0,0 +1 @@
|
|||||||
|
httpx>=0.27.0
|
||||||
@@ -0,0 +1,79 @@
|
|||||||
|
"""A2A server for kagentz — calls LiteLLM directly for responses."""
|
||||||
|
import os, json, uuid, asyncio
|
||||||
|
from datetime import datetime
|
||||||
|
import uvicorn
|
||||||
|
from fastapi import FastAPI, Request
|
||||||
|
import httpx
|
||||||
|
|
||||||
|
app = FastAPI()
|
||||||
|
task_results = {}
|
||||||
|
LITELLM_URL = os.getenv("LITELLM_URL", "https://litellm.sysloggh.net/v1")
|
||||||
|
LITELLM_KEY = os.getenv("LITELLM_KEY", "sk-akDPhdO8qlhYNtVet6KZog")
|
||||||
|
LITELLM_MODEL = os.getenv("LITELLM_MODEL", "syslog-auto")
|
||||||
|
NOW = datetime.utcnow().strftime("%Y-%m-%d %H:%M UTC")
|
||||||
|
|
||||||
|
@app.get("/.well-known/agent.json")
|
||||||
|
async def agent_card():
|
||||||
|
return {
|
||||||
|
"name": "kagentz",
|
||||||
|
"version": "1.0.0",
|
||||||
|
"description": "Agent Zero on CT 105 via Zulip + LiteLLM",
|
||||||
|
"capabilities": {"a2a": {"version": "1.0"}},
|
||||||
|
"skills": [{"id": "chat", "name": "Chat"}],
|
||||||
|
}
|
||||||
|
|
||||||
|
@app.post("/a2a")
|
||||||
|
async def a2a_endpoint(request: Request):
|
||||||
|
body = await request.json()
|
||||||
|
method = body.get("method", "")
|
||||||
|
|
||||||
|
if method == "tasks/send":
|
||||||
|
params = body.get("params", {})
|
||||||
|
msg = params.get("message", {})
|
||||||
|
parts = msg.get("parts", [])
|
||||||
|
text = " ".join(p.get("text", "") for p in parts if isinstance(p, dict))
|
||||||
|
task_id = f"az-{uuid.uuid4().hex[:12]}"
|
||||||
|
asyncio.create_task(call_litellm(task_id, text))
|
||||||
|
return {"jsonrpc": "2.0", "result": {"id": task_id, "status": {"state": "working"}}}
|
||||||
|
|
||||||
|
elif method == "tasks/get":
|
||||||
|
task_id = body.get("params", {}).get("id", "")
|
||||||
|
status, result = task_results.get(task_id, ("pending", None))
|
||||||
|
resp = {"jsonrpc": "2.0", "result": {"id": task_id, "status": {"state": status}}}
|
||||||
|
if status == "completed" and result:
|
||||||
|
resp["result"]["history"] = [
|
||||||
|
{"role": "user", "parts": [{"text": result.get("input", "")}]},
|
||||||
|
{"role": "assistant", "parts": [{"text": result.get("output", "")}]},
|
||||||
|
]
|
||||||
|
elif status == "failed":
|
||||||
|
resp["result"]["status"]["message"] = {"text": str(result)}
|
||||||
|
return resp
|
||||||
|
|
||||||
|
return {"jsonrpc": "2.0", "error": {"code": -32601, "message": "Method not found"}}
|
||||||
|
|
||||||
|
async def call_litellm(task_id, message):
|
||||||
|
try:
|
||||||
|
async with httpx.AsyncClient(timeout=120.0) as client:
|
||||||
|
resp = await client.post(
|
||||||
|
f"{LITELLM_URL}/chat/completions",
|
||||||
|
headers={"Authorization": f"Bearer {LITELLM_KEY}", "Content-Type": "application/json"},
|
||||||
|
json={
|
||||||
|
"model": LITELLM_MODEL,
|
||||||
|
"messages": [
|
||||||
|
{"role": "system", "content": f"You are kagentz, an Agent Zero instance. Current date: {NOW}. Keep responses concise and accurate."},
|
||||||
|
{"role": "user", "content": message},
|
||||||
|
],
|
||||||
|
"max_tokens": 2000,
|
||||||
|
},
|
||||||
|
)
|
||||||
|
if resp.is_success:
|
||||||
|
output = resp.json()["choices"][0]["message"]["content"]
|
||||||
|
task_results[task_id] = ("completed", {"input": message, "output": output})
|
||||||
|
else:
|
||||||
|
task_results[task_id] = ("failed", f"HTTP {resp.status_code}")
|
||||||
|
except Exception as e:
|
||||||
|
task_results[task_id] = ("failed", str(e))
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
print(f"kagentz A2A server on port 8001 (model={LITELLM_MODEL}, date={NOW})")
|
||||||
|
uvicorn.run(app, host="0.0.0.0", port=8001, log_level="info")
|
||||||
@@ -0,0 +1,485 @@
|
|||||||
|
"""
|
||||||
|
Agent Zero Zulip Adapter — Direct Zulip integration for Agent Zero agents.
|
||||||
|
|
||||||
|
Architecture:
|
||||||
|
Zulip event queue → poll loop → A2A send to Agent Zero →
|
||||||
|
wait for A2A response → post back to Zulip
|
||||||
|
|
||||||
|
Runs alongside Agent Zero on the same host. Communicates with Agent Zero
|
||||||
|
via local A2A protocol (port 8001). No intermediate bridge needed.
|
||||||
|
"""
|
||||||
|
|
||||||
|
import asyncio
|
||||||
|
import json
|
||||||
|
import logging
|
||||||
|
import os
|
||||||
|
import time
|
||||||
|
from datetime import datetime, timezone
|
||||||
|
from typing import Any, Optional
|
||||||
|
import urllib.parse
|
||||||
|
|
||||||
|
try:
|
||||||
|
import httpx
|
||||||
|
except ImportError:
|
||||||
|
httpx = None
|
||||||
|
|
||||||
|
logger = logging.getLogger("agent-zero-zulip")
|
||||||
|
|
||||||
|
# Constants
|
||||||
|
DEFAULT_A2A_URL = "http://localhost:8001/a2a"
|
||||||
|
DEFAULT_A2A_TOKEN = "8zNgdOEXzYxjQvTl"
|
||||||
|
DEFAULT_POLL_INTERVAL = 3.0
|
||||||
|
MAX_ZULIP_MSG = 10000
|
||||||
|
RECONNECT_BACKOFF = [2, 5, 10, 30, 60]
|
||||||
|
HEARTBEAT_INTERVAL = 300 # 5 min
|
||||||
|
|
||||||
|
|
||||||
|
class AgentZeroZulipAdapter:
|
||||||
|
"""Zulip adapter for Agent Zero agents.
|
||||||
|
|
||||||
|
Connects to Zulip via event queue, forwards DMs and @mentions
|
||||||
|
to Agent Zero via local A2A protocol, and posts responses back.
|
||||||
|
"""
|
||||||
|
|
||||||
|
def __init__(self):
|
||||||
|
# Zulip config from env vars
|
||||||
|
self._site = (os.getenv("ZULIP_SITE") or "").rstrip("/")
|
||||||
|
self._email = os.getenv("ZULIP_EMAIL") or ""
|
||||||
|
self._api_key = os.getenv("ZULIP_API_KEY") or ""
|
||||||
|
self._agent_name = os.getenv("ZULIP_AGENT_NAME") or "kagentz"
|
||||||
|
self._stream = os.getenv("ZULIP_STREAM") or "agent-hub"
|
||||||
|
|
||||||
|
# A2A config
|
||||||
|
self._a2a_url = os.getenv("A2A_URL") or DEFAULT_A2A_URL
|
||||||
|
self._a2a_token = os.getenv("A2A_TOKEN") or DEFAULT_A2A_TOKEN
|
||||||
|
|
||||||
|
# State
|
||||||
|
self._auth_header = self._build_auth()
|
||||||
|
self._http_client: Optional[httpx.AsyncClient] = None
|
||||||
|
self._queue_id: Optional[str] = None
|
||||||
|
self._last_event_id: int = -1
|
||||||
|
self._bot_user_id: Optional[int] = None
|
||||||
|
self._bot_email: str = self._email
|
||||||
|
self._running = False
|
||||||
|
self._poll_task: Optional[asyncio.Task] = None
|
||||||
|
|
||||||
|
# Stats
|
||||||
|
self._messages_processed = 0
|
||||||
|
self._poll_count = 0
|
||||||
|
self._reconnects = 0
|
||||||
|
self._last_heartbeat = 0.0
|
||||||
|
self._last_event_time = time.time()
|
||||||
|
self._a2a_sessions: dict = {} # chat_id -> A2A context_id
|
||||||
|
|
||||||
|
def _build_auth(self) -> str:
|
||||||
|
import base64
|
||||||
|
token = base64.b64encode(f"{self._email}:{self._api_key}".encode()).decode()
|
||||||
|
return f"Basic {token}"
|
||||||
|
|
||||||
|
async def start(self):
|
||||||
|
"""Start the adapter — connect to Zulip and begin polling."""
|
||||||
|
if not all([self._site, self._email, self._api_key]):
|
||||||
|
logger.error("Missing Zulip credentials. Set ZULIP_SITE, ZULIP_EMAIL, ZULIP_API_KEY")
|
||||||
|
return False
|
||||||
|
|
||||||
|
if not httpx:
|
||||||
|
logger.error("httpx not installed")
|
||||||
|
return False
|
||||||
|
|
||||||
|
self._running = True
|
||||||
|
self._http_client = httpx.AsyncClient(timeout=30.0)
|
||||||
|
|
||||||
|
# Connect to Zulip
|
||||||
|
if not await self._connect():
|
||||||
|
return False
|
||||||
|
|
||||||
|
logger.info(f"Adapter started for {self._agent_name} ({self._email})")
|
||||||
|
return True
|
||||||
|
|
||||||
|
async def stop(self):
|
||||||
|
"""Stop the adapter."""
|
||||||
|
self._running = False
|
||||||
|
if self._poll_task:
|
||||||
|
self._poll_task.cancel()
|
||||||
|
try:
|
||||||
|
await self._poll_task
|
||||||
|
except asyncio.CancelledError:
|
||||||
|
pass
|
||||||
|
if self._http_client:
|
||||||
|
await self._http_client.aclose()
|
||||||
|
|
||||||
|
async def _connect(self) -> bool:
|
||||||
|
"""Register Zulip event queue."""
|
||||||
|
try:
|
||||||
|
resp = await self._api_call("POST", "/api/v1/register", data={
|
||||||
|
"event_types": '["message"]',
|
||||||
|
"apply_markdown": "true",
|
||||||
|
})
|
||||||
|
if not resp:
|
||||||
|
logger.error("Queue registration failed")
|
||||||
|
return False
|
||||||
|
|
||||||
|
self._queue_id = resp.get("queue_id")
|
||||||
|
self._last_event_id = resp.get("last_event_id", -1)
|
||||||
|
self._bot_user_id = resp.get("user_id")
|
||||||
|
|
||||||
|
# Resolve bot user_id if not provided by register
|
||||||
|
if self._bot_user_id is None:
|
||||||
|
me = await self._api_call("GET", "/api/v1/users/me")
|
||||||
|
if me:
|
||||||
|
self._bot_user_id = me.get("user_id")
|
||||||
|
|
||||||
|
logger.info(
|
||||||
|
f"Connected to Zulip as {self._email} "
|
||||||
|
f"(queue={self._queue_id}, bot_id={self._bot_user_id})"
|
||||||
|
)
|
||||||
|
|
||||||
|
# Start poll loop
|
||||||
|
self._poll_task = asyncio.create_task(self._poll_forever())
|
||||||
|
return True
|
||||||
|
|
||||||
|
except Exception as e:
|
||||||
|
logger.error(f"Connection failed: {e}")
|
||||||
|
return False
|
||||||
|
|
||||||
|
async def _poll_forever(self):
|
||||||
|
"""Main poll loop."""
|
||||||
|
backoff = 0
|
||||||
|
while self._running:
|
||||||
|
if not self._queue_id:
|
||||||
|
await asyncio.sleep(1)
|
||||||
|
continue
|
||||||
|
|
||||||
|
try:
|
||||||
|
events = await self._fetch_events()
|
||||||
|
self._poll_count += 1
|
||||||
|
|
||||||
|
for event in events:
|
||||||
|
try:
|
||||||
|
await self._process_event(event)
|
||||||
|
except Exception as e:
|
||||||
|
logger.warning(f"Event processing error: {e}")
|
||||||
|
|
||||||
|
backoff = 0
|
||||||
|
|
||||||
|
# Heartbeat
|
||||||
|
now = time.time()
|
||||||
|
if now - self._last_heartbeat > HEARTBEAT_INTERVAL:
|
||||||
|
self._last_heartbeat = now
|
||||||
|
silence = now - self._last_event_time
|
||||||
|
logger.info(
|
||||||
|
f"Heartbeat — polls={self._poll_count} "
|
||||||
|
f"processed={self._messages_processed} "
|
||||||
|
f"silence={silence:.0f}s reconnects={self._reconnects}"
|
||||||
|
)
|
||||||
|
|
||||||
|
except asyncio.CancelledError:
|
||||||
|
break
|
||||||
|
except Exception as e:
|
||||||
|
err = str(e)
|
||||||
|
if "BAD_EVENT_QUEUE_ID" in err:
|
||||||
|
logger.info("Queue expired, reconnecting...")
|
||||||
|
await self._reconnect()
|
||||||
|
continue
|
||||||
|
delay = RECONNECT_BACKOFF[min(backoff, len(RECONNECT_BACKOFF) - 1)]
|
||||||
|
backoff += 1
|
||||||
|
logger.warning(f"Poll error: {e}")
|
||||||
|
await asyncio.sleep(delay)
|
||||||
|
|
||||||
|
await asyncio.sleep(DEFAULT_POLL_INTERVAL)
|
||||||
|
|
||||||
|
async def _fetch_events(self) -> list:
|
||||||
|
"""Fetch events from Zulip queue."""
|
||||||
|
resp = await self._api_call("GET", "/api/v1/events", params={
|
||||||
|
"queue_id": self._queue_id,
|
||||||
|
"last_event_id": str(self._last_event_id),
|
||||||
|
"dont_block": "true",
|
||||||
|
})
|
||||||
|
if resp is None:
|
||||||
|
return []
|
||||||
|
|
||||||
|
events = resp.get("events", [])
|
||||||
|
for event in events:
|
||||||
|
eid = event.get("id", 0)
|
||||||
|
if eid > self._last_event_id:
|
||||||
|
self._last_event_id = eid
|
||||||
|
|
||||||
|
return [e for e in events if e.get("type") == "message"]
|
||||||
|
|
||||||
|
async def _reconnect(self):
|
||||||
|
"""Re-register event queue."""
|
||||||
|
self._queue_id = None
|
||||||
|
try:
|
||||||
|
resp = await self._api_call("POST", "/api/v1/register", data={
|
||||||
|
"event_types": '["message"]',
|
||||||
|
"apply_markdown": "true",
|
||||||
|
})
|
||||||
|
if resp:
|
||||||
|
self._queue_id = resp.get("queue_id")
|
||||||
|
self._last_event_id = resp.get("last_event_id", -1)
|
||||||
|
self._reconnects += 1
|
||||||
|
logger.info(f"Reconnected, queue={self._queue_id}")
|
||||||
|
except Exception as e:
|
||||||
|
logger.error(f"Reconnect failed: {e}")
|
||||||
|
|
||||||
|
async def _process_event(self, event: dict):
|
||||||
|
"""Process a Zulip message event."""
|
||||||
|
msg = event.get("message", {})
|
||||||
|
msg_type = msg.get("type", "")
|
||||||
|
sender_email = msg.get("sender_email", "")
|
||||||
|
sender_name = msg.get("sender_full_name", "Unknown")
|
||||||
|
sender_id = msg.get("sender_id")
|
||||||
|
content = msg.get("content", "")
|
||||||
|
|
||||||
|
# Ignore own messages
|
||||||
|
if sender_email == self._bot_email:
|
||||||
|
return
|
||||||
|
|
||||||
|
# Determine targeting
|
||||||
|
mentioned_users = msg.get("mentioned_users", []) or []
|
||||||
|
mentioned_ids = [u.get("user_id") for u in mentioned_users if isinstance(u, dict)]
|
||||||
|
is_dm = msg_type == "private"
|
||||||
|
is_mention = self._bot_user_id and self._bot_user_id in mentioned_ids
|
||||||
|
|
||||||
|
if is_dm:
|
||||||
|
self._messages_processed += 1
|
||||||
|
self._last_event_time = time.time()
|
||||||
|
logger.info(f"DM from {sender_name}: {content[:80]}...")
|
||||||
|
|
||||||
|
# Send typing indicator
|
||||||
|
await self._typing(sender_id, "start")
|
||||||
|
|
||||||
|
# Send placeholder
|
||||||
|
placeholder_id = await self._send_msg("private", str(sender_id),
|
||||||
|
":robot: _Processing your message..._")
|
||||||
|
|
||||||
|
# Forward to Agent Zero via A2A
|
||||||
|
response = await self._a2a_chat(sender_name, content)
|
||||||
|
|
||||||
|
# Stop typing
|
||||||
|
await self._typing(sender_id, "stop")
|
||||||
|
|
||||||
|
# Post response
|
||||||
|
if response and placeholder_id:
|
||||||
|
await self._edit_msg(placeholder_id, response[:MAX_ZULIP_MSG])
|
||||||
|
logger.info(f"Responded to {sender_name} ({len(response)} chars)")
|
||||||
|
elif response:
|
||||||
|
await self._send_msg("private", str(sender_id), response[:MAX_ZULIP_MSG])
|
||||||
|
|
||||||
|
async def _a2a_chat(self, sender_name: str, message: str) -> Optional[str]:
|
||||||
|
"""Send message to Agent Zero via local A2A protocol."""
|
||||||
|
try:
|
||||||
|
a2a_payload = {
|
||||||
|
"jsonrpc": "2.0",
|
||||||
|
"method": "tasks/send",
|
||||||
|
"params": {
|
||||||
|
"id": f"zulip-{int(time.time())}",
|
||||||
|
"message": {
|
||||||
|
"role": "user",
|
||||||
|
"parts": [{"text": f"[Zulip DM from {sender_name}]: {message}"}]
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"id": 1
|
||||||
|
}
|
||||||
|
|
||||||
|
headers = {
|
||||||
|
"Content-Type": "application/json",
|
||||||
|
"Authorization": f"Bearer {self._a2a_token}",
|
||||||
|
}
|
||||||
|
|
||||||
|
async with httpx.AsyncClient(timeout=120.0) as client:
|
||||||
|
# Send the message to Agent Zero
|
||||||
|
resp = await client.post(
|
||||||
|
self._a2a_url,
|
||||||
|
json=a2a_payload,
|
||||||
|
headers=headers,
|
||||||
|
)
|
||||||
|
|
||||||
|
if resp.status_code != 200:
|
||||||
|
logger.error(f"A2A send failed: HTTP {resp.status_code}")
|
||||||
|
return f":warning: Failed to reach agent. Error: HTTP {resp.status_code}"
|
||||||
|
|
||||||
|
result = resp.json()
|
||||||
|
task_id = result.get("result", {}).get("id")
|
||||||
|
|
||||||
|
if not task_id:
|
||||||
|
logger.error("A2A: no task_id returned")
|
||||||
|
return ":warning: Agent did not create a task."
|
||||||
|
|
||||||
|
# Poll for completion
|
||||||
|
for _ in range(60): # max 60s wait
|
||||||
|
await asyncio.sleep(1)
|
||||||
|
status_resp = await client.post(
|
||||||
|
self._a2a_url,
|
||||||
|
json={
|
||||||
|
"jsonrpc": "2.0",
|
||||||
|
"method": "tasks/get",
|
||||||
|
"params": {"id": task_id},
|
||||||
|
"id": 2
|
||||||
|
},
|
||||||
|
headers=headers,
|
||||||
|
)
|
||||||
|
|
||||||
|
if status_resp.status_code != 200:
|
||||||
|
continue
|
||||||
|
|
||||||
|
status_data = status_resp.json()
|
||||||
|
result_data = status_data.get("result", {})
|
||||||
|
state = result_data.get("status", {}).get("state", "")
|
||||||
|
|
||||||
|
if state == "completed":
|
||||||
|
# Extract response text
|
||||||
|
return self._extract_a2a_response(result_data)
|
||||||
|
elif state in ("failed", "error"):
|
||||||
|
error_msg = result_data.get("status", {}).get("message", {}).get("text", "Unknown error")
|
||||||
|
return f":warning: Agent processing failed: {error_msg}"
|
||||||
|
|
||||||
|
return ":hourglass: Agent did not complete in time."
|
||||||
|
|
||||||
|
except httpx.TimeoutException:
|
||||||
|
return ":hourglass: Agent request timed out."
|
||||||
|
except Exception as e:
|
||||||
|
logger.error(f"A2A error: {e}")
|
||||||
|
return f":warning: Communication error: {type(e).__name__}"
|
||||||
|
|
||||||
|
def _extract_a2a_response(self, result: dict) -> str:
|
||||||
|
"""Extract assistant text from A2A response."""
|
||||||
|
history = result.get("history", [])
|
||||||
|
for msg in reversed(history):
|
||||||
|
if isinstance(msg, dict) and msg.get("role") == "assistant":
|
||||||
|
parts = msg.get("parts", [])
|
||||||
|
texts = [p.get("text", "") for p in parts if isinstance(p, dict)]
|
||||||
|
text = "\n".join(t for t in texts if t)
|
||||||
|
if text:
|
||||||
|
return text
|
||||||
|
|
||||||
|
artifacts = result.get("artifacts", [])
|
||||||
|
for artifact in reversed(artifacts):
|
||||||
|
if isinstance(artifact, dict):
|
||||||
|
text = artifact.get("text") or artifact.get("content") or ""
|
||||||
|
if text:
|
||||||
|
return text
|
||||||
|
|
||||||
|
return "(no response)"
|
||||||
|
|
||||||
|
# ── Zulip API ──
|
||||||
|
|
||||||
|
async def _api_call(self, method: str, path: str,
|
||||||
|
data: dict = None, params: dict = None) -> Optional[dict]:
|
||||||
|
"""Make Zulip API call."""
|
||||||
|
if not self._http_client:
|
||||||
|
return None
|
||||||
|
|
||||||
|
url = f"{self._site}{path}"
|
||||||
|
headers = {"Authorization": self._auth_header}
|
||||||
|
|
||||||
|
try:
|
||||||
|
if method == "GET":
|
||||||
|
resp = await self._http_client.get(url, params=params, headers=headers)
|
||||||
|
elif method == "POST":
|
||||||
|
resp = await self._http_client.post(url, data=data, headers=headers)
|
||||||
|
elif method == "PATCH":
|
||||||
|
resp = await self._http_client.patch(url, data=data, headers=headers)
|
||||||
|
else:
|
||||||
|
return None
|
||||||
|
|
||||||
|
if resp.status_code >= 400:
|
||||||
|
logger.debug(f"API {method} {path}: {resp.status_code}")
|
||||||
|
return None
|
||||||
|
|
||||||
|
return resp.json()
|
||||||
|
except Exception as e:
|
||||||
|
logger.debug(f"API error {method} {path}: {e}")
|
||||||
|
return None
|
||||||
|
|
||||||
|
async def _send_msg(self, msg_type: str, to: str, content: str) -> Optional[int]:
|
||||||
|
"""Send a message to Zulip."""
|
||||||
|
payload = {"type": msg_type, "content": content}
|
||||||
|
if msg_type == "private":
|
||||||
|
payload["to"] = json.dumps([int(to)])
|
||||||
|
else:
|
||||||
|
payload["to"] = to
|
||||||
|
payload["subject"] = "general"
|
||||||
|
|
||||||
|
resp = await self._api_call("POST", "/api/v1/messages", data=payload)
|
||||||
|
if resp and resp.get("id"):
|
||||||
|
return resp["id"]
|
||||||
|
return None
|
||||||
|
|
||||||
|
async def _edit_msg(self, message_id: int, content: str):
|
||||||
|
"""Edit a Zulip message."""
|
||||||
|
await self._api_call("PATCH", f"/api/v1/messages/{message_id}",
|
||||||
|
data={"content": content})
|
||||||
|
|
||||||
|
async def _typing(self, user_id: int, op: str):
|
||||||
|
"""Send typing indicator."""
|
||||||
|
if not user_id:
|
||||||
|
return
|
||||||
|
to_data = json.dumps([user_id])
|
||||||
|
await self._api_call("POST", "/api/v1/typing",
|
||||||
|
data={"to": to_data, "op": op})
|
||||||
|
|
||||||
|
def run(self):
|
||||||
|
"""Synchronous entry point."""
|
||||||
|
asyncio.run(self._run_async())
|
||||||
|
|
||||||
|
async def _run_async(self):
|
||||||
|
try:
|
||||||
|
if await self.start():
|
||||||
|
# Keep running until stopped
|
||||||
|
while self._running:
|
||||||
|
await asyncio.sleep(1)
|
||||||
|
except asyncio.CancelledError:
|
||||||
|
pass
|
||||||
|
finally:
|
||||||
|
await self.stop()
|
||||||
|
|
||||||
|
|
||||||
|
# ── Entry point ──
|
||||||
|
|
||||||
|
def main():
|
||||||
|
"""CLI entry point."""
|
||||||
|
logging.basicConfig(
|
||||||
|
level=logging.INFO,
|
||||||
|
format="%(asctime)s [%(name)s] %(levelname)s: %(message)s",
|
||||||
|
datefmt="%Y-%m-%d %H:%M:%S",
|
||||||
|
)
|
||||||
|
|
||||||
|
adapter = AgentZeroZulipAdapter()
|
||||||
|
|
||||||
|
try:
|
||||||
|
adapter.run()
|
||||||
|
except KeyboardInterrupt:
|
||||||
|
logger.info("Shutdown requested")
|
||||||
|
|
||||||
|
# Handle signals
|
||||||
|
import signal
|
||||||
|
shutdown = asyncio.Event()
|
||||||
|
|
||||||
|
def _handle_signal():
|
||||||
|
shutdown.set()
|
||||||
|
|
||||||
|
loop = asyncio.new_event_loop()
|
||||||
|
asyncio.set_event_loop(loop)
|
||||||
|
|
||||||
|
try:
|
||||||
|
loop.add_signal_handler(signal.SIGTERM, _handle_signal)
|
||||||
|
loop.add_signal_handler(signal.SIGINT, _handle_signal)
|
||||||
|
except NotImplementedError:
|
||||||
|
pass
|
||||||
|
|
||||||
|
async def _run():
|
||||||
|
if await adapter.start():
|
||||||
|
await shutdown.wait()
|
||||||
|
await adapter.stop()
|
||||||
|
|
||||||
|
try:
|
||||||
|
loop.run_until_complete(_run())
|
||||||
|
except KeyboardInterrupt:
|
||||||
|
pass
|
||||||
|
finally:
|
||||||
|
loop.close()
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
main()
|
||||||
@@ -1,10 +1,19 @@
|
|||||||
"""
|
"""
|
||||||
Zulip platform adapter (Hermes plugin) — Gen 3.
|
Zulip platform adapter (Hermes plugin) — Gen 4.
|
||||||
|
|
||||||
Connects a Hermes agent to Zulip via event queue polling. DMs and @mentions
|
Connects a Hermes agent to Zulip via event queue polling. DMs and @mentions
|
||||||
are routed to the agent via the Hermes Gateway's handle_message() interface.
|
are routed to the agent via the Hermes Gateway's handle_message() interface.
|
||||||
Replies use a placeholder->edit streaming pattern for UX feedback.
|
Replies use a placeholder->edit streaming pattern for UX feedback.
|
||||||
|
|
||||||
|
Gen 4 Improvements (2026-06-27):
|
||||||
|
1. HTTP client recreation on reconnect — new httpx.AsyncClient() after queue expiry
|
||||||
|
or sustained failures to prevent CLOSE-WAIT socket leaks
|
||||||
|
2. Heartbeat logging — periodic "still alive" message to prove poll loop is running
|
||||||
|
3. Log sanitization — truncates 502/error HTML to first 80 chars (no Netbird HTML spam)
|
||||||
|
4. Connection recovery — creates fresh HTTP client after N empty poll cycles
|
||||||
|
5. Poll silence detection — logs warnings when no events received for extended period
|
||||||
|
6. Connection reuse limit — periodic client recreation to prevent connection pool exhaustion
|
||||||
|
|
||||||
Gen 3 Improvements (2026-06-26):
|
Gen 3 Improvements (2026-06-26):
|
||||||
1. Malformed message resilience — try/except wraps each event, no crash on bad JSON
|
1. Malformed message resilience — try/except wraps each event, no crash on bad JSON
|
||||||
2. Periodic @all-bots refresh — background task re-resolves user ID every hour
|
2. Periodic @all-bots refresh — background task re-resolves user ID every hour
|
||||||
@@ -66,6 +75,13 @@ DEDUP_CLEANUP_INTERVAL = 120 # Clean old entries every 2 minutes
|
|||||||
ALL_BOTS_REFRESH_INTERVAL = 3600 # Re-resolve @all-bots user ID every hour
|
ALL_BOTS_REFRESH_INTERVAL = 3600 # Re-resolve @all-bots user ID every hour
|
||||||
SELFTEST_TIMEOUT = 30 # seconds to wait for self-test response
|
SELFTEST_TIMEOUT = 30 # seconds to wait for self-test response
|
||||||
|
|
||||||
|
# Gen 4: Connection pool health
|
||||||
|
HEARTBEAT_INTERVAL = 300 # Log heartbeat every 5 minutes
|
||||||
|
MAX_CONSECUTIVE_EMPTY_POLLS = 20 # Reset client after this many empty polls
|
||||||
|
CLIENT_REUSE_LIMIT = 500 # Create fresh client every N polls to prevent connection leaks
|
||||||
|
POLL_SILENCE_WARN_INTERVAL = 60 # Warn if no events received for this many seconds
|
||||||
|
MAX_ERROR_LOG_LEN = 80 # Truncate error response bodies to avoid HTML spam
|
||||||
|
|
||||||
# Regex to strip Zulip @mention markup
|
# Regex to strip Zulip @mention markup
|
||||||
MENTION_CLEANER = re.compile(r"@\*\*[^*]+\*\*")
|
MENTION_CLEANER = re.compile(r"@\*\*[^*]+\*\*")
|
||||||
|
|
||||||
@@ -158,7 +174,18 @@ class ZulipAdapter(BasePlatformAdapter):
|
|||||||
or os.getenv("ZULIP_POLL_INTERVAL", str(DEFAULT_POLL_INTERVAL))
|
or os.getenv("ZULIP_POLL_INTERVAL", str(DEFAULT_POLL_INTERVAL))
|
||||||
)
|
)
|
||||||
|
|
||||||
|
# --- Gen 4: Connection health ---
|
||||||
|
self._consecutive_empty_polls: int = 0
|
||||||
|
self._total_poll_count: int = 0
|
||||||
|
self._last_event_received_time: float = time.time()
|
||||||
|
self._last_heartbeat_time: float = 0.0
|
||||||
|
self._client_pool_reset_count: int = 0
|
||||||
|
|
||||||
# --- State ---
|
# --- State ---
|
||||||
|
# Support both ZULIP_SITE and ZULIP_URL env vars
|
||||||
|
if not self._site:
|
||||||
|
self._site = (os.getenv("ZULIP_URL", "") or "").rstrip("/")
|
||||||
|
|
||||||
self._auth_header: str = _build_auth_header(self._email, self._api_key)
|
self._auth_header: str = _build_auth_header(self._email, self._api_key)
|
||||||
self._queue_id: Optional[str] = None
|
self._queue_id: Optional[str] = None
|
||||||
self._last_event_id: int = -1
|
self._last_event_id: int = -1
|
||||||
@@ -201,7 +228,7 @@ class ZulipAdapter(BasePlatformAdapter):
|
|||||||
|
|
||||||
# --- Gen 3: Health stats callback ---
|
# --- Gen 3: Health stats callback ---
|
||||||
self._health_callback = None
|
self._health_callback = None
|
||||||
self._health_callback_interval: int = 600 # 10 min
|
self._health_callback_interval: int = 300 # 5 min
|
||||||
|
|
||||||
@staticmethod
|
@staticmethod
|
||||||
def _resolve_int(val: Any, default: int) -> int:
|
def _resolve_int(val: Any, default: int) -> int:
|
||||||
@@ -227,8 +254,11 @@ class ZulipAdapter(BasePlatformAdapter):
|
|||||||
# Connection lifecycle
|
# Connection lifecycle
|
||||||
# ------------------------------------------------------------------
|
# ------------------------------------------------------------------
|
||||||
|
|
||||||
async def connect(self) -> bool:
|
async def connect(self, **kwargs: Any) -> bool:
|
||||||
"""Connect to Zulip and register an event queue."""
|
"""Connect to Zulip and register an event queue.
|
||||||
|
|
||||||
|
Accepts **kwargs for Hermes Gateway compatibility (e.g., is_reconnect).
|
||||||
|
"""
|
||||||
if not HTTPX_AVAILABLE:
|
if not HTTPX_AVAILABLE:
|
||||||
logger.warning("[%s] httpx not installed", self.name)
|
logger.warning("[%s] httpx not installed", self.name)
|
||||||
return False
|
return False
|
||||||
@@ -238,9 +268,14 @@ class ZulipAdapter(BasePlatformAdapter):
|
|||||||
return False
|
return False
|
||||||
|
|
||||||
try:
|
try:
|
||||||
self._http_client = httpx.AsyncClient(timeout=30.0)
|
await self._create_http_client()
|
||||||
self._health_stats["started_at"] = datetime.now(timezone.utc).isoformat()
|
self._health_stats["started_at"] = datetime.now(timezone.utc).isoformat()
|
||||||
|
|
||||||
|
# Reset connection health counters
|
||||||
|
self._consecutive_empty_polls = 0
|
||||||
|
self._total_poll_count = 0
|
||||||
|
self._last_event_received_time = time.time()
|
||||||
|
|
||||||
# Register event queue
|
# Register event queue
|
||||||
queue_resp, _ = await self._api_call(
|
queue_resp, _ = await self._api_call(
|
||||||
"POST", "/api/v1/register",
|
"POST", "/api/v1/register",
|
||||||
@@ -259,6 +294,11 @@ class ZulipAdapter(BasePlatformAdapter):
|
|||||||
self._last_event_id = data.get("last_event_id", -1)
|
self._last_event_id = data.get("last_event_id", -1)
|
||||||
self._bot_user_id = data.get("user_id")
|
self._bot_user_id = data.get("user_id")
|
||||||
|
|
||||||
|
# Resolve bot user_id if register endpoint didn't provide it
|
||||||
|
# (common on some Zulip versions)
|
||||||
|
if self._bot_user_id is None:
|
||||||
|
await self._resolve_bot_user_id()
|
||||||
|
|
||||||
# Gen 2: Try to resolve @all-bots user ID dynamically
|
# Gen 2: Try to resolve @all-bots user ID dynamically
|
||||||
await self._resolve_all_bots_user_id()
|
await self._resolve_all_bots_user_id()
|
||||||
|
|
||||||
@@ -337,24 +377,94 @@ class ZulipAdapter(BasePlatformAdapter):
|
|||||||
try:
|
try:
|
||||||
events = await self._fetch_events()
|
events = await self._fetch_events()
|
||||||
self._health_stats["poll_count"] += 1
|
self._health_stats["poll_count"] += 1
|
||||||
|
self._total_poll_count += 1
|
||||||
self._health_stats["last_poll_at"] = datetime.now(
|
self._health_stats["last_poll_at"] = datetime.now(
|
||||||
timezone.utc
|
timezone.utc
|
||||||
).isoformat()
|
).isoformat()
|
||||||
for event in events:
|
|
||||||
try:
|
if events:
|
||||||
await self._process_zulip_event(event)
|
now = time.time()
|
||||||
except Exception as e:
|
self._consecutive_empty_polls = 0
|
||||||
# Gen 3: Malformed message resilience — catch per-event
|
self._last_event_received_time = now
|
||||||
# failures so one bad message never kills the poll loop
|
for event in events:
|
||||||
|
try:
|
||||||
|
await self._process_zulip_event(event)
|
||||||
|
except Exception as e:
|
||||||
|
# Gen 3: Malformed message resilience — catch per-event
|
||||||
|
# failures so one bad message never kills the poll loop
|
||||||
|
logger.warning(
|
||||||
|
"[%s] Malformed event skipped: %s. "
|
||||||
|
"Event id=%s",
|
||||||
|
self.name, e,
|
||||||
|
event.get("id", "unknown"),
|
||||||
|
)
|
||||||
|
self._health_stats["malformed_events"] = (
|
||||||
|
self._health_stats.get("malformed_events", 0) + 1
|
||||||
|
)
|
||||||
|
else:
|
||||||
|
# Gen 4: Track consecutive empty polls to detect silent failures
|
||||||
|
self._consecutive_empty_polls += 1
|
||||||
|
|
||||||
|
# Gen 4: Detect prolonged silence (no events for too long)
|
||||||
|
silence_duration = time.time() - self._last_event_received_time
|
||||||
|
if silence_duration > POLL_SILENCE_WARN_INTERVAL:
|
||||||
logger.warning(
|
logger.warning(
|
||||||
"[%s] Malformed event skipped: %s. "
|
"[%s] No events received for %.0fs "
|
||||||
"Event id=%s",
|
"(consecutive_empty=%d, total_polls=%d, "
|
||||||
self.name, e,
|
"queue=%s)",
|
||||||
event.get("id", "unknown"),
|
self.name, silence_duration,
|
||||||
|
self._consecutive_empty_polls,
|
||||||
|
self._total_poll_count,
|
||||||
|
self._queue_id,
|
||||||
)
|
)
|
||||||
self._health_stats["malformed_events"] = (
|
|
||||||
self._health_stats.get("malformed_events", 0) + 1
|
# Gen 4: Reset HTTP client if too many empty polls in a row
|
||||||
|
# (connection pool likely stuck in CLOSE-WAIT)
|
||||||
|
if (
|
||||||
|
self._consecutive_empty_polls
|
||||||
|
>= MAX_CONSECUTIVE_EMPTY_POLLS
|
||||||
|
):
|
||||||
|
logger.warning(
|
||||||
|
"[%s] %d consecutive empty polls — "
|
||||||
|
"recreating HTTP client and reconnecting",
|
||||||
|
self.name, self._consecutive_empty_polls,
|
||||||
)
|
)
|
||||||
|
await self._reconnect_with_fresh_client()
|
||||||
|
backoff_idx = 0
|
||||||
|
self._consecutive_empty_polls = 0
|
||||||
|
continue
|
||||||
|
|
||||||
|
# Gen 4: Periodic client refresh to prevent connection leaks
|
||||||
|
if self._total_poll_count % CLIENT_REUSE_LIMIT == 0:
|
||||||
|
logger.info(
|
||||||
|
"[%s] Client reuse limit reached (%d polls) — "
|
||||||
|
"creating fresh HTTP client",
|
||||||
|
self.name, self._total_poll_count,
|
||||||
|
)
|
||||||
|
old_client = self._http_client
|
||||||
|
await self._create_http_client()
|
||||||
|
if old_client:
|
||||||
|
try:
|
||||||
|
await old_client.aclose()
|
||||||
|
except Exception:
|
||||||
|
pass
|
||||||
|
|
||||||
|
# Gen 4: Heartbeat logging — prove poll loop is alive
|
||||||
|
now = time.time()
|
||||||
|
if now - self._last_heartbeat_time > HEARTBEAT_INTERVAL:
|
||||||
|
self._last_heartbeat_time = now
|
||||||
|
silence = now - self._last_event_received_time
|
||||||
|
logger.info(
|
||||||
|
"[%s] Heartbeat — polls=%d empty=%d "
|
||||||
|
"silence=%.0fs errors=%d reconnects=%d "
|
||||||
|
"queue=%s",
|
||||||
|
self.name, self._total_poll_count,
|
||||||
|
self._consecutive_empty_polls, silence,
|
||||||
|
self._health_stats["poll_errors"],
|
||||||
|
self._health_stats["reconnects"],
|
||||||
|
self._queue_id,
|
||||||
|
)
|
||||||
|
|
||||||
backoff_idx = 0
|
backoff_idx = 0
|
||||||
except asyncio.CancelledError:
|
except asyncio.CancelledError:
|
||||||
break
|
break
|
||||||
@@ -370,7 +480,7 @@ class ZulipAdapter(BasePlatformAdapter):
|
|||||||
err_str = str(e)
|
err_str = str(e)
|
||||||
if "BAD_EVENT_QUEUE_ID" in err_str or "queue_id" in err_str.lower():
|
if "BAD_EVENT_QUEUE_ID" in err_str or "queue_id" in err_str.lower():
|
||||||
logger.info("[%s] Queue expired, re-registering...", self.name)
|
logger.info("[%s] Queue expired, re-registering...", self.name)
|
||||||
await self._reconnect()
|
await self._reconnect_with_fresh_client()
|
||||||
backoff_idx = 0
|
backoff_idx = 0
|
||||||
continue
|
continue
|
||||||
logger.warning("[%s] Poll error: %s", self.name, e)
|
logger.warning("[%s] Poll error: %s", self.name, e)
|
||||||
@@ -412,6 +522,28 @@ class ZulipAdapter(BasePlatformAdapter):
|
|||||||
|
|
||||||
return [e for e in events if e.get("type") == "message"]
|
return [e for e in events if e.get("type") == "message"]
|
||||||
|
|
||||||
|
async def _create_http_client(self) -> None:
|
||||||
|
"""Create a fresh httpx client, closing the old one if it exists.
|
||||||
|
|
||||||
|
Gen 4: This ensures a clean connection pool after sustained failures
|
||||||
|
or queue expiry, preventing CLOSE-WAIT socket leaks.
|
||||||
|
"""
|
||||||
|
old_client = self._http_client
|
||||||
|
self._http_client = httpx.AsyncClient(
|
||||||
|
timeout=httpx.Timeout(30.0, connect=15.0),
|
||||||
|
limits=httpx.Limits(
|
||||||
|
max_keepalive_connections=5,
|
||||||
|
max_connections=10,
|
||||||
|
keepalive_expiry=60.0,
|
||||||
|
),
|
||||||
|
)
|
||||||
|
self._client_pool_reset_count += 1
|
||||||
|
if old_client:
|
||||||
|
try:
|
||||||
|
await old_client.aclose()
|
||||||
|
except Exception:
|
||||||
|
pass
|
||||||
|
|
||||||
async def _reconnect(self) -> None:
|
async def _reconnect(self) -> None:
|
||||||
"""Re-register the event queue."""
|
"""Re-register the event queue."""
|
||||||
self._queue_id = None
|
self._queue_id = None
|
||||||
@@ -429,9 +561,21 @@ class ZulipAdapter(BasePlatformAdapter):
|
|||||||
self._last_event_id = resp.get("last_event_id", -1)
|
self._last_event_id = resp.get("last_event_id", -1)
|
||||||
self._health_stats["reconnects"] += 1
|
self._health_stats["reconnects"] += 1
|
||||||
logger.info("[%s] Reconnected, queue=%s", self.name, self._queue_id)
|
logger.info("[%s] Reconnected, queue=%s", self.name, self._queue_id)
|
||||||
|
self._consecutive_empty_polls = 0
|
||||||
|
self._last_event_received_time = time.time()
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
logger.error("[%s] Reconnect failed: %s", self.name, e)
|
logger.error("[%s] Reconnect failed: %s", self.name, e)
|
||||||
|
|
||||||
|
async def _reconnect_with_fresh_client(self) -> None:
|
||||||
|
"""Re-register the event queue with a fresh HTTP client.
|
||||||
|
|
||||||
|
Gen 4: Creates a new httpx client to break out of stuck connection
|
||||||
|
pools (CLOSE-WAIT sockets from previous failures).
|
||||||
|
"""
|
||||||
|
logger.info("[%s] Reconnecting with fresh HTTP client", self.name)
|
||||||
|
await self._create_http_client()
|
||||||
|
await self._reconnect()
|
||||||
|
|
||||||
# ------------------------------------------------------------------
|
# ------------------------------------------------------------------
|
||||||
# Gen 2: Background dedup maintenance
|
# Gen 2: Background dedup maintenance
|
||||||
# ------------------------------------------------------------------
|
# ------------------------------------------------------------------
|
||||||
@@ -503,6 +647,32 @@ class ZulipAdapter(BasePlatformAdapter):
|
|||||||
"[%s] @all-bots refresh error (non-fatal)", self.name
|
"[%s] @all-bots refresh error (non-fatal)", self.name
|
||||||
)
|
)
|
||||||
|
|
||||||
|
# ------------------------------------------------------------------
|
||||||
|
# Gen 5: Bot user ID resolution
|
||||||
|
# ------------------------------------------------------------------
|
||||||
|
|
||||||
|
async def _resolve_bot_user_id(self) -> None:
|
||||||
|
"""Fetch the bot's own user ID from /api/v1/users/me.
|
||||||
|
|
||||||
|
The /register endpoint does not always return user_id on
|
||||||
|
all Zulip server versions. This ensures @mention detection
|
||||||
|
works by resolving it from the identity endpoint.
|
||||||
|
"""
|
||||||
|
try:
|
||||||
|
resp, _ = await self._api_call("GET", "/api/v1/users/me")
|
||||||
|
if resp:
|
||||||
|
uid = resp.get("user_id")
|
||||||
|
if uid is not None:
|
||||||
|
self._bot_user_id = int(uid)
|
||||||
|
logger.info(
|
||||||
|
"[%s] Resolved bot user_id=%s from /users/me",
|
||||||
|
self.name, uid,
|
||||||
|
)
|
||||||
|
except Exception as e:
|
||||||
|
logger.debug(
|
||||||
|
"[%s] Could not resolve bot user_id: %s", self.name, e
|
||||||
|
)
|
||||||
|
|
||||||
# ------------------------------------------------------------------
|
# ------------------------------------------------------------------
|
||||||
# Gen 2: Dynamic @all-bots resolution
|
# Gen 2: Dynamic @all-bots resolution
|
||||||
# ------------------------------------------------------------------
|
# ------------------------------------------------------------------
|
||||||
@@ -686,12 +856,15 @@ class ZulipAdapter(BasePlatformAdapter):
|
|||||||
content: str,
|
content: str,
|
||||||
reply_to: Optional[str] = None,
|
reply_to: Optional[str] = None,
|
||||||
metadata: Optional[Dict[str, Any]] = None,
|
metadata: Optional[Dict[str, Any]] = None,
|
||||||
|
**kwargs: Any,
|
||||||
) -> SendResult:
|
) -> SendResult:
|
||||||
"""Send a message to a Zulip chat.
|
"""Send a message to a Zulip chat.
|
||||||
|
|
||||||
For DMs, chat_id is the user_id. For streams, format is
|
For DMs, chat_id is the user_id. For streams, format is
|
||||||
"stream_name:topic". Sends a placeholder first if this is the
|
"stream_name:topic". Sends a placeholder first if this is the
|
||||||
first message in a turn, then edits it on subsequent calls.
|
first message in a turn, then edits it on subsequent calls.
|
||||||
|
|
||||||
|
Accepts **kwargs for Hermes Gateway compatibility.
|
||||||
"""
|
"""
|
||||||
# Determine target type and IDs
|
# Determine target type and IDs
|
||||||
is_dm = not chat_id or ":" not in chat_id
|
is_dm = not chat_id or ":" not in chat_id
|
||||||
@@ -734,28 +907,22 @@ class ZulipAdapter(BasePlatformAdapter):
|
|||||||
self._health_stats["send_count"] += 1
|
self._health_stats["send_count"] += 1
|
||||||
return SendResult(
|
return SendResult(
|
||||||
success=True,
|
success=True,
|
||||||
platform="zulip",
|
|
||||||
chat_id=chat_id,
|
|
||||||
message_id=msg_id,
|
message_id=msg_id,
|
||||||
metadata={"placeholder": True},
|
|
||||||
)
|
)
|
||||||
|
|
||||||
# Send actual content
|
# Send actual content
|
||||||
result = await self._send_api_call(payload)
|
result = await self._send_api_call(payload)
|
||||||
if result and result.get("id"):
|
if result and result.get("id"):
|
||||||
|
msg_id = str(result["id"])
|
||||||
self._health_stats["send_count"] += 1
|
self._health_stats["send_count"] += 1
|
||||||
return SendResult(
|
return SendResult(
|
||||||
success=True,
|
success=True,
|
||||||
platform="zulip",
|
message_id=msg_id,
|
||||||
chat_id=chat_id,
|
|
||||||
message_id=str(result["id"]),
|
|
||||||
)
|
)
|
||||||
|
|
||||||
self._health_stats["send_errors"] += 1
|
self._health_stats["send_errors"] += 1
|
||||||
return SendResult(
|
return SendResult(
|
||||||
success=False,
|
success=False,
|
||||||
platform="zulip",
|
|
||||||
chat_id=chat_id,
|
|
||||||
error="Failed to send message",
|
error="Failed to send message",
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -765,19 +932,43 @@ class ZulipAdapter(BasePlatformAdapter):
|
|||||||
message_id: str,
|
message_id: str,
|
||||||
content: str,
|
content: str,
|
||||||
metadata: Optional[Dict[str, Any]] = None,
|
metadata: Optional[Dict[str, Any]] = None,
|
||||||
) -> bool:
|
**kwargs: Any,
|
||||||
"""Edit a previously sent Zulip message (for placeholder replacement)."""
|
) -> SendResult:
|
||||||
|
"""Edit a previously sent Zulip message (for placeholder replacement).
|
||||||
|
|
||||||
|
Returns SendResult for Hermes Gateway streaming interface compatibility.
|
||||||
|
Accepts **kwargs (e.g., finalize=True) — extra kwargs are silently ignored.
|
||||||
|
|
||||||
|
Note: Zulip uses POST /api/v1/messages/{message_id} for editing.
|
||||||
|
"""
|
||||||
truncated = _truncate(content)
|
truncated = _truncate(content)
|
||||||
payload = {
|
payload = {
|
||||||
"message_id": int(message_id),
|
|
||||||
"content": truncated,
|
"content": truncated,
|
||||||
}
|
}
|
||||||
try:
|
try:
|
||||||
resp, _ = await self._api_call("PATCH", "/api/v1/messages", data=payload)
|
# Zulip API: PATCH /api/v1/messages/{message_id} with content in body
|
||||||
return resp is not None
|
resp, status = await self._api_call(
|
||||||
|
"PATCH", f"/api/v1/messages/{int(message_id)}",
|
||||||
|
data=payload,
|
||||||
|
)
|
||||||
|
if resp:
|
||||||
|
self._health_stats["send_count"] += 1
|
||||||
|
return SendResult(
|
||||||
|
success=True,
|
||||||
|
message_id=str(resp.get("id", message_id)),
|
||||||
|
)
|
||||||
|
self._health_stats["send_errors"] += 1
|
||||||
|
return SendResult(
|
||||||
|
success=False,
|
||||||
|
error=f"Edit failed (status={status})",
|
||||||
|
)
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
logger.warning("[%s] Edit message %s error: %s", self.name, message_id, e)
|
logger.warning("[%s] Edit message %s error: %s", self.name, message_id, e)
|
||||||
return False
|
self._health_stats["send_errors"] += 1
|
||||||
|
return SendResult(
|
||||||
|
success=False,
|
||||||
|
error=str(e),
|
||||||
|
)
|
||||||
|
|
||||||
async def send_typing(self, chat_id: str, metadata: Optional[Dict] = None) -> None:
|
async def send_typing(self, chat_id: str, metadata: Optional[Dict] = None) -> None:
|
||||||
"""Send typing indicator to a Zulip chat."""
|
"""Send typing indicator to a Zulip chat."""
|
||||||
@@ -815,12 +1006,14 @@ class ZulipAdapter(BasePlatformAdapter):
|
|||||||
return {"name": chat_id, "type": "dm"}
|
return {"name": chat_id, "type": "dm"}
|
||||||
|
|
||||||
async def delete_message(
|
async def delete_message(
|
||||||
self, chat_id: str, message_id: str, metadata: Optional[Dict] = None
|
self, chat_id: str, message_id: str,
|
||||||
) -> bool:
|
metadata: Optional[Dict] = None,
|
||||||
|
**kwargs: Any,
|
||||||
|
) -> SendResult:
|
||||||
"""Delete a message via Zulip API."""
|
"""Delete a message via Zulip API."""
|
||||||
# Zulip doesn't support message deletion via API for bots
|
# Zulip doesn't support message deletion via API for bots
|
||||||
# Send an empty edit instead
|
# Send an empty edit instead
|
||||||
return await self.edit_message(chat_id, message_id, "*deleted*")
|
return await self.edit_message(chat_id, message_id, "*deleted*", **kwargs)
|
||||||
|
|
||||||
# ------------------------------------------------------------------
|
# ------------------------------------------------------------------
|
||||||
# Gen 2: Self-test diagnostics
|
# Gen 2: Self-test diagnostics
|
||||||
@@ -999,6 +1192,10 @@ class ZulipAdapter(BasePlatformAdapter):
|
|||||||
stats["all_bots_user_id"] = self._all_bots_user_id
|
stats["all_bots_user_id"] = self._all_bots_user_id
|
||||||
stats["connected"] = self._connected
|
stats["connected"] = self._connected
|
||||||
stats["checked_at"] = now.isoformat()
|
stats["checked_at"] = now.isoformat()
|
||||||
|
stats["total_polls"] = self._total_poll_count
|
||||||
|
stats["consecutive_empty_polls"] = self._consecutive_empty_polls
|
||||||
|
stats["client_pool_resets"] = self._client_pool_reset_count
|
||||||
|
stats["silence_seconds"] = round(time.time() - self._last_event_received_time)
|
||||||
|
|
||||||
# Compute error rate
|
# Compute error rate
|
||||||
total_polls = stats.get("poll_count", 0) or 1
|
total_polls = stats.get("poll_count", 0) or 1
|
||||||
@@ -1050,10 +1247,12 @@ class ZulipAdapter(BasePlatformAdapter):
|
|||||||
return None, 0
|
return None, 0
|
||||||
|
|
||||||
if response.status_code >= 400:
|
if response.status_code >= 400:
|
||||||
|
# Gen 4: Truncate error bodies to prevent HTML spam
|
||||||
|
body = response.text[:MAX_ERROR_LOG_LEN].replace("\n", " ")
|
||||||
logger.warning(
|
logger.warning(
|
||||||
"[%s] API %s %s: %d %s",
|
"[%s] API %s %s: %d %s",
|
||||||
self.name, method, path,
|
self.name, method, path,
|
||||||
response.status_code, response.text[:200],
|
response.status_code, body,
|
||||||
)
|
)
|
||||||
return None, response.status_code
|
return None, response.status_code
|
||||||
|
|
||||||
|
|||||||
Reference in New Issue
Block a user