可以接入飞书
This commit is contained in:
Generated
+3
@@ -1,5 +1,8 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project version="4">
|
||||
<component name="Black">
|
||||
<option name="sdkName" value="uv (VoidBot)" />
|
||||
</component>
|
||||
<component name="KubernetesApiProvider"><![CDATA[{}]]></component>
|
||||
<component name="ProjectRootManager" version="2" project-jdk-name="uv (VoidBot)" project-jdk-type="Python SDK" />
|
||||
</project>
|
||||
@@ -4,7 +4,7 @@ VoidBot is a minimal Python agent runtime designed around three ideas:
|
||||
|
||||
- Borrow the lightweight execution loop and session persistence style from `nanobot`.
|
||||
- Borrow the provider compatibility and gateway/runtime separation from `openclaw`.
|
||||
- Keep the first version small: single session, direct CLI or standalone gateway, OpenAI-compatible model calls, tool loop.
|
||||
- Keep the first version small: direct CLI or standalone gateway, OpenAI-compatible model calls, tool loop.
|
||||
|
||||
## Architecture
|
||||
|
||||
@@ -20,9 +20,12 @@ CLI Agent
|
||||
Gateway Server
|
||||
-> GatewayApplication
|
||||
-> AgentRuntime
|
||||
-> ChannelManager
|
||||
-> Feishu
|
||||
-> QQ
|
||||
```
|
||||
|
||||
See [docs/architecture.md](/home/mcallzbl/File2/Workshop/Projects/VoidBot/docs/architecture.md) for the layer breakdown and message flow.
|
||||
See [docs/architecture.md](docs/architecture.md) for the layer breakdown and message flow.
|
||||
|
||||
## Initial Capabilities
|
||||
|
||||
@@ -30,6 +33,8 @@ See [docs/architecture.md](/home/mcallzbl/File2/Workshop/Projects/VoidBot/docs/a
|
||||
- Call an OpenAI-compatible chat completions endpoint
|
||||
- Execute tools and feed tool results back into the model loop
|
||||
- Run as a direct CLI agent or through a standalone gateway process
|
||||
- Let the standalone gateway listen on HTTP, Feishu, and QQ at the same time
|
||||
- Isolate transcript history by `session_id`, so each chat keeps its own context
|
||||
- Support provider presets for:
|
||||
- `openai_chatgpt`
|
||||
- `zhipu_coding_plan`
|
||||
@@ -49,7 +54,7 @@ See [docs/architecture.md](/home/mcallzbl/File2/Workshop/Projects/VoidBot/docs/a
|
||||
}
|
||||
```
|
||||
|
||||
You can also start from [config.example.json](/home/mcallzbl/File2/Workshop/Projects/VoidBot/config.example.json).
|
||||
You can also start from [config.example.json](config.example.json).
|
||||
|
||||
2. Put your real config in `config.json` in the current directory.
|
||||
|
||||
@@ -71,7 +76,7 @@ uv run voidbot --message "Summarize this repository"
|
||||
uv run voidbot gateway
|
||||
```
|
||||
|
||||
6. Call the agent through the gateway:
|
||||
6. Call the agent through the HTTP gateway:
|
||||
|
||||
```bash
|
||||
uv run voidbot --via gateway --message "Summarize this repository"
|
||||
@@ -98,13 +103,56 @@ uv run voidbot --via auto
|
||||
- `gateway_port`: default gateway bind port
|
||||
- `gateway_url`: optional default gateway URL for CLI client mode
|
||||
- `cli_via`: default CLI behavior, one of `local`, `gateway`, or `auto`
|
||||
- `channels.feishu.enabled`: enable Feishu long-connection listener
|
||||
- `channels.feishu.app_id`: Feishu app ID
|
||||
- `channels.feishu.app_secret`: Feishu app secret
|
||||
- `channels.feishu.group_policy`: `mention` or `open`
|
||||
- `channels.qq.enabled`: enable QQ bot listener
|
||||
- `channels.qq.app_id`: QQ bot app ID
|
||||
- `channels.qq.secret`: QQ bot secret
|
||||
|
||||
## Channel Gateway
|
||||
|
||||
The `voidbot gateway` process can expose the same runtime in three ways at once:
|
||||
|
||||
- HTTP requests on `/v1/agent/run`
|
||||
- Feishu events through `lark-oapi` WebSocket long connection
|
||||
- QQ bot events through `qq-botpy`
|
||||
|
||||
Example channel config:
|
||||
|
||||
```json
|
||||
{
|
||||
"provider": "openai_chatgpt",
|
||||
"api_key": "YOUR_API_KEY",
|
||||
"workspace": ".",
|
||||
"channels": {
|
||||
"feishu": {
|
||||
"enabled": true,
|
||||
"app_id": "cli_xxx",
|
||||
"app_secret": "xxx",
|
||||
"group_policy": "mention"
|
||||
},
|
||||
"qq": {
|
||||
"enabled": true,
|
||||
"app_id": "1024xxxx",
|
||||
"secret": "xxx"
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Platform notes:
|
||||
|
||||
- Feishu: enable bot capability and subscribe to `im.message.receive_v1`.
|
||||
- QQ: enable C2C messages and group `@bot` messages for the app.
|
||||
- Every Feishu or QQ chat is mapped to its own `session_id`, so contexts do not leak across chats.
|
||||
|
||||
## Notes
|
||||
|
||||
- The current runtime is single-session by design.
|
||||
- The model layer is deliberately OpenAI-compatible first, so adding more gateways later is straightforward.
|
||||
- The current built-in tools are `list_dir`, `read_file`, `write_file`, and `run_command`.
|
||||
- Every inbound request gets `session_id`, `run_id`, and `message_id` before entering the runtime.
|
||||
- `voidbot agent --via auto` tries the gateway first, then falls back to local execution.
|
||||
- `voidbot` without a subcommand starts the interactive CLI.
|
||||
- `voidbot gateway` starts the gateway listener.
|
||||
- `voidbot gateway` starts the HTTP listener and any enabled channel listeners.
|
||||
|
||||
+14
-1
@@ -11,5 +11,18 @@
|
||||
"gateway_host": "127.0.0.1",
|
||||
"gateway_port": 8787,
|
||||
"gateway_url": "http://127.0.0.1:8787",
|
||||
"cli_via": "local"
|
||||
"cli_via": "local",
|
||||
"channels": {
|
||||
"feishu": {
|
||||
"enabled": false,
|
||||
"app_id": "YOUR_FEISHU_APP_ID",
|
||||
"app_secret": "YOUR_FEISHU_APP_SECRET",
|
||||
"group_policy": "mention"
|
||||
},
|
||||
"qq": {
|
||||
"enabled": false,
|
||||
"app_id": "YOUR_QQ_APP_ID",
|
||||
"secret": "YOUR_QQ_SECRET"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+17
-1
@@ -16,6 +16,10 @@ Files:
|
||||
- `src/voidbot/gateway/client.py`
|
||||
- `src/voidbot/gateway/messages.py`
|
||||
- `src/voidbot/gateway/server.py`
|
||||
- `src/voidbot/channels/base.py`
|
||||
- `src/voidbot/channels/manager.py`
|
||||
- `src/voidbot/channels/feishu.py`
|
||||
- `src/voidbot/channels/qq.py`
|
||||
|
||||
Responsibilities:
|
||||
|
||||
@@ -24,6 +28,8 @@ Responsibilities:
|
||||
- Generate `session_id`, `run_id`, and `message_id`
|
||||
- Either call the local runtime directly or send the request to a standalone gateway server
|
||||
- Accept HTTP requests and forward them to the same runtime implementation
|
||||
- Accept Feishu and QQ messages and route them through the same runtime
|
||||
- Send the final agent reply back to the originating channel
|
||||
|
||||
### 2. Runtime
|
||||
|
||||
@@ -36,6 +42,7 @@ Files:
|
||||
Responsibilities:
|
||||
|
||||
- Load aligned history from JSONL
|
||||
- Keep a separate transcript file per `session_id`
|
||||
- Build a stable system prompt and a volatile runtime block
|
||||
- Execute the loop:
|
||||
- call model
|
||||
@@ -99,10 +106,19 @@ CLI input
|
||||
-> final JSON response
|
||||
```
|
||||
|
||||
```text
|
||||
Feishu / QQ message
|
||||
-> ChannelManager
|
||||
-> InboundMessageContext(session_id=<channel>:<chat>)
|
||||
-> AgentRuntime.run_turn()
|
||||
-> channel.send_text()
|
||||
```
|
||||
|
||||
## Why This Matches openclaw + nanobot
|
||||
|
||||
- From `nanobot`: the loop is kept simple and centered on normalized `LLMResponse`, tool schemas, and append-only history.
|
||||
- From `openclaw`: gateway context is explicit, direct and gateway modes coexist, provider presets are registry-driven, and compatibility logic is separated from the loop.
|
||||
- From both: channel ingress is outside the core runtime, so CLI, HTTP, Feishu, and QQ all converge on one `AgentRuntime`.
|
||||
|
||||
## Planned Next Extensions
|
||||
|
||||
@@ -110,4 +126,4 @@ CLI input
|
||||
- WebSocket gateway and event streaming in addition to the current HTTP gateway
|
||||
- More providers and provider-specific compat patches
|
||||
- Safer command execution policies and approval hooks
|
||||
- Multiple sessions and session routing
|
||||
- Richer channel payloads such as attachments, cards, and structured replies
|
||||
|
||||
@@ -8,7 +8,9 @@ authors = [
|
||||
{ name = "mcallzbl" }
|
||||
]
|
||||
dependencies = [
|
||||
"lark-oapi>=1.5.3",
|
||||
"prompt-toolkit>=3.0.52",
|
||||
"qq-botpy>=1.2.1",
|
||||
"rich>=14.3.3",
|
||||
]
|
||||
|
||||
|
||||
@@ -25,7 +25,10 @@ class AgentRuntime:
|
||||
|
||||
def run_turn(self, inbound: InboundMessageContext) -> RunTurnResult:
|
||||
"""Run one user turn through the tool loop."""
|
||||
history = self.session.load_history(limit=self.config.history_limit)
|
||||
history = self.session.load_history(
|
||||
limit=self.config.history_limit,
|
||||
session_id=inbound.session_id,
|
||||
)
|
||||
tool_summaries = self.tools.summaries()
|
||||
messages = self.context_builder.build_messages(history, inbound, tool_summaries)
|
||||
|
||||
@@ -37,7 +40,8 @@ class AgentRuntime:
|
||||
"message_id": inbound.message_id,
|
||||
"raw_body": inbound.raw_body,
|
||||
"session_id": inbound.session_id,
|
||||
}
|
||||
},
|
||||
session_id=inbound.session_id,
|
||||
)
|
||||
|
||||
tool_events: list[dict] = []
|
||||
@@ -57,7 +61,7 @@ class AgentRuntime:
|
||||
tool_call.as_openai_payload() for tool_call in response.tool_calls
|
||||
]
|
||||
messages.append(assistant_message)
|
||||
self.session.append(assistant_message)
|
||||
self.session.append(assistant_message, session_id=inbound.session_id)
|
||||
|
||||
if not response.has_tool_calls:
|
||||
final_reply = response.content or final_reply
|
||||
@@ -84,7 +88,7 @@ class AgentRuntime:
|
||||
),
|
||||
}
|
||||
messages.append(tool_message)
|
||||
self.session.append(tool_message)
|
||||
self.session.append(tool_message, session_id=inbound.session_id)
|
||||
else:
|
||||
final_reply = (
|
||||
f"Stopped after reaching max_iterations={self.config.max_iterations}."
|
||||
|
||||
@@ -0,0 +1,6 @@
|
||||
"""Gateway channel integrations."""
|
||||
|
||||
from voidbot.channels.base import BaseChannel, InboundChannelMessage
|
||||
from voidbot.channels.manager import ChannelManager
|
||||
|
||||
__all__ = ["BaseChannel", "ChannelManager", "InboundChannelMessage"]
|
||||
@@ -0,0 +1,80 @@
|
||||
"""Base gateway channel abstractions."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from abc import ABC, abstractmethod
|
||||
from dataclasses import dataclass, field
|
||||
from datetime import datetime, timezone
|
||||
from typing import Any, Awaitable, Callable
|
||||
import uuid
|
||||
|
||||
|
||||
def _new_id() -> str:
|
||||
return uuid.uuid4().hex
|
||||
|
||||
|
||||
def _now_utc() -> str:
|
||||
return datetime.now(timezone.utc).isoformat()
|
||||
|
||||
|
||||
@dataclass(slots=True)
|
||||
class InboundChannelMessage:
|
||||
"""Normalized channel event."""
|
||||
|
||||
channel: str
|
||||
chat_id: str
|
||||
sender_id: str
|
||||
body: str
|
||||
reply_target: str
|
||||
reply_target_type: str
|
||||
raw_body: str | None = None
|
||||
run_id: str = field(default_factory=_new_id)
|
||||
message_id: str = field(default_factory=_new_id)
|
||||
received_at: str = field(default_factory=_now_utc)
|
||||
metadata: dict[str, Any] = field(default_factory=dict)
|
||||
|
||||
@property
|
||||
def session_id(self) -> str:
|
||||
return f"{self.channel}:{self.chat_id}"
|
||||
|
||||
|
||||
InboundHandler = Callable[[InboundChannelMessage], Awaitable[None]]
|
||||
|
||||
|
||||
class BaseChannel(ABC):
|
||||
"""Abstract chat channel used by the standalone gateway."""
|
||||
|
||||
name: str = "base"
|
||||
|
||||
def __init__(self, config: Any, inbound_handler: InboundHandler) -> None:
|
||||
self.config = config
|
||||
self._inbound_handler = inbound_handler
|
||||
self._running = False
|
||||
|
||||
@abstractmethod
|
||||
async def start(self) -> None:
|
||||
"""Start listening for inbound messages."""
|
||||
|
||||
@abstractmethod
|
||||
async def stop(self) -> None:
|
||||
"""Stop the channel."""
|
||||
|
||||
@abstractmethod
|
||||
async def send_text(
|
||||
self,
|
||||
reply_target: str,
|
||||
content: str,
|
||||
*,
|
||||
reply_target_type: str,
|
||||
metadata: dict[str, Any] | None = None,
|
||||
) -> None:
|
||||
"""Send plain text back to the channel."""
|
||||
|
||||
async def emit(self, message: InboundChannelMessage) -> None:
|
||||
"""Forward an inbound channel message to the gateway runtime."""
|
||||
await self._inbound_handler(message)
|
||||
|
||||
@property
|
||||
def is_running(self) -> bool:
|
||||
"""Return whether the channel is active."""
|
||||
return self._running
|
||||
@@ -0,0 +1,252 @@
|
||||
"""Feishu gateway channel based on lark-oapi long connections."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
from collections import OrderedDict
|
||||
import json
|
||||
import logging
|
||||
import threading
|
||||
from typing import Any
|
||||
|
||||
from voidbot.channels.base import BaseChannel, InboundChannelMessage
|
||||
from voidbot.config import FeishuChannelConfig
|
||||
|
||||
LOGGER = logging.getLogger(__name__)
|
||||
|
||||
try:
|
||||
import lark_oapi as lark
|
||||
except ImportError: # pragma: no cover
|
||||
lark = None
|
||||
|
||||
|
||||
def _extract_post_text(content_json: dict[str, Any]) -> str:
|
||||
root = (
|
||||
content_json.get("post")
|
||||
if isinstance(content_json.get("post"), dict)
|
||||
else content_json
|
||||
)
|
||||
if not isinstance(root, dict):
|
||||
return ""
|
||||
|
||||
blocks: list[dict[str, Any]] = []
|
||||
if "content" in root:
|
||||
blocks.append(root)
|
||||
for locale in ("zh_cn", "en_us", "ja_jp"):
|
||||
if isinstance(root.get(locale), dict):
|
||||
blocks.append(root[locale])
|
||||
|
||||
for block in blocks:
|
||||
parts: list[str] = []
|
||||
title = block.get("title")
|
||||
if title:
|
||||
parts.append(str(title))
|
||||
for row in block.get("content", []):
|
||||
if not isinstance(row, list):
|
||||
continue
|
||||
for element in row:
|
||||
if not isinstance(element, dict):
|
||||
continue
|
||||
if element.get("tag") in {"text", "a"} and element.get("text"):
|
||||
parts.append(str(element["text"]))
|
||||
if element.get("tag") == "at" and element.get("user_name"):
|
||||
parts.append(f"@{element['user_name']}")
|
||||
text = " ".join(part for part in parts if part).strip()
|
||||
if text:
|
||||
return text
|
||||
return ""
|
||||
|
||||
|
||||
class FeishuChannel(BaseChannel):
|
||||
"""Feishu text channel for the gateway runtime."""
|
||||
|
||||
name = "feishu"
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
config: FeishuChannelConfig,
|
||||
inbound_handler,
|
||||
) -> None:
|
||||
super().__init__(config, inbound_handler)
|
||||
self.config = config
|
||||
self._client: Any = None
|
||||
self._ws_client: Any = None
|
||||
self._loop: asyncio.AbstractEventLoop | None = None
|
||||
self._ws_thread: threading.Thread | None = None
|
||||
self._processed_ids: OrderedDict[str, None] = OrderedDict()
|
||||
|
||||
async def start(self) -> None:
|
||||
"""Connect to Feishu and listen indefinitely."""
|
||||
if lark is None:
|
||||
raise RuntimeError("Feishu support requires the `lark-oapi` package.")
|
||||
if not self.config.app_id or not self.config.app_secret:
|
||||
raise ValueError("Feishu channel requires app_id and app_secret.")
|
||||
|
||||
self._running = True
|
||||
self._loop = asyncio.get_running_loop()
|
||||
self._client = (
|
||||
lark.Client.builder()
|
||||
.app_id(self.config.app_id)
|
||||
.app_secret(self.config.app_secret)
|
||||
.log_level(lark.LogLevel.INFO)
|
||||
.build()
|
||||
)
|
||||
event_handler = (
|
||||
lark.EventDispatcherHandler.builder(
|
||||
self.config.encrypt_key or "",
|
||||
self.config.verification_token or "",
|
||||
)
|
||||
.register_p2_im_message_receive_v1(self._on_message_sync)
|
||||
.build()
|
||||
)
|
||||
self._ws_client = lark.ws.Client(
|
||||
self.config.app_id,
|
||||
self.config.app_secret,
|
||||
event_handler=event_handler,
|
||||
log_level=lark.LogLevel.INFO,
|
||||
)
|
||||
self._ws_thread = threading.Thread(target=self._run_ws_client, daemon=True)
|
||||
self._ws_thread.start()
|
||||
|
||||
while self._running:
|
||||
await asyncio.sleep(1)
|
||||
|
||||
def _run_ws_client(self) -> None:
|
||||
import lark_oapi.ws.client as lark_ws_client
|
||||
|
||||
ws_loop = asyncio.new_event_loop()
|
||||
asyncio.set_event_loop(ws_loop)
|
||||
lark_ws_client.loop = ws_loop
|
||||
try:
|
||||
while self._running:
|
||||
try:
|
||||
self._ws_client.start()
|
||||
except Exception: # pragma: no cover
|
||||
LOGGER.exception("Feishu websocket client failed")
|
||||
if self._running:
|
||||
ws_loop.run_until_complete(asyncio.sleep(5))
|
||||
finally:
|
||||
ws_loop.close()
|
||||
|
||||
async def stop(self) -> None:
|
||||
"""Stop the Feishu listener."""
|
||||
self._running = False
|
||||
if self._ws_thread:
|
||||
self._ws_thread.join(timeout=3)
|
||||
self._ws_thread = None
|
||||
|
||||
def _on_message_sync(self, data: Any) -> None:
|
||||
if self._loop and self._loop.is_running():
|
||||
asyncio.run_coroutine_threadsafe(self._on_message(data), self._loop)
|
||||
|
||||
async def _on_message(self, data: Any) -> None:
|
||||
event = data.event
|
||||
message = event.message
|
||||
sender = event.sender
|
||||
|
||||
if getattr(sender, "sender_type", None) == "bot":
|
||||
return
|
||||
|
||||
message_id = str(message.message_id)
|
||||
if message_id in self._processed_ids:
|
||||
return
|
||||
self._processed_ids[message_id] = None
|
||||
if len(self._processed_ids) > 1000:
|
||||
self._processed_ids.popitem(last=False)
|
||||
|
||||
sender_id = (
|
||||
getattr(getattr(sender, "sender_id", None), "open_id", None) or "unknown"
|
||||
)
|
||||
chat_id = str(message.chat_id)
|
||||
chat_type = str(message.chat_type)
|
||||
msg_type = str(message.message_type)
|
||||
if chat_type == "group" and self.config.group_policy == "mention":
|
||||
if not self._is_bot_mentioned(message):
|
||||
return
|
||||
|
||||
content = self._extract_content(msg_type, message.content)
|
||||
if not content:
|
||||
return
|
||||
|
||||
reply_target = chat_id if chat_type == "group" else sender_id
|
||||
reply_target_type = "chat_id" if chat_type == "group" else "open_id"
|
||||
await self.emit(
|
||||
InboundChannelMessage(
|
||||
channel=self.name,
|
||||
chat_id=chat_id,
|
||||
sender_id=sender_id,
|
||||
body=content,
|
||||
raw_body=message.content,
|
||||
message_id=message_id,
|
||||
reply_target=reply_target,
|
||||
reply_target_type=reply_target_type,
|
||||
metadata={"chat_type": chat_type, "message_type": msg_type},
|
||||
)
|
||||
)
|
||||
|
||||
def _is_bot_mentioned(self, message: Any) -> bool:
|
||||
raw_content = message.content or ""
|
||||
if "@_all" in raw_content:
|
||||
return True
|
||||
for mention in getattr(message, "mentions", None) or []:
|
||||
mention_id = getattr(mention, "id", None)
|
||||
if mention_id and getattr(mention_id, "open_id", None):
|
||||
return True
|
||||
return False
|
||||
|
||||
def _extract_content(self, msg_type: str, raw_content: str | None) -> str:
|
||||
try:
|
||||
content_json = json.loads(raw_content) if raw_content else {}
|
||||
except json.JSONDecodeError:
|
||||
return (raw_content or "").strip()
|
||||
|
||||
if msg_type == "text":
|
||||
return str(content_json.get("text") or "").strip()
|
||||
if msg_type == "post":
|
||||
return _extract_post_text(content_json)
|
||||
return ""
|
||||
|
||||
async def send_text(
|
||||
self,
|
||||
reply_target: str,
|
||||
content: str,
|
||||
*,
|
||||
reply_target_type: str,
|
||||
metadata: dict[str, Any] | None = None,
|
||||
) -> None:
|
||||
payload = json.dumps({"text": content}, ensure_ascii=False)
|
||||
await asyncio.to_thread(
|
||||
self._send_text_sync,
|
||||
reply_target_type,
|
||||
reply_target,
|
||||
payload,
|
||||
)
|
||||
|
||||
def _send_text_sync(
|
||||
self,
|
||||
reply_target_type: str,
|
||||
reply_target: str,
|
||||
payload: str,
|
||||
) -> None:
|
||||
if self._client is None:
|
||||
raise RuntimeError("Feishu client is not initialized.")
|
||||
|
||||
from lark_oapi.api.im.v1 import CreateMessageRequest, CreateMessageRequestBody
|
||||
|
||||
request = (
|
||||
CreateMessageRequest.builder()
|
||||
.receive_id_type(reply_target_type)
|
||||
.request_body(
|
||||
CreateMessageRequestBody.builder()
|
||||
.receive_id(reply_target)
|
||||
.msg_type("text")
|
||||
.content(payload)
|
||||
.build()
|
||||
)
|
||||
.build()
|
||||
)
|
||||
response = self._client.im.v1.message.create(request)
|
||||
if not response.success():
|
||||
raise RuntimeError(
|
||||
f"Feishu send failed: code={response.code}, msg={response.msg}"
|
||||
)
|
||||
@@ -0,0 +1,154 @@
|
||||
"""Channel manager that bridges chat platforms into the agent runtime."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import logging
|
||||
import threading
|
||||
from typing import Any
|
||||
|
||||
from voidbot.agent import AgentRuntime
|
||||
from voidbot.channels.base import BaseChannel, InboundChannelMessage
|
||||
from voidbot.config import ChannelsConfig
|
||||
from voidbot.gateway.messages import InboundMessageContext
|
||||
|
||||
LOGGER = logging.getLogger(__name__)
|
||||
|
||||
|
||||
class ChannelManager:
|
||||
"""Run enabled channels and route replies through the agent runtime."""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
runtime: AgentRuntime,
|
||||
channels_config: ChannelsConfig,
|
||||
*,
|
||||
channel_factories: dict[str, type[BaseChannel]] | None = None,
|
||||
) -> None:
|
||||
self.runtime = runtime
|
||||
self.channels_config = channels_config
|
||||
self.channel_factories = channel_factories or self._default_channel_factories()
|
||||
self.channels: dict[str, BaseChannel] = {}
|
||||
self._loop: asyncio.AbstractEventLoop | None = None
|
||||
self._thread: threading.Thread | None = None
|
||||
self._started = threading.Event()
|
||||
self._channel_tasks: list[asyncio.Task[Any]] = []
|
||||
self._build_channels()
|
||||
|
||||
def _default_channel_factories(self) -> dict[str, type[BaseChannel]]:
|
||||
from voidbot.channels.feishu import FeishuChannel
|
||||
from voidbot.channels.qq import QQChannel
|
||||
|
||||
return {
|
||||
"feishu": FeishuChannel,
|
||||
"qq": QQChannel,
|
||||
}
|
||||
|
||||
def _build_channels(self) -> None:
|
||||
specs = {
|
||||
"feishu": self.channels_config.feishu,
|
||||
"qq": self.channels_config.qq,
|
||||
}
|
||||
for name, config in specs.items():
|
||||
if not getattr(config, "enabled", False):
|
||||
continue
|
||||
factory = self.channel_factories.get(name)
|
||||
if factory is None:
|
||||
LOGGER.warning("Skipping unknown channel factory: %s", name)
|
||||
continue
|
||||
self.channels[name] = factory(config, self.handle_inbound)
|
||||
|
||||
async def handle_inbound(self, message: InboundChannelMessage) -> None:
|
||||
"""Run one inbound channel message through the agent and reply."""
|
||||
channel = self.channels.get(message.channel)
|
||||
if channel is None:
|
||||
LOGGER.warning("Received message for unknown channel: %s", message.channel)
|
||||
return
|
||||
|
||||
inbound = InboundMessageContext(
|
||||
session_id=message.session_id,
|
||||
raw_body=message.raw_body or message.body,
|
||||
body_for_agent=message.body.strip(),
|
||||
run_id=message.run_id,
|
||||
message_id=message.message_id,
|
||||
received_at=message.received_at,
|
||||
)
|
||||
result = await asyncio.to_thread(self.runtime.run_turn, inbound)
|
||||
reply = result.reply.strip()
|
||||
if not reply:
|
||||
return
|
||||
|
||||
await channel.send_text(
|
||||
message.reply_target,
|
||||
reply,
|
||||
reply_target_type=message.reply_target_type,
|
||||
metadata={
|
||||
"message_id": message.message_id,
|
||||
"iterations": result.iterations,
|
||||
"tool_events": result.tool_events,
|
||||
**message.metadata,
|
||||
},
|
||||
)
|
||||
|
||||
def start_background(self) -> None:
|
||||
"""Start channel listeners on a dedicated asyncio loop thread."""
|
||||
if not self.channels:
|
||||
return
|
||||
if self._thread and self._thread.is_alive():
|
||||
return
|
||||
|
||||
self._started.clear()
|
||||
self._thread = threading.Thread(target=self._run_loop, daemon=True)
|
||||
self._thread.start()
|
||||
self._started.wait(timeout=5)
|
||||
|
||||
def _run_loop(self) -> None:
|
||||
loop = asyncio.new_event_loop()
|
||||
self._loop = loop
|
||||
asyncio.set_event_loop(loop)
|
||||
self._channel_tasks = [
|
||||
loop.create_task(channel.start(), name=f"channel:{name}")
|
||||
for name, channel in self.channels.items()
|
||||
]
|
||||
self._started.set()
|
||||
try:
|
||||
loop.run_forever()
|
||||
finally:
|
||||
pending = [task for task in asyncio.all_tasks(loop) if not task.done()]
|
||||
for task in pending:
|
||||
task.cancel()
|
||||
if pending:
|
||||
loop.run_until_complete(
|
||||
asyncio.gather(*pending, return_exceptions=True)
|
||||
)
|
||||
loop.close()
|
||||
self._loop = None
|
||||
|
||||
async def _stop_async(self) -> None:
|
||||
for channel in self.channels.values():
|
||||
try:
|
||||
await channel.stop()
|
||||
except Exception: # pragma: no cover
|
||||
LOGGER.exception("Failed to stop channel %s", channel.name)
|
||||
if self._channel_tasks:
|
||||
await asyncio.gather(*self._channel_tasks, return_exceptions=True)
|
||||
loop = asyncio.get_running_loop()
|
||||
loop.stop()
|
||||
|
||||
def stop_background(self) -> None:
|
||||
"""Stop all channel listeners."""
|
||||
if not self._loop:
|
||||
return
|
||||
future = asyncio.run_coroutine_threadsafe(self._stop_async(), self._loop)
|
||||
future.result(timeout=10)
|
||||
if self._thread:
|
||||
self._thread.join(timeout=10)
|
||||
self._thread = None
|
||||
self._started.clear()
|
||||
|
||||
def get_status(self) -> dict[str, Any]:
|
||||
"""Expose channel status for health checks."""
|
||||
return {
|
||||
name: {"enabled": True, "running": channel.is_running}
|
||||
for name, channel in self.channels.items()
|
||||
}
|
||||
@@ -0,0 +1,152 @@
|
||||
"""QQ gateway channel based on qq-botpy."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
from collections import deque
|
||||
import logging
|
||||
from typing import Any
|
||||
|
||||
from voidbot.channels.base import BaseChannel, InboundChannelMessage
|
||||
from voidbot.config import QQChannelConfig
|
||||
|
||||
LOGGER = logging.getLogger(__name__)
|
||||
|
||||
try:
|
||||
import botpy
|
||||
except ImportError: # pragma: no cover
|
||||
botpy = None
|
||||
|
||||
|
||||
def _make_bot_class(channel: "QQChannel") -> "type[botpy.Client]":
|
||||
intents = botpy.Intents(public_messages=True, direct_message=True)
|
||||
|
||||
class _Bot(botpy.Client):
|
||||
def __init__(self) -> None:
|
||||
super().__init__(intents=intents, ext_handlers=False)
|
||||
|
||||
async def on_ready(self) -> None:
|
||||
LOGGER.info("QQ bot ready")
|
||||
|
||||
async def on_c2c_message_create(self, message: Any) -> None:
|
||||
await channel._on_message(message, is_group=False)
|
||||
|
||||
async def on_group_at_message_create(self, message: Any) -> None:
|
||||
await channel._on_message(message, is_group=True)
|
||||
|
||||
async def on_direct_message_create(self, message: Any) -> None:
|
||||
await channel._on_message(message, is_group=False)
|
||||
|
||||
return _Bot
|
||||
|
||||
|
||||
class QQChannel(BaseChannel):
|
||||
"""QQ text channel for the gateway runtime."""
|
||||
|
||||
name = "qq"
|
||||
|
||||
def __init__(self, config: QQChannelConfig, inbound_handler) -> None:
|
||||
super().__init__(config, inbound_handler)
|
||||
self.config = config
|
||||
self._client: Any = None
|
||||
self._processed_ids: deque[str] = deque(maxlen=1000)
|
||||
self._msg_seq = 1
|
||||
|
||||
async def start(self) -> None:
|
||||
"""Connect to QQ and keep the bot running."""
|
||||
if botpy is None:
|
||||
raise RuntimeError("QQ support requires the `qq-botpy` package.")
|
||||
if not self.config.app_id or not self.config.secret:
|
||||
raise ValueError("QQ channel requires app_id and secret.")
|
||||
|
||||
self._running = True
|
||||
bot_class = _make_bot_class(self)
|
||||
self._client = bot_class()
|
||||
|
||||
while self._running:
|
||||
try:
|
||||
await self._client.start(
|
||||
appid=self.config.app_id,
|
||||
secret=self.config.secret,
|
||||
)
|
||||
except Exception: # pragma: no cover
|
||||
LOGGER.exception("QQ bot client failed")
|
||||
if self._running:
|
||||
await asyncio.sleep(5)
|
||||
|
||||
async def stop(self) -> None:
|
||||
"""Stop the QQ client."""
|
||||
self._running = False
|
||||
if self._client is not None:
|
||||
await self._client.close()
|
||||
|
||||
async def _on_message(self, message: Any, *, is_group: bool) -> None:
|
||||
message_id = str(message.id)
|
||||
if message_id in self._processed_ids:
|
||||
return
|
||||
self._processed_ids.append(message_id)
|
||||
|
||||
content = str(message.content or "").strip()
|
||||
if not content:
|
||||
return
|
||||
|
||||
if is_group:
|
||||
chat_id = str(message.group_openid)
|
||||
sender_id = str(message.author.member_openid)
|
||||
reply_target = chat_id
|
||||
reply_target_type = "group"
|
||||
else:
|
||||
sender_id = str(
|
||||
getattr(message.author, "id", None)
|
||||
or getattr(message.author, "user_openid", None)
|
||||
or "unknown"
|
||||
)
|
||||
chat_id = sender_id
|
||||
reply_target = sender_id
|
||||
reply_target_type = "c2c"
|
||||
|
||||
await self.emit(
|
||||
InboundChannelMessage(
|
||||
channel=self.name,
|
||||
chat_id=chat_id,
|
||||
sender_id=sender_id,
|
||||
body=content,
|
||||
raw_body=message.content,
|
||||
message_id=message_id,
|
||||
reply_target=reply_target,
|
||||
reply_target_type=reply_target_type,
|
||||
metadata={"is_group": is_group},
|
||||
)
|
||||
)
|
||||
|
||||
async def send_text(
|
||||
self,
|
||||
reply_target: str,
|
||||
content: str,
|
||||
*,
|
||||
reply_target_type: str,
|
||||
metadata: dict[str, Any] | None = None,
|
||||
) -> None:
|
||||
if self._client is None:
|
||||
raise RuntimeError("QQ client is not initialized.")
|
||||
|
||||
self._msg_seq += 1
|
||||
kwargs: dict[str, Any] = {
|
||||
"msg_type": 2,
|
||||
"markdown": {"content": content},
|
||||
"msg_seq": self._msg_seq,
|
||||
}
|
||||
message_id = (metadata or {}).get("message_id")
|
||||
if message_id:
|
||||
kwargs["msg_id"] = message_id
|
||||
|
||||
if reply_target_type == "group":
|
||||
await self._client.api.post_group_message(
|
||||
group_openid=reply_target,
|
||||
**kwargs,
|
||||
)
|
||||
return
|
||||
await self._client.api.post_c2c_message(
|
||||
openid=reply_target,
|
||||
**kwargs,
|
||||
)
|
||||
+65
-1
@@ -4,11 +4,73 @@ from __future__ import annotations
|
||||
|
||||
import json
|
||||
import os
|
||||
from dataclasses import dataclass
|
||||
from dataclasses import dataclass, field
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
|
||||
@dataclass(slots=True)
|
||||
class FeishuChannelConfig:
|
||||
"""Feishu channel configuration."""
|
||||
|
||||
enabled: bool = False
|
||||
app_id: str = ""
|
||||
app_secret: str = ""
|
||||
encrypt_key: str | None = None
|
||||
verification_token: str | None = None
|
||||
group_policy: str = "mention"
|
||||
|
||||
@classmethod
|
||||
def from_mapping(cls, data: dict[str, Any] | None) -> "FeishuChannelConfig":
|
||||
payload = data or {}
|
||||
return cls(
|
||||
enabled=bool(payload.get("enabled", False)),
|
||||
app_id=str(payload.get("app_id") or ""),
|
||||
app_secret=str(payload.get("app_secret") or ""),
|
||||
encrypt_key=str(payload["encrypt_key"])
|
||||
if payload.get("encrypt_key")
|
||||
else None,
|
||||
verification_token=str(payload["verification_token"])
|
||||
if payload.get("verification_token")
|
||||
else None,
|
||||
group_policy=str(payload.get("group_policy") or "mention"),
|
||||
)
|
||||
|
||||
|
||||
@dataclass(slots=True)
|
||||
class QQChannelConfig:
|
||||
"""QQ channel configuration."""
|
||||
|
||||
enabled: bool = False
|
||||
app_id: str = ""
|
||||
secret: str = ""
|
||||
|
||||
@classmethod
|
||||
def from_mapping(cls, data: dict[str, Any] | None) -> "QQChannelConfig":
|
||||
payload = data or {}
|
||||
return cls(
|
||||
enabled=bool(payload.get("enabled", False)),
|
||||
app_id=str(payload.get("app_id") or ""),
|
||||
secret=str(payload.get("secret") or ""),
|
||||
)
|
||||
|
||||
|
||||
@dataclass(slots=True)
|
||||
class ChannelsConfig:
|
||||
"""Gateway channel settings."""
|
||||
|
||||
feishu: FeishuChannelConfig = field(default_factory=FeishuChannelConfig)
|
||||
qq: QQChannelConfig = field(default_factory=QQChannelConfig)
|
||||
|
||||
@classmethod
|
||||
def from_mapping(cls, data: dict[str, Any] | None) -> "ChannelsConfig":
|
||||
payload = data or {}
|
||||
return cls(
|
||||
feishu=FeishuChannelConfig.from_mapping(payload.get("feishu")),
|
||||
qq=QQChannelConfig.from_mapping(payload.get("qq")),
|
||||
)
|
||||
|
||||
|
||||
@dataclass(slots=True)
|
||||
class AppConfig:
|
||||
"""Runtime configuration."""
|
||||
@@ -27,6 +89,7 @@ class AppConfig:
|
||||
gateway_port: int = 8787
|
||||
gateway_url: str | None = None
|
||||
cli_via: str = "local"
|
||||
channels: ChannelsConfig = field(default_factory=ChannelsConfig)
|
||||
|
||||
@classmethod
|
||||
def from_mapping(cls, data: dict[str, Any]) -> "AppConfig":
|
||||
@@ -54,6 +117,7 @@ class AppConfig:
|
||||
gateway_port=int(data.get("gateway_port") or 8787),
|
||||
gateway_url=str(data["gateway_url"]) if data.get("gateway_url") else None,
|
||||
cli_via=str(data.get("cli_via") or "local"),
|
||||
channels=ChannelsConfig.from_mapping(data.get("channels")),
|
||||
)
|
||||
|
||||
|
||||
|
||||
@@ -6,6 +6,7 @@ import argparse
|
||||
from pathlib import Path
|
||||
|
||||
from voidbot.app import build_app
|
||||
from voidbot.channels.manager import ChannelManager
|
||||
from voidbot.config import AppConfig, load_config
|
||||
from voidbot.gateway.client import GatewayClient
|
||||
from voidbot.gateway.messages import InboundMessageContext
|
||||
@@ -15,18 +16,26 @@ from voidbot.gateway.ui import render_single_turn, run_terminal_loop
|
||||
|
||||
def build_parser() -> argparse.ArgumentParser:
|
||||
"""Build CLI parser."""
|
||||
parser = argparse.ArgumentParser(prog="voidbot", description="VoidBot CLI and gateway")
|
||||
parser = argparse.ArgumentParser(
|
||||
prog="voidbot", description="VoidBot CLI and gateway"
|
||||
)
|
||||
_add_agent_arguments(parser)
|
||||
subparsers = parser.add_subparsers(dest="command", required=False)
|
||||
|
||||
agent_parser = subparsers.add_parser("agent", help="Run the agent locally or via gateway")
|
||||
agent_parser = subparsers.add_parser(
|
||||
"agent", help="Run the agent locally or via gateway"
|
||||
)
|
||||
_add_agent_arguments(agent_parser)
|
||||
|
||||
chat_parser = subparsers.add_parser("chat", help="Backward-compatible alias of agent")
|
||||
chat_parser = subparsers.add_parser(
|
||||
"chat", help="Backward-compatible alias of agent"
|
||||
)
|
||||
_add_agent_arguments(chat_parser)
|
||||
|
||||
gateway_parser = subparsers.add_parser("gateway", help="Run the gateway server")
|
||||
gateway_parser.add_argument("--config", type=Path, help="Path to a JSON config file")
|
||||
gateway_parser.add_argument(
|
||||
"--config", type=Path, help="Path to a JSON config file"
|
||||
)
|
||||
gateway_parser.add_argument("--host", help="Gateway bind host")
|
||||
gateway_parser.add_argument("--port", type=int, help="Gateway bind port")
|
||||
return parser
|
||||
@@ -63,7 +72,9 @@ def _add_agent_arguments(parser: argparse.ArgumentParser) -> None:
|
||||
default=None,
|
||||
help="Choose how the CLI reaches the agent runtime.",
|
||||
)
|
||||
parser.add_argument("--gateway-url", help="Gateway base URL, e.g. http://127.0.0.1:8787")
|
||||
parser.add_argument(
|
||||
"--gateway-url", help="Gateway base URL, e.g. http://127.0.0.1:8787"
|
||||
)
|
||||
parser.add_argument("--gateway-host", help="Gateway host override")
|
||||
parser.add_argument("--gateway-port", type=int, help="Gateway port override")
|
||||
|
||||
@@ -123,10 +134,14 @@ def run_gateway_command(
|
||||
"""Run the standalone gateway server."""
|
||||
config = load_config(config_path, require_api_key=True)
|
||||
app = build_app(config)
|
||||
channel_manager = ChannelManager(app.runtime, config.channels)
|
||||
bind_host = host or config.gateway_host
|
||||
bind_port = port or config.gateway_port
|
||||
run_gateway_server(
|
||||
application=GatewayApplication(runtime=app.runtime),
|
||||
application=GatewayApplication(
|
||||
runtime=app.runtime,
|
||||
channel_manager=channel_manager,
|
||||
),
|
||||
host=bind_host,
|
||||
port=bind_port,
|
||||
)
|
||||
@@ -226,4 +241,3 @@ def _resolve_gateway_url(
|
||||
if host and port:
|
||||
return f"http://{host}:{port}"
|
||||
return None
|
||||
|
||||
|
||||
@@ -8,6 +8,7 @@ from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
|
||||
from typing import Any
|
||||
|
||||
from voidbot.agent import AgentRuntime
|
||||
from voidbot.channels.manager import ChannelManager
|
||||
from voidbot.gateway.messages import InboundMessageContext
|
||||
|
||||
|
||||
@@ -16,6 +17,7 @@ class GatewayApplication:
|
||||
"""HTTP-facing gateway wrapper around the agent runtime."""
|
||||
|
||||
runtime: AgentRuntime
|
||||
channel_manager: ChannelManager | None = None
|
||||
|
||||
def health(self) -> dict[str, Any]:
|
||||
"""Return gateway health."""
|
||||
@@ -23,6 +25,9 @@ class GatewayApplication:
|
||||
"ok": True,
|
||||
"provider": self.runtime.config.provider,
|
||||
"workspace": str(self.runtime.config.workspace),
|
||||
"channels": self.channel_manager.get_status()
|
||||
if self.channel_manager
|
||||
else {},
|
||||
}
|
||||
|
||||
def run_agent(self, payload: dict[str, Any]) -> dict[str, Any]:
|
||||
@@ -35,8 +40,12 @@ class GatewayApplication:
|
||||
inbound = InboundMessageContext(
|
||||
session_id=str(payload.get("session_id") or "main"),
|
||||
run_id=str(payload["run_id"]) if payload.get("run_id") else None,
|
||||
message_id=str(payload["message_id"]) if payload.get("message_id") else None,
|
||||
received_at=str(payload["received_at"]) if payload.get("received_at") else None,
|
||||
message_id=str(payload["message_id"])
|
||||
if payload.get("message_id")
|
||||
else None,
|
||||
received_at=str(payload["received_at"])
|
||||
if payload.get("received_at")
|
||||
else None,
|
||||
raw_body=raw_body,
|
||||
body_for_agent=body_for_agent,
|
||||
)
|
||||
@@ -52,7 +61,9 @@ class GatewayApplication:
|
||||
}
|
||||
|
||||
|
||||
def create_gateway_handler(application: GatewayApplication) -> type[BaseHTTPRequestHandler]:
|
||||
def create_gateway_handler(
|
||||
application: GatewayApplication,
|
||||
) -> type[BaseHTTPRequestHandler]:
|
||||
"""Create a request handler bound to the given application."""
|
||||
|
||||
class GatewayRequestHandler(BaseHTTPRequestHandler):
|
||||
@@ -109,6 +120,8 @@ def run_gateway_server(
|
||||
port: int,
|
||||
) -> None:
|
||||
"""Run the gateway forever."""
|
||||
if application.channel_manager:
|
||||
application.channel_manager.start_background()
|
||||
server = ThreadingHTTPServer((host, port), create_gateway_handler(application))
|
||||
print(f"VoidBot gateway listening on http://{host}:{port}")
|
||||
try:
|
||||
@@ -117,3 +130,5 @@ def run_gateway_server(
|
||||
pass
|
||||
finally:
|
||||
server.server_close()
|
||||
if application.channel_manager:
|
||||
application.channel_manager.stop_background()
|
||||
|
||||
@@ -83,13 +83,16 @@ class TerminalUI:
|
||||
)
|
||||
details = [
|
||||
f"mode={self.via}",
|
||||
f"provider={self.config.provider}" if self.config else "provider=(gateway-only)",
|
||||
f"provider={self.config.provider}"
|
||||
if self.config
|
||||
else "provider=(gateway-only)",
|
||||
]
|
||||
if self.gateway_url:
|
||||
details.append(f"gateway={self.gateway_url}")
|
||||
self.console.print(
|
||||
Panel.fit(
|
||||
"\n".join(details) + "\nEnter submit, Esc+Enter newline, Ctrl+L clear screen",
|
||||
"\n".join(details)
|
||||
+ "\nEnter submit, Esc+Enter newline, Ctrl+L clear screen",
|
||||
title="[bold #c0caf5]Session[/bold #c0caf5]",
|
||||
border_style="#7aa2f7",
|
||||
padding=(0, 1),
|
||||
@@ -106,7 +109,9 @@ class TerminalUI:
|
||||
"<prompt.border>╰─➤ </prompt.border>"
|
||||
),
|
||||
bottom_toolbar=self._bottom_toolbar,
|
||||
prompt_continuation=lambda width, line_number, is_soft_wrap: " " * (width - 3) + "│ ",
|
||||
prompt_continuation=lambda width, line_number, is_soft_wrap: (
|
||||
" " * (width - 3) + "│ "
|
||||
),
|
||||
)
|
||||
|
||||
def busy(self) -> Status:
|
||||
|
||||
+32
-10
@@ -1,11 +1,13 @@
|
||||
"""Single-session transcript storage."""
|
||||
"""Session transcript storage."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
from dataclasses import dataclass
|
||||
from dataclasses import dataclass, field
|
||||
from datetime import datetime, timezone
|
||||
from pathlib import Path
|
||||
import re
|
||||
import threading
|
||||
from typing import Any
|
||||
|
||||
|
||||
@@ -18,21 +20,31 @@ class SessionStore:
|
||||
"""Append-only JSONL session storage."""
|
||||
|
||||
path: Path
|
||||
_lock: threading.RLock = field(default_factory=threading.RLock)
|
||||
|
||||
def ensure_parent(self) -> None:
|
||||
self.path.parent.mkdir(parents=True, exist_ok=True)
|
||||
def ensure_parent(self, path: Path) -> None:
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
def append(self, message: dict[str, Any]) -> None:
|
||||
self.ensure_parent()
|
||||
def append(self, message: dict[str, Any], *, session_id: str = "main") -> None:
|
||||
path = self.path_for(session_id)
|
||||
self.ensure_parent(path)
|
||||
record = {"timestamp": _utc_now(), **message}
|
||||
with self.path.open("a", encoding="utf-8") as handle:
|
||||
with self._lock:
|
||||
with path.open("a", encoding="utf-8") as handle:
|
||||
handle.write(json.dumps(record, ensure_ascii=False) + "\n")
|
||||
|
||||
def load_history(self, limit: int = 24) -> list[dict[str, Any]]:
|
||||
if not self.path.exists():
|
||||
def load_history(
|
||||
self,
|
||||
limit: int = 24,
|
||||
*,
|
||||
session_id: str = "main",
|
||||
) -> list[dict[str, Any]]:
|
||||
path = self.path_for(session_id)
|
||||
if not path.exists():
|
||||
return []
|
||||
rows: list[dict[str, Any]] = []
|
||||
with self.path.open("r", encoding="utf-8") as handle:
|
||||
with self._lock:
|
||||
with path.open("r", encoding="utf-8") as handle:
|
||||
for line in handle:
|
||||
line = line.strip()
|
||||
if not line:
|
||||
@@ -52,6 +64,16 @@ class SessionStore:
|
||||
messages.append(message)
|
||||
return messages
|
||||
|
||||
def path_for(self, session_id: str = "main") -> Path:
|
||||
"""Resolve the transcript file for a session."""
|
||||
if session_id == "main":
|
||||
return self.path
|
||||
|
||||
suffix = self.path.suffix or ".jsonl"
|
||||
safe_session = re.sub(r"[^a-zA-Z0-9._-]+", "_", session_id).strip("_")
|
||||
safe_session = safe_session or "session"
|
||||
return self.path.parent / f"{self.path.stem}-{safe_session}{suffix}"
|
||||
|
||||
@staticmethod
|
||||
def _to_llm_message(row: dict[str, Any]) -> dict[str, Any] | None:
|
||||
role = row.get("role")
|
||||
|
||||
+40
-3
@@ -18,12 +18,16 @@ class FakeProvider:
|
||||
self.calls = 0
|
||||
self.model_name = "fake-model"
|
||||
|
||||
def chat(self, messages: list[dict], tools: list[dict] | None = None) -> LLMResponse:
|
||||
def chat(
|
||||
self, messages: list[dict], tools: list[dict] | None = None
|
||||
) -> LLMResponse:
|
||||
self.calls += 1
|
||||
if self.calls == 1:
|
||||
return LLMResponse(
|
||||
content="I should inspect the workspace first.",
|
||||
tool_calls=[ToolCall(id="tool-1", name="list_dir", arguments={"path": "."})],
|
||||
tool_calls=[
|
||||
ToolCall(id="tool-1", name="list_dir", arguments={"path": "."})
|
||||
],
|
||||
)
|
||||
return LLMResponse(content="I checked the workspace and finished.")
|
||||
|
||||
@@ -57,10 +61,43 @@ class AgentRuntimeTests(unittest.TestCase):
|
||||
self.assertEqual(result.reply, "I checked the workspace and finished.")
|
||||
self.assertEqual(len(result.tool_events), 1)
|
||||
self.assertEqual(result.tool_events[0]["tool_name"], "list_dir")
|
||||
history = runtime.session.load_history(limit=10)
|
||||
history = runtime.session.load_history(limit=10, session_id="main")
|
||||
self.assertEqual(history[0]["role"], "user")
|
||||
self.assertEqual(history[-1]["role"], "assistant")
|
||||
|
||||
def test_session_history_is_isolated_by_session_id(self) -> None:
|
||||
with tempfile.TemporaryDirectory() as temp_dir:
|
||||
workspace = Path(temp_dir)
|
||||
config = AppConfig(
|
||||
api_key="test-key",
|
||||
workspace=workspace,
|
||||
session_file=workspace / ".voidbot/session.jsonl",
|
||||
)
|
||||
runtime = AgentRuntime(
|
||||
config=config,
|
||||
provider=FakeProvider(),
|
||||
session=SessionStore(config.session_file),
|
||||
tools=build_default_tool_registry(workspace),
|
||||
context_builder=ContextBuilder(config),
|
||||
)
|
||||
|
||||
runtime.session.append(
|
||||
{"role": "user", "content": "from main"}, session_id="main"
|
||||
)
|
||||
runtime.session.append(
|
||||
{"role": "user", "content": "from feishu"},
|
||||
session_id="feishu:oc_demo",
|
||||
)
|
||||
|
||||
main_history = runtime.session.load_history(limit=10, session_id="main")
|
||||
feishu_history = runtime.session.load_history(
|
||||
limit=10,
|
||||
session_id="feishu:oc_demo",
|
||||
)
|
||||
|
||||
self.assertEqual(main_history[0]["content"], "from main")
|
||||
self.assertEqual(feishu_history[0]["content"], "from feishu")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
|
||||
@@ -0,0 +1,98 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import tempfile
|
||||
import unittest
|
||||
from dataclasses import dataclass
|
||||
from pathlib import Path
|
||||
|
||||
from voidbot.channels.base import BaseChannel, InboundChannelMessage
|
||||
from voidbot.channels.manager import ChannelManager
|
||||
from voidbot.config import AppConfig
|
||||
from voidbot.models import RunTurnResult
|
||||
|
||||
|
||||
@dataclass
|
||||
class FakeRuntime:
|
||||
config: AppConfig
|
||||
|
||||
def __post_init__(self) -> None:
|
||||
self.calls: list[str] = []
|
||||
|
||||
def run_turn(self, inbound) -> RunTurnResult:
|
||||
self.calls.append(inbound.session_id)
|
||||
return RunTurnResult(reply=f"echo:{inbound.body_for_agent}", iterations=1)
|
||||
|
||||
|
||||
class FakeChannel(BaseChannel):
|
||||
name = "feishu"
|
||||
|
||||
def __init__(self, config, inbound_handler) -> None:
|
||||
super().__init__(config, inbound_handler)
|
||||
self.sent: list[dict] = []
|
||||
|
||||
async def start(self) -> None:
|
||||
self._running = True
|
||||
while self._running:
|
||||
await asyncio.sleep(0.1)
|
||||
|
||||
async def stop(self) -> None:
|
||||
self._running = False
|
||||
|
||||
async def send_text(
|
||||
self,
|
||||
reply_target: str,
|
||||
content: str,
|
||||
*,
|
||||
reply_target_type: str,
|
||||
metadata: dict | None = None,
|
||||
) -> None:
|
||||
self.sent.append(
|
||||
{
|
||||
"reply_target": reply_target,
|
||||
"reply_target_type": reply_target_type,
|
||||
"content": content,
|
||||
"metadata": metadata or {},
|
||||
}
|
||||
)
|
||||
|
||||
|
||||
class ChannelManagerTests(unittest.TestCase):
|
||||
def test_channel_message_routes_through_runtime_and_back(self) -> None:
|
||||
with tempfile.TemporaryDirectory() as temp_dir:
|
||||
config = AppConfig.from_mapping(
|
||||
{
|
||||
"api_key": "test-key",
|
||||
"workspace": temp_dir,
|
||||
"session_file": str(Path(temp_dir) / ".voidbot/session.jsonl"),
|
||||
"channels": {
|
||||
"feishu": {
|
||||
"enabled": True,
|
||||
"app_id": "app-id",
|
||||
"app_secret": "secret",
|
||||
}
|
||||
},
|
||||
}
|
||||
)
|
||||
runtime = FakeRuntime(config=config)
|
||||
manager = ChannelManager(
|
||||
runtime,
|
||||
config.channels,
|
||||
channel_factories={"feishu": FakeChannel},
|
||||
)
|
||||
message = InboundChannelMessage(
|
||||
channel="feishu",
|
||||
chat_id="oc_demo",
|
||||
sender_id="ou_demo",
|
||||
body="hello",
|
||||
reply_target="oc_demo",
|
||||
reply_target_type="chat_id",
|
||||
message_id="msg-1",
|
||||
)
|
||||
|
||||
asyncio.run(manager.handle_inbound(message))
|
||||
|
||||
self.assertEqual(runtime.calls, ["feishu:oc_demo"])
|
||||
channel = manager.channels["feishu"]
|
||||
self.assertEqual(channel.sent[0]["content"], "echo:hello")
|
||||
self.assertEqual(channel.sent[0]["reply_target"], "oc_demo")
|
||||
@@ -37,6 +37,38 @@ class ConfigLoadingTests(unittest.TestCase):
|
||||
self.assertEqual(config.api_key, "test-key")
|
||||
self.assertEqual(config.model, "glm-4.7")
|
||||
|
||||
def test_loads_nested_channel_settings(self) -> None:
|
||||
with tempfile.TemporaryDirectory() as temp_dir:
|
||||
config_path = Path(temp_dir) / "config.json"
|
||||
config_path.write_text(
|
||||
json.dumps(
|
||||
{
|
||||
"api_key": "test-key",
|
||||
"channels": {
|
||||
"feishu": {
|
||||
"enabled": True,
|
||||
"app_id": "cli_a",
|
||||
"app_secret": "cli_s",
|
||||
"group_policy": "open",
|
||||
},
|
||||
"qq": {
|
||||
"enabled": True,
|
||||
"app_id": "qq_a",
|
||||
"secret": "qq_s",
|
||||
},
|
||||
},
|
||||
}
|
||||
),
|
||||
encoding="utf-8",
|
||||
)
|
||||
config = load_config(config_path)
|
||||
|
||||
self.assertTrue(config.channels.feishu.enabled)
|
||||
self.assertEqual(config.channels.feishu.app_id, "cli_a")
|
||||
self.assertEqual(config.channels.feishu.group_policy, "open")
|
||||
self.assertTrue(config.channels.qq.enabled)
|
||||
self.assertEqual(config.channels.qq.secret, "qq_s")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
|
||||
@@ -72,7 +72,10 @@ class GatewayTests(unittest.TestCase):
|
||||
(),
|
||||
{"runtime": FakeRuntime(config=config)},
|
||||
)()
|
||||
with patch("voidbot.gateway.cli._run_via_gateway", side_effect=RuntimeError("gateway down")):
|
||||
with patch(
|
||||
"voidbot.gateway.cli._run_via_gateway",
|
||||
side_effect=RuntimeError("gateway down"),
|
||||
):
|
||||
with patch("voidbot.gateway.cli.build_app", return_value=fake_app):
|
||||
result = _run_one_turn(
|
||||
message="hello local",
|
||||
|
||||
@@ -8,7 +8,9 @@ from voidbot.providers.registry import get_provider_spec
|
||||
class ProviderRegistryTests(unittest.TestCase):
|
||||
def test_zhipu_coding_plan_preset_exists(self) -> None:
|
||||
spec = get_provider_spec("zhipu_coding_plan")
|
||||
self.assertEqual(spec.default_base_url, "https://open.bigmodel.cn/api/coding/paas/v4")
|
||||
self.assertEqual(
|
||||
spec.default_base_url, "https://open.bigmodel.cn/api/coding/paas/v4"
|
||||
)
|
||||
self.assertEqual(spec.default_model, "glm-4.7")
|
||||
|
||||
|
||||
|
||||
Reference in New Issue
Block a user