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: 引入四元组会话映射并统一通道状态入口

yechenzhen0d46885cc955
diff --git a/jiuwenclaw/channel/feishu.py b/jiuwenclaw/channel/feishu.py
index 9eb222a48f..41ce408344 100644
--- a/jiuwenclaw/channel/feishu.py
+++ b/jiuwenclaw/channel/feishu.py
@@ -10,6 +10,7 @@ import re
import threading
import time
from collections import OrderedDict
+from dataclasses import dataclass
from typing import Any, Callable
from pydantic import BaseModel, Field
@@ -86,6 +87,18 @@ class _ThreadLocalLoopProxy:
return self._get_loop().create_task(coro)
+@dataclass
+class FeishuInboundMessage:
+ """Feishu 入站消息载体,避免参数列表持续膨胀。"""
+
+ message_id: str
+ chat_id: str
+ content: str
+ user_id: str | None = None
+ bot_id: str | None = None
+ metadata: dict[str, Any] | None = None
+
+
class FeishuChannel(BaseChannel):
"""
飞书/飞书IM通道实现,基于WebSocket长连接。
@@ -146,10 +159,7 @@ class FeishuChannel(BaseChannel):
async def _handle_message(
self,
- message_id: str,
- chat_id: str,
- content: str,
- metadata: dict[str, Any] | None = None,
+ inbound: FeishuInboundMessage,
) -> None:
"""
处理接收到的消息并分发。
@@ -157,20 +167,22 @@ class FeishuChannel(BaseChannel):
若已通过on_message注册网关回调,则直接回调;否则通过router路由消息。
Args:
- chat_id: 聊天ID
- content: 消息内容
- metadata: 额外的元数据
+ inbound: Feishu 入站消息
"""
msg = Message(
- id=message_id,
+ id=inbound.message_id,
type="req",
channel_id=self.channel_id,
- session_id=str(chat_id),
- params={"content": content, "query": content},
+ session_id=str(inbound.chat_id),
+ params={"content": inbound.content, "query": inbound.content},
timestamp=time.time(), ok=True,
+ provider=self.name,
+ chat_id=str(inbound.chat_id or ""),
+ user_id=str(inbound.user_id or ""),
+ bot_id=str(inbound.bot_id or self.config.app_id or ""),
req_method=ReqMethod.CHAT_SEND,
is_stream=True,
- metadata=metadata
+ metadata=inbound.metadata,
)
if self._message_callback:
self._message_callback(msg)
@@ -1167,10 +1179,12 @@ class FeishuChannel(BaseChannel):
pass
# 处理消息:将平台身份写入 metadata,供回发时使用(与 session_id 解耦,\new_session 后仍可正确回发)
- await self._handle_message(
+ inbound = FeishuInboundMessage(
message_id=message.message_id,
chat_id=message.chat_id,
content=content,
+ user_id=open_id,
+ bot_id=self.config.app_id or "",
metadata={
"message_id": message.message_id,
"chat_type": message.chat_type,
@@ -1180,6 +1194,7 @@ class FeishuChannel(BaseChannel):
"feishu_chat_id": getattr(message, "chat_id", None) or "",
},
)
+ await self._handle_message(inbound)
except Exception as e:
logger.error(f"处理飞书消息时发生异常: {e}")
diff --git a/jiuwenclaw/gateway/message_handler.py b/jiuwenclaw/gateway/message_handler.py
index df6dde8b9f..229235e560 100644
--- a/jiuwenclaw/gateway/message_handler.py
+++ b/jiuwenclaw/gateway/message_handler.py
@@ -12,12 +12,13 @@ from abc import ABC, abstractmethod
from dataclasses import dataclass
from enum import Enum
from typing import TYPE_CHECKING, Any, Dict
-
-
+from jiuwenclaw.channel.base import ChannelType
+from jiuwenclaw.gateway.session_map import SessionMap
logger = logging.getLogger(__name__)
+
class ChannelMode(str, Enum):
PLAN = "plan"
AGENT = "agent"
@@ -64,9 +65,17 @@ class MessageHandler(ABC):
self._stream_tasks: dict[str, asyncio.Task] = {} # request_id -> task
self._stream_sessions: dict[str, str | None] = {} # request_id -> session_id
- # per-channel 控制状态:支持 \new_session / \mode 指令(feishu/xiaoyi/dingding/whatsapp/wecom)
- self._control_channels = {"feishu", "xiaoyi", "dingtalk", "whatsapp", "wecom"}
+ # per-channel 控制状态:支持 \new_session / \mode 指令。
+ # 使用 ChannelType 的 value 作为标准键,避免散落的硬编码字符串。
+ self._control_channel_types = {
+ ChannelType.FEISHU.value,
+ ChannelType.XIAOYI.value,
+ ChannelType.DINGTALK.value,
+ ChannelType.WHATSAPP.value,
+ ChannelType.WECOM.value,
+ }
self._channel_states: Dict[str, ChannelControlState] = {}
+ self._session_map = SessionMap()
# 直接使用 jiuwenclaw.config 的 get_config_raw/set_config/update_channel_in_config
# 避免在此处重复实现 config 模块加载逻辑。
@@ -141,6 +150,9 @@ class MessageHandler(ABC):
# 否则从 config 加载默认值,并缓存
state = self._get_channel_default_state(ch)
+ identity_key = self._extract_identity_tuple(msg)
+ if identity_key:
+ state.session_id = self._session_map.get_session_id(*identity_key)
self._channel_states[key] = state
return state
@@ -169,6 +181,25 @@ class MessageHandler(ABC):
suffix = secrets.token_hex(3)
return f"{channel_id}_{ts}_{suffix}"
+ @staticmethod
+ def _extract_identity_tuple(msg: "Message") -> tuple[str, str, str, str] | None:
+ provider = str(getattr(msg, "provider", None) or "").strip()
+ chat_id = str(getattr(msg, "chat_id", None) or "").strip()
+ bot_id = str(getattr(msg, "bot_id", None) or "").strip()
+ user_id = str(getattr(msg, "user_id", None) or "").strip()
+ identity_parts = (provider, chat_id, bot_id, user_id)
+ if all(identity_parts):
+ return (provider, chat_id, bot_id, user_id)
+ return None
+
+ def _resolve_control_channel_type(self, msg: "Message") -> str:
+ """Resolve control channel type key: prefer provider, fallback to channel_id."""
+ provider_raw = getattr(msg, "provider", None)
+ provider = str(getattr(provider_raw, "value", provider_raw) or "").strip()
+ if provider:
+ return provider
+ return str(getattr(msg, "channel_id", "") or "")
+
async def _send_channel_notice(self, channel_id: str, session_id: str | None, text: str) -> None:
"""向指定 channel 发送一条系统提示消息."""
from jiuwenclaw.schema.message import Message, EventType
@@ -194,7 +225,8 @@ class MessageHandler(ABC):
False: 非控制指令,继续正常处理。
"""
ch = msg.channel_id
- if ch not in self._control_channels:
+ channel_type = self._resolve_control_channel_type(msg)
+ if channel_type not in self._control_channel_types:
return False
params = msg.params or {}
@@ -202,14 +234,23 @@ class MessageHandler(ABC):
if not text:
return False
- logger.info('this is in _handle_channel_control, channel id is %s, text is %s, "\\new_session" in text is %s', ch, text, str("\\new_session" in text))
+ logger.info(
+ 'this is in _handle_channel_control, channel id is %s, text is %s, "\\new_session" in text is %s',
+ channel_type,
+ text,
+ str("\\new_session" in text),
+ )
# 获取当前会话的状态(使用复合键)
state = self._get_or_create_channel_state(msg)
# \new_session:重置当前会话的 session_id
if "/new_session" == text:
- new_sid = self._generate_channel_session_id(ch)
+ identity_key = self._extract_identity_tuple(msg)
+ if identity_key:
+ new_sid = self._session_map.get_session_id(*identity_key, rotate=True)
+ else:
+ new_sid = self._generate_channel_session_id(channel_type)
state.session_id = new_sid
# 给当前会话回复提示(用原有 session_id)
asyncio.create_task(
@@ -241,14 +282,18 @@ class MessageHandler(ABC):
def _apply_channel_state(self, msg: "Message") -> None:
"""将当前 Channel 的控制状态应用到消息上(session_id / mode)."""
- ch = msg.channel_id
- if ch not in self._control_channels:
+ channel_type = self._resolve_control_channel_type(msg)
+ if channel_type not in self._control_channel_types:
return
-
state = self._get_or_create_channel_state(msg)
- # 对 feishu/xiaoyi/dingtalk/whatsapp 强制覆盖 session_id;web 等保持原有行为
- if state.session_id:
+ # 仅受控通道优先使用 provider/chat_id/bot_id/user_id 映射;其它通道保持原有行为。
+ identity_key = self._extract_identity_tuple(msg)
+ if identity_key:
+ sid = self._session_map.get_session_id(*identity_key)
+ state.session_id = sid
+ msg.session_id = sid
+ elif state.session_id:
msg.session_id = state.session_id
# 将 mode 写入 params,后续 AgentRequest 会从 params["mode"] 里读取
diff --git a/jiuwenclaw/gateway/session_map.py b/jiuwenclaw/gateway/session_map.py
new file mode 100644
index 0000000000..edd381c174
--- /dev/null
+++ b/jiuwenclaw/gateway/session_map.py
@@ -0,0 +1,67 @@
+from __future__ import annotations
+
+import json
+import secrets
+import time
+from pathlib import Path
+
+from jiuwenclaw.utils import get_checkpoint_dir, logger
+
+
+def _make_key(provider: str, chat_id: str, bot_id: str, user_id: str) -> str:
+ return f"{provider}::{chat_id}::{bot_id}::{user_id}"
+
+
+def _make_session_id(provider: str, chat_id: str, bot_id: str, user_id: str) -> str:
+ ts = format(int(time.time() * 1000), "x")
+ suffix = secrets.token_hex(3)
+ return f"{provider}_{chat_id}_{bot_id}_{user_id}_{ts}_{suffix}"
+
+
+class SessionMap:
+ """Simple mapping: (provider,chat_id,bot_id,user_id) -> session_id."""
+
+ def __init__(self) -> None:
+ self._store_path: Path = get_checkpoint_dir() / "session_map.json"
+ self._mapping: dict[str, str] = {}
+ self._load()
+
+ def _load(self) -> None:
+ try:
+ if not self._store_path.exists():
+ return
+ with open(self._store_path, "r", encoding="utf-8") as f:
+ data = json.load(f)
+ if isinstance(data, dict):
+ self._mapping = {str(k): str(v) for k, v in data.items() if isinstance(v, str) and v}
+ except Exception as exc: # noqa: BLE001
+ logger.warning("SessionMap load failed: %s", exc)
+
+ def _save(self) -> None:
+ try:
+ self._store_path.parent.mkdir(parents=True, exist_ok=True)
+ with open(self._store_path, "w", encoding="utf-8") as f:
+ json.dump(self._mapping, f, ensure_ascii=False, indent=2)
+ except Exception as exc: # noqa: BLE001
+ logger.warning("SessionMap save failed: %s", exc)
+
+ def get_session_id(
+ self,
+ provider: str,
+ chat_id: str,
+ bot_id: str,
+ user_id: str,
+ *,
+ rotate: bool = False,
+ ) -> str:
+ key = _make_key(provider, chat_id, bot_id, user_id)
+ existing = self._mapping.get(key)
+ if existing and not rotate:
+ return existing
+
+ sid = _make_session_id(provider, chat_id, bot_id, user_id)
+ if existing == sid:
+ return sid
+ self._mapping[key] = sid
+ self._save()
+ return sid
diff --git a/jiuwenclaw/schema/message.py b/jiuwenclaw/schema/message.py
index ea8d31b229..b64e81cc6d 100644
--- a/jiuwenclaw/schema/message.py
+++ b/jiuwenclaw/schema/message.py
@@ -111,6 +111,10 @@ class Message:
params: dict
timestamp: float
ok: bool
+ provider: str | None = None
+ chat_id: str | None = None
+ user_id: str | None = None
+ bot_id: str | None = None
payload: dict | None = None
req_method: ReqMethod | None = None
event_type: EventType | None = None