Skip to content

JiuwenSwarm is an intelligent AI Agent built on openJiuwen. It extends the powerful capabilities of large language models directly to your fingertips through various communication apps you use daily.

Python

feat: multi session

douran672459942e1c
diff --git a/jiuwenclaw/gateway/agent_ws_server.py b/jiuwenclaw/agentserver/agent_ws_server.py
similarity index 73%
rename from jiuwenclaw/gateway/agent_ws_server.py
rename to jiuwenclaw/agentserver/agent_ws_server.py
index 0dd23f286c..4f52bad6cd 100644
--- a/jiuwenclaw/gateway/agent_ws_server.py
+++ b/jiuwenclaw/agentserver/agent_ws_server.py
@@ -7,7 +7,7 @@ from __future__ import annotations
import asyncio
import json
from dataclasses import asdict
-from typing import Any
+from typing import Any, ClassVar
from jiuwenclaw.utils import logger
from jiuwenclaw.schema.agent import AgentRequest, AgentResponse, AgentResponseChunk
@@ -44,14 +44,18 @@ def _chunk_to_payload(chunk: AgentResponseChunk) -> dict[str, Any]:
class AgentWebSocketServer:
- """Gateway 与 AgentServer 之间的 WebSocket 服务端.
+ """Gateway 与 AgentServer 之间的 WebSocket 服务端(单例).
监听来自 Gateway (WebSocketAgentServerClient) 的连接,按协议约定处理请求:
- 收到 JSON 载荷,字段为 AgentRequest(含 is_stream)
- is_stream=False:调用 IAgentServer.process_message(),返回一条完整 AgentResponse JSON
- is_stream=True:调用 IAgentServer.process_message_stream(),逐条返回 AgentResponseChunk JSON
+
+ 支持 send_push:AgentServer 主动向 Gateway 推送消息(需 Gateway 预注册 agent-push 队列)。
"""
+ _instance: ClassVar[AgentWebSocketServer | None] = None
+
def __init__(
self,
agent,
@@ -67,6 +71,47 @@ class AgentWebSocketServer:
self._ping_interval = ping_interval
self._ping_timeout = ping_timeout
self._server: Any = None
+ # 当前 Gateway 连接,用于 send_push 主动推送
+ self._current_ws: Any = None
+ self._current_send_lock: asyncio.Lock | None = None
+
+ @classmethod
+ def get_instance(
+ cls,
+ *,
+ agent: Any = None,
+ host: str = "127.0.0.1",
+ port: int = 18000,
+ ping_interval: float | None = 30.0,
+ ping_timeout: float | None = 300.0,
+ ) -> "AgentWebSocketServer":
+ """返回单例实例。
+
+ 首次调用时 agent 必填,host/port/ping_* 可选。
+ 后续调用可省略所有参数,返回已存在的实例。
+
+ Raises:
+ RuntimeError: 首次调用未提供 agent。
+ """
+ if cls._instance is not None:
+ return cls._instance
+ if agent is None:
+ raise RuntimeError(
+ "AgentWebSocketServer 未初始化。首次调用需传入 agent=..."
+ )
+ cls._instance = cls(
+ agent=agent,
+ host=host,
+ port=port,
+ ping_interval=ping_interval,
+ ping_timeout=ping_timeout,
+ )
+ return cls._instance
+
+ @classmethod
+ def reset_instance(cls) -> None:
+ """重置单例(仅用于测试)。"""
+ cls._instance = None
@property
def host(self) -> str:
@@ -124,6 +169,10 @@ class AgentWebSocketServer:
remote = ws.remote_address
logger.info("[AgentWebSocketServer] 新连接: %s", remote)
+ send_lock = asyncio.Lock()
+ self._current_ws = ws
+ self._current_send_lock = send_lock
+
# 发送 connection.ack 事件,通知 Gateway 服务端已就绪
try:
ack_frame = {
@@ -136,7 +185,6 @@ class AgentWebSocketServer:
except Exception as e:
logger.warning("[AgentWebSocketServer] 发送 connection.ack 失败: %s", e)
- send_lock = asyncio.Lock()
tasks: set[asyncio.Task] = set()
try:
@@ -149,6 +197,8 @@ class AgentWebSocketServer:
except Exception as e:
logger.exception("[AgentWebSocketServer] 连接处理异常 (%s): %s", remote, e)
finally:
+ self._current_ws = None
+ self._current_send_lock = None
if tasks:
await asyncio.gather(*tasks, return_exceptions=True)
@@ -223,90 +273,27 @@ class AgentWebSocketServer:
chunk_count,
)
+ async def send_push(self, msg) -> None:
+ """AgentServer 主动向 Gateway 推送消息。
-# ---------------------------------------------------------------------------
-# 自验证:Mock IAgentServer + 端对端测试
-# ---------------------------------------------------------------------------
-
-
-class _MockAgentServer:
- """用于自验证的 Mock IAgentServer 实现."""
-
- async def process_message(self, request: AgentRequest) -> AgentResponse:
- params_str = json.dumps(request.params, ensure_ascii=False)
- return AgentResponse(
- request_id=request.request_id,
- channel_id=request.channel_id,
- ok=True,
- payload={"content": f"Echo: {params_str}"},
- metadata=request.metadata,
- )
-
- async def process_message_stream(self, request: AgentRequest):
- params_str = json.dumps(request.params, ensure_ascii=False)
- parts = [f"流式-1({params_str}) ", "流式-2 ", "流式-3(完)"]
- for i, part in enumerate(parts):
- yield AgentResponseChunk(
- request_id=request.request_id,
- channel_id=request.channel_id,
- payload={"content": part},
- is_complete=(i == len(parts) - 1),
+ payload 格式与 AgentResponse.payload 一致,
+ 可含 event_type 等字段供 Gateway 转为 Message 派发到 Channel。
+ """
+ if self._current_ws is None or self._current_send_lock is None:
+ logger.warning(
+ "[AgentWebSocketServer] send_push 失败: 无活跃 Gateway 连接"
)
+ return
+ try:
+ async with self._current_send_lock:
+ await self._current_ws.send(json.dumps(msg, ensure_ascii=False))
+ logger.info(
+ "[AgentWebSocketServer] send_push 已发送: channel_id=%s",
+ msg["channel_id"],
+ )
+ except Exception as e:
+ logger.warning("[AgentWebSocketServer] send_push 失败: %s", e)
-async def _run_verification() -> None:
- """端对端验证:AgentWebSocketServer + WebSocketAgentServerClient."""
- from jiuwenclaw.gateway.agent_client import WebSocketAgentServerClient
-
- agent = _MockAgentServer()
- port = 18765
- server = AgentWebSocketServer(agent, host="127.0.0.1", port=port)
- await server.start()
- logger.info("[验证] AgentWebSocketServer 已启动: ws://127.0.0.1:%s", port)
-
- client = WebSocketAgentServerClient()
- try:
- await client.connect(f"ws://127.0.0.1:{port}")
-
- # 非流式请求
- req1 = AgentRequest(
- request_id="req-1",
- channel_id="ch-1",
- session_id="sess-1",
- params={"message": "你好"},
- )
- resp1 = await client.send_request(req1)
- assert resp1.request_id == "req-1"
- assert resp1.ok is True
- assert "Echo:" in str(resp1.payload)
- logger.info("[验证] 非流式通过: payload=%s", resp1.payload)
-
- # 流式请求
- req2 = AgentRequest(
- request_id="req-2",
- channel_id="ch-1",
- session_id="sess-1",
- params={"message": "测试"},
- )
- chunks = []
- async for chunk in client.send_request_stream(req2):
- chunks.append(chunk)
- assert len(chunks) == 3
- assert chunks[-1].is_complete
- full = "".join(c.payload.get("content", "") for c in chunks if c.payload)
- logger.info("[验证] 流式通过: %s 个 chunk, 内容=%r", len(chunks), full)
-
- finally:
- await client.disconnect()
- await server.stop()
-
- logger.info("[验证] 端对端验证完成")
-
-
-def main() -> None:
- """入口"""
- asyncio.run(_run_verification())
-
-
-if __name__ == "__main__":
- main()
+ def get_agent(self):
+ return getattr(self._agent, "_instance", None)
\ No newline at end of file
diff --git a/jiuwenclaw/agentserver/interface.py b/jiuwenclaw/agentserver/interface.py
index f8264942ca..8e3d43f109 100644
--- a/jiuwenclaw/agentserver/interface.py
+++ b/jiuwenclaw/agentserver/interface.py
@@ -5,6 +5,7 @@
from __future__ import annotations
import asyncio
+import json
import os
from typing import Any, AsyncIterator
@@ -19,6 +20,8 @@ from openjiuwen.core.session.checkpointer import CheckpointerFactory
from openjiuwen.core.session.checkpointer.checkpointer import CheckpointerConfig
from openjiuwen.core.session.checkpointer.persistence import PersistenceCheckpointerProvider
+from jiuwenclaw.agentserver.prompt_builder import build_system_prompt
+from jiuwenclaw.agentserver.tools.multi_session_toolkits import MultiSessionToolkit
from jiuwenclaw.agentserver.prompt_builder import build_system_prompt, build_user_prompt
from jiuwenclaw.gateway.cron import CronController, CronTargetChannel
from jiuwenclaw.utils import (
@@ -132,6 +135,8 @@ class JiuWenClaw:
self._todo_tool_sessions_registered: set[str] = set()
self._sysop_card_id: str | None = None
+ self._session_tool = None
+
@staticmethod
async def set_checkpoint():
try:
@@ -359,7 +364,6 @@ class JiuWenClaw:
)
logger.info("[JiuWenClaw] 初始化完成: agent_name=%s", self._agent_name)
-
def reload_agent_config(self) -> None:
"""从 config.yaml 重新加载配置并 reconfigure 当前实例,使模型/API 等配置生效且不重启进程。"""
if self._instance is None:
@@ -397,12 +401,17 @@ class JiuWenClaw:
logger.info("[JiuWenClaw] 配置已热更新,未重启进程")
async def _register_runtime_tools(
- self, session_id: str | None, mode="plan", channel_id: str | None = None
+ self, session_id: str | None,
+ channel_id: str | None,
+ request_id: str | None,
+ mode="plan"
) -> None:
"""Register per-request tools for current agent execution."""
if self._instance is None:
raise RuntimeError("JiuWenClaw 未初始化,请先调用 create_instance()")
+ self._session_tool = None
+
tool_list = self._instance.ability_manager.list()
for tool in tool_list:
if isinstance(tool, ToolCard):
@@ -410,6 +419,8 @@ class JiuWenClaw:
self._instance.ability_manager.remove(tool.name)
elif tool.name.startswith("cron_"):
self._instance.ability_manager.remove(tool.name)
+ elif tool.name.startswith("session_"):
+ self._instance.ability_manager.remove(tool.name)
# 定时工具:按 channel 注册;优先用 channel_id,否则从 session_id 前缀推断
channel = (channel_id or "").strip() or (
@@ -418,7 +429,6 @@ class JiuWenClaw:
logger.info(f"[JiuwenClaw] update tool and prompt for channel {channel}")
if channel not in ["heartbeat", "cron"]:
cron_controller = CronController.get_instance()
-
if channel == "feishu":
cron_controller.set_target_channel(CronTargetChannel.FEISHU)
elif channel == "wecom":
@@ -435,18 +445,29 @@ class JiuWenClaw:
effective_session_id = session_id or "default"
if mode == "plan":
- # if effective_session_id not in self._todo_tool_sessions_registered:
todo_toolkit = TodoToolkit(session_id=effective_session_id)
for tool in todo_toolkit.get_tools():
Runner.resource_mgr.add_tool(tool)
self._instance.ability_manager.add(tool.card)
self._todo_tool_sessions_registered.add(effective_session_id)
else:
- tool_list = self._instance.ability_manager.list()
- for tool in tool_list:
- if isinstance(tool, ToolCard):
- if tool.name.startswith("todo_"):
- self._instance.ability_manager.remove(tool.name)
+ config_base = get_config()
+ config = config_base.get('react', {}).copy()
+ session_toolkits = MultiSessionToolkit(
+ session_id=effective_session_id,
+ channel_id=channel_id,
+ request_id=request_id,
+ sub_agent_config=self._load_react_config(config)
+ )
+ self._session_tool = session_toolkits
+ for tool in session_toolkits.get_tools():
+ Runner.resource_mgr.add_tool(tool)
+ self._instance.ability_manager.add(tool.card)
+ # tool_list = self._instance.ability_manager.list()
+ # for tool in tool_list:
+ # if isinstance(tool, ToolCard):
+ # if tool.name.startswith("todo_"):
+ # self._instance.ability_manager.remove(tool.name)
if not self._memory_tools_registered:
await init_memory_manager_async(
@@ -863,8 +884,9 @@ class JiuWenClaw:
try:
await self._register_runtime_tools(
request.session_id,
- request.params.get("mode", "plan"),
- channel_id=request.channel_id,
+ request.channel_id,
+ request.request_id,
+ request.params.get("mode", "plan")
)
return await Runner.run_agent(agent=self._instance, inputs=inputs)
except asyncio.CancelledError:
@@ -1009,8 +1031,9 @@ class JiuWenClaw:
try:
await self._register_runtime_tools(
request.session_id,
- request.params.get("mode", "plan"),
- channel_id=request.channel_id,
+ request.channel_id,
+ request.request_id,
+ request.params.get("mode", "plan")
)
async for chunk in Runner.run_agent_streaming(self._instance, inputs):
parsed = self._parse_stream_chunk(chunk)
@@ -1067,13 +1090,21 @@ class JiuWenClaw:
logger.info("[JiuWenClaw] 流式处理被中断: request_id=%s", rid)
raise
- # 终止 chunk
- yield AgentResponseChunk(
- request_id=rid,
- channel_id=cid,
- payload=None,
- is_complete=True,
- )
+ if request.params.get("mode", "plan") == "plan":
+ # 终止 chunk
+ yield AgentResponseChunk(
+ request_id=rid,
+ channel_id=cid,
+ payload=None,
+ is_complete=True,
+ )
+ else:
+ yield AgentResponseChunk(
+ request_id=rid,
+ channel_id=cid,
+ payload=None,
+ is_complete=True and self._session_tool.all_tasks_done(),
+ )
# ------------------------------------------------------------------
# OutputSchema 解析
diff --git a/jiuwenclaw/agentserver/prompt_builder.py b/jiuwenclaw/agentserver/prompt_builder.py
index e842137f4d..88817e0fa1 100644
--- a/jiuwenclaw/agentserver/prompt_builder.py
+++ b/jiuwenclaw/agentserver/prompt_builder.py
@@ -695,7 +695,7 @@ def _response_prompt(language: str) -> str:
```json
{
- "type": "【cron 或 heartbeat】",
+ "type": "【cron 或 heartbeat 或 notify】",
"preferred_response_language": "【en 或 zh】",
"content": "【任务信息】",
"source": "system"
@@ -727,7 +727,7 @@ You receive user messages and system messages; handle each by source and type.
```json
{
- "type": "【cron or heartbeat】",
+ "type": "【cron or heartbeat or notify】",
"preferred_response_language": "【en or zh】",
"content": "【task info】",
"source": "system"
@@ -851,10 +851,10 @@ def build_user_prompt(content: str, files: dict, channel: str, language: str) ->
prompt = "你收到一条消息:\n"
if channel in ["cron", "heartbeat"]:
return prompt + json.dumps({
- "source": channel,
+ "source": "system",
"preferred_response_language": language,
"content": content,
- "type": "cron job"
+ "type": channel
})
return prompt + json.dumps({
"source": channel,
diff --git a/jiuwenclaw/agentserver/tools/multi_session_toolkits.py b/jiuwenclaw/agentserver/tools/multi_session_toolkits.py
new file mode 100644
index 0000000000..deb4404daf
--- /dev/null
+++ b/jiuwenclaw/agentserver/tools/multi_session_toolkits.py
@@ -0,0 +1,410 @@
+# Copyright (c) Huawei Technologies Co., Ltd. 2025. All rights reserved.
+
+"""Session Toolkit
+生命周期:Agent创建新session开始,到所有session协程结束
+在结束后,MultiSessionToolkit所有内容
+
+Agent 可以通过以下工具操控协程
+1. create_new_sessions
+接收一个任务描述的列表,对列表里每一个任务,创建一个agent实例,并通过Runner运行该agent,同时把session信息记录在self.sessions中
+2. cancel_session
+根据session_id取消对应协程
+3. list_all_sessions
+查看所有协程信息
+
+协程管理原则:
+1. 协程创建后,任务信息保存在self.sessions中
+2. 协程取消后,对应信息需要同步在self.sessions中
+3. 某一协程结束后,会调用notify方法,通过MessageHandler将消息发送出去
+"""
+
+from __future__ import annotations
+
+import asyncio
+import json
+import secrets
+import time
+from enum import Enum
+from typing import Dict, List
+
+from openjiuwen.core.runner import Runner
+from openjiuwen.core.single_agent import ReActAgent, ReActAgentConfig, AgentCard
+from pydantic import BaseModel
+
+from openjiuwen.core.foundation.tool import LocalFunction, Tool, ToolCard
+
+from jiuwenclaw.agentserver.agent_ws_server import AgentWebSocketServer
+from jiuwenclaw.agentserver.tools.mcp_toolkits import get_mcp_tools
+from jiuwenclaw.gateway.message_handler import MessageHandler
+from jiuwenclaw.schema import AgentResponseChunk
+from jiuwenclaw.schema.message import EventType, Message
+from jiuwenclaw.utils import logger
+
+
+class Status(str, Enum):
+ RUNNING = "running"
+ COMPLETED = "completed"
+ CANCELLED = "cancelled"
+ ERROR = "error"
+
+
+class SessionTask(BaseModel):
+ session_id: str
+ description: str
+ status: Status
+ result: str = ""
+
+
+class MultiSessionToolkit:
+ """Toolkit for multi-session agent task tracking. Supports parallel sub-agent execution."""
+
+ def __init__(self, session_id: str, channel_id: str, request_id: str, sub_agent_config: ReActAgentConfig) -> None:
+ """Initialize MultiSessionToolkit for a session.
+
+ Args:
+ session_id: Parent session/conversation identifier.
+ channel_id: Channel ID for routing notify messages back to parent.
+ """
+ self.session_id = session_id
+ self.channel_id = channel_id
+ self.request_id = request_id
+ self.sessions: List[SessionTask] = []
+ self._tasks: Dict[str, asyncio.Task] = {}
+ self._sub_agent_config: ReActAgentConfig = sub_agent_config
+ logger.info(
+ "[MultiSessionToolkit] 初始化 parent_session_id=%s channel_id=%s request_id=%s",
+ session_id,
+ channel_id,
+ request_id,
+ )
+
+ async def get_sub_agent(self) -> ReActAgent:
+ """Create and return a sub-agent instance. Override in subclass."""
+ logger.debug("[MultiSessionToolkit] get_sub_agent 创建子 agent")
+ agent_card = AgentCard(
+ name="spawn_sub_agent"
+ )
+ agent = ReActAgent(agent_card)
+ agent.configure(self._sub_agent_config)
+ mcp_tools = get_mcp_tools()
+ for mcp_tool in mcp_tools:
+ Runner.resource_mgr.add_tool(mcp_tool)
+ agent.ability_manager.add(mcp_tool.card)
+ logger.debug("[MultiSessionToolkit] get_sub_agent 完成 mcp_tools_count=%d", len(mcp_tools))
+ return agent
+
+ async def _run_and_notify(
+ self,
+ session_id: str,
+ description: str,
+ agent: ReActAgent,
+ inputs: dict,
+ ) -> None:
+ """Run agent and call notify on completion (success/cancel/error)."""
+ logger.debug(
+ "[MultiSessionToolkit] _run_and_notify 开始 session_id=%s description=%s",
+ session_id,
+ description[:80] + "..." if len(description) > 80 else description,
+ )
+ task = SessionTask(
+ session_id=session_id,
+ description=description,
+ status=Status.RUNNING,
+ result="",
+ )
+ self.sessions.append(task)
+
+ try:
+ result = await Runner.run_agent(agent, inputs)
+ result_str = result.get("output", "") if isinstance(result, dict) else str(result)
+ logger.info(
+ "[MultiSessionToolkit] 协程完成 session_id=%s status=completed result_len=%d",
+ session_id,
+ len(result_str),
+ )
+ self._update_session(session_id, Status.COMPLETED, result_str)
+ await self.notify(session_id, Status.COMPLETED, result=result_str)
+ except asyncio.CancelledError:
+ logger.info("[MultiSessionToolkit] 协程已取消 session_id=%s", session_id)
+ self._update_session(session_id, Status.CANCELLED, "任务已取消")
+ await self.notify(session_id, Status.CANCELLED)
+ raise
+ except Exception as e:
+ err_str = str(e)
+ logger.exception(
+ "[MultiSessionToolkit] 协程异常 session_id=%s error=%s",
+ session_id,
+ err_str,
+ )
+ self._update_session(session_id, Status.ERROR, err_str)
+ await self.notify(session_id, Status.ERROR, error=err_str)
+ raise
+ finally:
+ self._tasks.pop(session_id, None)
+ logger.debug(
+ "[MultiSessionToolkit] _run_and_notify 结束 session_id=%s 剩余协程数=%d",
+ session_id, len(self._tasks)
+ )
+
+ def _update_session(self, session_id: str, status: Status, result: str = "") -> None:
+ """Update session task status in self.sessions."""
+ for st in self.sessions:
+ if st.session_id == session_id:
+ st.status = status
+ st.result = result
+ logger.debug(
+ "[MultiSessionToolkit] _update_session session_id=%s status=%s",
+ session_id,
+ status.value,
+ )
+ break
+
+ async def notify(
+ self,
+ session_id: str,
+ status: Status,
+ result: str = "",
+ error: str = "",
+ ) -> None:
+ """Send subtask update to MessageHandler. Called on completion (success/cancel/error)."""
+ try:
+ mh = MessageHandler.get_instance()
+ except RuntimeError as e:
+ logger.warning(
+ "[MultiSessionToolkit] MessageHandler 未初始化,跳过 notify: session_id=%s %s",
+ session_id,
+ e,
+ )
+ return
+
+ st = next((s for s in self.sessions if s.session_id == session_id), None)
+ description = st.description if st else ""
+ index = next((i for i, s in enumerate(self.sessions) if s.session_id == session_id), 0)
+ total = len(self.sessions)
+
+ # 前端 SubtaskStatus: 'completed' | 'error',cancelled 映射为 error
+ if status == Status.COMPLETED:
+ payload_status = "completed"
+ message = result or ""
+ else:
+ payload_status = "error"
+ message = error or "任务已取消" if status == Status.CANCELLED else error
+ payload = {
+ "event_type": "chat.session_result",
+ "session_id": session_id,
+ "description": description,
+ "status": payload_status,
+ "index": index + 1,
+ "total": total,
+ "result": message,
+ "is_parallel": True,
+ }
+ msg = {
+ "request_id": self.request_id,
+ "channel_id": self.channel_id,
+ "payload": payload,
+ "is_complete": False,
+ }
+ logger.debug(
+ "[MultiSessionToolkit] notify 发送 subtask_update session_id=%s status=%s index=%d/%d",
+ session_id,
+ payload_status,
+ index + 1,
+ total,
+ )
+ server = AgentWebSocketServer.get_instance()
+ await server.send_push(msg)
+
+ if self.all_tasks_done():
+ session_result_summary = "后台会话任务均已完成:\n"
+ for st in self.sessions:
+ session_result_summary += (f"\nsession_id: {st.session_id}\n"
+ f"description: {st.description}\nresult: {st.result}\n")
+ inputs = {
+ "conversation_id": self.session_id,
+ "query": json.dumps({
+ "source": "system",
+ "content": session_result_summary,
+ "type": "notify"
+ }),
+ }
+ # 使用 run_agent_streaming 而非 run_agent,以确保 session.post_run() 被调用,
+ # 从而将对话历史持久化到 checkpoint。run_agent 不会创建 Session 或调用 post_run,
+ # 导致 notify 中的 agent 对话未保存。
+ accumulated: list[str] = []
+ final_output: str | None = None
+ async for chunk in Runner.run_agent_streaming(
+ server.get_agent(),
+ inputs=inputs,
+ ):
+ if not hasattr(chunk, "type") or not hasattr(chunk, "payload"):
+ continue
+ payload = chunk.payload if isinstance(chunk.payload, dict) else {}
+ if chunk.type == "content_chunk":
+ c = payload.get("content", "")
+ if c:
+ accumulated.append(str(c))
+ elif chunk.type == "answer":
+ out = payload.get("output")
+ if isinstance(out, dict):
+ temp = out.get("output", str(out)) or "".join(accumulated)
+ if temp != "":
+ final_output = temp
+ elif out is not None:
+ final_output = str(out)
+ else:
+ final_output = "".join(accumulated) if accumulated else ""
+ result = {
+ "output": final_output if final_output is not None else "".join(accumulated),
+ "result_type": "answer",
+ }
+ payload = {
+ "event_type": "chat.final",
+ "task_id": self.session_id,
+ "content": result,
+ }
+ msg = {
+ "request_id": self.request_id,
+ "channel_id": self.channel_id,
+ "payload": payload,
+ "is_complete": True,
+ }
+ await server.send_push(msg)
+
+ async def create_new_sessions(self, task_descriptions: List[str]) -> str:
+ """Create sub-agent sessions for each task description."""
+ logger.info(
+ "[MultiSessionToolkit] create_new_sessions 开始 parent_session_id=%s 任务数=%d",
+ self.session_id,
+ len(task_descriptions),
+ )
+ created = []
+ for i, task_description in enumerate(task_descriptions):
+ session_id = f"spawn_{time.monotonic_ns()}_{secrets.token_hex(4)}"
+ logger.debug(
+ "[MultiSessionToolkit] 创建协程 [%d/%d] session_id=%s description=%s",
+ i + 1,
+ len(task_descriptions),
+ session_id,
+ task_description[:60] + "..." if len(task_description) > 60 else task_description,
+ )
+ agent = await self.get_sub_agent()
+ inputs = {
+ "conversation_id": session_id,
+ "query": task_description,
+ }
+ coro = self._run_and_notify(session_id, task_description, agent, inputs)
+ task = asyncio.create_task(coro)
+ self._tasks[session_id] = task
+ created.append(session_id)
+ logger.info(
+ "[MultiSessionToolkit] create_new_sessions 完成 已创建 %d 个协程: %s",
+ len(created),
+ ", ".join(created),
+ )
+ return f"已创建 {len(created)} 个协程: {', '.join(created)}"
+
+ async def cancel_session(self, session_id: str) -> str:
+ """Cancel a running session by session_id."""
+ logger.info(
+ "[MultiSessionToolkit] cancel_session 请求 parent_session_id=%s target_session_id=%s",
+ self.session_id,
+ session_id,
+ )
+ task = self._tasks.get(session_id)
+ if task is None:
+ logger.warning(
+ "[MultiSessionToolkit] cancel_session 未找到 session_id=%s 当前协程: %s",
+ session_id,
+ list(self._tasks.keys()),
+ )
+ return f"未找到 session_id={session_id}"
+ if task.done():
+ logger.info("[MultiSessionToolkit] cancel_session session_id=%s 已结束,无需取消", session_id)
+ return f"session_id={session_id} 已结束"
+ task.cancel()
+ try:
+ await asyncio.gather(task, return_exceptions=True)
+ except asyncio.CancelledError:
+ pass
+ logger.info("[MultiSessionToolkit] cancel_session 已取消 session_id=%s", session_id)
+ return f"已取消 session_id={session_id}"
+
+ async def list_all_sessions(self) -> str:
+ """List all session tasks with status."""
+ logger.debug(
+ "[MultiSessionToolkit] list_all_sessions parent_session_id=%s 协程数=%d",
+ self.session_id,
+ len(self.sessions),
+ )
+ if not self.sessions:
+ return "暂无协程"
+ lines = []
+ for st in self.sessions:
+ lines.append(f"{st.session_id} | {st.description} | {st.status.value} | {st.result}")
+ return "\n".join(lines)
+
+ def get_tools(self) -> List[Tool]:
+ """Return tools for registration in Runner."""
+ session_id = self.session_id
+
+ def make_tool(
+ name: str,
+ description: str,
+ input_params: dict,
+ func,
+ ) -> Tool:
+ card = ToolCard(
+ id=f"{name}_{session_id}_{self.request_id}",
+ name=name,
+ description=description,
+ input_params=input_params,
+ )
+ return LocalFunction(card=card, func=func)
+
+ return [
+ make_tool(
+ name="session_new",
+ description=(
+ "创建多个协程任务。接收任务描述列表,每个任务创建一个子 agent 并异步运行。"
+ "协程完成后会通过 notify 发送结果。"
+ ),
+ input_params={
+ "type": "object",
+ "properties": {
+ "task_descriptions": {
+ "type": "array",
+ "items": {"type": "string"},
+ "description": "任务描述列表",
+ }
+ },
+ "required": ["task_descriptions"],
+ },
+ func=self.create_new_sessions,
+ ),
+ make_tool(
+ name="session_cancel",
+ description="根据 session_id 取消正在运行的协程。",
+ input_params={
+ "type": "object",
+ "properties": {
+ "session_id": {
+ "type": "string",
+ "description": "要取消的协程 session_id",
+ }
+ },
+ "required": ["session_id"],
+ },
+ func=self.cancel_session,
+ ),
+ make_tool(
+ name="session_list",
+ description="查看所有协程列表及其状态(session_id | description | status | result)。",
+ input_params={"type": "object", "properties": {}},
+ func=self.list_all_sessions,
+ ),
+ ]
+
+ def all_tasks_done(self) -> bool:
+ """判断是否所有任务都已结束。"""
+ return all([s.status in [Status.COMPLETED, Status.ERROR] for s in self.sessions])
\ No newline at end of file
diff --git a/jiuwenclaw/app.py b/jiuwenclaw/app.py
index 7b1f7082b8..d7dd0979a0 100644
--- a/jiuwenclaw/app.py
+++ b/jiuwenclaw/app.py
@@ -1207,9 +1207,12 @@ async def _run() -> None:
# ---------- 一次启动所有服务 ----------
agent = JiuWenClaw()
- server = AgentWebSocketServer(
- agent, host="127.0.0.1", port=agent_port,
- ping_interval=20.0, ping_timeout=20.0,
+ server = AgentWebSocketServer.get_instance(
+ agent=agent,
+ host="127.0.0.1",
+ port=agent_port,
+ ping_interval=20.0,
+ ping_timeout=20.0,
)
await server.start()
await asyncio.sleep(0.3)
diff --git a/jiuwenclaw/gateway/__init__.py b/jiuwenclaw/gateway/__init__.py
index d10da0fbc1..f45ee05e2d 100644
--- a/jiuwenclaw/gateway/__init__.py
+++ b/jiuwenclaw/gateway/__init__.py
@@ -3,7 +3,7 @@
"""Gateway 模块 - 系统枢纽."""
from jiuwenclaw.gateway.agent_client import AgentServerClient, WebSocketAgentServerClient
-from jiuwenclaw.gateway.agent_ws_server import AgentWebSocketServer
+from jiuwenclaw.agentserver.agent_ws_server import AgentWebSocketServer
from jiuwenclaw.gateway.channel_manager import ChannelManager
from jiuwenclaw.gateway.heartbeat import (
HEARTBEAT_CHANNEL_ID,
@@ -22,7 +22,6 @@ __all__ = [
"GatewayHeartbeatService",
"HEARTBEAT_CHANNEL_ID",
"HEARTBEAT_PROMPT",
- "HEARTBEAT_SESSION_ID",
"HeartbeatConfig",
"IHeartbeat",
"MessageHandler",
diff --git a/jiuwenclaw/gateway/message_handler.py b/jiuwenclaw/gateway/message_handler.py
index 5b756be81c..43a07300d5 100644
--- a/jiuwenclaw/gateway/message_handler.py
+++ b/jiuwenclaw/gateway/message_handler.py
@@ -37,9 +37,22 @@ class MessageHandler(ABC):
- _user_messages:Channel 发来的消息,由内部转发循环消费并调用 agent_client.send_request
- _robot_messages:AgentServer 的响应,由 ChannelManager 消费并派发到对应 Channel
+
+ 单例模式:全局仅存在一个 MessageHandler 实例,可通过 MessageHandler(client) 或
+ MessageHandler.get_instance(client) 获取。
"""
+ _instance: "MessageHandler | None" = None
+
+ def __new__(cls, agent_client: "AgentServerClient", *args: Any, **kwargs: Any) -> "MessageHandler":
+ if cls._instance is None:
+ cls._instance = super().__new__(cls)
+ return cls._instance
+
def __init__(self, agent_client: "AgentServerClient") -> None:
+ if getattr(self, "_singleton_initialized", False):
+ return
+ self._singleton_initialized = True
self._agent_client = agent_client
self._user_messages: asyncio.Queue["Message"] = asyncio.Queue()
self._robot_messages: asyncio.Queue["Message"] = asyncio.Queue()
@@ -61,6 +74,21 @@ class MessageHandler(ABC):
self._load_channel_states_from_config()
+ @classmethod
+ def get_instance(cls, agent_client: "AgentServerClient | None" = None) -> "MessageHandler":
+ """获取单例实例。
+
+ - 若实例已存在:可直接调用 get_instance() 或 get_instance(None),无需传入 client。
+ - 若尚未创建:需传入 agent_client,即 get_instance(client) 或 MessageHandler(client)。
+ """
+ if cls._instance is not None:
+ return cls._instance
+ if agent_client is None:
+ raise RuntimeError(
+ "MessageHandler 尚未初始化,请先使用 MessageHandler(client) 或 get_instance(client) 创建"
+ )
+ return cls(agent_client)
+
def handle_message(self, msg: "Message") -> None:
"""Channel 同步回调:将消息放入 user_messages 队列,由转发循环发给 AgentServer."""
self._user_messages.put_nowait(msg)