Skip to content

DeepTutor: Lifelong Personalized Tutoring. https://deeptutor.info/.

feat(partners): production IM infra — retry/dedup/coalescing, per-channel delivery flags, stream-delta protocol, slack/telegram connection fixes

Bingxi Zhao (Frank)da1061910b8f
diff --git a/deeptutor/api/routers/_partners_channel_schema.py b/deeptutor/api/routers/_partners_channel_schema.py
new file mode 100644
index 000000000..e34e132e3
--- /dev/null
+++ b/deeptutor/api/routers/_partners_channel_schema.py
@@ -0,0 +1,170 @@
+"""Channel-schema introspection — bridges Pydantic channel configs to the Web UI.
+
+Used by ``GET /api/v1/partners/channels/schema`` so the front-end can render
+generic forms for ANY channel (built-in or plugin) without hard-coding fields.
+
+Why live here vs inside ``deeptutor.partners.channels``?
+ * This is an API-shaping concern (JSON Schema flattening, secret-field
+ detection) — keeping it next to the route avoids polluting the runtime
+ channel package with HTTP-specific helpers.
+"""
+
+from __future__ import annotations
+
+import inspect
+from typing import Any
+
+from pydantic import BaseModel
+
+from deeptutor.services.partners.manager import _is_secret_field
+
+
+def resolve_config_model(channel_cls: type) -> type[BaseModel] | None:
+ """Find the Pydantic config model paired with ``channel_cls``.
+
+ Convention every built-in channel follows: ``XxxChannel`` lives in the
+ same module as ``XxxConfig`` (e.g. ``TelegramChannel`` ↔ ``TelegramConfig``).
+ Falls back to "any ``*Config`` BaseModel in the module".
+ """
+ module = inspect.getmodule(channel_cls)
+ if module is None:
+ return None
+
+ expected = channel_cls.__name__.replace("Channel", "") + "Config"
+ candidate = getattr(module, expected, None)
+ if isinstance(candidate, type) and issubclass(candidate, BaseModel):
+ return candidate
+
+ for _, obj in inspect.getmembers(module):
+ if (
+ isinstance(obj, type)
+ and obj is not BaseModel
+ and issubclass(obj, BaseModel)
+ and obj.__name__.endswith("Config")
+ ):
+ return obj
+ return None
+
+
+def inline_refs(schema: dict[str, Any]) -> dict[str, Any]:
+ """Flatten Pydantic's ``$defs`` / ``$ref`` so the front-end doesn't need a resolver.
+
+ Nested model fields (e.g. ``slack.dm: SlackDMConfig``) become inline
+ ``type: object`` subtrees with their own ``properties``.
+ """
+ defs: dict[str, Any] = dict(schema.get("$defs", {}))
+
+ def _walk(node: Any) -> Any:
+ if isinstance(node, dict):
+ ref = node.get("$ref")
+ if isinstance(ref, str) and ref.startswith("#/$defs/"):
+ ref_name = ref.rsplit("/", 1)[-1]
+ resolved = defs.get(ref_name, {})
+ merged = {**resolved}
+ # Allow per-field overrides (description, default) from the ref site.
+ for k, v in node.items():
+ if k != "$ref":
+ merged[k] = v
+ return _walk(merged)
+ return {k: _walk(v) for k, v in node.items()}
+ if isinstance(node, list):
+ return [_walk(item) for item in node]
+ return node
+
+ out = _walk(schema)
+ if isinstance(out, dict):
+ out.pop("$defs", None)
+ return out
+
+
+def _schema_accepts_string(prop_schema: dict[str, Any]) -> bool:
+ """True iff the JSON-Schema fragment can hold a string value.
+
+ Used to filter out booleans/integers/arrays whose name happens to contain
+ a secret-looking substring (e.g. ``user_token_read_only: bool``).
+ """
+ t = prop_schema.get("type")
+ if t == "string":
+ return True
+ if isinstance(t, list) and "string" in t:
+ return True
+ for variant in prop_schema.get("anyOf", []):
+ if isinstance(variant, dict) and variant.get("type") == "string":
+ return True
+ return False
+
+
+def collect_secret_fields(schema: dict[str, Any], prefix: str = "") -> list[str]:
+ """Return dot-paths for every string-typed property whose name hints at a secret.
+
+ e.g. ``["token"]`` for telegram, ``["imap_password", "smtp_password"]``
+ for email, ``["bot_token", "app_token"]`` for slack. A field like
+ ``user_token_read_only: bool`` is intentionally skipped.
+ """
+ paths: list[str] = []
+ properties = schema.get("properties") if isinstance(schema, dict) else None
+ if not isinstance(properties, dict):
+ return paths
+
+ for prop_name, prop_schema in properties.items():
+ if not isinstance(prop_schema, dict):
+ continue
+ full = f"{prefix}{prop_name}" if not prefix else f"{prefix}.{prop_name}"
+ if _is_secret_field(prop_name) and _schema_accepts_string(prop_schema):
+ paths.append(full)
+ if prop_schema.get("type") == "object":
+ paths.extend(collect_secret_fields(prop_schema, prefix=full))
+ return paths
+
+
+def channel_schema_payload(channel_cls: type) -> dict[str, Any] | None:
+ """Build the per-channel schema payload, or ``None`` if no config model found."""
+ model = resolve_config_model(channel_cls)
+ if model is None:
+ return None
+
+ # by_alias=False → property names match Python field names (snake_case),
+ # which is exactly the shape we persist in ``config.yaml`` and what every
+ # channel's ``__init__`` expects when ``model_validate(dict)`` is called.
+ # The pydantic Base config has populate_by_name=True so the runtime still
+ # accepts both forms; we standardise on snake_case for the wire schema.
+ raw = model.model_json_schema(by_alias=False)
+ flat = inline_refs(raw)
+ secret_fields = collect_secret_fields(flat)
+
+ try:
+ default_config = model().model_dump(mode="json", by_alias=False)
+ except Exception:
+ default_config = {}
+
+ return {
+ "name": getattr(channel_cls, "name", channel_cls.__name__),
+ "display_name": getattr(channel_cls, "display_name", channel_cls.__name__),
+ "default_config": default_config,
+ "secret_fields": secret_fields,
+ "json_schema": flat,
+ }
+
+
+def all_channel_schemas() -> dict[str, dict[str, Any]]:
+ """Build the schema dict for every discovered channel (built-in + plugins)."""
+ from deeptutor.partners.channels.registry import discover_all
+
+ out: dict[str, dict[str, Any]] = {}
+ for name, cls in discover_all().items():
+ payload = channel_schema_payload(cls)
+ if payload is not None:
+ out[name] = payload
+ return out
+
+
+def global_channels_schema() -> dict[str, Any]:
+ """Schema for the top-level ``ChannelsConfig`` flags (send_progress / send_tool_hints)."""
+ from deeptutor.partners.config.schema import ChannelsConfig
+
+ raw = ChannelsConfig.model_json_schema(by_alias=False)
+ flat = inline_refs(raw)
+ return {
+ "json_schema": flat,
+ "secret_fields": collect_secret_fields(flat),
+ }
diff --git a/deeptutor/partners/__init__.py b/deeptutor/partners/__init__.py
new file mode 100644
index 000000000..7d9bd665c
--- /dev/null
+++ b/deeptutor/partners/__init__.py
@@ -0,0 +1,11 @@
+"""Partners — IM-connected companions driven by the DeepTutor chat agent loop.
+
+This package hosts the channel (IM) layer: the chat-platform integrations,
+the message bus that decouples them from the agent runtime, and their
+configuration schema. The agent runtime itself lives in
+``deeptutor.services.partners`` and reuses the chat capability's agent loop
+(``ChatOrchestrator`` → ``AgenticChatPipeline``) — there is no separate
+partner engine.
+"""
+
+__version__ = "2.0.0"
diff --git a/deeptutor/partners/bus/__init__.py b/deeptutor/partners/bus/__init__.py
new file mode 100644
index 000000000..1a93b724b
--- /dev/null
+++ b/deeptutor/partners/bus/__init__.py
@@ -0,0 +1,6 @@
+"""Message bus module for decoupled channel-agent communication."""
+
+from deeptutor.partners.bus.events import InboundMessage, OutboundMessage
+from deeptutor.partners.bus.queue import MessageBus
+
+__all__ = ["MessageBus", "InboundMessage", "OutboundMessage"]
diff --git a/deeptutor/partners/bus/events.py b/deeptutor/partners/bus/events.py
new file mode 100644
index 000000000..40da8ec8f
--- /dev/null
+++ b/deeptutor/partners/bus/events.py
@@ -0,0 +1,36 @@
+"""Event types for the message bus."""
+
+from dataclasses import dataclass, field
+from datetime import datetime
+from typing import Any
+
+
+@dataclass
+class InboundMessage:
+ """Message received from a chat channel."""
+
+ channel: str # telegram, discord, slack, whatsapp
+ sender_id: str # User identifier
+ chat_id: str # Chat/channel identifier
+ content: str # Message text
+ timestamp: datetime = field(default_factory=datetime.now)
+ media: list[str] = field(default_factory=list) # Media URLs
+ metadata: dict[str, Any] = field(default_factory=dict) # Channel-specific data
+ session_key_override: str | None = None # Optional override for thread-scoped sessions
+
+ @property
+ def session_key(self) -> str:
+ """Unique key for session identification."""
+ return self.session_key_override or f"{self.channel}:{self.chat_id}"
+
+
+@dataclass
+class OutboundMessage:
+ """Message to send to a chat channel."""
+
+ channel: str
+ chat_id: str
+ content: str
+ reply_to: str | None = None
+ media: list[str] = field(default_factory=list)
+ metadata: dict[str, Any] = field(default_factory=dict)
diff --git a/deeptutor/partners/bus/queue.py b/deeptutor/partners/bus/queue.py
new file mode 100644
index 000000000..6e534da95
--- /dev/null
+++ b/deeptutor/partners/bus/queue.py
@@ -0,0 +1,44 @@
+"""Async message queue for decoupled channel-agent communication."""
+
+import asyncio
+
+from deeptutor.partners.bus.events import InboundMessage, OutboundMessage
+
+
+class MessageBus:
+ """
+ Async message bus that decouples chat channels from the agent core.
+
+ Channels push messages to the inbound queue, and the agent processes
+ them and pushes responses to the outbound queue.
+ """
+
+ def __init__(self):
+ self.inbound: asyncio.Queue[InboundMessage] = asyncio.Queue()
+ self.outbound: asyncio.Queue[OutboundMessage] = asyncio.Queue()
+
+ async def publish_inbound(self, msg: InboundMessage) -> None:
+ """Publish a message from a channel to the agent."""
+ await self.inbound.put(msg)
+
+ async def consume_inbound(self) -> InboundMessage:
+ """Consume the next inbound message (blocks until available)."""
+ return await self.inbound.get()
+
+ async def publish_outbound(self, msg: OutboundMessage) -> None:
+ """Publish a response from the agent to channels."""
+ await self.outbound.put(msg)
+
+ async def consume_outbound(self) -> OutboundMessage:
+ """Consume the next outbound message (blocks until available)."""
+ return await self.outbound.get()
+
+ @property
+ def inbound_size(self) -> int:
+ """Number of pending inbound messages."""
+ return self.inbound.qsize()
+
+ @property
+ def outbound_size(self) -> int:
+ """Number of pending outbound messages."""
+ return self.outbound.qsize()
diff --git a/deeptutor/partners/channels/__init__.py b/deeptutor/partners/channels/__init__.py
new file mode 100644
index 000000000..f6575e5af
--- /dev/null
+++ b/deeptutor/partners/channels/__init__.py
@@ -0,0 +1,6 @@
+"""Chat channels module with plugin architecture."""
+
+from deeptutor.partners.channels.base import BaseChannel
+from deeptutor.partners.channels.manager import ChannelManager
+
+__all__ = ["BaseChannel", "ChannelManager"]
diff --git a/deeptutor/partners/channels/base.py b/deeptutor/partners/channels/base.py
new file mode 100644
index 000000000..bc059e886
--- /dev/null
+++ b/deeptutor/partners/channels/base.py
@@ -0,0 +1,184 @@
+"""Base channel interface for chat platforms."""
+
+from __future__ import annotations
+
+from abc import ABC, abstractmethod
+from pathlib import Path
+from typing import Any
+
+from deeptutor.partners.bus.events import InboundMessage, OutboundMessage
+from deeptutor.partners.bus.queue import MessageBus
+
+
+def _logger():
+ from loguru import logger as _log
+
+ return _log
+
+
+class BaseChannel(ABC):
+ """
+ Abstract base class for chat channel implementations.
+
+ Each channel (Telegram, Discord, etc.) should implement this interface
+ to integrate with the TutorBot message bus.
+ """
+
+ name: str = "base"
+ display_name: str = "Base"
+ transcription_api_key: str = ""
+ # Effective delivery flags for this channel instance — the manager sets
+ # them to (partner-level flag AND per-channel override) at init time.
+ send_progress: bool = True
+ send_tool_hints: bool = True
+
+ def __init__(self, config: Any, bus: MessageBus):
+ """
+ Initialize the channel.
+
+ Args:
+ config: Channel-specific configuration.
+ bus: The message bus for communication.
+ """
+ self.config = config
+ self.bus = bus
+ self._running = False
+
+ async def transcribe_audio(self, file_path: str | Path) -> str:
+ """Transcribe an audio file via Groq Whisper. Returns empty string on failure."""
+ if not self.transcription_api_key:
+ return ""
+ try:
+ from deeptutor.partners.transcription import GroqTranscriptionProvider
+
+ provider = GroqTranscriptionProvider(api_key=self.transcription_api_key)
+ return await provider.transcribe(file_path)
+ except Exception as e:
+ _logger().warning("{}: audio transcription failed: {}", self.name, e)
+ return ""
+
+ @abstractmethod
+ async def start(self) -> None:
+ """
+ Start the channel and begin listening for messages.
+
+ This should be a long-running async task that:
+ 1. Connects to the chat platform
+ 2. Listens for incoming messages
+ 3. Forwards messages to the bus via _handle_message()
+ """
+ pass
+
+ @abstractmethod
+ async def stop(self) -> None:
+ """Stop the channel and clean up resources."""
+ pass
+
+ @abstractmethod
+ async def send(self, msg: OutboundMessage) -> None:
+ """
+ Send a message through this channel.
+
+ Args:
+ msg: The message to send.
+
+ Implementations should raise on delivery failure so the channel
+ manager can apply the retry policy in one place.
+ """
+ pass
+
+ async def send_delta(
+ self, chat_id: str, delta: str, metadata: dict[str, Any] | None = None
+ ) -> None:
+ """Deliver a streaming text chunk.
+
+ Override in subclasses to enable streaming (in-place message edits).
+ Implementations should raise on delivery failure so the channel
+ manager can retry.
+
+ Streaming contract: ``_stream_delta`` marks a chunk, ``_stream_end``
+ ends the current segment, and stateful implementations must key
+ buffers by ``_stream_id`` rather than only by ``chat_id``.
+ """
+ pass
+
+ @property
+ def supports_streaming(self) -> bool:
+ """True when config enables streaming AND this subclass implements send_delta."""
+ cfg = self.config
+ streaming = (
+ cfg.get("streaming", False)
+ if isinstance(cfg, dict)
+ else getattr(cfg, "streaming", False)
+ )
+ return bool(streaming) and type(self).send_delta is not BaseChannel.send_delta
+
+ def is_allowed(self, sender_id: str) -> bool:
+ """Check if *sender_id* is permitted. Empty list → deny all; ``"*"`` → allow all."""
+ allow_list = getattr(self.config, "allow_from", [])
+ if not allow_list:
+ _logger().warning("{}: allow_from is empty — all access denied", self.name)
+ return False
+ if "*" in allow_list:
+ return True
+ return str(sender_id) in allow_list
+
+ async def _handle_message(
+ self,
+ sender_id: str,
+ chat_id: str,
+ content: str,
+ media: list[str] | None = None,
+ metadata: dict[str, Any] | None = None,
+ session_key: str | None = None,
+ ) -> None:
+ """
+ Handle an incoming message from the chat platform.
+
+ This method checks permissions and forwards to the bus.
+
+ Args:
+ sender_id: The sender's identifier.
+ chat_id: The chat/channel identifier.
+ content: Message text content.
+ media: Optional list of media URLs.
+ metadata: Optional channel-specific metadata.
+ session_key: Optional session key override (e.g. thread-scoped sessions).
+ """
+ if not self.is_allowed(sender_id):
+ _logger().warning(
+ "Access denied for sender {} on channel {}. "
+ "Add them to allowFrom list in config to grant access.",
+ sender_id,
+ self.name,
+ )
+ return
+
+ meta = metadata or {}
+ if self.supports_streaming and self.send_progress:
+ # The runner streams reply text live only when asked to. Streaming
+ # requires send_progress: narration rounds stream as they happen,
+ # so with progress muted we fall back to buffered delivery.
+ meta = {**meta, "_wants_stream": True}
+
+ msg = InboundMessage(
+ channel=self.name,
+ sender_id=str(sender_id),
+ chat_id=str(chat_id),
+ content=content,
+ media=media or [],
+ metadata=meta,
+ session_key_override=session_key,
+ )
+
+ await self.bus.publish_inbound(msg)
+
+ @classmethod
+ def default_config(cls) -> dict[str, Any]:
+ """Return default config for onboard. Override in plugins to auto-populate config.json."""
+ return {"enabled": False}
+
+ @property
+ def is_running(self) -> bool:
+ """Check if the channel is running."""
+ return self._running
diff --git a/deeptutor/partners/channels/dingtalk.py b/deeptutor/partners/channels/dingtalk.py
new file mode 100644
index 000000000..971aecd52
--- /dev/null
+++ b/deeptutor/partners/channels/dingtalk.py
@@ -0,0 +1,527 @@
+"""DingTalk/DingDing channel implementation using Stream Mode."""
+
+import asyncio
+import json
+import mimetypes
+import os
+from pathlib import Path
+import time
+from typing import Any
+from urllib.parse import unquote, urlparse
+
+import httpx
+from loguru import logger
+from pydantic import Field
+
+from deeptutor.partners.bus.events import OutboundMessage
+from deeptutor.partners.bus.queue import MessageBus
+from deeptutor.partners.channels.base import BaseChannel
+from deeptutor.partners.config.schema import Base, DeliveryOverrides
+
+try:
+ from dingtalk_stream import (
+ AckMessage,
+ CallbackHandler,
+ CallbackMessage,
+ Credential,
+ DingTalkStreamClient,
+ )
+ from dingtalk_stream.chatbot import ChatbotMessage
+
+ DINGTALK_AVAILABLE = True
+except ImportError:
+ DINGTALK_AVAILABLE = False
+ # Fallback so class definitions don't crash at module level
+ CallbackHandler = object # type: ignore[assignment,misc]
+ CallbackMessage = None # type: ignore[assignment,misc]
+ AckMessage = None # type: ignore[assignment,misc]
+ ChatbotMessage = None # type: ignore[assignment,misc]
+
+
+class NanobotDingTalkHandler(CallbackHandler):
+ """
+ Standard DingTalk Stream SDK Callback Handler.
+ Parses incoming messages and forwards them to the Nanobot channel.
+ """
+
+ def __init__(self, channel: "DingTalkChannel"):
+ super().__init__()
+ self.channel = channel
+
+ async def process(self, message: CallbackMessage):
+ """Process incoming stream message."""
+ try:
+ # Parse using SDK's ChatbotMessage for robust handling
+ chatbot_msg = ChatbotMessage.from_dict(message.data)
+
+ # Extract text content; fall back to raw dict if SDK object is empty
+ content = ""
+ if chatbot_msg.text:
+ content = chatbot_msg.text.content.strip()
+ elif chatbot_msg.extensions.get("content", {}).get("recognition"):
+ content = chatbot_msg.extensions["content"]["recognition"].strip()
+ if not content:
+ content = message.data.get("text", {}).get("content", "").strip()
+
+ if not content:
+ logger.warning(
+ "Received empty or unsupported message type: {}",
+ chatbot_msg.message_type,
+ )
+ return AckMessage.STATUS_OK, "OK"
+
+ sender_id = chatbot_msg.sender_staff_id or chatbot_msg.sender_id
+ sender_name = chatbot_msg.sender_nick or "Unknown"
+
+ conversation_type = message.data.get("conversationType")
+ conversation_id = message.data.get("conversationId") or message.data.get(
+ "openConversationId"
+ )
+
+ logger.info(
+ "Received DingTalk message from {} ({}): {}", sender_name, sender_id, content
+ )
+
+ # Forward to Nanobot via _on_message (non-blocking).
+ # Store reference to prevent GC before task completes.
+ task = asyncio.create_task(
+ self.channel._on_message(
+ content,
+ sender_id,
+ sender_name,
+ conversation_type,
+ conversation_id,
+ )
+ )
+ self.channel._background_tasks.add(task)
+ task.add_done_callback(self.channel._background_tasks.discard)
+
+ return AckMessage.STATUS_OK, "OK"
+
+ except Exception as e:
+ logger.error("Error processing DingTalk message: {}", e)
+ # Return OK to avoid retry loop from DingTalk server
+ return AckMessage.STATUS_OK, "Error"
+
+
+class DingTalkConfig(DeliveryOverrides):
+ """DingTalk channel configuration using Stream mode."""
+
+ enabled: bool = False
+ client_id: str = ""
+ client_secret: str = ""
+ allow_from: list[str] = Field(default_factory=list)
+
+
+class DingTalkChannel(BaseChannel):
+ """
+ DingTalk channel using Stream Mode.
+
+ Uses WebSocket to receive events via `dingtalk-stream` SDK.
+ Uses direct HTTP API to send messages (SDK is mainly for receiving).
+
+ Supports both private (1:1) and group chats.
+ Group chat_id is stored with a "group:" prefix to route replies back.
+ """
+
+ name = "dingtalk"
+ display_name = "DingTalk"
+ _IMAGE_EXTS = {".jpg", ".jpeg", ".png", ".gif", ".bmp", ".webp"}
+ _AUDIO_EXTS = {".amr", ".mp3", ".wav", ".ogg", ".m4a", ".aac"}
+ _VIDEO_EXTS = {".mp4", ".mov", ".avi", ".mkv", ".webm"}
+
+ @classmethod
+ def default_config(cls) -> dict[str, Any]:
+ return DingTalkConfig().model_dump(by_alias=True)
+
+ def __init__(self, config: Any, bus: MessageBus):
+ if isinstance(config, dict):
+ config = DingTalkConfig.model_validate(config)
+ super().__init__(config, bus)
+ self.config: DingTalkConfig = config
+ self._client: Any = None
+ self._http: httpx.AsyncClient | None = None
+
+ # Access Token management for sending messages
+ self._access_token: str | None = None
+ self._token_expiry: float = 0
+
+ # Hold references to background tasks to prevent GC
+ self._background_tasks: set[asyncio.Task] = set()
+
+ async def start(self) -> None:
+ """Start the DingTalk bot with Stream Mode."""
+ try:
+ if not DINGTALK_AVAILABLE:
+ logger.error("DingTalk Stream SDK not installed. Run: pip install dingtalk-stream")
+ return
+
+ if not self.config.client_id or not self.config.client_secret:
+ logger.error("DingTalk client_id and client_secret not configured")
+ return
+
+ self._running = True
+ self._http = httpx.AsyncClient()
+
+ logger.info(
+ "Initializing DingTalk Stream Client with Client ID: {}...",
+ self.config.client_id,
+ )
+ credential = Credential(self.config.client_id, self.config.client_secret)
+ self._client = DingTalkStreamClient(credential)
+
+ # Register standard handler
+ handler = NanobotDingTalkHandler(self)
+ self._client.register_callback_handler(ChatbotMessage.TOPIC, handler)
+
+ logger.info("DingTalk bot started with Stream Mode")
+
+ # Reconnect loop: restart stream if SDK exits or crashes
+ while self._running:
+ try:
+ await self._client.start()
+ except Exception as e:
+ logger.warning("DingTalk stream error: {}", e)
+ if self._running:
+ logger.info("Reconnecting DingTalk stream in 5 seconds...")
+ await asyncio.sleep(5)
+
+ except Exception as e:
+ logger.exception("Failed to start DingTalk channel: {}", e)
+
+ async def stop(self) -> None:
+ """Stop the DingTalk bot."""
+ self._running = False
+ # Close the shared HTTP client
+ if self._http:
+ await self._http.aclose()
+ self._http = None
+ # Cancel outstanding background tasks
+ for task in self._background_tasks:
+ task.cancel()
+ self._background_tasks.clear()
+
+ async def _get_access_token(self) -> str | None:
+ """Get or refresh Access Token."""
+ if self._access_token and time.time() < self._token_expiry:
+ return self._access_token
+
+ url = "https://api.dingtalk.com/v1.0/oauth2/accessToken"
+ data = {
+ "appKey": self.config.client_id,
+ "appSecret": self.config.client_secret,
+ }
+
+ if not self._http:
+ logger.warning("DingTalk HTTP client not initialized, cannot refresh token")
+ return None
+
+ try:
+ resp = await self._http.post(url, json=data)
+ resp.raise_for_status()
+ res_data = resp.json()
+ self._access_token = res_data.get("accessToken")
+ # Expire 60s early to be safe
+ self._token_expiry = time.time() + int(res_data.get("expireIn", 7200)) - 60
+ return self._access_token
+ except Exception as e:
+ logger.error("Failed to get DingTalk access token: {}", e)
+ return None
+
+ @staticmethod
+ def _is_http_url(value: str) -> bool:
+ return urlparse(value).scheme in ("http", "https")
+
+ def _guess_upload_type(self, media_ref: str) -> str:
+ ext = Path(urlparse(media_ref).path).suffix.lower()
+ if ext in self._IMAGE_EXTS:
+ return "image"
+ if ext in self._AUDIO_EXTS:
+ return "voice"
+ if ext in self._VIDEO_EXTS:
+ return "video"
+ return "file"
+
+ def _guess_filename(self, media_ref: str, upload_type: str) -> str:
+ name = os.path.basename(urlparse(media_ref).path)
+ return name or {"image": "image.jpg", "voice": "audio.amr", "video": "video.mp4"}.get(
+ upload_type, "file.bin"
+ )
+
+ async def _read_media_bytes(
+ self,
+ media_ref: str,
+ ) -> tuple[bytes | None, str | None, str | None]:
+ if not media_ref:
+ return None, None, None
+
+ if self._is_http_url(media_ref):
+ if not self._http:
+ return None, None, None
+ try:
+ resp = await self._http.get(media_ref, follow_redirects=True)
+ if resp.status_code >= 400:
+ logger.warning(
+ "DingTalk media download failed status={} ref={}",
+ resp.status_code,
+ media_ref,
+ )
+ return None, None, None
+ content_type = (resp.headers.get("content-type") or "").split(";")[0].strip()
+ filename = self._guess_filename(media_ref, self._guess_upload_type(media_ref))
+ return resp.content, filename, content_type or None
+ except Exception as e:
+ logger.error("DingTalk media download error ref={} err={}", media_ref, e)
+ return None, None, None
+
+ try:
+ if media_ref.startswith("file://"):
+ parsed = urlparse(media_ref)
+ local_path = Path(unquote(parsed.path))
+ else:
+ local_path = Path(os.path.expanduser(media_ref))
+ if not local_path.is_file():
+ logger.warning("DingTalk media file not found: {}", local_path)
+ return None, None, None
+ data = await asyncio.to_thread(local_path.read_bytes)
+ content_type = mimetypes.guess_type(local_path.name)[0]
+ return data, local_path.name, content_type
+ except Exception as e:
+ logger.error("DingTalk media read error ref={} err={}", media_ref, e)
+ return None, None, None
+
+ async def _upload_media(
+ self,
+ token: str,
+ data: bytes,
+ media_type: str,
+ filename: str,
+ content_type: str | None,
+ ) -> str | None:
+ if not self._http:
+ return None
+ url = f"https://oapi.dingtalk.com/media/upload?access_token={token}&type={media_type}"
+ mime = content_type or mimetypes.guess_type(filename)[0] or "application/octet-stream"
+ files = {"media": (filename, data, mime)}
+
+ try:
+ resp = await self._http.post(url, files=files)
+ text = resp.text
+ result = (
+ resp.json()
+ if resp.headers.get("content-type", "").startswith("application/json")
+ else {}
+ )
+ if resp.status_code >= 400:
+ logger.error(
+ "DingTalk media upload failed status={} type={} body={}",
+ resp.status_code,
+ media_type,
+ text[:500],
+ )
+ return None
+ errcode = result.get("errcode", 0)
+ if errcode != 0:
+ logger.error(
+ "DingTalk media upload api error type={} errcode={} body={}",
+ media_type,
+ errcode,
+ text[:500],
+ )
+ return None
+ sub = result.get("result") or {}
+ media_id = (
+ result.get("media_id")
+ or result.get("mediaId")
+ or sub.get("media_id")
+ or sub.get("mediaId")
+ )
+ if not media_id:
+ logger.error("DingTalk media upload missing media_id body={}", text[:500])
+ return None
+ return str(media_id)
+ except Exception as e:
+ logger.error("DingTalk media upload error type={} err={}", media_type, e)
+ return None
+
+ async def _send_batch_message(
+ self,
+ token: str,
+ chat_id: str,
+ msg_key: str,
+ msg_param: dict[str, Any],
+ ) -> bool:
+ if not self._http:
+ logger.warning("DingTalk HTTP client not initialized, cannot send")
+ return False
+
+ headers = {"x-acs-dingtalk-access-token": token}
+ if chat_id.startswith("group:"):
+ # Group chat
+ url = "https://api.dingtalk.com/v1.0/robot/groupMessages/send"
+ payload: dict[str, Any] = {
+ "robotCode": self.config.client_id,
+ "openConversationId": chat_id[6:], # Remove "group:" prefix,
+ "msgKey": msg_key,
+ "msgParam": json.dumps(msg_param, ensure_ascii=False),
+ }
+ else:
+ # Private chat
+ url = "https://api.dingtalk.com/v1.0/robot/oToMessages/batchSend"
+ payload = {
+ "robotCode": self.config.client_id,
+ "userIds": [chat_id],
+ "msgKey": msg_key,
+ "msgParam": json.dumps(msg_param, ensure_ascii=False),
+ }
+
+ try:
+ resp = await self._http.post(url, json=payload, headers=headers)
+ body = resp.text
+ if resp.status_code != 200:
+ logger.error(
+ "DingTalk send failed msgKey={} status={} body={}",
+ msg_key,
+ resp.status_code,
+ body[:500],
+ )
+ return False
+ try:
+ result = resp.json()
+ except Exception:
+ result = {}
+ errcode = result.get("errcode")
+ if errcode not in (None, 0):
+ logger.error(
+ "DingTalk send api error msgKey={} errcode={} body={}",
+ msg_key,
+ errcode,
+ body[:500],
+ )
+ return False
+ logger.debug("DingTalk message sent to {} with msgKey={}", chat_id, msg_key)
+ return True
+ except Exception as e:
+ logger.error("Error sending DingTalk message msgKey={} err={}", msg_key, e)
+ return False
+
+ async def _send_markdown_text(self, token: str, chat_id: str, content: str) -> bool:
+ return await self._send_batch_message(
+ token,
+ chat_id,
+ "sampleMarkdown",
+ {"text": content, "title": "Nanobot Reply"},
+ )
+
+ async def _send_media_ref(self, token: str, chat_id: str, media_ref: str) -> bool:
+ media_ref = (media_ref or "").strip()
+ if not media_ref:
+ return True
+
+ upload_type = self._guess_upload_type(media_ref)
+ if upload_type == "image" and self._is_http_url(media_ref):
+ ok = await self._send_batch_message(
+ token,
+ chat_id,
+ "sampleImageMsg",
+ {"photoURL": media_ref},
+ )
+ if ok:
+ return True
+ logger.warning("DingTalk image url send failed, trying upload fallback: {}", media_ref)
+
+ data, filename, content_type = await self._read_media_bytes(media_ref)
+ if not data:
+ logger.error("DingTalk media read failed: {}", media_ref)
+ return False
+
+ filename = filename or self._guess_filename(media_ref, upload_type)
+ file_type = Path(filename).suffix.lower().lstrip(".")
+ if not file_type:
+ guessed = mimetypes.guess_extension(content_type or "")
+ file_type = (guessed or ".bin").lstrip(".")
+ if file_type == "jpeg":
+ file_type = "jpg"
+
+ media_id = await self._upload_media(
+ token=token,
+ data=data,
+ media_type=upload_type,
+ filename=filename,
+ content_type=content_type,
+ )
+ if not media_id:
+ return False
+
+ if upload_type == "image":
+ # Verified in production: sampleImageMsg accepts media_id in photoURL.
+ ok = await self._send_batch_message(
+ token,
+ chat_id,
+ "sampleImageMsg",
+ {"photoURL": media_id},
+ )
+ if ok:
+ return True
+ logger.warning(
+ "DingTalk image media_id send failed, falling back to file: {}", media_ref
+ )
+
+ return await self._send_batch_message(
+ token,
+ chat_id,
+ "sampleFile",
+ {"mediaId": media_id, "fileName": filename, "fileType": file_type},
+ )
+
+ async def send(self, msg: OutboundMessage) -> None:
+ """Send a message through DingTalk."""
+ token = await self._get_access_token()
+ if not token:
+ return
+
+ if msg.content and msg.content.strip():
+ await self._send_markdown_text(token, msg.chat_id, msg.content.strip())
+
+ for media_ref in msg.media or []:
+ ok = await self._send_media_ref(token, msg.chat_id, media_ref)
+ if ok:
+ continue
+ logger.error("DingTalk media send failed for {}", media_ref)
+ # Send visible fallback so failures are observable by the user.
+ filename = self._guess_filename(media_ref, self._guess_upload_type(media_ref))
+ await self._send_markdown_text(
+ token,
+ msg.chat_id,
+ f"[Attachment send failed: {filename}]",
+ )
+
+ async def _on_message(
+ self,
+ content: str,
+ sender_id: str,
+ sender_name: str,
+ conversation_type: str | None = None,
+ conversation_id: str | None = None,
+ ) -> None:
+ """Handle incoming message (called by NanobotDingTalkHandler).
+
+ Delegates to BaseChannel._handle_message() which enforces allow_from
+ permission checks before publishing to the bus.
+ """
+ try:
+ logger.info("DingTalk inbound: {} from {}", content, sender_name)
+ is_group = conversation_type == "2" and conversation_id
+ chat_id = f"group:{conversation_id}" if is_group else sender_id
+ await self._handle_message(
+ sender_id=sender_id,
+ chat_id=chat_id,
+ content=str(content),
+ metadata={
+ "sender_name": sender_name,
+ "platform": "dingtalk",
+ "conversation_type": conversation_type,
+ },
+ )
+ except Exception as e:
+ logger.error("Error publishing DingTalk message: {}", e)
diff --git a/deeptutor/partners/channels/discord.py b/deeptutor/partners/channels/discord.py
new file mode 100644
index 000000000..7ae40e8d9
--- /dev/null
+++ b/deeptutor/partners/channels/discord.py
@@ -0,0 +1,397 @@
+"""Discord channel implementation using Discord Gateway websocket."""
+
+import asyncio
+import json
+from pathlib import Path
+from typing import Any, Literal
+
+import httpx
+from loguru import logger
+from pydantic import Field
+import websockets
+
+from deeptutor.partners.bus.events import OutboundMessage
+from deeptutor.partners.bus.queue import MessageBus
+from deeptutor.partners.channels.base import BaseChannel
+from deeptutor.partners.config.paths import get_media_dir
+from deeptutor.partners.config.schema import Base, DeliveryOverrides
+from deeptutor.partners.helpers import split_message
+
+DISCORD_API_BASE = "https://discord.com/api/v10"
+MAX_ATTACHMENT_BYTES = 20 * 1024 * 1024 # 20MB
+MAX_MESSAGE_LEN = 2000 # Discord message character limit
+
+
+class DiscordConfig(DeliveryOverrides):
+ """Discord channel configuration."""
+
+ enabled: bool = False
+ token: str = ""
+ allow_from: list[str] = Field(default_factory=list)
+ gateway_url: str = "wss://gateway.discord.gg/?v=10&encoding=json"
+ intents: int = 37377
+ group_policy: Literal["mention", "open"] = "mention"
+
+
+class DiscordChannel(BaseChannel):
+ """Discord channel using Gateway websocket."""
+
+ name = "discord"
+ display_name = "Discord"
+
+ @classmethod
+ def default_config(cls) -> dict[str, Any]:
+ return DiscordConfig().model_dump(by_alias=True)
+
+ def __init__(self, config: Any, bus: MessageBus):
+ if isinstance(config, dict):
+ config = DiscordConfig.model_validate(config)
+ super().__init__(config, bus)
+ self.config: DiscordConfig = config
+ self._ws: websockets.WebSocketClientProtocol | None = None
+ self._seq: int | None = None
+ self._heartbeat_task: asyncio.Task | None = None
+ self._typing_tasks: dict[str, asyncio.Task] = {}
+ self._http: httpx.AsyncClient | None = None
+ self._bot_user_id: str | None = None
+
+ async def start(self) -> None:
+ """Start the Discord gateway connection."""
+ if not self.config.token:
+ logger.error("Discord bot token not configured")
+ return
+
+ self._running = True
+ self._http = httpx.AsyncClient(timeout=30.0)
+
+ while self._running:
+ try:
+ logger.info("Connecting to Discord gateway...")
+ async with websockets.connect(self.config.gateway_url) as ws:
+ self._ws = ws
+ await self._gateway_loop()
+ except asyncio.CancelledError:
+ break
+ except Exception as e:
+ logger.warning("Discord gateway error: {}", e)
+ if self._running:
+ logger.info("Reconnecting to Discord gateway in 5 seconds...")
+ await asyncio.sleep(5)
+
+ async def stop(self) -> None:
+ """Stop the Discord channel."""
+ self._running = False
+ if self._heartbeat_task:
+ self._heartbeat_task.cancel()
+ self._heartbeat_task = None
+ for task in self._typing_tasks.values():
+ task.cancel()
+ self._typing_tasks.clear()
+ if self._ws:
+ await self._ws.close()
+ self._ws = None
+ if self._http:
+ await self._http.aclose()
+ self._http = None
+
+ async def send(self, msg: OutboundMessage) -> None:
+ """Send a message through Discord REST API, including file attachments."""
+ if not self._http:
+ logger.warning("Discord HTTP client not initialized")
+ return
+
+ url = f"{DISCORD_API_BASE}/channels/{msg.chat_id}/messages"
+ headers = {"Authorization": f"Bot {self.config.token}"}
+
+ try:
+ sent_media = False
+ failed_media: list[str] = []
+
+ # Send file attachments first
+ for media_path in msg.media or []:
+ if await self._send_file(url, headers, media_path, reply_to=msg.reply_to):
+ sent_media = True
+ else:
+ failed_media.append(Path(media_path).name)
+
+ # Send text content
+ chunks = split_message(msg.content or "", MAX_MESSAGE_LEN)
+ if not chunks and failed_media and not sent_media:
+ chunks = split_message(
+ "\n".join(f"[attachment: {name} - send failed]" for name in failed_media),
+ MAX_MESSAGE_LEN,
+ )
+ if not chunks:
+ return
+
+ for i, chunk in enumerate(chunks):
+ payload: dict[str, Any] = {"content": chunk}
+
+ # Let the first successful attachment carry the reply if present.
+ if i == 0 and msg.reply_to and not sent_media:
+ payload["message_reference"] = {"message_id": msg.reply_to}
+ payload["allowed_mentions"] = {"replied_user": False}
+
+ if not await self._send_payload(url, headers, payload):
+ break # Abort remaining chunks on failure
+ finally:
+ await self._stop_typing(msg.chat_id)
+
+ async def _send_payload(
+ self, url: str, headers: dict[str, str], payload: dict[str, Any]
+ ) -> bool:
+ """Send a single Discord API payload with retry on rate-limit. Returns True on success."""
+ for attempt in range(3):
+ try:
+ response = await self._http.post(url, headers=headers, json=payload)
+ if response.status_code == 429:
+ data = response.json()
+ retry_after = float(data.get("retry_after", 1.0))
+ logger.warning("Discord rate limited, retrying in {}s", retry_after)
+ await asyncio.sleep(retry_after)
+ continue
+ response.raise_for_status()
+ return True
+ except Exception as e:
+ if attempt == 2:
+ logger.error("Error sending Discord message: {}", e)
+ else:
+ await asyncio.sleep(1)
+ return False
+
+ async def _send_file(
+ self,
+ url: str,
+ headers: dict[str, str],
+ file_path: str,
+ reply_to: str | None = None,
+ ) -> bool:
+ """Send a file attachment via Discord REST API using multipart/form-data."""
+ path = Path(file_path)
+ if not path.is_file():
+ logger.warning("Discord file not found, skipping: {}", file_path)
+ return False
+
+ if path.stat().st_size > MAX_ATTACHMENT_BYTES:
+ logger.warning("Discord file too large (>20MB), skipping: {}", path.name)
+ return False
+
+ payload_json: dict[str, Any] = {}
+ if reply_to:
+ payload_json["message_reference"] = {"message_id": reply_to}
+ payload_json["allowed_mentions"] = {"replied_user": False}
+
+ for attempt in range(3):
+ try:
+ with open(path, "rb") as f:
+ files = {"files[0]": (path.name, f, "application/octet-stream")}
+ data: dict[str, Any] = {}
+ if payload_json:
+ data["payload_json"] = json.dumps(payload_json)
+ response = await self._http.post(url, headers=headers, files=files, data=data)
+ if response.status_code == 429:
+ resp_data = response.json()
+ retry_after = float(resp_data.get("retry_after", 1.0))
+ logger.warning("Discord rate limited, retrying in {}s", retry_after)
+ await asyncio.sleep(retry_after)
+ continue
+ response.raise_for_status()
+ logger.info("Discord file sent: {}", path.name)
+ return True
+ except Exception as e:
+ if attempt == 2:
+ logger.error("Error sending Discord file {}: {}", path.name, e)
+ else:
+ await asyncio.sleep(1)
+ return False
+
+ async def _gateway_loop(self) -> None:
+ """Main gateway loop: identify, heartbeat, dispatch events."""
+ if not self._ws:
+ return
+
+ async for raw in self._ws:
+ try:
+ data = json.loads(raw)
+ except json.JSONDecodeError:
+ logger.warning("Invalid JSON from Discord gateway: {}", raw[:100])
+ continue
+
+ op = data.get("op")
+ event_type = data.get("t")
+ seq = data.get("s")
+ payload = data.get("d")
+
+ if seq is not None:
+ self._seq = seq
+
+ if op == 10:
+ # HELLO: start heartbeat and identify
+ interval_ms = payload.get("heartbeat_interval", 45000)
+ await self._start_heartbeat(interval_ms / 1000)
+ await self._identify()
+ elif op == 0 and event_type == "READY":
+ logger.info("Discord gateway READY")
+ # Capture bot user ID for mention detection
+ user_data = payload.get("user") or {}
+ self._bot_user_id = user_data.get("id")
+ logger.info("Discord bot connected as user {}", self._bot_user_id)
+ elif op == 0 and event_type == "MESSAGE_CREATE":
+ await self._handle_message_create(payload)
+ elif op == 7:
+ # RECONNECT: exit loop to reconnect
+ logger.info("Discord gateway requested reconnect")
+ break
+ elif op == 9:
+ # INVALID_SESSION: reconnect
+ logger.warning("Discord gateway invalid session")
+ break
+
+ async def _identify(self) -> None:
+ """Send IDENTIFY payload."""
+ if not self._ws:
+ return
+
+ identify = {
+ "op": 2,
+ "d": {
+ "token": self.config.token,
+ "intents": self.config.intents,
+ "properties": {
+ "os": "deeptutor",
+ "browser": "deeptutor",
+ "device": "deeptutor",
+ },
+ },
+ }
+ await self._ws.send(json.dumps(identify))
+
+ async def _start_heartbeat(self, interval_s: float) -> None:
+ """Start or restart the heartbeat loop."""
+ if self._heartbeat_task:
+ self._heartbeat_task.cancel()
+
+ async def heartbeat_loop() -> None:
+ while self._running and self._ws:
+ payload = {"op": 1, "d": self._seq}
+ try:
+ await self._ws.send(json.dumps(payload))
+ except Exception as e:
+ logger.warning("Discord heartbeat failed: {}", e)
+ break
+ await asyncio.sleep(interval_s)
+
+ self._heartbeat_task = asyncio.create_task(heartbeat_loop())
+
+ async def _handle_message_create(self, payload: dict[str, Any]) -> None:
+ """Handle incoming Discord messages."""
+ author = payload.get("author") or {}
+ if author.get("bot"):
+ return
+
+ sender_id = str(author.get("id", ""))
+ channel_id = str(payload.get("channel_id", ""))
+ content = payload.get("content") or ""
+ guild_id = payload.get("guild_id")
+
+ if not sender_id or not channel_id:
+ return
+
+ if not self.is_allowed(sender_id):
+ return
+
+ # Check group channel policy (DMs always respond if is_allowed passes)
+ if guild_id is not None:
+ if not self._should_respond_in_group(payload, content):
+ return
+
+ content_parts = [content] if content else []
+ media_paths: list[str] = []
+ media_dir = get_media_dir("discord")
+
+ for attachment in payload.get("attachments") or []:
+ url = attachment.get("url")
+ filename = attachment.get("filename") or "attachment"
+ size = attachment.get("size") or 0
+ if not url or not self._http:
+ continue
+ if size and size > MAX_ATTACHMENT_BYTES:
+ content_parts.append(f"[attachment: {filename} - too large]")
+ continue
+ try:
+ media_dir.mkdir(parents=True, exist_ok=True)
+ file_path = (
+ media_dir / f"{attachment.get('id', 'file')}_{filename.replace('/', '_')}"
+ )
+ resp = await self._http.get(url)
+ resp.raise_for_status()
+ file_path.write_bytes(resp.content)
+ media_paths.append(str(file_path))
+ content_parts.append(f"[attachment: {file_path}]")
+ except Exception as e:
+ logger.warning("Failed to download Discord attachment: {}", e)
+ content_parts.append(f"[attachment: {filename} - download failed]")
+
+ reply_to = (payload.get("referenced_message") or {}).get("id")
+
+ await self._start_typing(channel_id)
+
+ await self._handle_message(
+ sender_id=sender_id,
+ chat_id=channel_id,
+ content="\n".join(p for p in content_parts if p) or "[empty message]",
+ media=media_paths,
+ metadata={
+ "message_id": str(payload.get("id", "")),
+ "guild_id": guild_id,
+ "reply_to": reply_to,
+ },
+ )
+
+ def _should_respond_in_group(self, payload: dict[str, Any], content: str) -> bool:
+ """Check if bot should respond in a group channel based on policy."""
+ if self.config.group_policy == "open":
+ return True
+
+ if self.config.group_policy == "mention":
+ # Check if bot was mentioned in the message
+ if self._bot_user_id:
+ # Check mentions array
+ mentions = payload.get("mentions") or []
+ for mention in mentions:
+ if str(mention.get("id")) == self._bot_user_id:
+ return True
+ # Also check content for mention format <@USER_ID>
+ if f"<@{self._bot_user_id}>" in content or f"<@!{self._bot_user_id}>" in content:
+ return True
+ logger.debug(
+ "Discord message in {} ignored (bot not mentioned)", payload.get("channel_id")
+ )
+ return False
+
+ return True
+
+ async def _start_typing(self, channel_id: str) -> None:
+ """Start periodic typing indicator for a channel."""
+ await self._stop_typing(channel_id)
+
+ async def typing_loop() -> None:
+ url = f"{DISCORD_API_BASE}/channels/{channel_id}/typing"
+ headers = {"Authorization": f"Bot {self.config.token}"}
+ while self._running:
+ try:
+ await self._http.post(url, headers=headers)
+ except asyncio.CancelledError:
+ return
+ except Exception as e:
+ logger.debug("Discord typing indicator failed for {}: {}", channel_id, e)
+ return
+ await asyncio.sleep(8)
+
+ self._typing_tasks[channel_id] = asyncio.create_task(typing_loop())
+
+ async def _stop_typing(self, channel_id: str) -> None:
+ """Stop typing indicator for a channel."""
+ task = self._typing_tasks.pop(channel_id, None)
+ if task:
+ task.cancel()
diff --git a/deeptutor/partners/channels/email.py b/deeptutor/partners/channels/email.py
new file mode 100644
index 000000000..41ed6c008
--- /dev/null
+++ b/deeptutor/partners/channels/email.py
@@ -0,0 +1,454 @@
+"""Email channel implementation using IMAP polling + SMTP replies."""
+
+import asyncio
+from datetime import date
+from email import policy
+from email.header import decode_header, make_header
+from email.message import EmailMessage
+from email.parser import BytesParser
+from email.utils import parseaddr
+import html
+import imaplib
+import re
+import smtplib
+import ssl
+from typing import Any
+
+from loguru import logger
+from pydantic import Field
+
+from deeptutor.partners.bus.events import OutboundMessage
+from deeptutor.partners.bus.queue import MessageBus
+from deeptutor.partners.channels.base import BaseChannel
+from deeptutor.partners.config.schema import Base, DeliveryOverrides
+
+
+class EmailConfig(DeliveryOverrides):
+ """Email channel configuration (IMAP inbound + SMTP outbound)."""
+
+ enabled: bool = False
+ consent_granted: bool = False
+
+ imap_host: str = ""
+ imap_port: int = 993
+ imap_username: str = ""
+ imap_password: str = ""
+ imap_mailbox: str = "INBOX"
+ imap_use_ssl: bool = True
+
+ smtp_host: str = ""
+ smtp_port: int = 587
+ smtp_username: str = ""
+ smtp_password: str = ""
+ smtp_use_tls: bool = True
+ smtp_use_ssl: bool = False
+ from_address: str = ""
+
+ auto_reply_enabled: bool = True
+ poll_interval_seconds: int = 30
+ mark_seen: bool = True
+ max_body_chars: int = 12000
+ subject_prefix: str = "Re: "
+ allow_from: list[str] = Field(default_factory=list)
+
+
+class EmailChannel(BaseChannel):
+ """
+ Email channel.
+
+ Inbound:
+ - Poll IMAP mailbox for unread messages.
+ - Convert each message into an inbound event.
+
+ Outbound:
+ - Send responses via SMTP back to the sender address.
+ """
+
+ name = "email"
+ display_name = "Email"
+ _IMAP_MONTHS = (
+ "Jan",
+ "Feb",
+ "Mar",
+ "Apr",
+ "May",
+ "Jun",
+ "Jul",
+ "Aug",
+ "Sep",
+ "Oct",
+ "Nov",
+ "Dec",
+ )
+
+ @classmethod
+ def default_config(cls) -> dict[str, Any]:
+ return EmailConfig().model_dump(by_alias=True)
+
+ def __init__(self, config: Any, bus: MessageBus):
+ if isinstance(config, dict):
+ config = EmailConfig.model_validate(config)
+ super().__init__(config, bus)
+ self.config: EmailConfig = config
+ self._last_subject_by_chat: dict[str, str] = {}
+ self._last_message_id_by_chat: dict[str, str] = {}
+ self._processed_uids: set[str] = set() # Capped to prevent unbounded growth
+ self._MAX_PROCESSED_UIDS = 100000
+
+ async def start(self) -> None:
+ """Start polling IMAP for inbound emails."""
+ if not self.config.consent_granted:
+ logger.warning(
+ "Email channel disabled: consent_granted is false. "
+ "Set channels.email.consentGranted=true after explicit user permission."
+ )
+ return
+
+ if not self._validate_config():
+ return
+
+ self._running = True
+ logger.info("Starting Email channel (IMAP polling mode)...")
+
+ poll_seconds = max(5, int(self.config.poll_interval_seconds))
+ while self._running:
+ try:
+ inbound_items = await asyncio.to_thread(self._fetch_new_messages)
+ for item in inbound_items:
+ sender = item["sender"]
+ subject = item.get("subject", "")
+ message_id = item.get("message_id", "")
+
+ if subject:
+ self._last_subject_by_chat[sender] = subject
+ if message_id:
+ self._last_message_id_by_chat[sender] = message_id
+
+ await self._handle_message(
+ sender_id=sender,
+ chat_id=sender,
+ content=item["content"],
+ metadata=item.get("metadata", {}),
+ )
+ except Exception as e:
+ logger.error("Email polling error: {}", e)
+
+ await asyncio.sleep(poll_seconds)
+
+ async def stop(self) -> None:
+ """Stop polling loop."""
+ self._running = False
+
+ async def send(self, msg: OutboundMessage) -> None:
+ """Send email via SMTP."""
+ if not self.config.consent_granted:
+ logger.warning("Skip email send: consent_granted is false")
+ return
+
+ if not self.config.smtp_host:
+ logger.warning("Email channel SMTP host not configured")
+ return
+
+ to_addr = msg.chat_id.strip()
+ if not to_addr:
+ logger.warning("Email channel missing recipient address")
+ return
+
+ # Determine if this is a reply (recipient has sent us an email before)
+ is_reply = to_addr in self._last_subject_by_chat
+ force_send = bool((msg.metadata or {}).get("force_send"))
+
+ # autoReplyEnabled only controls automatic replies, not proactive sends
+ if is_reply and not self.config.auto_reply_enabled and not force_send:
+ logger.info("Skip automatic email reply to {}: auto_reply_enabled is false", to_addr)
+ return
+
+ base_subject = self._last_subject_by_chat.get(to_addr, "TutorBot reply")
+ subject = self._reply_subject(base_subject)
+ if msg.metadata and isinstance(msg.metadata.get("subject"), str):
+ override = msg.metadata["subject"].strip()
+ if override:
+ subject = override
+
+ email_msg = EmailMessage()
+ email_msg["From"] = (
+ self.config.from_address or self.config.smtp_username or self.config.imap_username
+ )
+ email_msg["To"] = to_addr
+ email_msg["Subject"] = subject
+ email_msg.set_content(msg.content or "")
+
+ in_reply_to = self._last_message_id_by_chat.get(to_addr)
+ if in_reply_to:
+ email_msg["In-Reply-To"] = in_reply_to
+ email_msg["References"] = in_reply_to
+
+ try:
+ await asyncio.to_thread(self._smtp_send, email_msg)
+ except Exception as e:
+ logger.error("Error sending email to {}: {}", to_addr, e)
+ raise
+
+ def _validate_config(self) -> bool:
+ missing = []
+ if not self.config.imap_host:
+ missing.append("imap_host")
+ if not self.config.imap_username:
+ missing.append("imap_username")
+ if not self.config.imap_password:
+ missing.append("imap_password")
+ if not self.config.smtp_host:
+ missing.append("smtp_host")
+ if not self.config.smtp_username:
+ missing.append("smtp_username")
+ if not self.config.smtp_password:
+ missing.append("smtp_password")
+
+ if missing:
+ logger.error("Email channel not configured, missing: {}", ", ".join(missing))
+ return False
+ return True
+
+ def _smtp_send(self, msg: EmailMessage) -> None:
+ timeout = 30
+ if self.config.smtp_use_ssl:
+ with smtplib.SMTP_SSL(
+ self.config.smtp_host,
+ self.config.smtp_port,
+ timeout=timeout,
+ ) as smtp:
+ smtp.login(self.config.smtp_username, self.config.smtp_password)
+ smtp.send_message(msg)
+ return
+
+ with smtplib.SMTP(self.config.smtp_host, self.config.smtp_port, timeout=timeout) as smtp:
+ if self.config.smtp_use_tls:
+ smtp.starttls(context=ssl.create_default_context())
+ smtp.login(self.config.smtp_username, self.config.smtp_password)
+ smtp.send_message(msg)
+
+ def _fetch_new_messages(self) -> list[dict[str, Any]]:
+ """Poll IMAP and return parsed unread messages."""
+ return self._fetch_messages(
+ search_criteria=("UNSEEN",),
+ mark_seen=self.config.mark_seen,
+ dedupe=True,
+ limit=0,
+ )
+
+ def fetch_messages_between_dates(
+ self,
+ start_date: date,
+ end_date: date,
+ limit: int = 20,
+ ) -> list[dict[str, Any]]:
+ """
+ Fetch messages in [start_date, end_date) by IMAP date search.
+
+ This is used for historical summarization tasks (e.g. "yesterday").
+ """
+ if end_date <= start_date:
+ return []
+
+ return self._fetch_messages(
+ search_criteria=(
+ "SINCE",
+ self._format_imap_date(start_date),
+ "BEFORE",
+ self._format_imap_date(end_date),
+ ),
+ mark_seen=False,
+ dedupe=False,
+ limit=max(1, int(limit)),
+ )
+
+ def _fetch_messages(
+ self,
+ search_criteria: tuple[str, ...],
+ mark_seen: bool,
+ dedupe: bool,
+ limit: int,
+ ) -> list[dict[str, Any]]:
+ """Fetch messages by arbitrary IMAP search criteria."""
+ messages: list[dict[str, Any]] = []
+ mailbox = self.config.imap_mailbox or "INBOX"
+
+ client: imaplib.IMAP4 | imaplib.IMAP4_SSL
+ if self.config.imap_use_ssl:
+ client = imaplib.IMAP4_SSL(self.config.imap_host, self.config.imap_port)
+ else:
+ client = imaplib.IMAP4(self.config.imap_host, self.config.imap_port)
+
+ try:
+ client.login(self.config.imap_username, self.config.imap_password)
+ status, _ = client.select(mailbox)
+ if status != "OK":
+ return messages
+
+ status, data = client.search(None, *search_criteria)
+ if status != "OK" or not data:
+ return messages
+
+ ids = data[0].split()
+ if limit > 0 and len(ids) > limit:
+ ids = ids[-limit:]
+ for imap_id in ids:
+ status, fetched = client.fetch(imap_id, "(BODY.PEEK[] UID)")
+ if status != "OK" or not fetched:
+ continue
+
+ raw_bytes = self._extract_message_bytes(fetched)
+ if raw_bytes is None:
+ continue
+
+ uid = self._extract_uid(fetched)
+ if dedupe and uid and uid in self._processed_uids:
+ continue
+
+ parsed = BytesParser(policy=policy.default).parsebytes(raw_bytes)
+ sender = parseaddr(parsed.get("From", ""))[1].strip().lower()
+ if not sender:
+ continue
+
+ subject = self._decode_header_value(parsed.get("Subject", ""))
+ date_value = parsed.get("Date", "")
+ message_id = parsed.get("Message-ID", "").strip()
+ body = self._extract_text_body(parsed)
+
+ if not body:
+ body = "(empty email body)"
+
+ body = body[: self.config.max_body_chars]
+ content = (
+ f"Email received.\n"
+ f"From: {sender}\n"
+ f"Subject: {subject}\n"
+ f"Date: {date_value}\n\n"
+ f"{body}"
+ )
+
+ metadata = {
+ "message_id": message_id,
+ "subject": subject,
+ "date": date_value,
+ "sender_email": sender,
+ "uid": uid,
+ }
+ messages.append(
+ {
+ "sender": sender,
+ "subject": subject,
+ "message_id": message_id,
+ "content": content,
+ "metadata": metadata,
+ }
+ )
+
+ if dedupe and uid:
+ self._processed_uids.add(uid)
+ # mark_seen is the primary dedup; this set is a safety net
+ if len(self._processed_uids) > self._MAX_PROCESSED_UIDS:
+ # Evict a random half to cap memory; mark_seen is the primary dedup
+ self._processed_uids = set(
+ list(self._processed_uids)[len(self._processed_uids) // 2 :]
+ )
+
+ if mark_seen:
+ client.store(imap_id, "+FLAGS", "\\Seen")
+ finally:
+ try:
+ client.logout()
+ except Exception:
+ pass
+
+ return messages
+
+ @classmethod
+ def _format_imap_date(cls, value: date) -> str:
+ """Format date for IMAP search (always English month abbreviations)."""
+ month = cls._IMAP_MONTHS[value.month - 1]
+ return f"{value.day:02d}-{month}-{value.year}"
+
+ @staticmethod
+ def _extract_message_bytes(fetched: list[Any]) -> bytes | None:
+ for item in fetched:
+ if (
+ isinstance(item, tuple)
+ and len(item) >= 2
+ and isinstance(item[1], (bytes, bytearray))
+ ):
+ return bytes(item[1])
+ return None
+
+ @staticmethod
+ def _extract_uid(fetched: list[Any]) -> str:
+ for item in fetched:
+ if isinstance(item, tuple) and item and isinstance(item[0], (bytes, bytearray)):
+ head = bytes(item[0]).decode("utf-8", errors="ignore")
+ m = re.search(r"UID\s+(\d+)", head)
+ if m:
+ return m.group(1)
+ return ""
+
+ @staticmethod
+ def _decode_header_value(value: str) -> str:
+ if not value:
+ return ""
+ try:
+ return str(make_header(decode_header(value)))
+ except Exception:
+ return value
+
+ @classmethod
+ def _extract_text_body(cls, msg: Any) -> str:
+ """Best-effort extraction of readable body text."""
+ if msg.is_multipart():
+ plain_parts: list[str] = []
+ html_parts: list[str] = []
+ for part in msg.walk():
+ if part.get_content_disposition() == "attachment":
+ continue
+ content_type = part.get_content_type()
+ try:
+ payload = part.get_content()
+ except Exception:
+ payload_bytes = part.get_payload(decode=True) or b""
+ charset = part.get_content_charset() or "utf-8"
+ payload = payload_bytes.decode(charset, errors="replace")
+ if not isinstance(payload, str):
+ continue
+ if content_type == "text/plain":
+ plain_parts.append(payload)
+ elif content_type == "text/html":
+ html_parts.append(payload)
+ if plain_parts:
+ return "\n\n".join(plain_parts).strip()
+ if html_parts:
+ return cls._html_to_text("\n\n".join(html_parts)).strip()
+ return ""
+
+ try:
+ payload = msg.get_content()
+ except Exception:
+ payload_bytes = msg.get_payload(decode=True) or b""
+ charset = msg.get_content_charset() or "utf-8"
+ payload = payload_bytes.decode(charset, errors="replace")
+ if not isinstance(payload, str):
+ return ""
+ if msg.get_content_type() == "text/html":
+ return cls._html_to_text(payload).strip()
+ return payload.strip()
+
+ @staticmethod
+ def _html_to_text(raw_html: str) -> str:
+ text = re.sub(r"<\s*br\s*/?>", "\n", raw_html, flags=re.IGNORECASE)
+ text = re.sub(r"<\s*/\s*p\s*>", "\n", text, flags=re.IGNORECASE)
+ text = re.sub(r"<[^>]+>", "", text)
+ return html.unescape(text)
+
+ def _reply_subject(self, base_subject: str) -> str:
+ subject = (base_subject or "").strip() or "TutorBot reply"
+ prefix = self.config.subject_prefix or "Re: "
+ if subject.lower().startswith("re:"):
+ return subject
+ return f"{prefix}{subject}"
diff --git a/deeptutor/partners/channels/feishu.py b/deeptutor/partners/channels/feishu.py
new file mode 100644
index 000000000..f13e4e87f
--- /dev/null
+++ b/deeptutor/partners/channels/feishu.py
@@ -0,0 +1,1117 @@
+"""Feishu/Lark channel implementation using lark-oapi SDK with WebSocket long connection."""
+
+import asyncio
+from collections import OrderedDict
+import importlib.util
+import json
+import os
+import re
+import threading
+from typing import Any, Literal
+
+from loguru import logger
+from pydantic import Field
+
+from deeptutor.partners.bus.events import OutboundMessage
+from deeptutor.partners.bus.queue import MessageBus
+from deeptutor.partners.channels.base import BaseChannel
+from deeptutor.partners.config.paths import get_media_dir
+from deeptutor.partners.config.schema import Base, DeliveryOverrides
+
+FEISHU_AVAILABLE = importlib.util.find_spec("lark_oapi") is not None
+
+# Message type display mapping
+MSG_TYPE_MAP = {
+ "image": "[image]",
+ "audio": "[audio]",
+ "file": "[file]",
+ "sticker": "[sticker]",
+}
+
+
+def _extract_share_card_content(content_json: dict, msg_type: str) -> str:
+ """Extract text representation from share cards and interactive messages."""
+ parts = []
+
+ if msg_type == "share_chat":
+ parts.append(f"[shared chat: {content_json.get('chat_id', '')}]")
+ elif msg_type == "share_user":
+ parts.append(f"[shared user: {content_json.get('user_id', '')}]")
+ elif msg_type == "interactive":
+ parts.extend(_extract_interactive_content(content_json))
+ elif msg_type == "share_calendar_event":
+ parts.append(f"[shared calendar event: {content_json.get('event_key', '')}]")
+ elif msg_type == "system":
+ parts.append("[system message]")
+ elif msg_type == "merge_forward":
+ parts.append("[merged forward messages]")
+
+ return "\n".join(parts) if parts else f"[{msg_type}]"
+
+
+def _extract_interactive_content(content: dict) -> list[str]:
+ """Recursively extract text and links from interactive card content."""
+ parts = []
+
+ if isinstance(content, str):
+ try:
+ content = json.loads(content)
+ except (json.JSONDecodeError, TypeError):
+ return [content] if content.strip() else []
+
+ if not isinstance(content, dict):
+ return parts
+
+ if "title" in content:
+ title = content["title"]
+ if isinstance(title, dict):
+ title_content = title.get("content", "") or title.get("text", "")
+ if title_content:
+ parts.append(f"title: {title_content}")
+ elif isinstance(title, str):
+ parts.append(f"title: {title}")
+
+ for elements in (
+ content.get("elements", []) if isinstance(content.get("elements"), list) else []
+ ):
+ for element in elements:
+ parts.extend(_extract_element_content(element))
+
+ card = content.get("card", {})
+ if card:
+ parts.extend(_extract_interactive_content(card))
+
+ header = content.get("header", {})
+ if header:
+ header_title = header.get("title", {})
+ if isinstance(header_title, dict):
+ header_text = header_title.get("content", "") or header_title.get("text", "")
+ if header_text:
+ parts.append(f"title: {header_text}")
+
+ return parts
+
+
+def _extract_element_content(element: dict) -> list[str]:
+ """Extract content from a single card element."""
+ parts = []
+
+ if not isinstance(element, dict):
+ return parts
+
+ tag = element.get("tag", "")
+
+ if tag in ("markdown", "lark_md"):
+ content = element.get("content", "")
+ if content:
+ parts.append(content)
+
+ elif tag == "div":
+ text = element.get("text", {})
+ if isinstance(text, dict):
+ text_content = text.get("content", "") or text.get("text", "")
+ if text_content:
+ parts.append(text_content)
+ elif isinstance(text, str):
+ parts.append(text)
+ for field in element.get("fields", []):
+ if isinstance(field, dict):
+ field_text = field.get("text", {})
+ if isinstance(field_text, dict):
+ c = field_text.get("content", "")
+ if c:
+ parts.append(c)
+
+ elif tag == "a":
+ href = element.get("href", "")
+ text = element.get("text", "")
+ if href:
+ parts.append(f"link: {href}")
+ if text:
+ parts.append(text)
+
+ elif tag == "button":
+ text = element.get("text", {})
+ if isinstance(text, dict):
+ c = text.get("content", "")
+ if c:
+ parts.append(c)
+ url = element.get("url", "") or element.get("multi_url", {}).get("url", "")
+ if url:
+ parts.append(f"link: {url}")
+
+ elif tag == "img":
+ alt = element.get("alt", {})
+ parts.append(alt.get("content", "[image]") if isinstance(alt, dict) else "[image]")
+
+ elif tag == "note":
+ for ne in element.get("elements", []):
+ parts.extend(_extract_element_content(ne))
+
+ elif tag == "column_set":
+ for col in element.get("columns", []):
+ for ce in col.get("elements", []):
+ parts.extend(_extract_element_content(ce))
+
+ elif tag == "plain_text":
+ content = element.get("content", "")
+ if content:
+ parts.append(content)
+
+ else:
+ for ne in element.get("elements", []):
+ parts.extend(_extract_element_content(ne))
+
+ return parts
+
+
+def _extract_post_content(content_json: dict) -> tuple[str, list[str]]:
+ """Extract text and image keys from Feishu post (rich text) message.
+
+ Handles three payload shapes:
+ - Direct: {"title": "...", "content": [[...]]}
+ - Localized: {"zh_cn": {"title": "...", "content": [...]}}
+ - Wrapped: {"post": {"zh_cn": {"title": "...", "content": [...]}}}
+ """
+
+ def _parse_block(block: dict) -> tuple[str | None, list[str]]:
+ if not isinstance(block, dict) or not isinstance(block.get("content"), list):
+ return None, []
+ texts, images = [], []
+ if title := block.get("title"):
+ texts.append(title)
+ for row in block["content"]:
+ if not isinstance(row, list):
+ continue
+ for el in row:
+ if not isinstance(el, dict):
+ continue
+ tag = el.get("tag")
+ if tag in ("text", "a"):
+ texts.append(el.get("text", ""))
+ elif tag == "at":
+ texts.append(f"@{el.get('user_name', 'user')}")
+ elif tag == "img" and (key := el.get("image_key")):
+ images.append(key)
+ return (" ".join(texts).strip() or None), images
+
+ # Unwrap optional {"post": ...} envelope
+ root = content_json
+ if isinstance(root, dict) and isinstance(root.get("post"), dict):
+ root = root["post"]
+ if not isinstance(root, dict):
+ return "", []
+
+ # Direct format
+ if "content" in root:
+ text, imgs = _parse_block(root)
+ if text or imgs:
+ return text or "", imgs
+
+ # Localized: prefer known locales, then fall back to any dict child
+ for key in ("zh_cn", "en_us", "ja_jp"):
+ if key in root:
+ text, imgs = _parse_block(root[key])
+ if text or imgs:
+ return text or "", imgs
+ for val in root.values():
+ if isinstance(val, dict):
+ text, imgs = _parse_block(val)
+ if text or imgs:
+ return text or "", imgs
+
+ return "", []
+
+
+def _extract_post_text(content_json: dict) -> str:
+ """Extract plain text from Feishu post (rich text) message content.
+
+ Legacy wrapper for _extract_post_content, returns only text.
+ """
+ text, _ = _extract_post_content(content_json)
+ return text
+
+
+class FeishuConfig(DeliveryOverrides):
+ """Feishu/Lark channel configuration using WebSocket long connection."""
+
+ enabled: bool = False
+ app_id: str = ""
+ app_secret: str = ""
+ encrypt_key: str = ""
+ verification_token: str = ""
+ allow_from: list[str] = Field(default_factory=list)
+ react_emoji: str = "THUMBSUP"
+ group_policy: Literal["open", "mention"] = "mention"
+
+
+class FeishuChannel(BaseChannel):
+ """
+ Feishu/Lark channel using WebSocket long connection.
+
+ Uses WebSocket to receive events - no public IP or webhook required.
+
+ Requires:
+ - App ID and App Secret from Feishu Open Platform
+ - Bot capability enabled
+ - Event subscription enabled (im.message.receive_v1)
+ """
+
+ name = "feishu"
+ display_name = "Feishu"
+
+ @classmethod
+ def default_config(cls) -> dict[str, Any]:
+ return FeishuConfig().model_dump(by_alias=True)
+
+ def __init__(self, config: Any, bus: MessageBus):
+ if isinstance(config, dict):
+ config = FeishuConfig.model_validate(config)
+ super().__init__(config, bus)
+ self.config: FeishuConfig = config
+ self._client: Any = None
+ self._ws_client: Any = None
+ self._ws_thread: threading.Thread | None = None
+ self._processed_message_ids: OrderedDict[str, None] = OrderedDict() # Ordered dedup cache
+ self._loop: asyncio.AbstractEventLoop | None = None
+
+ @staticmethod
+ def _register_optional_event(builder: Any, method_name: str, handler: Any) -> Any:
+ """Register an event handler only when the SDK supports it."""
+ method = getattr(builder, method_name, None)
+ return method(handler) if callable(method) else builder
+
+ async def start(self) -> None:
+ """Start the Feishu bot with WebSocket long connection."""
+ if not FEISHU_AVAILABLE:
+ logger.error("Feishu SDK not installed. Run: pip install lark-oapi")
+ return
+
+ if not self.config.app_id or not self.config.app_secret:
+ logger.error("Feishu app_id and app_secret not configured")
+ return
+
+ import lark_oapi as lark
+
+ self._running = True
+ self._loop = asyncio.get_running_loop()
+
+ # Create Lark client for sending messages
+ self._client = (
+ lark.Client.builder()
+ .app_id(self.config.app_id)
+ .app_secret(self.config.app_secret)
+ .log_level(lark.LogLevel.INFO)
+ .build()
+ )
+ builder = lark.EventDispatcherHandler.builder(
+ self.config.encrypt_key or "",
+ self.config.verification_token or "",
+ ).register_p2_im_message_receive_v1(self._on_message_sync)
+ builder = self._register_optional_event(
+ builder, "register_p2_im_message_reaction_created_v1", self._on_reaction_created
+ )
+ builder = self._register_optional_event(
+ builder, "register_p2_im_message_message_read_v1", self._on_message_read
+ )
+ builder = self._register_optional_event(
+ builder,
+ "register_p2_im_chat_access_event_bot_p2p_chat_entered_v1",
+ self._on_bot_p2p_chat_entered,
+ )
+ event_handler = builder.build()
+
+ # Create WebSocket client for long connection
+ self._ws_client = lark.ws.Client(
+ self.config.app_id,
+ self.config.app_secret,
+ event_handler=event_handler,
+ log_level=lark.LogLevel.INFO,
+ )
+
+ # Start WebSocket client in a separate thread with reconnect loop.
+ # A dedicated event loop is created for this thread so that lark_oapi's
+ # module-level `loop = asyncio.get_event_loop()` picks up an idle loop
+ # instead of the already-running main asyncio loop, which would cause
+ # "This event loop is already running" errors.
+ def run_ws():
+ import time
+
+ import lark_oapi.ws.client as _lark_ws_client
+
+ ws_loop = asyncio.new_event_loop()
+ asyncio.set_event_loop(ws_loop)
+ # Patch the module-level loop used by lark's ws Client.start()
+ _lark_ws_client.loop = ws_loop
+ try:
+ while self._running:
+ try:
+ self._ws_client.start()
+ except Exception as e:
+ logger.warning("Feishu WebSocket error: {}", e)
+ if self._running:
+ time.sleep(5)
+ finally:
+ ws_loop.close()
+
+ self._ws_thread = threading.Thread(target=run_ws, daemon=True)
+ self._ws_thread.start()
+
+ logger.info("Feishu bot started with WebSocket long connection")
+ logger.info("No public IP required - using WebSocket to receive events")
+
+ # Keep running until stopped
+ while self._running:
+ await asyncio.sleep(1)
+
+ async def stop(self) -> None:
+ """
+ Stop the Feishu bot.
+
+ Notice: lark.ws.Client does not expose stop method, simply exiting the program will close the client.
+
+ Reference: https://github.com/larksuite/oapi-sdk-python/blob/v2_main/lark_oapi/ws/client.py#L86
+ """
+ self._running = False
+ logger.info("Feishu bot stopped")
+
+ def _is_bot_mentioned(self, message: Any) -> bool:
+ """Check if the bot is @mentioned in the message."""
+ raw_content = message.content or ""
+ if "@_all" in raw_content:
+ return True
+
+ for mention in getattr(message, "mentions", None) or []:
+ mid = getattr(mention, "id", None)
+ if not mid:
+ continue
+ # Bot mentions have no user_id (None or "") but a valid open_id
+ if not getattr(mid, "user_id", None) and (
+ getattr(mid, "open_id", None) or ""
+ ).startswith("ou_"):
+ return True
+ return False
+
+ def _is_group_message_for_bot(self, message: Any) -> bool:
+ """Allow group messages when policy is open or bot is @mentioned."""
+ if self.config.group_policy == "open":
+ return True
+ return self._is_bot_mentioned(message)
+
+ def _add_reaction_sync(self, message_id: str, emoji_type: str) -> None:
+ """Sync helper for adding reaction (runs in thread pool)."""
+ from lark_oapi.api.im.v1 import (
+ CreateMessageReactionRequest,
+ CreateMessageReactionRequestBody,
+ Emoji,
+ )
+
+ try:
+ request = (
+ CreateMessageReactionRequest.builder()
+ .message_id(message_id)
+ .request_body(
+ CreateMessageReactionRequestBody.builder()
+ .reaction_type(Emoji.builder().emoji_type(emoji_type).build())
+ .build()
+ )
+ .build()
+ )
+
+ response = self._client.im.v1.message_reaction.create(request)
+
+ if not response.success():
+ logger.warning(
+ "Failed to add reaction: code={}, msg={}", response.code, response.msg
+ )
+ else:
+ logger.debug("Added {} reaction to message {}", emoji_type, message_id)
+ except Exception as e:
+ logger.warning("Error adding reaction: {}", e)
+
+ async def _add_reaction(self, message_id: str, emoji_type: str = "THUMBSUP") -> None:
+ """
+ Add a reaction emoji to a message (non-blocking).
+
+ Common emoji types: THUMBSUP, OK, EYES, DONE, OnIt, HEART
+ """
+ if not self._client:
+ return
+
+ loop = asyncio.get_running_loop()
+ await loop.run_in_executor(None, self._add_reaction_sync, message_id, emoji_type)
+
+ # Regex to match markdown tables (header + separator + data rows)
+ _TABLE_RE = re.compile(
+ r"((?:^[ \t]*\|.+\|[ \t]*\n)(?:^[ \t]*\|[-:\s|]+\|[ \t]*\n)(?:^[ \t]*\|.+\|[ \t]*\n?)+)",
+ re.MULTILINE,
+ )
+
+ _HEADING_RE = re.compile(r"^(#{1,6})\s+(.+)$", re.MULTILINE)
+
+ _CODE_BLOCK_RE = re.compile(r"(```[\s\S]*?```)", re.MULTILINE)
+
+ @staticmethod
+ def _parse_md_table(table_text: str) -> dict | None:
+ """Parse a markdown table into a Feishu table element."""
+ lines = [_line.strip() for _line in table_text.strip().split("\n") if _line.strip()]
+ if len(lines) < 3:
+ return None
+
+ def split(_line: str) -> list[str]:
+ return [c.strip() for c in _line.strip("|").split("|")]
+
+ headers = split(lines[0])
+ rows = [split(_line) for _line in lines[2:]]
+ columns = [
+ {"tag": "column", "name": f"c{i}", "display_name": h, "width": "auto"}
+ for i, h in enumerate(headers)
+ ]
+ return {
+ "tag": "table",
+ "page_size": len(rows) + 1,
+ "columns": columns,
+ "rows": [
+ {f"c{i}": r[i] if i < len(r) else "" for i in range(len(headers))} for r in rows
+ ],
+ }
+
+ def _build_card_elements(self, content: str) -> list[dict]:
+ """Split content into div/markdown + table elements for Feishu card."""
+ elements, last_end = [], 0
+ for m in self._TABLE_RE.finditer(content):
+ before = content[last_end : m.start()]
+ if before.strip():
+ elements.extend(self._split_headings(before))
+ elements.append(
+ self._parse_md_table(m.group(1)) or {"tag": "markdown", "content": m.group(1)}
+ )
+ last_end = m.end()
+ remaining = content[last_end:]
+ if remaining.strip():
+ elements.extend(self._split_headings(remaining))
+ return elements or [{"tag": "markdown", "content": content}]
+
+ @staticmethod
+ def _split_elements_by_table_limit(
+ elements: list[dict], max_tables: int = 1
+ ) -> list[list[dict]]:
+ """Split card elements into groups with at most *max_tables* table elements each.
+
+ Feishu cards have a hard limit of one table per card (API error 11310).
+ When the rendered content contains multiple markdown tables each table is
+ placed in a separate card message so every table reaches the user.
+ """
+ if not elements:
+ return [[]]
+ groups: list[list[dict]] = []
+ current: list[dict] = []
+ table_count = 0
+ for el in elements:
+ if el.get("tag") == "table":
+ if table_count >= max_tables:
+ if current:
+ groups.append(current)
+ current = []
+ table_count = 0
+ current.append(el)
+ table_count += 1
+ else:
+ current.append(el)
+ if current:
+ groups.append(current)
+ return groups or [[]]
+
+ def _split_headings(self, content: str) -> list[dict]:
+ """Split content by headings, converting headings to div elements."""
+ protected = content
+ code_blocks: list[str] = []
+ for m in self._CODE_BLOCK_RE.finditer(content):
+ code_blocks.append(m.group(1))
+ protected = protected.replace(m.group(1), f"\x00CODE{len(code_blocks) - 1}\x00", 1)
+
+ elements: list[dict[str, Any]] = []
+ last_end = 0
+ for m in self._HEADING_RE.finditer(protected):
+ before = protected[last_end : m.start()].strip()
+ if before:
+ elements.append({"tag": "markdown", "content": before})
+ text = m.group(2).strip()
+ elements.append(
+ {
+ "tag": "div",
+ "text": {
+ "tag": "lark_md",
+ "content": f"**{text}**",
+ },
+ }
+ )
+ last_end = m.end()
+ remaining = protected[last_end:].strip()
+ if remaining:
+ elements.append({"tag": "markdown", "content": remaining})
+
+ for i, cb in enumerate(code_blocks):
+ for el in elements:
+ if el.get("tag") == "markdown":
+ el["content"] = el["content"].replace(f"\x00CODE{i}\x00", cb)
+
+ return elements or [{"tag": "markdown", "content": content}]
+
+ # ── Smart format detection ──────────────────────────────────────────
+ # Patterns that indicate "complex" markdown needing card rendering
+ _COMPLEX_MD_RE = re.compile(
+ r"```" # fenced code block
+ r"|^\|.+\|.*\n\s*\|[-:\s|]+\|" # markdown table (header + separator)
+ r"|^#{1,6}\s+", # headings
+ re.MULTILINE,
+ )
+
+ # Simple markdown patterns (bold, italic, strikethrough)
+ _SIMPLE_MD_RE = re.compile(
+ r"\*\*.+?\*\*" # **bold**
+ r"|__.+?__" # __bold__
+ r"|(?<!\*)\*(?!\*)(.+?)(?<!\*)\*(?!\*)" # *italic* (single *)
+ r"|~~.+?~~", # ~~strikethrough~~
+ re.DOTALL,
+ )
+
+ # Markdown link: [text](url)
+ _MD_LINK_RE = re.compile(r"\[([^\]]+)\]\((https?://[^\)]+)\)")
+
+ # Unordered list items
+ _LIST_RE = re.compile(r"^[\s]*[-*+]\s+", re.MULTILINE)
+
+ # Ordered list items
+ _OLIST_RE = re.compile(r"^[\s]*\d+\.\s+", re.MULTILINE)
+
+ # Max length for plain text format
+ _TEXT_MAX_LEN = 200
+
+ # Max length for post (rich text) format; beyond this, use card
+ _POST_MAX_LEN = 2000
+
+ @classmethod
+ def _detect_msg_format(cls, content: str) -> str:
+ """Determine the optimal Feishu message format for *content*.
+
+ Returns one of:
+ - ``"text"`` – plain text, short and no markdown
+ - ``"post"`` – rich text (links only, moderate length)
+ - ``"interactive"`` – card with full markdown rendering
+ """
+ stripped = content.strip()
+
+ # Complex markdown (code blocks, tables, headings) → always card
+ if cls._COMPLEX_MD_RE.search(stripped):
+ return "interactive"
+
+ # Long content → card (better readability with card layout)
+ if len(stripped) > cls._POST_MAX_LEN:
+ return "interactive"
+
+ # Has bold/italic/strikethrough → card (post format can't render these)
+ if cls._SIMPLE_MD_RE.search(stripped):
+ return "interactive"
+
+ # Has list items → card (post format can't render list bullets well)
+ if cls._LIST_RE.search(stripped) or cls._OLIST_RE.search(stripped):
+ return "interactive"
+
+ # Has links → post format (supports <a> tags)
+ if cls._MD_LINK_RE.search(stripped):
+ return "post"
+
+ # Short plain text → text format
+ if len(stripped) <= cls._TEXT_MAX_LEN:
+ return "text"
+
+ # Medium plain text without any formatting → post format
+ return "post"
+
+ @classmethod
+ def _markdown_to_post(cls, content: str) -> str:
+ """Convert markdown content to Feishu post message JSON.
+
+ Handles links ``[text](url)`` as ``a`` tags; everything else as ``text`` tags.
+ Each line becomes a paragraph (row) in the post body.
+ """
+ lines = content.strip().split("\n")
+ paragraphs: list[list[dict]] = []
+
+ for line in lines:
+ elements: list[dict] = []
+ last_end = 0
+
+ for m in cls._MD_LINK_RE.finditer(line):
+ # Text before this link
+ before = line[last_end : m.start()]
+ if before:
+ elements.append({"tag": "text", "text": before})
+ elements.append(
+ {
+ "tag": "a",
+ "text": m.group(1),
+ "href": m.group(2),
+ }
+ )
+ last_end = m.end()
+
+ # Remaining text after last link
+ remaining = line[last_end:]
+ if remaining:
+ elements.append({"tag": "text", "text": remaining})
+
+ # Empty line → empty paragraph for spacing
+ if not elements:
+ elements.append({"tag": "text", "text": ""})
+
+ paragraphs.append(elements)
+
+ post_body = {
+ "zh_cn": {
+ "content": paragraphs,
+ }
+ }
+ return json.dumps(post_body, ensure_ascii=False)
+
+ _IMAGE_EXTS = {".png", ".jpg", ".jpeg", ".gif", ".bmp", ".webp", ".ico", ".tiff", ".tif"}
+ _AUDIO_EXTS = {".opus"}
+ _VIDEO_EXTS = {".mp4", ".mov", ".avi"}
+ _FILE_TYPE_MAP = {
+ ".opus": "opus",
+ ".mp4": "mp4",
+ ".pdf": "pdf",
+ ".doc": "doc",
+ ".docx": "doc",
+ ".xls": "xls",
+ ".xlsx": "xls",
+ ".ppt": "ppt",
+ ".pptx": "ppt",
+ }
+
+ def _upload_image_sync(self, file_path: str) -> str | None:
+ """Upload an image to Feishu and return the image_key."""
+ from lark_oapi.api.im.v1 import CreateImageRequest, CreateImageRequestBody
+
+ try:
+ with open(file_path, "rb") as f:
+ request = (
+ CreateImageRequest.builder()
+ .request_body(
+ CreateImageRequestBody.builder().image_type("message").image(f).build()
+ )
+ .build()
+ )
+ response = self._client.im.v1.image.create(request)
+ if response.success():
+ image_key = response.data.image_key
+ logger.debug("Uploaded image {}: {}", os.path.basename(file_path), image_key)
+ return image_key
+ else:
+ logger.error(
+ "Failed to upload image: code={}, msg={}", response.code, response.msg
+ )
+ return None
+ except Exception as e:
+ logger.error("Error uploading image {}: {}", file_path, e)
+ return None
+
+ def _upload_file_sync(self, file_path: str) -> str | None:
+ """Upload a file to Feishu and return the file_key."""
+ from lark_oapi.api.im.v1 import CreateFileRequest, CreateFileRequestBody
+
+ ext = os.path.splitext(file_path)[1].lower()
+ file_type = self._FILE_TYPE_MAP.get(ext, "stream")
+ file_name = os.path.basename(file_path)
+ try:
+ with open(file_path, "rb") as f:
+ request = (
+ CreateFileRequest.builder()
+ .request_body(
+ CreateFileRequestBody.builder()
+ .file_type(file_type)
+ .file_name(file_name)
+ .file(f)
+ .build()
+ )
+ .build()
+ )
+ response = self._client.im.v1.file.create(request)
+ if response.success():
+ file_key = response.data.file_key
+ logger.debug("Uploaded file {}: {}", file_name, file_key)
+ return file_key
+ else:
+ logger.error(
+ "Failed to upload file: code={}, msg={}", response.code, response.msg
+ )
+ return None
+ except Exception as e:
+ logger.error("Error uploading file {}: {}", file_path, e)
+ return None
+
+ def _download_image_sync(
+ self, message_id: str, image_key: str
+ ) -> tuple[bytes | None, str | None]:
+ """Download an image from Feishu message by message_id and image_key."""
+ from lark_oapi.api.im.v1 import GetMessageResourceRequest
+
+ try:
+ request = (
+ GetMessageResourceRequest.builder()
+ .message_id(message_id)
+ .file_key(image_key)
+ .type("image")
+ .build()
+ )
+ response = self._client.im.v1.message_resource.get(request)
+ if response.success():
+ file_data = response.file
+ # GetMessageResourceRequest returns BytesIO, need to read bytes
+ if hasattr(file_data, "read"):
+ file_data = file_data.read()
+ return file_data, response.file_name
+ else:
+ logger.error(
+ "Failed to download image: code={}, msg={}", response.code, response.msg
+ )
+ return None, None
+ except Exception as e:
+ logger.error("Error downloading image {}: {}", image_key, e)
+ return None, None
+
+ def _download_file_sync(
+ self, message_id: str, file_key: str, resource_type: str = "file"
+ ) -> tuple[bytes | None, str | None]:
+ """Download a file/audio/media from a Feishu message by message_id and file_key."""
+ from lark_oapi.api.im.v1 import GetMessageResourceRequest
+
+ # Feishu API only accepts 'image' or 'file' as type parameter
+ # Convert 'audio' to 'file' for API compatibility
+ if resource_type == "audio":
+ resource_type = "file"
+
+ try:
+ request = (
+ GetMessageResourceRequest.builder()
+ .message_id(message_id)
+ .file_key(file_key)
+ .type(resource_type)
+ .build()
+ )
+ response = self._client.im.v1.message_resource.get(request)
+ if response.success():
+ file_data = response.file
+ if hasattr(file_data, "read"):
+ file_data = file_data.read()
+ return file_data, response.file_name
+ else:
+ logger.error(
+ "Failed to download {}: code={}, msg={}",
+ resource_type,
+ response.code,
+ response.msg,
+ )
+ return None, None
+ except Exception:
+ logger.exception("Error downloading {} {}", resource_type, file_key)
+ return None, None
+
+ async def _download_and_save_media(
+ self, msg_type: str, content_json: dict, message_id: str | None = None
+ ) -> tuple[str | None, str]:
+ """
+ Download media from Feishu and save to local disk.
+
+ Returns:
+ (file_path, content_text) - file_path is None if download failed
+ """
+ loop = asyncio.get_running_loop()
+ media_dir = get_media_dir("feishu")
+
+ data, filename = None, None
+
+ if msg_type == "image":
+ image_key = content_json.get("image_key")
+ if image_key and message_id:
+ data, filename = await loop.run_in_executor(
+ None, self._download_image_sync, message_id, image_key
+ )
+ if not filename:
+ filename = f"{image_key[:16]}.jpg"
+
+ elif msg_type in ("audio", "file", "media"):
+ file_key = content_json.get("file_key")
+ if file_key and message_id:
+ data, filename = await loop.run_in_executor(
+ None, self._download_file_sync, message_id, file_key, msg_type
+ )
+ if not filename:
+ filename = file_key[:16]
+ if msg_type == "audio" and not filename.endswith(".opus"):
+ filename = f"{filename}.opus"
+
+ if data and filename:
+ file_path = media_dir / filename
+ file_path.write_bytes(data)
+ logger.debug("Downloaded {} to {}", msg_type, file_path)
+ return str(file_path), f"[{msg_type}: {filename}]"
+
+ return None, f"[{msg_type}: download failed]"
+
+ def _send_message_sync(
+ self, receive_id_type: str, receive_id: str, msg_type: str, content: str
+ ) -> bool:
+ """Send a single message (text/image/file/interactive) synchronously."""
+ from lark_oapi.api.im.v1 import CreateMessageRequest, CreateMessageRequestBody
+
+ try:
+ request = (
+ CreateMessageRequest.builder()
+ .receive_id_type(receive_id_type)
+ .request_body(
+ CreateMessageRequestBody.builder()
+ .receive_id(receive_id)
+ .msg_type(msg_type)
+ .content(content)
+ .build()
+ )
+ .build()
+ )
+ response = self._client.im.v1.message.create(request)
+ if not response.success():
+ logger.error(
+ "Failed to send Feishu {} message: code={}, msg={}, log_id={}",
+ msg_type,
+ response.code,
+ response.msg,
+ response.get_log_id(),
+ )
+ return False
+ logger.debug("Feishu {} message sent to {}", msg_type, receive_id)
+ return True
+ except Exception as e:
+ logger.error("Error sending Feishu {} message: {}", msg_type, e)
+ return False
+
+ async def send(self, msg: OutboundMessage) -> None:
+ """Send a message through Feishu, including media (images/files) if present."""
+ if not self._client:
+ logger.warning("Feishu client not initialized")
+ return
+
+ try:
+ receive_id_type = "chat_id" if msg.chat_id.startswith("oc_") else "open_id"
+ loop = asyncio.get_running_loop()
+
+ for file_path in msg.media:
+ if not os.path.isfile(file_path):
+ logger.warning("Media file not found: {}", file_path)
+ continue
+ ext = os.path.splitext(file_path)[1].lower()
+ if ext in self._IMAGE_EXTS:
+ key = await loop.run_in_executor(None, self._upload_image_sync, file_path)
+ if key:
+ await loop.run_in_executor(
+ None,
+ self._send_message_sync,
+ receive_id_type,
+ msg.chat_id,
+ "image",
+ json.dumps({"image_key": key}, ensure_ascii=False),
+ )
+ else:
+ key = await loop.run_in_executor(None, self._upload_file_sync, file_path)
+ if key:
+ # Use msg_type "media" for audio/video so users can play inline;
+ # "file" for everything else (documents, archives, etc.)
+ if ext in self._AUDIO_EXTS or ext in self._VIDEO_EXTS:
+ media_type = "media"
+ else:
+ media_type = "file"
+ await loop.run_in_executor(
+ None,
+ self._send_message_sync,
+ receive_id_type,
+ msg.chat_id,
+ media_type,
+ json.dumps({"file_key": key}, ensure_ascii=False),
+ )
+
+ if msg.content and msg.content.strip():
+ fmt = self._detect_msg_format(msg.content)
+
+ if fmt == "text":
+ # Short plain text – send as simple text message
+ text_body = json.dumps({"text": msg.content.strip()}, ensure_ascii=False)
+ await loop.run_in_executor(
+ None,
+ self._send_message_sync,
+ receive_id_type,
+ msg.chat_id,
+ "text",
+ text_body,
+ )
+
+ elif fmt == "post":
+ # Medium content with links – send as rich-text post
+ post_body = self._markdown_to_post(msg.content)
+ await loop.run_in_executor(
+ None,
+ self._send_message_sync,
+ receive_id_type,
+ msg.chat_id,
+ "post",
+ post_body,
+ )
+
+ else:
+ # Complex / long content – send as interactive card
+ elements = self._build_card_elements(msg.content)
+ for chunk in self._split_elements_by_table_limit(elements):
+ card = {"config": {"wide_screen_mode": True}, "elements": chunk}
+ await loop.run_in_executor(
+ None,
+ self._send_message_sync,
+ receive_id_type,
+ msg.chat_id,
+ "interactive",
+ json.dumps(card, ensure_ascii=False),
+ )
+
+ except Exception as e:
+ logger.error("Error sending Feishu message: {}", e)
+
+ def _on_message_sync(self, data: Any) -> None:
+ """
+ Sync handler for incoming messages (called from WebSocket thread).
+ Schedules async handling in the main event loop.
+ """
+ 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:
+ """Handle incoming message from Feishu."""
+ try:
+ event = data.event
+ message = event.message
+ sender = event.sender
+
+ # Deduplication check
+ message_id = message.message_id
+ if message_id in self._processed_message_ids:
+ return
+ self._processed_message_ids[message_id] = None
+
+ # Trim cache
+ while len(self._processed_message_ids) > 1000:
+ self._processed_message_ids.popitem(last=False)
+
+ # Skip bot messages
+ if sender.sender_type == "bot":
+ return
+
+ sender_id = sender.sender_id.open_id if sender.sender_id else "unknown"
+ chat_id = message.chat_id
+ chat_type = message.chat_type
+ msg_type = message.message_type
+
+ if chat_type == "group" and not self._is_group_message_for_bot(message):
+ logger.debug("Feishu: skipping group message (not mentioned)")
+ return
+
+ # Add reaction
+ await self._add_reaction(message_id, self.config.react_emoji)
+
+ # Parse content
+ content_parts = []
+ media_paths = []
+
+ try:
+ content_json = json.loads(message.content) if message.content else {}
+ except json.JSONDecodeError:
+ content_json = {}
+
+ if msg_type == "text":
+ text = content_json.get("text", "")
+ if text:
+ content_parts.append(text)
+
+ elif msg_type == "post":
+ text, image_keys = _extract_post_content(content_json)
+ if text:
+ content_parts.append(text)
+ # Download images embedded in post
+ for img_key in image_keys:
+ file_path, content_text = await self._download_and_save_media(
+ "image", {"image_key": img_key}, message_id
+ )
+ if file_path:
+ media_paths.append(file_path)
+ content_parts.append(content_text)
+
+ elif msg_type in ("image", "audio", "file", "media"):
+ file_path, content_text = await self._download_and_save_media(
+ msg_type, content_json, message_id
+ )
+ if file_path:
+ media_paths.append(file_path)
+
+ if msg_type == "audio" and file_path:
+ transcription = await self.transcribe_audio(file_path)
+ if transcription:
+ content_text = f"[transcription: {transcription}]"
+
+ content_parts.append(content_text)
+
+ elif msg_type in (
+ "share_chat",
+ "share_user",
+ "interactive",
+ "share_calendar_event",
+ "system",
+ "merge_forward",
+ ):
+ # Handle share cards and interactive messages
+ text = _extract_share_card_content(content_json, msg_type)
+ if text:
+ content_parts.append(text)
+
+ else:
+ content_parts.append(MSG_TYPE_MAP.get(msg_type, f"[{msg_type}]"))
+
+ content = "\n".join(content_parts) if content_parts else ""
+
+ if not content and not media_paths:
+ return
+
+ # Forward to message bus
+ reply_to = chat_id if chat_type == "group" else sender_id
+ await self._handle_message(
+ sender_id=sender_id,
+ chat_id=reply_to,
+ content=content,
+ media=media_paths,
+ metadata={
+ "message_id": message_id,
+ "chat_type": chat_type,
+ "msg_type": msg_type,
+ },
+ )
+
+ except Exception as e:
+ logger.error("Error processing Feishu message: {}", e)
+
+ def _on_reaction_created(self, data: Any) -> None:
+ """Ignore reaction events so they do not generate SDK noise."""
+ pass
+
+ def _on_message_read(self, data: Any) -> None:
+ """Ignore read events so they do not generate SDK noise."""
+ pass
+
+ def _on_bot_p2p_chat_entered(self, data: Any) -> None:
+ """Ignore p2p-enter events when a user opens a bot chat."""
+ logger.debug("Bot entered p2p chat (user opened chat window)")
+ pass
diff --git a/deeptutor/partners/channels/manager.py b/deeptutor/partners/channels/manager.py
new file mode 100644
index 000000000..be4ab5ac8
--- /dev/null
+++ b/deeptutor/partners/channels/manager.py
@@ -0,0 +1,338 @@
+"""Channel manager for coordinating chat channels."""
+
+from __future__ import annotations
+
+import asyncio
+import hashlib
+from contextlib import suppress
+from typing import Any
+
+from deeptutor.partners.bus.events import OutboundMessage
+from deeptutor.partners.bus.queue import MessageBus
+from deeptutor.partners.channels.base import BaseChannel
+from deeptutor.partners.config.schema import ChannelsConfig
+
+
+def _logger():
+ from loguru import logger as _log
+
+ return _log
+
+
+# Retry delays for message sending (exponential backoff: 1s, 2s, 4s)
+_SEND_RETRY_DELAYS = (1, 2, 4)
+
+_BOOL_CAMEL_ALIASES: dict[str, str] = {
+ "send_progress": "sendProgress",
+ "send_tool_hints": "sendToolHints",
+}
+
+
+class ChannelManager:
+ """
+ Manages chat channels and coordinates message routing.
+
+ Responsibilities:
+ - Initialize enabled channels (Telegram, WhatsApp, etc.)
+ - Start/stop channels
+ - Route outbound messages with retry, duplicate suppression and
+ stream-delta coalescing
+ """
+
+ def __init__(
+ self,
+ channels_config: ChannelsConfig,
+ bus: MessageBus,
+ groq_api_key: str = "",
+ ):
+ self.channels_config = channels_config
+ self.bus = bus
+ self._groq_api_key = groq_api_key
+ self.channels: dict[str, BaseChannel] = {}
+ self._dispatch_task: asyncio.Task | None = None
+ self._origin_reply_fingerprints: dict[tuple[str, str, str], str] = {}
+
+ self._init_channels()
+
+ def _init_channels(self) -> None:
+ """Initialize channels discovered via pkgutil scan + entry_points plugins."""
+ from deeptutor.partners.channels.registry import discover_all
+
+ for name, cls in discover_all().items():
+ section = getattr(self.channels_config, name, None)
+ if section is None:
+ continue
+ enabled = (
+ section.get("enabled", False)
+ if isinstance(section, dict)
+ else getattr(section, "enabled", False)
+ )
+ if not enabled:
+ continue
+ try:
+ channel = cls(section, self.bus)
+ channel.transcription_api_key = self._groq_api_key
+ # Effective per-channel delivery flags: partner-level master
+ # switch AND the channel's own override (both default True).
+ channel.send_progress = self.channels_config.send_progress and (
+ self._resolve_bool_override(section, "send_progress", default=True)
+ )
+ channel.send_tool_hints = self.channels_config.send_tool_hints and (
+ self._resolve_bool_override(section, "send_tool_hints", default=True)
+ )
+ self.channels[name] = channel
+ _logger().info("{} channel enabled", cls.display_name)
+ except Exception as e:
+ _logger().warning("{} channel not available: {}", name, e)
+
+ self._validate_allow_from()
+
+ @staticmethod
+ def _resolve_bool_override(section: Any, key: str, *, default: bool) -> bool:
+ """Return *key* from *section* if it is a bool, otherwise *default*.
+
+ For dict configs also checks the camelCase alias (e.g. ``sendProgress``
+ for ``send_progress``) so raw JSON configs work alongside Pydantic
+ models.
+ """
+ if isinstance(section, dict):
+ value = section.get(key)
+ if value is None:
+ camel = _BOOL_CAMEL_ALIASES.get(key)
+ if camel:
+ value = section.get(camel)
+ return value if isinstance(value, bool) else default
+ value = getattr(section, key, None)
+ return value if isinstance(value, bool) else default
+
+ def _validate_allow_from(self) -> None:
+ for name, ch in self.channels.items():
+ if getattr(ch.config, "allow_from", None) == []:
+ raise SystemExit(
+ f'Error: "{name}" has empty allowFrom (denies all). '
+ f'Set ["*"] to allow everyone, or add specific user IDs.'
+ )
+
+ async def _start_channel(self, name: str, channel: BaseChannel) -> None:
+ try:
+ await channel.start()
+ except Exception as e:
+ _logger().error("Failed to start channel {}: {}", name, e)
+
+ async def start_all(self) -> None:
+ """Start all channels and the outbound dispatcher."""
+ if not self.channels:
+ _logger().warning("No channels enabled")
+ return
+
+ self._dispatch_task = asyncio.create_task(self._dispatch_outbound())
+
+ tasks = []
+ for name, channel in self.channels.items():
+ _logger().info("Starting {} channel...", name)
+ tasks.append(asyncio.create_task(self._start_channel(name, channel)))
+
+ await asyncio.gather(*tasks, return_exceptions=True)
+
+ async def stop_all(self) -> None:
+ """Stop all channels and the dispatcher."""
+ _logger().info("Stopping all channels...")
+
+ if self._dispatch_task:
+ self._dispatch_task.cancel()
+ with suppress(asyncio.CancelledError):
+ await self._dispatch_task
+
+ for name, channel in self.channels.items():
+ try:
+ await channel.stop()
+ _logger().info("Stopped {} channel", name)
+ except Exception as e:
+ _logger().error("Error stopping {}: {}", name, e)
+
+ @staticmethod
+ def _fingerprint_content(content: str) -> str:
+ normalized = " ".join(content.split())
+ return hashlib.sha1(normalized.encode("utf-8")).hexdigest() if normalized else ""
+
+ def _should_suppress_outbound(self, msg: OutboundMessage) -> bool:
+ """Suppress an exact-duplicate reply to the same source message.
+
+ Duplicate suppression is scoped to a known origin message id so
+ repeated content from separate turns is still delivered.
+ """
+ metadata = msg.metadata or {}
+ if metadata.get("_progress"):
+ return False
+ fingerprint = self._fingerprint_content(msg.content)
+ if not fingerprint:
+ return False
+
+ origin_message_id = metadata.get("origin_message_id")
+ if isinstance(origin_message_id, str) and origin_message_id:
+ key = (msg.channel, msg.chat_id, origin_message_id)
+ if self._origin_reply_fingerprints.get(key) == fingerprint:
+ return True
+ self._origin_reply_fingerprints[key] = fingerprint
+
+ message_id = metadata.get("message_id")
+ if isinstance(message_id, str) and message_id:
+ key = (msg.channel, msg.chat_id, message_id)
+ self._origin_reply_fingerprints[key] = fingerprint
+
+ return False
+
+ async def _dispatch_outbound(self) -> None:
+ """Dispatch outbound messages to the appropriate channel."""
+ _logger().info("Outbound dispatcher started")
+
+ # Buffer for messages that couldn't be processed during delta
+ # coalescing (asyncio.Queue doesn't support push_front).
+ pending: list[OutboundMessage] = []
+
+ while True:
+ try:
+ if pending:
+ msg = pending.pop(0)
+ else:
+ msg = await asyncio.wait_for(self.bus.consume_outbound(), timeout=1.0)
+
+ channel = self.channels.get(msg.channel)
+ if not channel:
+ _logger().warning("Unknown channel: {}", msg.channel)
+ continue
+
+ if msg.metadata.get("_progress"):
+ if msg.metadata.get("_tool_hint") and not channel.send_tool_hints:
+ continue
+ if not msg.metadata.get("_tool_hint") and not channel.send_progress:
+ continue
+
+ # Coalesce consecutive _stream_delta messages for the same
+ # (channel, chat_id) to reduce edit-API calls when the LLM
+ # generates faster than the channel can process.
+ if msg.metadata.get("_stream_delta") and not msg.metadata.get("_stream_end"):
+ msg, extra_pending = self._coalesce_stream_deltas(msg)
+ pending.extend(extra_pending)
+
+ if (
+ not msg.metadata.get("_stream_delta")
+ and not msg.metadata.get("_stream_end")
+ and not msg.metadata.get("_streamed")
+ ):
+ if self._should_suppress_outbound(msg):
+ _logger().info(
+ "Suppressing duplicate outbound message to {}:{}",
+ msg.channel,
+ msg.chat_id,
+ )
+ continue
+ await self._send_with_retry(channel, msg)
+
+ except asyncio.TimeoutError:
+ continue
+ except asyncio.CancelledError:
+ break
+
+ @staticmethod
+ async def _send_once(channel: BaseChannel, msg: OutboundMessage) -> None:
+ """Send one outbound message without retry policy."""
+ if msg.metadata.get("_stream_delta") or msg.metadata.get("_stream_end"):
+ await channel.send_delta(msg.chat_id, msg.content, msg.metadata)
+ elif not msg.metadata.get("_streamed"):
+ # ``_streamed`` marks a final reply already delivered live via
+ # send_delta — skip the plain send to avoid a duplicate message.
+ await channel.send(msg)
+
+ def _coalesce_stream_deltas(
+ self, first_msg: OutboundMessage
+ ) -> tuple[OutboundMessage, list[OutboundMessage]]:
+ """Merge consecutive _stream_delta messages for the same (channel, chat_id).
+
+ Returns:
+ tuple of (merged_message, list_of_non_matching_messages)
+ """
+ target_key = (first_msg.channel, first_msg.chat_id)
+ target_stream = (first_msg.metadata or {}).get("_stream_id")
+ combined_content = first_msg.content
+ final_metadata = dict(first_msg.metadata or {})
+ non_matching: list[OutboundMessage] = []
+
+ # Only merge consecutive deltas of the same stream segment. As soon
+ # as we hit any other message, stop and hand that boundary back to
+ # the dispatcher via `pending`.
+ while True:
+ try:
+ next_msg = self.bus.outbound.get_nowait()
+ except asyncio.QueueEmpty:
+ break
+
+ next_meta = next_msg.metadata or {}
+ same_target = (next_msg.channel, next_msg.chat_id) == target_key
+ same_stream = next_meta.get("_stream_id") == target_stream
+ is_delta = bool(next_meta.get("_stream_delta"))
+ is_end = bool(next_meta.get("_stream_end"))
+
+ if same_target and same_stream and is_delta:
+ combined_content += next_msg.content
+ if is_end:
+ final_metadata["_stream_end"] = True
+ break
+ else:
+ # First non-matching message defines the coalescing boundary.
+ non_matching.append(next_msg)
+ break
+
+ merged = OutboundMessage(
+ channel=first_msg.channel,
+ chat_id=first_msg.chat_id,
+ content=combined_content,
+ metadata=final_metadata,
+ )
+ return merged, non_matching
+
+ async def _send_with_retry(self, channel: BaseChannel, msg: OutboundMessage) -> None:
+ """Send a message with retry on failure using exponential backoff.
+
+ Note: CancelledError is re-raised to allow graceful shutdown.
+ """
+ max_attempts = max(getattr(self.channels_config, "send_max_retries", 3), 1)
+
+ for attempt in range(max_attempts):
+ try:
+ await self._send_once(channel, msg)
+ return
+ except asyncio.CancelledError:
+ raise
+ except Exception as e:
+ if attempt == max_attempts - 1:
+ _logger().exception(
+ "Failed to send to {} after {} attempts", msg.channel, max_attempts
+ )
+ return
+ delay = _SEND_RETRY_DELAYS[min(attempt, len(_SEND_RETRY_DELAYS) - 1)]
+ _logger().warning(
+ "Send to {} failed (attempt {}/{}): {}, retrying in {}s",
+ msg.channel,
+ attempt + 1,
+ max_attempts,
+ type(e).__name__,
+ delay,
+ )
+ try:
+ await asyncio.sleep(delay)
+ except asyncio.CancelledError:
+ raise
+
+ def get_channel(self, name: str) -> BaseChannel | None:
+ return self.channels.get(name)
+
+ def get_status(self) -> dict[str, Any]:
+ return {
+ name: {"enabled": True, "running": channel.is_running}
+ for name, channel in self.channels.items()
+ }
+
+ @property
+ def enabled_channels(self) -> list[str]:
+ return list(self.channels.keys())
diff --git a/deeptutor/partners/channels/matrix.py b/deeptutor/partners/channels/matrix.py
new file mode 100644
index 000000000..e7ffcef69
--- /dev/null
+++ b/deeptutor/partners/channels/matrix.py
@@ -0,0 +1,843 @@
+"""Matrix (Element) channel — inbound sync + outbound message/media delivery."""
+
+import asyncio
+import logging
+import mimetypes
+from pathlib import Path
+from typing import Any, Literal, TypeAlias
+
+from loguru import logger
+from pydantic import Field
+
+try:
+ from mistune import create_markdown
+ import nh3
+ from nio import (
+ AsyncClient,
+ AsyncClientConfig,
+ DownloadError,
+ InviteEvent,
+ JoinError,
+ MatrixRoom,
+ MemoryDownloadResponse,
+ RoomEncryptedMedia,
+ RoomMessage,
+ RoomMessageMedia,
+ RoomMessageText,
+ RoomSendError,
+ RoomTypingError,
+ SyncError,
+ UploadError,
+ )
+except ImportError as e:
+ raise ImportError(
+ "Matrix dependencies not installed. Run: pip install deeptutor[matrix]"
+ ) from e
+
+try:
+ from nio.crypto.attachments import decrypt_attachment
+ from nio.exceptions import EncryptionError
+except ImportError:
+ decrypt_attachment = None
+ EncryptionError = Exception
+ MATRIX_E2EE_AVAILABLE = False
+else:
+ MATRIX_E2EE_AVAILABLE = True
+
+from deeptutor.partners.bus.events import OutboundMessage
+from deeptutor.partners.bus.queue import MessageBus
+from deeptutor.partners.channels.base import BaseChannel
+from deeptutor.partners.config.paths import get_data_dir, get_media_dir
+from deeptutor.partners.config.schema import Base, DeliveryOverrides
+from deeptutor.partners.helpers import safe_filename
+
+TYPING_NOTICE_TIMEOUT_MS = 30_000
+# Must stay below TYPING_NOTICE_TIMEOUT_MS so the indicator doesn't expire mid-processing.
+TYPING_KEEPALIVE_INTERVAL_MS = 20_000
+MATRIX_HTML_FORMAT = "org.matrix.custom.html"
+_ATTACH_MARKER = "[attachment: {}]"
+_ATTACH_TOO_LARGE = "[attachment: {} - too large]"
+_ATTACH_FAILED = "[attachment: {} - download failed]"
+_ATTACH_UPLOAD_FAILED = "[attachment: {} - upload failed]"
+_DEFAULT_ATTACH_NAME = "attachment"
+_MSGTYPE_MAP = {"m.image": "image", "m.audio": "audio", "m.video": "video", "m.file": "file"}
+
+MATRIX_MEDIA_EVENT_FILTER = (RoomMessageMedia, RoomEncryptedMedia)
+MatrixMediaEvent: TypeAlias = RoomMessageMedia | RoomEncryptedMedia
+
+MATRIX_MARKDOWN = create_markdown(
+ escape=True,
+ plugins=["table", "strikethrough", "url", "superscript", "subscript"],
+)
+
+MATRIX_ALLOWED_HTML_TAGS = {
+ "p",
+ "a",
+ "strong",
+ "em",
+ "del",
+ "code",
+ "pre",
+ "blockquote",
+ "ul",
+ "ol",
+ "li",
+ "h1",
+ "h2",
+ "h3",
+ "h4",
+ "h5",
+ "h6",
+ "hr",
+ "br",
+ "table",
+ "thead",
+ "tbody",
+ "tr",
+ "th",
+ "td",
+ "caption",
+ "sup",
+ "sub",
+ "img",
+}
+MATRIX_ALLOWED_HTML_ATTRIBUTES: dict[str, set[str]] = {
+ "a": {"href"},
+ "code": {"class"},
+ "ol": {"start"},
+ "img": {"src", "alt", "title", "width", "height"},
+}
+MATRIX_ALLOWED_URL_SCHEMES = {"https", "http", "matrix", "mailto", "mxc"}
+
+
+def _filter_matrix_html_attribute(tag: str, attr: str, value: str) -> str | None:
+ """Filter attribute values to a safe Matrix-compatible subset."""
+ if tag == "a" and attr == "href":
+ return (
+ value
+ if value.lower().startswith(("https://", "http://", "matrix:", "mailto:"))
+ else None
+ )
+ if tag == "img" and attr == "src":
+ return value if value.lower().startswith("mxc://") else None
+ if tag == "code" and attr == "class":
+ classes = [
+ c for c in value.split() if c.startswith("language-") and not c.startswith("language-_")
+ ]
+ return " ".join(classes) if classes else None
+ return value
+
+
+MATRIX_HTML_CLEANER = nh3.Cleaner(
+ tags=MATRIX_ALLOWED_HTML_TAGS,
+ attributes=MATRIX_ALLOWED_HTML_ATTRIBUTES,
+ attribute_filter=_filter_matrix_html_attribute,
+ url_schemes=MATRIX_ALLOWED_URL_SCHEMES,
+ strip_comments=True,
+ link_rel="noopener noreferrer",
+)
+
+
+def _render_markdown_html(text: str) -> str | None:
+ """Render markdown to sanitized HTML; returns None for plain text."""
+ try:
+ formatted = MATRIX_HTML_CLEANER.clean(MATRIX_MARKDOWN(text)).strip()
+ except Exception:
+ return None
+ if not formatted:
+ return None
+ # Skip formatted_body for plain <p>text</p> to keep payload minimal.
+ if formatted.startswith("<p>") and formatted.endswith("</p>"):
+ inner = formatted[3:-4]
+ if "<" not in inner and ">" not in inner:
+ return None
+ return formatted
+
+
+def _build_matrix_text_content(text: str) -> dict[str, object]:
+ """Build Matrix m.text payload with optional HTML formatted_body."""
+ content: dict[str, object] = {"msgtype": "m.text", "body": text, "m.mentions": {}}
+ if html := _render_markdown_html(text):
+ content["format"] = MATRIX_HTML_FORMAT
+ content["formatted_body"] = html
+ return content
+
+
+class _NioLoguruHandler(logging.Handler):
+ """Route matrix-nio stdlib logs into Loguru."""
+
+ def emit(self, record: logging.LogRecord) -> None:
+ try:
+ level = logger.level(record.levelname).name
+ except ValueError:
+ level = record.levelno
+ frame, depth = logging.currentframe(), 2
+ while frame and frame.f_code.co_filename == logging.__file__:
+ frame, depth = frame.f_back, depth + 1
+ logger.opt(depth=depth, exception=record.exc_info).log(level, record.getMessage())
+
+
+def _configure_nio_logging_bridge() -> None:
+ """Bridge matrix-nio logs to Loguru (idempotent)."""
+ nio_logger = logging.getLogger("nio")
+ if not any(isinstance(h, _NioLoguruHandler) for h in nio_logger.handlers):
+ nio_logger.handlers = [_NioLoguruHandler()]
+ nio_logger.propagate = False
+
+
+class MatrixConfig(DeliveryOverrides):
+ """Matrix (Element) channel configuration."""
+
+ enabled: bool = False
+ homeserver: str = "https://matrix.org"
+ access_token: str = ""
+ user_id: str = ""
+ device_id: str = ""
+ e2ee_enabled: bool = False
+ sync_stop_grace_seconds: int = 2
+ max_media_bytes: int = 20 * 1024 * 1024
+ allow_from: list[str] = Field(default_factory=list)
+ group_policy: Literal["open", "mention", "allowlist"] = "open"
+ group_allow_from: list[str] = Field(default_factory=list)
+ allow_room_mentions: bool = False
+
+
+class MatrixChannel(BaseChannel):
+ """Matrix (Element) channel using long-polling sync."""
+
+ name = "matrix"
+ display_name = "Matrix"
+
+ @classmethod
+ def default_config(cls) -> dict[str, Any]:
+ return MatrixConfig().model_dump(by_alias=True)
+
+ def __init__(
+ self,
+ config: Any,
+ bus: MessageBus,
+ *,
+ restrict_to_workspace: bool = False,
+ workspace: str | Path | None = None,
+ ):
+ if isinstance(config, dict):
+ config = MatrixConfig.model_validate(config)
+ super().__init__(config, bus)
+ self.client: AsyncClient | None = None
+ self._sync_task: asyncio.Task | None = None
+ self._typing_tasks: dict[str, asyncio.Task] = {}
+ self._restrict_to_workspace = bool(restrict_to_workspace)
+ self._workspace = (
+ Path(workspace).expanduser().resolve(strict=False) if workspace is not None else None
+ )
+ self._server_upload_limit_bytes: int | None = None
+ self._server_upload_limit_checked = False
+
+ async def start(self) -> None:
+ """Start Matrix client and begin sync loop."""
+ self._running = True
+ _configure_nio_logging_bridge()
+ if self.config.e2ee_enabled and not MATRIX_E2EE_AVAILABLE:
+ raise ImportError(
+ "Matrix E2EE dependencies are not installed. Install "
+ "`deeptutor[matrix-e2e]` or `requirements/matrix-e2e.txt`, and make "
+ "sure libolm is available on your system."
+ )
+
+ store_path = get_data_dir() / "matrix-store"
+ store_path.mkdir(parents=True, exist_ok=True)
+
+ self.client = AsyncClient(
+ homeserver=self.config.homeserver,
+ user=self.config.user_id,
+ store_path=store_path,
+ config=AsyncClientConfig(
+ store_sync_tokens=True, encryption_enabled=self.config.e2ee_enabled
+ ),
+ )
+ self.client.user_id = self.config.user_id
+ self.client.access_token = self.config.access_token
+ self.client.device_id = self.config.device_id
+
+ self._register_event_callbacks()
+ self._register_response_callbacks()
+
+ if not self.config.e2ee_enabled:
+ logger.warning("Matrix E2EE disabled; encrypted rooms may be undecryptable.")
+
+ if self.config.device_id:
+ try:
+ self.client.load_store()
+ except Exception:
+ logger.exception("Matrix store load failed; restart may replay recent messages.")
+ else:
+ logger.warning("Matrix device_id empty; restart may replay recent messages.")
+
+ self._sync_task = asyncio.create_task(self._sync_loop())
+
+ async def stop(self) -> None:
+ """Stop the Matrix channel with graceful sync shutdown."""
+ self._running = False
+ for room_id in list(self._typing_tasks):
+ await self._stop_typing_keepalive(room_id, clear_typing=False)
+ if self.client:
+ self.client.stop_sync_forever()
+ if self._sync_task:
+ try:
+ await asyncio.wait_for(
+ asyncio.shield(self._sync_task), timeout=self.config.sync_stop_grace_seconds
+ )
+ except (asyncio.TimeoutError, asyncio.CancelledError):
+ self._sync_task.cancel()
+ try:
+ await self._sync_task
+ except asyncio.CancelledError:
+ pass
+ if self.client:
+ await self.client.close()
+
+ def _is_workspace_path_allowed(self, path: Path) -> bool:
+ """Check path is inside workspace (when restriction enabled)."""
+ if not self._restrict_to_workspace or not self._workspace:
+ return True
+ try:
+ path.resolve(strict=False).relative_to(self._workspace)
+ return True
+ except ValueError:
+ return False
+
+ def _collect_outbound_media_candidates(self, media: list[str]) -> list[Path]:
+ """Deduplicate and resolve outbound attachment paths."""
+ seen: set[str] = set()
+ candidates: list[Path] = []
+ for raw in media:
+ if not isinstance(raw, str) or not raw.strip():
+ continue
+ path = Path(raw.strip()).expanduser()
+ try:
+ key = str(path.resolve(strict=False))
+ except OSError:
+ key = str(path)
+ if key not in seen:
+ seen.add(key)
+ candidates.append(path)
+ return candidates
+
+ @staticmethod
+ def _build_outbound_attachment_content(
+ *,
+ filename: str,
+ mime: str,
+ size_bytes: int,
+ mxc_url: str,
+ encryption_info: dict[str, Any] | None = None,
+ ) -> dict[str, Any]:
+ """Build Matrix content payload for an uploaded file/image/audio/video."""
+ prefix = mime.split("/")[0]
+ msgtype = {"image": "m.image", "audio": "m.audio", "video": "m.video"}.get(prefix, "m.file")
+ content: dict[str, Any] = {
+ "msgtype": msgtype,
+ "body": filename,
+ "filename": filename,
+ "info": {"mimetype": mime, "size": size_bytes},
+ "m.mentions": {},
+ }
+ if encryption_info:
+ content["file"] = {**encryption_info, "url": mxc_url}
+ else:
+ content["url"] = mxc_url
+ return content
+
+ def _is_encrypted_room(self, room_id: str) -> bool:
+ if not self.client:
+ return False
+ room = getattr(self.client, "rooms", {}).get(room_id)
+ return bool(getattr(room, "encrypted", False))
+
+ async def _send_room_content(self, room_id: str, content: dict[str, Any]) -> None:
+ """Send m.room.message with E2EE options."""
+ if not self.client:
+ return
+ kwargs: dict[str, Any] = {
+ "room_id": room_id,
+ "message_type": "m.room.message",
+ "content": content,
+ }
+ if self.config.e2ee_enabled:
+ kwargs["ignore_unverified_devices"] = True
+ await self.client.room_send(**kwargs)
+
+ async def _resolve_server_upload_limit_bytes(self) -> int | None:
+ """Query homeserver upload limit once per channel lifecycle."""
+ if self._server_upload_limit_checked:
+ return self._server_upload_limit_bytes
+ self._server_upload_limit_checked = True
+ if not self.client:
+ return None
+ try:
+ response = await self.client.content_repository_config()
+ except Exception:
+ return None
+ upload_size = getattr(response, "upload_size", None)
+ if isinstance(upload_size, int) and upload_size > 0:
+ self._server_upload_limit_bytes = upload_size
+ return upload_size
+ return None
+
+ async def _effective_media_limit_bytes(self) -> int:
+ """min(local config, server advertised) — 0 blocks all uploads."""
+ local_limit = max(int(self.config.max_media_bytes), 0)
+ server_limit = await self._resolve_server_upload_limit_bytes()
+ if server_limit is None:
+ return local_limit
+ return min(local_limit, server_limit) if local_limit else 0
+
+ async def _upload_and_send_attachment(
+ self,
+ room_id: str,
+ path: Path,
+ limit_bytes: int,
+ relates_to: dict[str, Any] | None = None,
+ ) -> str | None:
+ """Upload one local file to Matrix and send it as a media message. Returns failure marker or None."""
+ if not self.client:
+ return _ATTACH_UPLOAD_FAILED.format(path.name or _DEFAULT_ATTACH_NAME)
+
+ resolved = path.expanduser().resolve(strict=False)
+ filename = safe_filename(resolved.name) or _DEFAULT_ATTACH_NAME
+ fail = _ATTACH_UPLOAD_FAILED.format(filename)
+
+ if not resolved.is_file() or not self._is_workspace_path_allowed(resolved):
+ return fail
+ try:
+ size_bytes = resolved.stat().st_size
+ except OSError:
+ return fail
+ if limit_bytes <= 0 or size_bytes > limit_bytes:
+ return _ATTACH_TOO_LARGE.format(filename)
+
+ mime = mimetypes.guess_type(filename, strict=False)[0] or "application/octet-stream"
+ try:
+ with resolved.open("rb") as f:
+ upload_result = await self.client.upload(
+ f,
+ content_type=mime,
+ filename=filename,
+ encrypt=self.config.e2ee_enabled and self._is_encrypted_room(room_id),
+ filesize=size_bytes,
+ )
+ except Exception:
+ return fail
+
+ upload_response = upload_result[0] if isinstance(upload_result, tuple) else upload_result
+ encryption_info = (
+ upload_result[1]
+ if isinstance(upload_result, tuple) and isinstance(upload_result[1], dict)
+ else None
+ )
+ if isinstance(upload_response, UploadError):
+ return fail
+ mxc_url = getattr(upload_response, "content_uri", None)
+ if not isinstance(mxc_url, str) or not mxc_url.startswith("mxc://"):
+ return fail
+
+ content = self._build_outbound_attachment_content(
+ filename=filename,
+ mime=mime,
+ size_bytes=size_bytes,
+ mxc_url=mxc_url,
+ encryption_info=encryption_info,
+ )
+ if relates_to:
+ content["m.relates_to"] = relates_to
+ try:
+ await self._send_room_content(room_id, content)
+ except Exception:
+ return fail
+ return None
+
+ async def send(self, msg: OutboundMessage) -> None:
+ """Send outbound content; clear typing for non-progress messages."""
+ if not self.client:
+ return
+ text = msg.content or ""
+ candidates = self._collect_outbound_media_candidates(msg.media)
+ relates_to = self._build_thread_relates_to(msg.metadata)
+ is_progress = bool((msg.metadata or {}).get("_progress"))
+ try:
+ failures: list[str] = []
+ if candidates:
+ limit_bytes = await self._effective_media_limit_bytes()
+ for path in candidates:
+ if fail := await self._upload_and_send_attachment(
+ room_id=msg.chat_id,
+ path=path,
+ limit_bytes=limit_bytes,
+ relates_to=relates_to,
+ ):
+ failures.append(fail)
+ if failures:
+ text = (
+ f"{text.rstrip()}\n{chr(10).join(failures)}"
+ if text.strip()
+ else "\n".join(failures)
+ )
+ if text or not candidates:
+ content = _build_matrix_text_content(text)
+ if relates_to:
+ content["m.relates_to"] = relates_to
+ await self._send_room_content(msg.chat_id, content)
+ finally:
+ if not is_progress:
+ await self._stop_typing_keepalive(msg.chat_id, clear_typing=True)
+
+ def _register_event_callbacks(self) -> None:
+ self.client.add_event_callback(self._on_message, RoomMessageText)
+ self.client.add_event_callback(self._on_media_message, MATRIX_MEDIA_EVENT_FILTER)
+ self.client.add_event_callback(self._on_room_invite, InviteEvent)
+
+ def _register_response_callbacks(self) -> None:
+ self.client.add_response_callback(self._on_sync_error, SyncError)
+ self.client.add_response_callback(self._on_join_error, JoinError)
+ self.client.add_response_callback(self._on_send_error, RoomSendError)
+
+ def _log_response_error(self, label: str, response: Any) -> None:
+ """Log Matrix response errors — auth errors at ERROR level, rest at WARNING."""
+ code = getattr(response, "status_code", None)
+ is_auth = code in {"M_UNKNOWN_TOKEN", "M_FORBIDDEN", "M_UNAUTHORIZED"}
+ is_fatal = is_auth or getattr(response, "soft_logout", False)
+ (logger.error if is_fatal else logger.warning)("Matrix {} failed: {}", label, response)
+
+ async def _on_sync_error(self, response: SyncError) -> None:
+ self._log_response_error("sync", response)
+
+ async def _on_join_error(self, response: JoinError) -> None:
+ self._log_response_error("join", response)
+
+ async def _on_send_error(self, response: RoomSendError) -> None:
+ self._log_response_error("send", response)
+
+ async def _set_typing(self, room_id: str, typing: bool) -> None:
+ """Best-effort typing indicator update."""
+ if not self.client:
+ return
+ try:
+ response = await self.client.room_typing(
+ room_id=room_id, typing_state=typing, timeout=TYPING_NOTICE_TIMEOUT_MS
+ )
+ if isinstance(response, RoomTypingError):
+ logger.debug("Matrix typing failed for {}: {}", room_id, response)
+ except Exception:
+ pass
+
+ async def _start_typing_keepalive(self, room_id: str) -> None:
+ """Start periodic typing refresh (spec-recommended keepalive)."""
+ await self._stop_typing_keepalive(room_id, clear_typing=False)
+ await self._set_typing(room_id, True)
+ if not self._running:
+ return
+
+ async def loop() -> None:
+ try:
+ while self._running:
+ await asyncio.sleep(TYPING_KEEPALIVE_INTERVAL_MS / 1000)
+ await self._set_typing(room_id, True)
+ except asyncio.CancelledError:
+ pass
+
+ self._typing_tasks[room_id] = asyncio.create_task(loop())
+
+ async def _stop_typing_keepalive(self, room_id: str, *, clear_typing: bool) -> None:
+ if task := self._typing_tasks.pop(room_id, None):
+ task.cancel()
+ try:
+ await task
+ except asyncio.CancelledError:
+ pass
+ if clear_typing:
+ await self._set_typing(room_id, False)
+
+ async def _sync_loop(self) -> None:
+ while self._running:
+ try:
+ await self.client.sync_forever(timeout=30000, full_state=True)
+ except asyncio.CancelledError:
+ break
+ except Exception:
+ await asyncio.sleep(2)
+
+ async def _on_room_invite(self, room: MatrixRoom, event: InviteEvent) -> None:
+ if self.is_allowed(event.sender):
+ await self.client.join(room.room_id)
+
+ def _is_direct_room(self, room: MatrixRoom) -> bool:
+ count = getattr(room, "member_count", None)
+ return isinstance(count, int) and count <= 2
+
+ def _is_bot_mentioned(self, event: RoomMessage) -> bool:
+ """Check m.mentions payload for bot mention."""
+ source = getattr(event, "source", None)
+ if not isinstance(source, dict):
+ return False
+ mentions = (source.get("content") or {}).get("m.mentions")
+ if not isinstance(mentions, dict):
+ return False
+ user_ids = mentions.get("user_ids")
+ if isinstance(user_ids, list) and self.config.user_id in user_ids:
+ return True
+ return bool(self.config.allow_room_mentions and mentions.get("room") is True)
+
+ def _should_process_message(self, room: MatrixRoom, event: RoomMessage) -> bool:
+ """Apply sender and room policy checks."""
+ if not self.is_allowed(event.sender):
+ return False
+ if self._is_direct_room(room):
+ return True
+ policy = self.config.group_policy
+ if policy == "open":
+ return True
+ if policy == "allowlist":
+ return room.room_id in (self.config.group_allow_from or [])
+ if policy == "mention":
+ return self._is_bot_mentioned(event)
+ return False
+
+ def _media_dir(self) -> Path:
+ return get_media_dir("matrix")
+
+ @staticmethod
+ def _event_source_content(event: RoomMessage) -> dict[str, Any]:
+ source = getattr(event, "source", None)
+ if not isinstance(source, dict):
+ return {}
+ content = source.get("content")
+ return content if isinstance(content, dict) else {}
+
+ def _event_thread_root_id(self, event: RoomMessage) -> str | None:
+ relates_to = self._event_source_content(event).get("m.relates_to")
+ if not isinstance(relates_to, dict) or relates_to.get("rel_type") != "m.thread":
+ return None
+ root_id = relates_to.get("event_id")
+ return root_id if isinstance(root_id, str) and root_id else None
+
+ def _thread_metadata(self, event: RoomMessage) -> dict[str, str] | None:
+ if not (root_id := self._event_thread_root_id(event)):
+ return None
+ meta: dict[str, str] = {"thread_root_event_id": root_id}
+ if isinstance(reply_to := getattr(event, "event_id", None), str) and reply_to:
+ meta["thread_reply_to_event_id"] = reply_to
+ return meta
+
+ @staticmethod
+ def _build_thread_relates_to(metadata: dict[str, Any] | None) -> dict[str, Any] | None:
+ if not metadata:
+ return None
+ root_id = metadata.get("thread_root_event_id")
+ if not isinstance(root_id, str) or not root_id:
+ return None
+ reply_to = metadata.get("thread_reply_to_event_id") or metadata.get("event_id")
+ if not isinstance(reply_to, str) or not reply_to:
+ return None
+ return {
+ "rel_type": "m.thread",
+ "event_id": root_id,
+ "m.in_reply_to": {"event_id": reply_to},
+ "is_falling_back": True,
+ }
+
+ def _event_attachment_type(self, event: MatrixMediaEvent) -> str:
+ msgtype = self._event_source_content(event).get("msgtype")
+ return _MSGTYPE_MAP.get(msgtype, "file")
+
+ @staticmethod
+ def _is_encrypted_media_event(event: MatrixMediaEvent) -> bool:
+ return (
+ isinstance(getattr(event, "key", None), dict)
+ and isinstance(getattr(event, "hashes", None), dict)
+ and isinstance(getattr(event, "iv", None), str)
+ )
+
+ def _event_declared_size_bytes(self, event: MatrixMediaEvent) -> int | None:
+ info = self._event_source_content(event).get("info")
+ size = info.get("size") if isinstance(info, dict) else None
+ return size if isinstance(size, int) and size >= 0 else None
+
+ def _event_mime(self, event: MatrixMediaEvent) -> str | None:
+ info = self._event_source_content(event).get("info")
+ if isinstance(info, dict) and isinstance(m := info.get("mimetype"), str) and m:
+ return m
+ m = getattr(event, "mimetype", None)
+ return m if isinstance(m, str) and m else None
+
+ def _event_filename(self, event: MatrixMediaEvent, attachment_type: str) -> str:
+ body = getattr(event, "body", None)
+ if isinstance(body, str) and body.strip():
+ if candidate := safe_filename(Path(body).name):
+ return candidate
+ return _DEFAULT_ATTACH_NAME if attachment_type == "file" else attachment_type
+
+ def _build_attachment_path(
+ self, event: MatrixMediaEvent, attachment_type: str, filename: str, mime: str | None
+ ) -> Path:
+ safe_name = safe_filename(Path(filename).name) or _DEFAULT_ATTACH_NAME
+ suffix = Path(safe_name).suffix
+ if not suffix and mime:
+ if guessed := mimetypes.guess_extension(mime, strict=False):
+ safe_name, suffix = f"{safe_name}{guessed}", guessed
+ stem = (Path(safe_name).stem or attachment_type)[:72]
+ suffix = suffix[:16]
+ event_id = safe_filename(str(getattr(event, "event_id", "") or "evt").lstrip("$"))
+ event_prefix = (event_id[:24] or "evt").strip("_")
+ return self._media_dir() / f"{event_prefix}_{stem}{suffix}"
+
+ async def _download_media_bytes(self, mxc_url: str) -> bytes | None:
+ if not self.client:
+ return None
+ response = await self.client.download(mxc=mxc_url)
+ if isinstance(response, DownloadError):
+ logger.warning("Matrix download failed for {}: {}", mxc_url, response)
+ return None
+ body = getattr(response, "body", None)
+ if isinstance(body, (bytes, bytearray)):
+ return bytes(body)
+ if isinstance(response, MemoryDownloadResponse):
+ return bytes(response.body)
+ if isinstance(body, (str, Path)):
+ path = Path(body)
+ if path.is_file():
+ try:
+ return path.read_bytes()
+ except OSError:
+ return None
+ return None
+
+ def _decrypt_media_bytes(self, event: MatrixMediaEvent, ciphertext: bytes) -> bytes | None:
+ if decrypt_attachment is None:
+ logger.warning(
+ "Matrix encrypted attachment received but E2EE dependencies are not installed. "
+ "Install deeptutor[matrix-e2e] to decrypt encrypted media."
+ )
+ return None
+ key_obj, hashes, iv = (
+ getattr(event, "key", None),
+ getattr(event, "hashes", None),
+ getattr(event, "iv", None),
+ )
+ key = key_obj.get("k") if isinstance(key_obj, dict) else None
+ sha256 = hashes.get("sha256") if isinstance(hashes, dict) else None
+ if not all(isinstance(v, str) for v in (key, sha256, iv)):
+ return None
+ try:
+ return decrypt_attachment(ciphertext, key, sha256, iv)
+ except (EncryptionError, ValueError, TypeError):
+ logger.warning("Matrix decrypt failed for event {}", getattr(event, "event_id", ""))
+ return None
+
+ async def _fetch_media_attachment(
+ self,
+ room: MatrixRoom,
+ event: MatrixMediaEvent,
+ ) -> tuple[dict[str, Any] | None, str]:
+ """Download, decrypt if needed, and persist a Matrix attachment."""
+ atype = self._event_attachment_type(event)
+ mime = self._event_mime(event)
+ filename = self._event_filename(event, atype)
+ mxc_url = getattr(event, "url", None)
+ fail = _ATTACH_FAILED.format(filename)
+
+ if not isinstance(mxc_url, str) or not mxc_url.startswith("mxc://"):
+ return None, fail
+
+ limit_bytes = await self._effective_media_limit_bytes()
+ declared = self._event_declared_size_bytes(event)
+ if declared is not None and declared > limit_bytes:
+ return None, _ATTACH_TOO_LARGE.format(filename)
+
+ downloaded = await self._download_media_bytes(mxc_url)
+ if downloaded is None:
+ return None, fail
+
+ encrypted = self._is_encrypted_media_event(event)
+ data = downloaded
+ if encrypted:
+ if (data := self._decrypt_media_bytes(event, downloaded)) is None:
+ return None, fail
+
+ if len(data) > limit_bytes:
+ return None, _ATTACH_TOO_LARGE.format(filename)
+
+ path = self._build_attachment_path(event, atype, filename, mime)
+ try:
+ path.write_bytes(data)
+ except OSError:
+ return None, fail
+
+ attachment = {
+ "type": atype,
+ "mime": mime,
+ "filename": filename,
+ "event_id": str(getattr(event, "event_id", "") or ""),
+ "encrypted": encrypted,
+ "size_bytes": len(data),
+ "path": str(path),
+ "mxc_url": mxc_url,
+ }
+ return attachment, _ATTACH_MARKER.format(path)
+
+ def _base_metadata(self, room: MatrixRoom, event: RoomMessage) -> dict[str, Any]:
+ """Build common metadata for text and media handlers."""
+ meta: dict[str, Any] = {"room": getattr(room, "display_name", room.room_id)}
+ if isinstance(eid := getattr(event, "event_id", None), str) and eid:
+ meta["event_id"] = eid
+ if thread := self._thread_metadata(event):
+ meta.update(thread)
+ return meta
+
+ async def _on_message(self, room: MatrixRoom, event: RoomMessageText) -> None:
+ if event.sender == self.config.user_id or not self._should_process_message(room, event):
+ return
+ await self._start_typing_keepalive(room.room_id)
+ try:
+ await self._handle_message(
+ sender_id=event.sender,
+ chat_id=room.room_id,
+ content=event.body,
+ metadata=self._base_metadata(room, event),
+ )
+ except Exception:
+ await self._stop_typing_keepalive(room.room_id, clear_typing=True)
+ raise
+
+ async def _on_media_message(self, room: MatrixRoom, event: MatrixMediaEvent) -> None:
+ if event.sender == self.config.user_id or not self._should_process_message(room, event):
+ return
+ attachment, marker = await self._fetch_media_attachment(room, event)
+ parts: list[str] = []
+ if isinstance(body := getattr(event, "body", None), str) and body.strip():
+ parts.append(body.strip())
+
+ if attachment and attachment.get("type") == "audio":
+ transcription = await self.transcribe_audio(attachment["path"])
+ if transcription:
+ parts.append(f"[transcription: {transcription}]")
+ else:
+ parts.append(marker)
+ elif marker:
+ parts.append(marker)
+
+ await self._start_typing_keepalive(room.room_id)
+ try:
+ meta = self._base_metadata(room, event)
+ meta["attachments"] = []
+ if attachment:
+ meta["attachments"] = [attachment]
+ await self._handle_message(
+ sender_id=event.sender,
+ chat_id=room.room_id,
+ content="\n".join(parts),
+ media=[attachment["path"]] if attachment else [],
+ metadata=meta,
+ )
+ except Exception:
+ await self._stop_typing_keepalive(room.room_id, clear_typing=True)
+ raise
diff --git a/deeptutor/partners/channels/mochat.py b/deeptutor/partners/channels/mochat.py
new file mode 100644
index 000000000..8e93dc363
--- /dev/null
+++ b/deeptutor/partners/channels/mochat.py
@@ -0,0 +1,1062 @@
+"""Mochat channel implementation using Socket.IO with HTTP polling fallback."""
+
+from __future__ import annotations
+
+import asyncio
+from collections import deque
+from dataclasses import dataclass, field
+from datetime import datetime, timezone
+import json
+from typing import Any
+
+import httpx
+from loguru import logger
+from pydantic import Field
+
+from deeptutor.partners.bus.events import OutboundMessage
+from deeptutor.partners.bus.queue import MessageBus
+from deeptutor.partners.channels.base import BaseChannel
+from deeptutor.partners.config.paths import get_runtime_subdir
+from deeptutor.partners.config.schema import Base, DeliveryOverrides
+
+try:
+ import socketio
+
+ SOCKETIO_AVAILABLE = True
+except ImportError:
+ socketio = None
+ SOCKETIO_AVAILABLE = False
+
+try:
+ import msgpack # noqa: F401
+
+ MSGPACK_AVAILABLE = True
+except ImportError:
+ MSGPACK_AVAILABLE = False
+
+MAX_SEEN_MESSAGE_IDS = 2000
+CURSOR_SAVE_DEBOUNCE_S = 0.5
+
+
+# ---------------------------------------------------------------------------
+# Data classes
+# ---------------------------------------------------------------------------
+
+
+@dataclass
+class MochatBufferedEntry:
+ """Buffered inbound entry for delayed dispatch."""
+
+ raw_body: str
+ author: str
+ sender_name: str = ""
+ sender_username: str = ""
+ timestamp: int | None = None
+ message_id: str = ""
+ group_id: str = ""
+
+
+@dataclass
+class DelayState:
+ """Per-target delayed message state."""
+
+ entries: list[MochatBufferedEntry] = field(default_factory=list)
+ lock: asyncio.Lock = field(default_factory=asyncio.Lock)
+ timer: asyncio.Task | None = None
+
+
+@dataclass
+class MochatTarget:
+ """Outbound target resolution result."""
+
+ id: str
+ is_panel: bool
+
+
+# ---------------------------------------------------------------------------
+# Pure helpers
+# ---------------------------------------------------------------------------
+
+
+def _safe_dict(value: Any) -> dict:
+ """Return *value* if it's a dict, else empty dict."""
+ return value if isinstance(value, dict) else {}
+
+
+def _str_field(src: dict, *keys: str) -> str:
+ """Return the first non-empty str value found for *keys*, stripped."""
+ for k in keys:
+ v = src.get(k)
+ if isinstance(v, str) and v.strip():
+ return v.strip()
+ return ""
+
+
+def _make_synthetic_event(
+ message_id: str,
+ author: str,
+ content: Any,
+ meta: Any,
+ group_id: str,
+ converse_id: str,
+ timestamp: Any = None,
+ *,
+ author_info: Any = None,
+) -> dict[str, Any]:
+ """Build a synthetic ``message.add`` event dict."""
+ payload: dict[str, Any] = {
+ "messageId": message_id,
+ "author": author,
+ "content": content,
+ "meta": _safe_dict(meta),
+ "groupId": group_id,
+ "converseId": converse_id,
+ }
+ if author_info is not None:
+ payload["authorInfo"] = _safe_dict(author_info)
+ return {
+ "type": "message.add",
+ "timestamp": timestamp or datetime.now(timezone.utc).replace(tzinfo=None).isoformat(),
+ "payload": payload,
+ }
+
+
+def normalize_mochat_content(content: Any) -> str:
+ """Normalize content payload to text."""
+ if isinstance(content, str):
+ return content.strip()
+ if content is None:
+ return ""
+ try:
+ return json.dumps(content, ensure_ascii=False)
+ except TypeError:
+ return str(content)
+
+
+def resolve_mochat_target(raw: str) -> MochatTarget:
+ """Resolve id and target kind from user-provided target string."""
+ trimmed = (raw or "").strip()
+ if not trimmed:
+ return MochatTarget(id="", is_panel=False)
+
+ lowered = trimmed.lower()
+ cleaned, forced_panel = trimmed, False
+ for prefix in ("mochat:", "group:", "channel:", "panel:"):
+ if lowered.startswith(prefix):
+ cleaned = trimmed[len(prefix) :].strip()
+ forced_panel = prefix in {"group:", "channel:", "panel:"}
+ break
+
+ if not cleaned:
+ return MochatTarget(id="", is_panel=False)
+ return MochatTarget(id=cleaned, is_panel=forced_panel or not cleaned.startswith("session_"))
+
+
+def extract_mention_ids(value: Any) -> list[str]:
+ """Extract mention ids from heterogeneous mention payload."""
+ if not isinstance(value, list):
+ return []
+ ids: list[str] = []
+ for item in value:
+ if isinstance(item, str):
+ if item.strip():
+ ids.append(item.strip())
+ elif isinstance(item, dict):
+ for key in ("id", "userId", "_id"):
+ candidate = item.get(key)
+ if isinstance(candidate, str) and candidate.strip():
+ ids.append(candidate.strip())
+ break
+ return ids
+
+
+def resolve_was_mentioned(payload: dict[str, Any], agent_user_id: str) -> bool:
+ """Resolve mention state from payload metadata and text fallback."""
+ meta = payload.get("meta")
+ if isinstance(meta, dict):
+ if meta.get("mentioned") is True or meta.get("wasMentioned") is True:
+ return True
+ for f in ("mentions", "mentionIds", "mentionedUserIds", "mentionedUsers"):
+ if agent_user_id and agent_user_id in extract_mention_ids(meta.get(f)):
+ return True
+ if not agent_user_id:
+ return False
+ content = payload.get("content")
+ if not isinstance(content, str) or not content:
+ return False
+ return f"<@{agent_user_id}>" in content or f"@{agent_user_id}" in content
+
+
+def resolve_require_mention(config: MochatConfig, session_id: str, group_id: str) -> bool:
+ """Resolve mention requirement for group/panel conversations."""
+ groups = config.groups or {}
+ for key in (group_id, session_id, "*"):
+ if key and key in groups:
+ return bool(groups[key].require_mention)
+ return bool(config.mention.require_in_groups)
+
+
+def build_buffered_body(entries: list[MochatBufferedEntry], is_group: bool) -> str:
+ """Build text body from one or more buffered entries."""
+ if not entries:
+ return ""
+ if len(entries) == 1:
+ return entries[0].raw_body
+ lines: list[str] = []
+ for entry in entries:
+ if not entry.raw_body:
+ continue
+ if is_group:
+ label = entry.sender_name.strip() or entry.sender_username.strip() or entry.author
+ if label:
+ lines.append(f"{label}: {entry.raw_body}")
+ continue
+ lines.append(entry.raw_body)
+ return "\n".join(lines).strip()
+
+
+def parse_timestamp(value: Any) -> int | None:
+ """Parse event timestamp to epoch milliseconds."""
+ if not isinstance(value, str) or not value.strip():
+ return None
+ try:
+ return int(datetime.fromisoformat(value.replace("Z", "+00:00")).timestamp() * 1000)
+ except ValueError:
+ return None
+
+
+# ---------------------------------------------------------------------------
+# Config classes
+# ---------------------------------------------------------------------------
+
+
+class MochatMentionConfig(Base):
+ """Mochat mention behavior configuration."""
+
+ require_in_groups: bool = False
+
+
+class MochatGroupRule(Base):
+ """Mochat per-group mention requirement."""
+
+ require_mention: bool = False
+
+
+class MochatConfig(DeliveryOverrides):
+ """Mochat channel configuration."""
+
+ enabled: bool = False
+ base_url: str = "https://mochat.io"
+ socket_url: str = ""
+ socket_path: str = "/socket.io"
+ socket_disable_msgpack: bool = False
+ socket_reconnect_delay_ms: int = 1000
+ socket_max_reconnect_delay_ms: int = 10000
+ socket_connect_timeout_ms: int = 10000
+ refresh_interval_ms: int = 30000
+ watch_timeout_ms: int = 25000
+ watch_limit: int = 100
+ retry_delay_ms: int = 500
+ max_retry_attempts: int = 0
+ claw_token: str = ""
+ agent_user_id: str = ""
+ sessions: list[str] = Field(default_factory=list)
+ panels: list[str] = Field(default_factory=list)
+ allow_from: list[str] = Field(default_factory=list)
+ mention: MochatMentionConfig = Field(default_factory=MochatMentionConfig)
+ groups: dict[str, MochatGroupRule] = Field(default_factory=dict)
+ reply_delay_mode: str = "non-mention"
+ reply_delay_ms: int = 120000
+
+
+# ---------------------------------------------------------------------------
+# Channel
+# ---------------------------------------------------------------------------
+
+
+class MochatChannel(BaseChannel):
+ """Mochat channel using socket.io with fallback polling workers."""
+
+ name = "mochat"
+ display_name = "Mochat"
+
+ @classmethod
+ def default_config(cls) -> dict[str, Any]:
+ return MochatConfig().model_dump(by_alias=True)
+
+ def __init__(self, config: Any, bus: MessageBus):
+ if isinstance(config, dict):
+ config = MochatConfig.model_validate(config)
+ super().__init__(config, bus)
+ self.config: MochatConfig = config
+ self._http: httpx.AsyncClient | None = None
+ self._socket: Any = None
+ self._ws_connected = self._ws_ready = False
+
+ self._state_dir = get_runtime_subdir("mochat")
+ self._cursor_path = self._state_dir / "session_cursors.json"
+ self._session_cursor: dict[str, int] = {}
+ self._cursor_save_task: asyncio.Task | None = None
+
+ self._session_set: set[str] = set()
+ self._panel_set: set[str] = set()
+ self._auto_discover_sessions = self._auto_discover_panels = False
+
+ self._cold_sessions: set[str] = set()
+ self._session_by_converse: dict[str, str] = {}
+
+ self._seen_set: dict[str, set[str]] = {}
+ self._seen_queue: dict[str, deque[str]] = {}
+ self._delay_states: dict[str, DelayState] = {}
+
+ self._fallback_mode = False
+ self._session_fallback_tasks: dict[str, asyncio.Task] = {}
+ self._panel_fallback_tasks: dict[str, asyncio.Task] = {}
+ self._refresh_task: asyncio.Task | None = None
+ self._target_locks: dict[str, asyncio.Lock] = {}
+
+ # ---- lifecycle ---------------------------------------------------------
+
+ async def start(self) -> None:
+ """Start Mochat channel workers and websocket connection."""
+ if not self.config.claw_token:
+ logger.error("Mochat claw_token not configured")
+ return
+
+ self._running = True
+ self._http = httpx.AsyncClient(timeout=30.0)
+ self._state_dir.mkdir(parents=True, exist_ok=True)
+ await self._load_session_cursors()
+ self._seed_targets_from_config()
+ await self._refresh_targets(subscribe_new=False)
+
+ if not await self._start_socket_client():
+ await self._ensure_fallback_workers()
+
+ self._refresh_task = asyncio.create_task(self._refresh_loop())
+ while self._running:
+ await asyncio.sleep(1)
+
+ async def stop(self) -> None:
+ """Stop all workers and clean up resources."""
+ self._running = False
+ if self._refresh_task:
+ self._refresh_task.cancel()
+ self._refresh_task = None
+
+ await self._stop_fallback_workers()
+ await self._cancel_delay_timers()
+
+ if self._socket:
+ try:
+ await self._socket.disconnect()
+ except Exception:
+ pass
+ self._socket = None
+
+ if self._cursor_save_task:
+ self._cursor_save_task.cancel()
+ self._cursor_save_task = None
+ await self._save_session_cursors()
+
+ if self._http:
+ await self._http.aclose()
+ self._http = None
+ self._ws_connected = self._ws_ready = False
+
+ async def send(self, msg: OutboundMessage) -> None:
+ """Send outbound message to session or panel."""
+ if not self.config.claw_token:
+ logger.warning("Mochat claw_token missing, skip send")
+ return
+
+ parts = [msg.content.strip()] if msg.content and msg.content.strip() else []
+ if msg.media:
+ parts.extend(m for m in msg.media if isinstance(m, str) and m.strip())
+ content = "\n".join(parts).strip()
+ if not content:
+ return
+
+ target = resolve_mochat_target(msg.chat_id)
+ if not target.id:
+ logger.warning("Mochat outbound target is empty")
+ return
+
+ is_panel = (target.is_panel or target.id in self._panel_set) and not target.id.startswith(
+ "session_"
+ )
+ try:
+ if is_panel:
+ await self._api_send(
+ "/api/claw/groups/panels/send",
+ "panelId",
+ target.id,
+ content,
+ msg.reply_to,
+ self._read_group_id(msg.metadata),
+ )
+ else:
+ await self._api_send(
+ "/api/claw/sessions/send", "sessionId", target.id, content, msg.reply_to
+ )
+ except Exception as e:
+ logger.error("Failed to send Mochat message: {}", e)
+
+ # ---- config / init helpers ---------------------------------------------
+
+ def _seed_targets_from_config(self) -> None:
+ sessions, self._auto_discover_sessions = self._normalize_id_list(self.config.sessions)
+ panels, self._auto_discover_panels = self._normalize_id_list(self.config.panels)
+ self._session_set.update(sessions)
+ self._panel_set.update(panels)
+ for sid in sessions:
+ if sid not in self._session_cursor:
+ self._cold_sessions.add(sid)
+
+ @staticmethod
+ def _normalize_id_list(values: list[str]) -> tuple[list[str], bool]:
+ cleaned = [str(v).strip() for v in values if str(v).strip()]
+ return sorted({v for v in cleaned if v != "*"}), "*" in cleaned
+
+ # ---- websocket ---------------------------------------------------------
+
+ async def _start_socket_client(self) -> bool:
+ if not SOCKETIO_AVAILABLE:
+ logger.warning("python-socketio not installed, Mochat using polling fallback")
+ return False
+
+ serializer = "default"
+ if not self.config.socket_disable_msgpack:
+ if MSGPACK_AVAILABLE:
+ serializer = "msgpack"
+ else:
+ logger.warning("msgpack not installed but socket_disable_msgpack=false; using JSON")
+
+ client = socketio.AsyncClient(
+ reconnection=True,
+ reconnection_attempts=self.config.max_retry_attempts or None,
+ reconnection_delay=max(0.1, self.config.socket_reconnect_delay_ms / 1000.0),
+ reconnection_delay_max=max(0.1, self.config.socket_max_reconnect_delay_ms / 1000.0),
+ logger=False,
+ engineio_logger=False,
+ serializer=serializer,
+ )
+
+ @client.event
+ async def connect() -> None:
+ self._ws_connected, self._ws_ready = True, False
+ logger.info("Mochat websocket connected")
+ subscribed = await self._subscribe_all()
+ self._ws_ready = subscribed
+ await (self._stop_fallback_workers() if subscribed else self._ensure_fallback_workers())
+
+ @client.event
+ async def disconnect() -> None:
+ if not self._running:
+ return
+ self._ws_connected = self._ws_ready = False
+ logger.warning("Mochat websocket disconnected")
+ await self._ensure_fallback_workers()
+
+ @client.event
+ async def connect_error(data: Any) -> None:
+ logger.error("Mochat websocket connect error: {}", data)
+
+ @client.on("claw.session.events")
+ async def on_session_events(payload: dict[str, Any]) -> None:
+ await self._handle_watch_payload(payload, "session")
+
+ @client.on("claw.panel.events")
+ async def on_panel_events(payload: dict[str, Any]) -> None:
+ await self._handle_watch_payload(payload, "panel")
+
+ for ev in (
+ "notify:chat.inbox.append",
+ "notify:chat.message.add",
+ "notify:chat.message.update",
+ "notify:chat.message.recall",
+ "notify:chat.message.delete",
+ ):
+ client.on(ev, self._build_notify_handler(ev))
+
+ socket_url = (self.config.socket_url or self.config.base_url).strip().rstrip("/")
+ socket_path = (self.config.socket_path or "/socket.io").strip().lstrip("/")
+
+ try:
+ self._socket = client
+ await client.connect(
+ socket_url,
+ transports=["websocket"],
+ socketio_path=socket_path,
+ auth={"token": self.config.claw_token},
+ wait_timeout=max(1.0, self.config.socket_connect_timeout_ms / 1000.0),
+ )
+ return True
+ except Exception as e:
+ logger.error("Failed to connect Mochat websocket: {}", e)
+ try:
+ await client.disconnect()
+ except Exception:
+ pass
+ self._socket = None
+ return False
+
+ def _build_notify_handler(self, event_name: str):
+ async def handler(payload: Any) -> None:
+ if event_name == "notify:chat.inbox.append":
+ await self._handle_notify_inbox_append(payload)
+ elif event_name.startswith("notify:chat.message."):
+ await self._handle_notify_chat_message(payload)
+
+ return handler
+
+ # ---- subscribe ---------------------------------------------------------
+
+ async def _subscribe_all(self) -> bool:
+ ok = await self._subscribe_sessions(sorted(self._session_set))
+ ok = await self._subscribe_panels(sorted(self._panel_set)) and ok
+ if self._auto_discover_sessions or self._auto_discover_panels:
+ await self._refresh_targets(subscribe_new=True)
+ return ok
+
+ async def _subscribe_sessions(self, session_ids: list[str]) -> bool:
+ if not session_ids:
+ return True
+ for sid in session_ids:
+ if sid not in self._session_cursor:
+ self._cold_sessions.add(sid)
+
+ ack = await self._socket_call(
+ "com.claw.im.subscribeSessions",
+ {
+ "sessionIds": session_ids,
+ "cursors": self._session_cursor,
+ "limit": self.config.watch_limit,
+ },
+ )
+ if not ack.get("result"):
+ logger.error("Mochat subscribeSessions failed: {}", ack.get("message", "unknown error"))
+ return False
+
+ data = ack.get("data")
+ items: list[dict[str, Any]] = []
+ if isinstance(data, list):
+ items = [i for i in data if isinstance(i, dict)]
+ elif isinstance(data, dict):
+ sessions = data.get("sessions")
+ if isinstance(sessions, list):
+ items = [i for i in sessions if isinstance(i, dict)]
+ elif "sessionId" in data:
+ items = [data]
+ for p in items:
+ await self._handle_watch_payload(p, "session")
+ return True
+
+ async def _subscribe_panels(self, panel_ids: list[str]) -> bool:
+ if not self._auto_discover_panels and not panel_ids:
+ return True
+ ack = await self._socket_call("com.claw.im.subscribePanels", {"panelIds": panel_ids})
+ if not ack.get("result"):
+ logger.error("Mochat subscribePanels failed: {}", ack.get("message", "unknown error"))
+ return False
+ return True
+
+ async def _socket_call(self, event_name: str, payload: dict[str, Any]) -> dict[str, Any]:
+ if not self._socket:
+ return {"result": False, "message": "socket not connected"}
+ try:
+ raw = await self._socket.call(event_name, payload, timeout=10)
+ except Exception as e:
+ return {"result": False, "message": str(e)}
+ return raw if isinstance(raw, dict) else {"result": True, "data": raw}
+
+ # ---- refresh / discovery -----------------------------------------------
+
+ async def _refresh_loop(self) -> None:
+ interval_s = max(1.0, self.config.refresh_interval_ms / 1000.0)
+ while self._running:
+ await asyncio.sleep(interval_s)
+ try:
+ await self._refresh_targets(subscribe_new=self._ws_ready)
+ except Exception as e:
+ logger.warning("Mochat refresh failed: {}", e)
+ if self._fallback_mode:
+ await self._ensure_fallback_workers()
+
+ async def _refresh_targets(self, subscribe_new: bool) -> None:
+ if self._auto_discover_sessions:
+ await self._refresh_sessions_directory(subscribe_new)
+ if self._auto_discover_panels:
+ await self._refresh_panels(subscribe_new)
+
+ async def _refresh_sessions_directory(self, subscribe_new: bool) -> None:
+ try:
+ response = await self._post_json("/api/claw/sessions/list", {})
+ except Exception as e:
+ logger.warning("Mochat listSessions failed: {}", e)
+ return
+
+ sessions = response.get("sessions")
+ if not isinstance(sessions, list):
+ return
+
+ new_ids: list[str] = []
+ for s in sessions:
+ if not isinstance(s, dict):
+ continue
+ sid = _str_field(s, "sessionId")
+ if not sid:
+ continue
+ if sid not in self._session_set:
+ self._session_set.add(sid)
+ new_ids.append(sid)
+ if sid not in self._session_cursor:
+ self._cold_sessions.add(sid)
+ cid = _str_field(s, "converseId")
+ if cid:
+ self._session_by_converse[cid] = sid
+
+ if not new_ids:
+ return
+ if self._ws_ready and subscribe_new:
+ await self._subscribe_sessions(new_ids)
+ if self._fallback_mode:
+ await self._ensure_fallback_workers()
+
+ async def _refresh_panels(self, subscribe_new: bool) -> None:
+ try:
+ response = await self._post_json("/api/claw/groups/get", {})
+ except Exception as e:
+ logger.warning("Mochat getWorkspaceGroup failed: {}", e)
+ return
+
+ raw_panels = response.get("panels")
+ if not isinstance(raw_panels, list):
+ return
+
+ new_ids: list[str] = []
+ for p in raw_panels:
+ if not isinstance(p, dict):
+ continue
+ pt = p.get("type")
+ if isinstance(pt, int) and pt != 0:
+ continue
+ pid = _str_field(p, "id", "_id")
+ if pid and pid not in self._panel_set:
+ self._panel_set.add(pid)
+ new_ids.append(pid)
+
+ if not new_ids:
+ return
+ if self._ws_ready and subscribe_new:
+ await self._subscribe_panels(new_ids)
+ if self._fallback_mode:
+ await self._ensure_fallback_workers()
+
+ # ---- fallback workers --------------------------------------------------
+
+ async def _ensure_fallback_workers(self) -> None:
+ if not self._running:
+ return
+ self._fallback_mode = True
+ for sid in sorted(self._session_set):
+ t = self._session_fallback_tasks.get(sid)
+ if not t or t.done():
+ self._session_fallback_tasks[sid] = asyncio.create_task(
+ self._session_watch_worker(sid)
+ )
+ for pid in sorted(self._panel_set):
+ t = self._panel_fallback_tasks.get(pid)
+ if not t or t.done():
+ self._panel_fallback_tasks[pid] = asyncio.create_task(self._panel_poll_worker(pid))
+
+ async def _stop_fallback_workers(self) -> None:
+ self._fallback_mode = False
+ tasks = [*self._session_fallback_tasks.values(), *self._panel_fallback_tasks.values()]
+ for t in tasks:
+ t.cancel()
+ if tasks:
+ await asyncio.gather(*tasks, return_exceptions=True)
+ self._session_fallback_tasks.clear()
+ self._panel_fallback_tasks.clear()
+
+ async def _session_watch_worker(self, session_id: str) -> None:
+ while self._running and self._fallback_mode:
+ try:
+ payload = await self._post_json(
+ "/api/claw/sessions/watch",
+ {
+ "sessionId": session_id,
+ "cursor": self._session_cursor.get(session_id, 0),
+ "timeoutMs": self.config.watch_timeout_ms,
+ "limit": self.config.watch_limit,
+ },
+ )
+ await self._handle_watch_payload(payload, "session")
+ except asyncio.CancelledError:
+ break
+ except Exception as e:
+ logger.warning("Mochat watch fallback error ({}): {}", session_id, e)
+ await asyncio.sleep(max(0.1, self.config.retry_delay_ms / 1000.0))
+
+ async def _panel_poll_worker(self, panel_id: str) -> None:
+ sleep_s = max(1.0, self.config.refresh_interval_ms / 1000.0)
+ while self._running and self._fallback_mode:
+ try:
+ resp = await self._post_json(
+ "/api/claw/groups/panels/messages",
+ {
+ "panelId": panel_id,
+ "limit": min(100, max(1, self.config.watch_limit)),
+ },
+ )
+ msgs = resp.get("messages")
+ if isinstance(msgs, list):
+ for m in reversed(msgs):
+ if not isinstance(m, dict):
+ continue
+ evt = _make_synthetic_event(
+ message_id=str(m.get("messageId") or ""),
+ author=str(m.get("author") or ""),
+ content=m.get("content"),
+ meta=m.get("meta"),
+ group_id=str(resp.get("groupId") or ""),
+ converse_id=panel_id,
+ timestamp=m.get("createdAt"),
+ author_info=m.get("authorInfo"),
+ )
+ await self._process_inbound_event(panel_id, evt, "panel")
+ except asyncio.CancelledError:
+ break
+ except Exception as e:
+ logger.warning("Mochat panel polling error ({}): {}", panel_id, e)
+ await asyncio.sleep(sleep_s)
+
+ # ---- inbound event processing ------------------------------------------
+
+ async def _handle_watch_payload(self, payload: dict[str, Any], target_kind: str) -> None:
+ if not isinstance(payload, dict):
+ return
+ target_id = _str_field(payload, "sessionId")
+ if not target_id:
+ return
+
+ lock = self._target_locks.setdefault(f"{target_kind}:{target_id}", asyncio.Lock())
+ async with lock:
+ prev = self._session_cursor.get(target_id, 0) if target_kind == "session" else 0
+ pc = payload.get("cursor")
+ if target_kind == "session" and isinstance(pc, int) and pc >= 0:
+ self._mark_session_cursor(target_id, pc)
+
+ raw_events = payload.get("events")
+ if not isinstance(raw_events, list):
+ return
+ if target_kind == "session" and target_id in self._cold_sessions:
+ self._cold_sessions.discard(target_id)
+ return
+
+ for event in raw_events:
+ if not isinstance(event, dict):
+ continue
+ seq = event.get("seq")
+ if (
+ target_kind == "session"
+ and isinstance(seq, int)
+ and seq > self._session_cursor.get(target_id, prev)
+ ):
+ self._mark_session_cursor(target_id, seq)
+ if event.get("type") == "message.add":
+ await self._process_inbound_event(target_id, event, target_kind)
+
+ async def _process_inbound_event(
+ self, target_id: str, event: dict[str, Any], target_kind: str
+ ) -> None:
+ payload = event.get("payload")
+ if not isinstance(payload, dict):
+ return
+
+ author = _str_field(payload, "author")
+ if not author or (self.config.agent_user_id and author == self.config.agent_user_id):
+ return
+ if not self.is_allowed(author):
+ return
+
+ message_id = _str_field(payload, "messageId")
+ seen_key = f"{target_kind}:{target_id}"
+ if message_id and self._remember_message_id(seen_key, message_id):
+ return
+
+ raw_body = normalize_mochat_content(payload.get("content")) or "[empty message]"
+ ai = _safe_dict(payload.get("authorInfo"))
+ sender_name = _str_field(ai, "nickname", "email")
+ sender_username = _str_field(ai, "agentId")
+
+ group_id = _str_field(payload, "groupId")
+ is_group = bool(group_id)
+ was_mentioned = resolve_was_mentioned(payload, self.config.agent_user_id)
+ require_mention = (
+ target_kind == "panel"
+ and is_group
+ and resolve_require_mention(self.config, target_id, group_id)
+ )
+ use_delay = target_kind == "panel" and self.config.reply_delay_mode == "non-mention"
+
+ if require_mention and not was_mentioned and not use_delay:
+ return
+
+ entry = MochatBufferedEntry(
+ raw_body=raw_body,
+ author=author,
+ sender_name=sender_name,
+ sender_username=sender_username,
+ timestamp=parse_timestamp(event.get("timestamp")),
+ message_id=message_id,
+ group_id=group_id,
+ )
+
+ if use_delay:
+ delay_key = seen_key
+ if was_mentioned:
+ await self._flush_delayed_entries(
+ delay_key, target_id, target_kind, "mention", entry
+ )
+ else:
+ await self._enqueue_delayed_entry(delay_key, target_id, target_kind, entry)
+ return
+
+ await self._dispatch_entries(target_id, target_kind, [entry], was_mentioned)
+
+ # ---- dedup / buffering -------------------------------------------------
+
+ def _remember_message_id(self, key: str, message_id: str) -> bool:
+ seen_set = self._seen_set.setdefault(key, set())
+ seen_queue = self._seen_queue.setdefault(key, deque())
+ if message_id in seen_set:
+ return True
+ seen_set.add(message_id)
+ seen_queue.append(message_id)
+ while len(seen_queue) > MAX_SEEN_MESSAGE_IDS:
+ seen_set.discard(seen_queue.popleft())
+ return False
+
+ async def _enqueue_delayed_entry(
+ self, key: str, target_id: str, target_kind: str, entry: MochatBufferedEntry
+ ) -> None:
+ state = self._delay_states.setdefault(key, DelayState())
+ async with state.lock:
+ state.entries.append(entry)
+ if state.timer:
+ state.timer.cancel()
+ state.timer = asyncio.create_task(self._delay_flush_after(key, target_id, target_kind))
+
+ async def _delay_flush_after(self, key: str, target_id: str, target_kind: str) -> None:
+ await asyncio.sleep(max(0, self.config.reply_delay_ms) / 1000.0)
+ await self._flush_delayed_entries(key, target_id, target_kind, "timer", None)
+
+ async def _flush_delayed_entries(
+ self,
+ key: str,
+ target_id: str,
+ target_kind: str,
+ reason: str,
+ entry: MochatBufferedEntry | None,
+ ) -> None:
+ state = self._delay_states.setdefault(key, DelayState())
+ async with state.lock:
+ if entry:
+ state.entries.append(entry)
+ current = asyncio.current_task()
+ if state.timer and state.timer is not current:
+ state.timer.cancel()
+ state.timer = None
+ entries = state.entries[:]
+ state.entries.clear()
+ if entries:
+ await self._dispatch_entries(target_id, target_kind, entries, reason == "mention")
+
+ async def _dispatch_entries(
+ self,
+ target_id: str,
+ target_kind: str,
+ entries: list[MochatBufferedEntry],
+ was_mentioned: bool,
+ ) -> None:
+ if not entries:
+ return
+ last = entries[-1]
+ is_group = bool(last.group_id)
+ body = build_buffered_body(entries, is_group) or "[empty message]"
+ await self._handle_message(
+ sender_id=last.author,
+ chat_id=target_id,
+ content=body,
+ metadata={
+ "message_id": last.message_id,
+ "timestamp": last.timestamp,
+ "is_group": is_group,
+ "group_id": last.group_id,
+ "sender_name": last.sender_name,
+ "sender_username": last.sender_username,
+ "target_kind": target_kind,
+ "was_mentioned": was_mentioned,
+ "buffered_count": len(entries),
+ },
+ )
+
+ async def _cancel_delay_timers(self) -> None:
+ for state in self._delay_states.values():
+ if state.timer:
+ state.timer.cancel()
+ self._delay_states.clear()
+
+ # ---- notify handlers ---------------------------------------------------
+
+ async def _handle_notify_chat_message(self, payload: Any) -> None:
+ if not isinstance(payload, dict):
+ return
+ group_id = _str_field(payload, "groupId")
+ panel_id = _str_field(payload, "converseId", "panelId")
+ if not group_id or not panel_id:
+ return
+ if self._panel_set and panel_id not in self._panel_set:
+ return
+
+ evt = _make_synthetic_event(
+ message_id=str(payload.get("_id") or payload.get("messageId") or ""),
+ author=str(payload.get("author") or ""),
+ content=payload.get("content"),
+ meta=payload.get("meta"),
+ group_id=group_id,
+ converse_id=panel_id,
+ timestamp=payload.get("createdAt"),
+ author_info=payload.get("authorInfo"),
+ )
+ await self._process_inbound_event(panel_id, evt, "panel")
+
+ async def _handle_notify_inbox_append(self, payload: Any) -> None:
+ if not isinstance(payload, dict) or payload.get("type") != "message":
+ return
+ detail = payload.get("payload")
+ if not isinstance(detail, dict):
+ return
+ if _str_field(detail, "groupId"):
+ return
+ converse_id = _str_field(detail, "converseId")
+ if not converse_id:
+ return
+
+ session_id = self._session_by_converse.get(converse_id)
+ if not session_id:
+ await self._refresh_sessions_directory(self._ws_ready)
+ session_id = self._session_by_converse.get(converse_id)
+ if not session_id:
+ return
+
+ evt = _make_synthetic_event(
+ message_id=str(detail.get("messageId") or payload.get("_id") or ""),
+ author=str(detail.get("messageAuthor") or ""),
+ content=str(detail.get("messagePlainContent") or detail.get("messageSnippet") or ""),
+ meta={"source": "notify:chat.inbox.append", "converseId": converse_id},
+ group_id="",
+ converse_id=converse_id,
+ timestamp=payload.get("createdAt"),
+ )
+ await self._process_inbound_event(session_id, evt, "session")
+
+ # ---- cursor persistence ------------------------------------------------
+
+ def _mark_session_cursor(self, session_id: str, cursor: int) -> None:
+ if cursor < 0 or cursor < self._session_cursor.get(session_id, 0):
+ return
+ self._session_cursor[session_id] = cursor
+ if not self._cursor_save_task or self._cursor_save_task.done():
+ self._cursor_save_task = asyncio.create_task(self._save_cursor_debounced())
+
+ async def _save_cursor_debounced(self) -> None:
+ await asyncio.sleep(CURSOR_SAVE_DEBOUNCE_S)
+ await self._save_session_cursors()
+
+ async def _load_session_cursors(self) -> None:
+ if not self._cursor_path.exists():
+ return
+ try:
+ data = json.loads(self._cursor_path.read_text("utf-8"))
+ except Exception as e:
+ logger.warning("Failed to read Mochat cursor file: {}", e)
+ return
+ cursors = data.get("cursors") if isinstance(data, dict) else None
+ if isinstance(cursors, dict):
+ for sid, cur in cursors.items():
+ if isinstance(sid, str) and isinstance(cur, int) and cur >= 0:
+ self._session_cursor[sid] = cur
+
+ async def _save_session_cursors(self) -> None:
+ try:
+ self._state_dir.mkdir(parents=True, exist_ok=True)
+ self._cursor_path.write_text(
+ json.dumps(
+ {
+ "schemaVersion": 1,
+ "updatedAt": datetime.now(timezone.utc).replace(tzinfo=None).isoformat(),
+ "cursors": self._session_cursor,
+ },
+ ensure_ascii=False,
+ indent=2,
+ )
+ + "\n",
+ "utf-8",
+ )
+ except Exception as e:
+ logger.warning("Failed to save Mochat cursor file: {}", e)
+
+ # ---- HTTP helpers ------------------------------------------------------
+
+ async def _post_json(self, path: str, payload: dict[str, Any]) -> dict[str, Any]:
+ if not self._http:
+ raise RuntimeError("Mochat HTTP client not initialized")
+ url = f"{self.config.base_url.strip().rstrip('/')}{path}"
+ response = await self._http.post(
+ url,
+ headers={
+ "Content-Type": "application/json",
+ "X-Claw-Token": self.config.claw_token,
+ },
+ json=payload,
+ )
+ if not response.is_success:
+ raise RuntimeError(f"Mochat HTTP {response.status_code}: {response.text[:200]}")
+ try:
+ parsed = response.json()
+ except Exception:
+ parsed = response.text
+ if isinstance(parsed, dict) and isinstance(parsed.get("code"), int):
+ if parsed["code"] != 200:
+ msg = str(parsed.get("message") or parsed.get("name") or "request failed")
+ raise RuntimeError(f"Mochat API error: {msg} (code={parsed['code']})")
+ data = parsed.get("data")
+ return data if isinstance(data, dict) else {}
+ return parsed if isinstance(parsed, dict) else {}
+
+ async def _api_send(
+ self,
+ path: str,
+ id_key: str,
+ id_val: str,
+ content: str,
+ reply_to: str | None,
+ group_id: str | None = None,
+ ) -> dict[str, Any]:
+ """Unified send helper for session and panel messages."""
+ body: dict[str, Any] = {id_key: id_val, "content": content}
+ if reply_to:
+ body["replyTo"] = reply_to
+ if group_id:
+ body["groupId"] = group_id
+ return await self._post_json(path, body)
+
+ @staticmethod
+ def _read_group_id(metadata: dict[str, Any]) -> str | None:
+ if not isinstance(metadata, dict):
+ return None
+ value = metadata.get("group_id") or metadata.get("groupId")
+ return value.strip() if isinstance(value, str) and value.strip() else None
diff --git a/deeptutor/partners/channels/qq.py b/deeptutor/partners/channels/qq.py
new file mode 100644
index 000000000..b03e4fb67
--- /dev/null
+++ b/deeptutor/partners/channels/qq.py
@@ -0,0 +1,186 @@
+"""QQ channel implementation using botpy SDK."""
+
+import asyncio
+from collections import deque
+from typing import TYPE_CHECKING, Any, Literal
+
+from loguru import logger
+from pydantic import Field
+
+from deeptutor.partners.bus.events import OutboundMessage
+from deeptutor.partners.bus.queue import MessageBus
+from deeptutor.partners.channels.base import BaseChannel
+from deeptutor.partners.config.schema import Base, DeliveryOverrides
+
+try:
+ import botpy
+ from botpy.message import C2CMessage, GroupMessage
+
+ QQ_AVAILABLE = True
+except ImportError:
+ QQ_AVAILABLE = False
+ botpy = None
+ C2CMessage = None
+ GroupMessage = None
+
+if TYPE_CHECKING:
+ from botpy.message import C2CMessage, GroupMessage
+
+
+def _make_bot_class(channel: "QQChannel") -> "type[botpy.Client]":
+ """Create a botpy Client subclass bound to the given channel."""
+ intents = botpy.Intents(public_messages=True, direct_message=True)
+
+ class _Bot(botpy.Client):
+ def __init__(self):
+ # Disable botpy's file log — tutorbot uses loguru; default "botpy.log" fails on read-only fs
+ super().__init__(intents=intents, ext_handlers=False)
+
+ async def on_ready(self):
+ logger.info("QQ bot ready: {}", self.robot.name)
+
+ async def on_c2c_message_create(self, message: "C2CMessage"):
+ await channel._on_message(message, is_group=False)
+
+ async def on_group_at_message_create(self, message: "GroupMessage"):
+ await channel._on_message(message, is_group=True)
+
+ async def on_direct_message_create(self, message):
+ await channel._on_message(message, is_group=False)
+
+ return _Bot
+
+
+class QQConfig(DeliveryOverrides):
+ """QQ channel configuration using botpy SDK."""
+
+ enabled: bool = False
+ app_id: str = ""
+ secret: str = ""
+ allow_from: list[str] = Field(default_factory=list)
+ msg_format: Literal["plain", "markdown"] = "plain"
+
+
+class QQChannel(BaseChannel):
+ """QQ channel using botpy SDK with WebSocket connection."""
+
+ name = "qq"
+ display_name = "QQ"
+
+ @classmethod
+ def default_config(cls) -> dict[str, Any]:
+ return QQConfig().model_dump(by_alias=True)
+
+ def __init__(self, config: Any, bus: MessageBus):
+ if isinstance(config, dict):
+ config = QQConfig.model_validate(config)
+ super().__init__(config, bus)
+ self.config: QQConfig = config
+ self._client: "botpy.Client | None" = None
+ self._processed_ids: deque = deque(maxlen=1000)
+ self._msg_seq: int = 1 # 消息序列号,避免被 QQ API 去重
+ self._chat_type_cache: dict[str, str] = {}
+
+ async def start(self) -> None:
+ """Start the QQ bot."""
+ if not QQ_AVAILABLE:
+ logger.error("QQ SDK not installed. Run: pip install qq-botpy")
+ return
+
+ if not self.config.app_id or not self.config.secret:
+ logger.error("QQ app_id and secret not configured")
+ return
+
+ self._running = True
+ BotClass = _make_bot_class(self)
+ self._client = BotClass()
+ logger.info("QQ bot started (C2C & Group supported)")
+ await self._run_bot()
+
+ async def _run_bot(self) -> None:
+ """Run the bot connection with auto-reconnect."""
+ while self._running:
+ try:
+ await self._client.start(appid=self.config.app_id, secret=self.config.secret)
+ except Exception as e:
+ logger.warning("QQ bot error: {}", e)
+ if self._running:
+ logger.info("Reconnecting QQ bot in 5 seconds...")
+ await asyncio.sleep(5)
+
+ async def stop(self) -> None:
+ """Stop the QQ bot."""
+ self._running = False
+ if self._client:
+ try:
+ await self._client.close()
+ except Exception:
+ pass
+ logger.info("QQ bot stopped")
+
+ async def send(self, msg: OutboundMessage) -> None:
+ """Send a message through QQ."""
+ if not self._client:
+ logger.warning("QQ client not initialized")
+ return
+
+ try:
+ msg_id = msg.metadata.get("message_id")
+ self._msg_seq += 1
+ use_markdown = self.config.msg_format == "markdown"
+ payload: dict[str, Any] = {
+ "msg_type": 2 if use_markdown else 0,
+ "msg_id": msg_id,
+ "msg_seq": self._msg_seq,
+ }
+ if use_markdown:
+ payload["markdown"] = {"content": msg.content}
+ else:
+ payload["content"] = msg.content
+
+ chat_type = self._chat_type_cache.get(msg.chat_id, "c2c")
+ if chat_type == "group":
+ await self._client.api.post_group_message(
+ group_openid=msg.chat_id,
+ **payload,
+ )
+ else:
+ await self._client.api.post_c2c_message(
+ openid=msg.chat_id,
+ **payload,
+ )
+ except Exception as e:
+ logger.error("Error sending QQ message: {}", e)
+
+ async def _on_message(self, data: "C2CMessage | GroupMessage", is_group: bool = False) -> None:
+ """Handle incoming message from QQ."""
+ try:
+ # Dedup by message ID
+ if data.id in self._processed_ids:
+ return
+ self._processed_ids.append(data.id)
+
+ content = (data.content or "").strip()
+ if not content:
+ return
+
+ if is_group:
+ chat_id = data.group_openid
+ user_id = data.author.member_openid
+ self._chat_type_cache[chat_id] = "group"
+ else:
+ chat_id = str(
+ getattr(data.author, "id", None)
+ or getattr(data.author, "user_openid", "unknown")
+ )
+ user_id = chat_id
+ self._chat_type_cache[chat_id] = "c2c"
+
+ await self._handle_message(
+ sender_id=user_id,
+ chat_id=chat_id,
+ content=content,
+ metadata={"message_id": data.id},
+ )
+ except Exception:
+ logger.exception("Error handling QQ message")
diff --git a/deeptutor/partners/channels/registry.py b/deeptutor/partners/channels/registry.py
new file mode 100644
index 000000000..f71b3cbe5
--- /dev/null
+++ b/deeptutor/partners/channels/registry.py
@@ -0,0 +1,71 @@
+"""Auto-discovery for built-in channel modules and external plugins."""
+
+from __future__ import annotations
+
+import importlib
+import pkgutil
+from typing import TYPE_CHECKING
+
+from loguru import logger
+
+if TYPE_CHECKING:
+ from deeptutor.partners.channels.base import BaseChannel
+
+_INTERNAL = frozenset({"base", "manager", "registry"})
+
+
+def discover_channel_names() -> list[str]:
+ """Return all built-in channel module names by scanning the package (zero imports)."""
+ import deeptutor.partners.channels as pkg
+
+ return [
+ name
+ for _, name, ispkg in pkgutil.iter_modules(pkg.__path__)
+ if name not in _INTERNAL and not ispkg
+ ]
+
+
+def load_channel_class(module_name: str) -> type[BaseChannel]:
+ """Import *module_name* and return the first BaseChannel subclass found."""
+ from deeptutor.partners.channels.base import BaseChannel as _Base
+
+ mod = importlib.import_module(f"deeptutor.partners.channels.{module_name}")
+ for attr in dir(mod):
+ obj = getattr(mod, attr)
+ if isinstance(obj, type) and issubclass(obj, _Base) and obj is not _Base:
+ return obj
+ raise ImportError(f"No BaseChannel subclass in deeptutor.partners.channels.{module_name}")
+
+
+def discover_plugins() -> dict[str, type[BaseChannel]]:
+ """Discover external channel plugins registered via entry_points."""
+ from importlib.metadata import entry_points
+
+ plugins: dict[str, type[BaseChannel]] = {}
+ for ep in entry_points(group="deeptutor.partners.channels"):
+ try:
+ cls = ep.load()
+ plugins[ep.name] = cls
+ except Exception as e:
+ logger.warning("Failed to load channel plugin '{}': {}", ep.name, e)
+ return plugins
+
+
+def discover_all() -> dict[str, type[BaseChannel]]:
+ """Return all channels: built-in (pkgutil) merged with external (entry_points).
+
+ Built-in channels take priority — an external plugin cannot shadow a built-in name.
+ """
+ builtin: dict[str, type[BaseChannel]] = {}
+ for modname in discover_channel_names():
+ try:
+ builtin[modname] = load_channel_class(modname)
+ except ImportError as e:
+ logger.debug("Skipping built-in channel '{}': {}", modname, e)
+
+ external = discover_plugins()
+ shadowed = set(external) & set(builtin)
+ if shadowed:
+ logger.warning("Plugin(s) shadowed by built-in channels (ignored): {}", shadowed)
+
+ return {**external, **builtin}
diff --git a/deeptutor/partners/channels/slack.py b/deeptutor/partners/channels/slack.py
new file mode 100644
index 000000000..24ef4b20c
--- /dev/null
+++ b/deeptutor/partners/channels/slack.py
@@ -0,0 +1,332 @@
+"""Slack channel implementation using Socket Mode."""
+
+import asyncio
+import re
+from typing import Any
+
+from loguru import logger
+from pydantic import Field
+from slack_sdk.socket_mode.request import SocketModeRequest
+from slack_sdk.socket_mode.response import SocketModeResponse
+from slack_sdk.socket_mode.websockets import SocketModeClient
+from slack_sdk.web.async_client import AsyncWebClient
+from slackify_markdown import slackify_markdown
+
+from deeptutor.partners.bus.events import OutboundMessage
+from deeptutor.partners.bus.queue import MessageBus
+from deeptutor.partners.channels.base import BaseChannel
+from deeptutor.partners.config.schema import Base, DeliveryOverrides
+
+# Slack's WSS endpoint can be blocked while HTTPS still works (auth_test
+# succeeds, Socket Mode hangs) — bound the handshake so the failure is loud.
+SLACK_SOCKET_CONNECT_TIMEOUT_S = 30.0
+
+
+class SlackDMConfig(Base):
+ """Slack DM policy configuration."""
+
+ enabled: bool = True
+ policy: str = "open"
+ allow_from: list[str] = Field(default_factory=list)
+
+
+class SlackConfig(DeliveryOverrides):
+ """Slack channel configuration."""
+
+ enabled: bool = False
+ mode: str = "socket"
+ webhook_path: str = "/slack/events"
+ bot_token: str = ""
+ app_token: str = ""
+ user_token_read_only: bool = True
+ reply_in_thread: bool = True
+ react_emoji: str = "eyes"
+ allow_from: list[str] = Field(default_factory=list)
+ group_policy: str = "mention"
+ group_allow_from: list[str] = Field(default_factory=list)
+ dm: SlackDMConfig = Field(default_factory=SlackDMConfig)
+
+
+class SlackChannel(BaseChannel):
+ """Slack channel using Socket Mode."""
+
+ name = "slack"
+ display_name = "Slack"
+
+ @classmethod
+ def default_config(cls) -> dict[str, Any]:
+ return SlackConfig().model_dump(by_alias=True)
+
+ def __init__(self, config: Any, bus: MessageBus):
+ if isinstance(config, dict):
+ config = SlackConfig.model_validate(config)
+ super().__init__(config, bus)
+ self.config: SlackConfig = config
+ self._web_client: AsyncWebClient | None = None
+ self._socket_client: SocketModeClient | None = None
+ self._bot_user_id: str | None = None
+
+ async def start(self) -> None:
+ """Start the Slack Socket Mode client."""
+ if not self.config.bot_token or not self.config.app_token:
+ logger.error("Slack bot/app token not configured")
+ return
+ if self.config.mode != "socket":
+ logger.error("Unsupported Slack mode: {}", self.config.mode)
+ return
+
+ self._running = True
+
+ self._web_client = AsyncWebClient(token=self.config.bot_token)
+ self._socket_client = SocketModeClient(
+ app_token=self.config.app_token,
+ web_client=self._web_client,
+ )
+
+ self._socket_client.socket_mode_request_listeners.append(self._on_socket_request)
+
+ # Resolve bot user ID for mention handling
+ try:
+ auth = await self._web_client.auth_test()
+ self._bot_user_id = auth.get("user_id")
+ logger.info("Slack bot connected as {}", self._bot_user_id)
+ except Exception as e:
+ logger.warning("Slack auth_test failed: {}", e)
+
+ logger.info("Starting Slack Socket Mode client...")
+ try:
+ await asyncio.wait_for(
+ self._socket_client.connect(),
+ timeout=SLACK_SOCKET_CONNECT_TIMEOUT_S,
+ )
+ except asyncio.TimeoutError:
+ logger.error(
+ "Slack Socket Mode WebSocket handshake timed out after {:.0f}s. "
+ "auth_test uses HTTPS and may still succeed while WSS is blocked. "
+ "Check outbound access to Slack WebSockets; slack-sdk Socket Mode "
+ "does not apply HTTP(S)_PROXY to websockets.connect.",
+ SLACK_SOCKET_CONNECT_TIMEOUT_S,
+ )
+ await self.stop()
+ raise RuntimeError("Slack Socket Mode WebSocket connect timed out") from None
+
+ logger.info("Slack Socket Mode WebSocket connected (events enabled)")
+
+ while self._running:
+ await asyncio.sleep(1)
+
+ async def stop(self) -> None:
+ """Stop the Slack client."""
+ self._running = False
+ if self._socket_client:
+ try:
+ await self._socket_client.close()
+ except Exception as e:
+ logger.warning("Slack socket close failed: {}", e)
+ self._socket_client = None
+
+ async def send(self, msg: OutboundMessage) -> None:
+ """Send a message through Slack.
+
+ Raises on text-delivery failure so the channel manager's retry
+ policy applies; per-file upload failures stay best-effort.
+ """
+ if not self._web_client:
+ logger.warning("Slack client not running")
+ return
+ slack_meta = msg.metadata.get("slack", {}) if msg.metadata else {}
+ thread_ts = slack_meta.get("thread_ts")
+ channel_type = slack_meta.get("channel_type")
+ # Slack DMs don't use threads; channel/group replies may keep thread_ts.
+ thread_ts_param = thread_ts if thread_ts and channel_type != "im" else None
+
+ # Slack rejects empty text payloads. Keep media-only messages media-only,
+ # but send a single blank message when the bot has no text or files to send.
+ if msg.content or not (msg.media or []):
+ await self._web_client.chat_postMessage(
+ channel=msg.chat_id,
+ text=self._to_mrkdwn(msg.content) if msg.content else " ",
+ thread_ts=thread_ts_param,
+ )
+
+ for media_path in msg.media or []:
+ try:
+ await self._web_client.files_upload_v2(
+ channel=msg.chat_id,
+ file=media_path,
+ thread_ts=thread_ts_param,
+ )
+ except Exception as e:
+ logger.error("Failed to upload file {}: {}", media_path, e)
+
+ async def _on_socket_request(
+ self,
+ client: SocketModeClient,
+ req: SocketModeRequest,
+ ) -> None:
+ """Handle incoming Socket Mode requests."""
+ if req.type != "events_api":
+ return
+
+ # Acknowledge right away
+ await client.send_socket_mode_response(SocketModeResponse(envelope_id=req.envelope_id))
+
+ payload = req.payload or {}
+ event = payload.get("event") or {}
+ event_type = event.get("type")
+
+ # Handle app mentions or plain messages
+ if event_type not in ("message", "app_mention"):
+ return
+
+ sender_id = event.get("user")
+ chat_id = event.get("channel")
+
+ # Ignore bot/system messages (any subtype = not a normal user message)
+ if event.get("subtype"):
+ return
+ if self._bot_user_id and sender_id == self._bot_user_id:
+ return
+
+ # Avoid double-processing: Slack sends both `message` and `app_mention`
+ # for mentions in channels. Prefer `app_mention`.
+ text = event.get("text") or ""
+ if event_type == "message" and self._bot_user_id and f"<@{self._bot_user_id}>" in text:
+ return
+
+ # Debug: log basic event shape
+ logger.debug(
+ "Slack event: type={} subtype={} user={} channel={} channel_type={} text={}",
+ event_type,
+ event.get("subtype"),
+ sender_id,
+ chat_id,
+ event.get("channel_type"),
+ text[:80],
+ )
+ if not sender_id or not chat_id:
+ return
+
+ channel_type = event.get("channel_type") or ""
+
+ if not self._is_allowed(sender_id, chat_id, channel_type):
+ return
+
+ if channel_type != "im" and not self._should_respond_in_channel(event_type, text, chat_id):
+ return
+
+ text = self._strip_bot_mention(text)
+
+ thread_ts = event.get("thread_ts")
+ if self.config.reply_in_thread and not thread_ts:
+ thread_ts = event.get("ts")
+ # Add :eyes: reaction to the triggering message (best-effort)
+ try:
+ if self._web_client and event.get("ts"):
+ await self._web_client.reactions_add(
+ channel=chat_id,
+ name=self.config.react_emoji,
+ timestamp=event.get("ts"),
+ )
+ except Exception as e:
+ logger.debug("Slack reactions_add failed: {}", e)
+
+ # Thread-scoped session key for channel/group messages
+ session_key = f"slack:{chat_id}:{thread_ts}" if thread_ts and channel_type != "im" else None
+
+ try:
+ await self._handle_message(
+ sender_id=sender_id,
+ chat_id=chat_id,
+ content=text,
+ metadata={
+ "slack": {
+ "event": event,
+ "thread_ts": thread_ts,
+ "channel_type": channel_type,
+ },
+ },
+ session_key=session_key,
+ )
+ except Exception:
+ logger.exception("Error handling Slack message from {}", sender_id)
+
+ def _is_allowed(self, sender_id: str, chat_id: str, channel_type: str) -> bool:
+ if channel_type == "im":
+ if not self.config.dm.enabled:
+ return False
+ if self.config.dm.policy == "allowlist":
+ return sender_id in self.config.dm.allow_from
+ return True
+
+ # Group / channel messages
+ if self.config.group_policy == "allowlist":
+ return chat_id in self.config.group_allow_from
+ return True
+
+ def _should_respond_in_channel(self, event_type: str, text: str, chat_id: str) -> bool:
+ if self.config.group_policy == "open":
+ return True
+ if self.config.group_policy == "mention":
+ if event_type == "app_mention":
+ return True
+ return self._bot_user_id is not None and f"<@{self._bot_user_id}>" in text
+ if self.config.group_policy == "allowlist":
+ return chat_id in self.config.group_allow_from
+ return False
+
+ def _strip_bot_mention(self, text: str) -> str:
+ if not text or not self._bot_user_id:
+ return text
+ return re.sub(rf"<@{re.escape(self._bot_user_id)}>\s*", "", text).strip()
+
+ _TABLE_RE = re.compile(r"(?m)^\|.*\|$(?:\n\|[\s:|-]*\|$)(?:\n\|.*\|$)*")
+ _CODE_FENCE_RE = re.compile(r"```[\s\S]*?```")
+ _INLINE_CODE_RE = re.compile(r"`[^`]+`")
+ _LEFTOVER_BOLD_RE = re.compile(r"\*\*(.+?)\*\*")
+ _LEFTOVER_HEADER_RE = re.compile(r"^#{1,6}\s+(.+)$", re.MULTILINE)
+ _BARE_URL_RE = re.compile(r"(?<![|<])(https?://\S+)")
+
+ @classmethod
+ def _to_mrkdwn(cls, text: str) -> str:
+ """Convert Markdown to Slack mrkdwn, including tables."""
+ if not text:
+ return ""
+ text = cls._TABLE_RE.sub(cls._convert_table, text)
+ return cls._fixup_mrkdwn(slackify_markdown(text))
+
+ @classmethod
+ def _fixup_mrkdwn(cls, text: str) -> str:
+ """Fix markdown artifacts that slackify_markdown misses."""
+ code_blocks: list[str] = []
+
+ def _save_code(m: re.Match) -> str:
+ code_blocks.append(m.group(0))
+ return f"\x00CB{len(code_blocks) - 1}\x00"
+
+ text = cls._CODE_FENCE_RE.sub(_save_code, text)
+ text = cls._INLINE_CODE_RE.sub(_save_code, text)
+ text = cls._LEFTOVER_BOLD_RE.sub(r"*\1*", text)
+ text = cls._LEFTOVER_HEADER_RE.sub(r"*\1*", text)
+ text = cls._BARE_URL_RE.sub(lambda m: m.group(0).replace("&amp;", "&"), text)
+
+ for i, block in enumerate(code_blocks):
+ text = text.replace(f"\x00CB{i}\x00", block)
+ return text
+
+ @staticmethod
+ def _convert_table(match: re.Match) -> str:
+ """Convert a Markdown table to a Slack-readable list."""
+ lines = [ln.strip() for ln in match.group(0).strip().splitlines() if ln.strip()]
+ if len(lines) < 2:
+ return match.group(0)
+ headers = [h.strip() for h in lines[0].strip("|").split("|")]
+ start = 2 if re.fullmatch(r"[|\s:\-]+", lines[1]) else 1
+ rows: list[str] = []
+ for line in lines[start:]:
+ cells = [c.strip() for c in line.strip("|").split("|")]
+ cells = (cells + [""] * len(headers))[: len(headers)]
+ parts = [f"**{headers[i]}**: {cells[i]}" for i in range(len(headers)) if cells[i]]
+ if parts:
+ rows.append(" · ".join(parts))
+ return "\n".join(rows)
diff --git a/deeptutor/partners/channels/telegram.py b/deeptutor/partners/channels/telegram.py
new file mode 100644
index 000000000..65da624b4
--- /dev/null
+++ b/deeptutor/partners/channels/telegram.py
@@ -0,0 +1,828 @@
+"""Telegram channel implementation using python-telegram-bot."""
+
+from __future__ import annotations
+
+import asyncio
+import re
+import time
+from typing import Any, Literal
+import unicodedata
+
+from loguru import logger
+from pydantic import Field
+from telegram import BotCommand, ReplyParameters, Update
+from telegram.ext import Application, CommandHandler, ContextTypes, MessageHandler, filters
+from telegram.request import HTTPXRequest
+
+from deeptutor.partners.bus.events import OutboundMessage
+from deeptutor.partners.bus.queue import MessageBus
+from deeptutor.partners.channels.base import BaseChannel
+from deeptutor.partners.config.paths import get_media_dir
+from deeptutor.partners.config.schema import Base, DeliveryOverrides, StreamingSupport
+from deeptutor.partners.helpers import split_message
+
+TELEGRAM_MAX_MESSAGE_LEN = 4000 # Telegram message character limit
+TELEGRAM_REPLY_CONTEXT_MAX_LEN = (
+ TELEGRAM_MAX_MESSAGE_LEN # Max length for reply context in user message
+)
+
+
+def _strip_md(s: str) -> str:
+ """Strip markdown inline formatting from text."""
+ s = re.sub(r"\*\*(.+?)\*\*", r"\1", s)
+ s = re.sub(r"__(.+?)__", r"\1", s)
+ s = re.sub(r"~~(.+?)~~", r"\1", s)
+ s = re.sub(r"`([^`]+)`", r"\1", s)
+ return s.strip()
+
+
+def _render_table_box(table_lines: list[str]) -> str:
+ """Convert markdown pipe-table to compact aligned text for <pre> display."""
+
+ def dw(s: str) -> int:
+ return sum(2 if unicodedata.east_asian_width(c) in ("W", "F") else 1 for c in s)
+
+ rows: list[list[str]] = []
+ has_sep = False
+ for line in table_lines:
+ cells = [_strip_md(c) for c in line.strip().strip("|").split("|")]
+ if all(re.match(r"^:?-+:?$", c) for c in cells if c):
+ has_sep = True
+ continue
+ rows.append(cells)
+ if not rows or not has_sep:
+ return "\n".join(table_lines)
+
+ ncols = max(len(r) for r in rows)
+ for r in rows:
+ r.extend([""] * (ncols - len(r)))
+ widths = [max(dw(r[c]) for r in rows) for c in range(ncols)]
+
+ def dr(cells: list[str]) -> str:
+ return " ".join(f"{c}{' ' * (w - dw(c))}" for c, w in zip(cells, widths))
+
+ out = [dr(rows[0])]
+ out.append(" ".join("─" * w for w in widths))
+ for row in rows[1:]:
+ out.append(dr(row))
+ return "\n".join(out)
+
+
+def _markdown_to_telegram_html(text: str) -> str:
+ """
+ Convert markdown to Telegram-safe HTML.
+ """
+ if not text:
+ return ""
+
+ # 1. Extract and protect code blocks (preserve content from other processing)
+ code_blocks: list[str] = []
+
+ def save_code_block(m: re.Match) -> str:
+ code_blocks.append(m.group(1))
+ return f"\x00CB{len(code_blocks) - 1}\x00"
+
+ text = re.sub(r"```[\w]*\n?([\s\S]*?)```", save_code_block, text)
+
+ # 1.5. Convert markdown tables to box-drawing (reuse code_block placeholders)
+ lines = text.split("\n")
+ rebuilt: list[str] = []
+ li = 0
+ while li < len(lines):
+ if re.match(r"^\s*\|.+\|", lines[li]):
+ tbl: list[str] = []
+ while li < len(lines) and re.match(r"^\s*\|.+\|", lines[li]):
+ tbl.append(lines[li])
+ li += 1
+ box = _render_table_box(tbl)
+ if box != "\n".join(tbl):
+ code_blocks.append(box)
+ rebuilt.append(f"\x00CB{len(code_blocks) - 1}\x00")
+ else:
+ rebuilt.extend(tbl)
+ else:
+ rebuilt.append(lines[li])
+ li += 1
+ text = "\n".join(rebuilt)
+
+ # 2. Extract and protect inline code
+ inline_codes: list[str] = []
+
+ def save_inline_code(m: re.Match) -> str:
+ inline_codes.append(m.group(1))
+ return f"\x00IC{len(inline_codes) - 1}\x00"
+
+ text = re.sub(r"`([^`]+)`", save_inline_code, text)
+
+ # 3. Headers # Title -> just the title text
+ text = re.sub(r"^#{1,6}\s+(.+)$", r"\1", text, flags=re.MULTILINE)
+
+ # 4. Blockquotes > text -> just the text (before HTML escaping)
+ text = re.sub(r"^>\s*(.*)$", r"\1", text, flags=re.MULTILINE)
+
+ # 5. Escape HTML special characters
+ text = text.replace("&", "&amp;").replace("<", "&lt;").replace(">", "&gt;")
+
+ # 6. Links [text](url) - must be before bold/italic to handle nested cases
+ text = re.sub(r"\[([^\]]+)\]\(([^)]+)\)", r'<a href="\2">\1</a>', text)
+
+ # 7. Bold **text** or __text__
+ text = re.sub(r"\*\*(.+?)\*\*", r"<b>\1</b>", text)
+ text = re.sub(r"__(.+?)__", r"<b>\1</b>", text)
+
+ # 8. Italic _text_ (avoid matching inside words like some_var_name)
+ text = re.sub(r"(?<![a-zA-Z0-9])_([^_]+)_(?![a-zA-Z0-9])", r"<i>\1</i>", text)
+
+ # 9. Strikethrough ~~text~~
+ text = re.sub(r"~~(.+?)~~", r"<s>\1</s>", text)
+
+ # 10. Bullet lists - item -> • item
+ text = re.sub(r"^[-*]\s+", "• ", text, flags=re.MULTILINE)
+
+ # 11. Restore inline code with HTML tags
+ for i, code in enumerate(inline_codes):
+ # Escape HTML in code content
+ escaped = code.replace("&", "&amp;").replace("<", "&lt;").replace(">", "&gt;")
+ text = text.replace(f"\x00IC{i}\x00", f"<code>{escaped}</code>")
+
+ # 12. Restore code blocks with HTML tags
+ for i, code in enumerate(code_blocks):
+ # Escape HTML in code content
+ escaped = code.replace("&", "&amp;").replace("<", "&lt;").replace(">", "&gt;")
+ text = text.replace(f"\x00CB{i}\x00", f"<pre><code>{escaped}</code></pre>")
+
+ return text
+
+
+class TelegramConfig(DeliveryOverrides, StreamingSupport):
+ """Telegram channel configuration."""
+
+ enabled: bool = False
+ token: str = ""
+ allow_from: list[str] = Field(default_factory=list)
+ proxy: str | None = None
+ reply_to_message: bool = False
+ group_policy: Literal["open", "mention"] = "mention"
+ # Outbound API connection pool; long-polling uses its own small pool so
+ # getUpdates never starves sends.
+ connection_pool_size: int = 16
+ pool_timeout: float = 15.0
+
+
+class TelegramChannel(BaseChannel):
+ """
+ Telegram channel using long polling.
+
+ Simple and reliable - no webhook/public IP needed.
+ """
+
+ name = "telegram"
+ display_name = "Telegram"
+
+ # Commands registered with Telegram's command menu. Only commands the
+ # partner runtime actually handles belong here — the agent loop has no
+ # command router, so anything else would be silently broken UX.
+ BOT_COMMANDS = [
+ BotCommand("start", "Start the bot"),
+ BotCommand("help", "Show available commands"),
+ ]
+
+ @classmethod
+ def default_config(cls) -> dict[str, Any]:
+ return TelegramConfig().model_dump(by_alias=True)
+
+ def __init__(self, config: Any, bus: MessageBus):
+ if isinstance(config, dict):
+ config = TelegramConfig.model_validate(config)
+ super().__init__(config, bus)
+ self.config: TelegramConfig = config
+ self._app: Application | None = None
+ self._chat_ids: dict[str, int] = {} # Map sender_id to chat_id for replies
+ self._typing_tasks: dict[str, asyncio.Task] = {} # chat_id -> typing loop task
+ self._media_group_buffers: dict[str, dict] = {}
+ self._media_group_tasks: dict[str, asyncio.Task] = {}
+ self._message_threads: dict[tuple[str, int], int] = {}
+ self._bot_user_id: int | None = None
+ self._bot_username: str | None = None
+
+ def is_allowed(self, sender_id: str) -> bool:
+ """Preserve Telegram's legacy id|username allowlist matching."""
+ if super().is_allowed(sender_id):
+ return True
+
+ allow_list = getattr(self.config, "allow_from", [])
+ if not allow_list or "*" in allow_list:
+ return False
+
+ sender_str = str(sender_id)
+ if sender_str.count("|") != 1:
+ return False
+
+ sid, username = sender_str.split("|", 1)
+ if not sid.isdigit() or not username:
+ return False
+
+ return sid in allow_list or username in allow_list
+
+ async def start(self) -> None:
+ """Start the Telegram bot with long polling."""
+ if not self.config.token:
+ logger.error("Telegram bot token not configured")
+ return
+
+ self._running = True
+
+ proxy = self.config.proxy or None
+
+ # Separate pools so long-polling (getUpdates) never starves outbound
+ # sends — sharing one pool exhausts it under load and every send
+ # starts failing with PoolTimeout.
+ api_request = HTTPXRequest(
+ connection_pool_size=self.config.connection_pool_size,
+ pool_timeout=self.config.pool_timeout,
+ connect_timeout=30.0,
+ read_timeout=30.0,
+ proxy=proxy,
+ )
+ poll_request = HTTPXRequest(
+ connection_pool_size=4,
+ pool_timeout=self.config.pool_timeout,
+ connect_timeout=30.0,
+ read_timeout=30.0,
+ proxy=proxy,
+ )
+ builder = (
+ Application.builder()
+ .token(self.config.token)
+ .request(api_request)
+ .get_updates_request(poll_request)
+ )
+ self._app = builder.build()
+ self._app.add_error_handler(self._on_error)
+
+ # Add command handlers
+ self._app.add_handler(CommandHandler("start", self._on_start))
+ self._app.add_handler(CommandHandler("help", self._on_help))
+
+ # Add message handler for text, photos, voice, documents
+ self._app.add_handler(
+ MessageHandler(
+ (
+ filters.TEXT
+ | filters.PHOTO
+ | filters.VOICE
+ | filters.AUDIO
+ | filters.Document.ALL
+ )
+ & ~filters.COMMAND,
+ self._on_message,
+ )
+ )
+
+ logger.info("Starting Telegram bot (polling mode)...")
+
+ # Initialize and start polling
+ await self._app.initialize()
+ await self._app.start()
+
+ # Get bot info and register command menu
+ bot_info = await self._app.bot.get_me()
+ self._bot_user_id = getattr(bot_info, "id", None)
+ self._bot_username = getattr(bot_info, "username", None)
+ logger.info("Telegram bot @{} connected", bot_info.username)
+
+ try:
+ await self._app.bot.set_my_commands(self.BOT_COMMANDS)
+ logger.debug("Telegram bot commands registered")
+ except Exception as e:
+ logger.warning("Failed to register bot commands: {}", e)
+
+ # Start polling (this runs until stopped)
+ await self._app.updater.start_polling(
+ allowed_updates=["message"],
+ drop_pending_updates=True, # Ignore old messages on startup
+ )
+
+ # Keep running until stopped
+ while self._running:
+ await asyncio.sleep(1)
+
+ async def stop(self) -> None:
+ """Stop the Telegram bot."""
+ self._running = False
+
+ # Cancel all typing indicators
+ for chat_id in list(self._typing_tasks):
+ self._stop_typing(chat_id)
+
+ for task in self._media_group_tasks.values():
+ task.cancel()
+ self._media_group_tasks.clear()
+ self._media_group_buffers.clear()
+
+ if self._app:
+ logger.info("Stopping Telegram bot...")
+ await self._app.updater.stop()
+ await self._app.stop()
+ await self._app.shutdown()
+ self._app = None
+
+ @staticmethod
+ def _get_media_type(path: str) -> str:
+ """Guess media type from file extension."""
+ ext = path.rsplit(".", 1)[-1].lower() if "." in path else ""
+ if ext in ("jpg", "jpeg", "png", "gif", "webp"):
+ return "photo"
+ if ext == "ogg":
+ return "voice"
+ if ext in ("mp3", "m4a", "wav", "aac"):
+ return "audio"
+ return "document"
+
+ async def send(self, msg: OutboundMessage) -> None:
+ """Send a message through Telegram."""
+ if not self._app:
+ logger.warning("Telegram bot not running")
+ return
+
+ # Only stop typing indicator for final responses
+ if not msg.metadata.get("_progress", False):
+ self._stop_typing(msg.chat_id)
+
+ try:
+ chat_id = int(msg.chat_id)
+ except ValueError:
+ logger.error("Invalid chat_id: {}", msg.chat_id)
+ return
+ reply_to_message_id = msg.metadata.get("message_id")
+ message_thread_id = msg.metadata.get("message_thread_id")
+ if message_thread_id is None and reply_to_message_id is not None:
+ message_thread_id = self._message_threads.get((msg.chat_id, reply_to_message_id))
+ thread_kwargs = {}
+ if message_thread_id is not None:
+ thread_kwargs["message_thread_id"] = message_thread_id
+
+ reply_params = None
+ if self.config.reply_to_message:
+ if reply_to_message_id:
+ reply_params = ReplyParameters(
+ message_id=reply_to_message_id, allow_sending_without_reply=True
+ )
+
+ # Send media files
+ for media_path in msg.media or []:
+ try:
+ media_type = self._get_media_type(media_path)
+ sender = {
+ "photo": self._app.bot.send_photo,
+ "voice": self._app.bot.send_voice,
+ "audio": self._app.bot.send_audio,
+ }.get(media_type, self._app.bot.send_document)
+ param = (
+ "photo"
+ if media_type == "photo"
+ else media_type
+ if media_type in ("voice", "audio")
+ else "document"
+ )
+ with open(media_path, "rb") as f:
+ await sender(
+ chat_id=chat_id,
+ **{param: f},
+ reply_parameters=reply_params,
+ **thread_kwargs,
+ )
+ except Exception as e:
+ filename = media_path.rsplit("/", 1)[-1]
+ logger.error("Failed to send media {}: {}", media_path, e)
+ await self._app.bot.send_message(
+ chat_id=chat_id,
+ text=f"[Failed to send: {filename}]",
+ reply_parameters=reply_params,
+ **thread_kwargs,
+ )
+
+ # Send text content
+ if msg.content and msg.content != "[empty message]":
+ is_progress = msg.metadata.get("_progress", False)
+
+ for chunk in split_message(msg.content, TELEGRAM_MAX_MESSAGE_LEN):
+ # Final response: simulate streaming via draft, then persist
+ if not is_progress:
+ await self._send_with_streaming(chat_id, chunk, reply_params, thread_kwargs)
+ else:
+ await self._send_text(chat_id, chunk, reply_params, thread_kwargs)
+
+ async def _send_text(
+ self,
+ chat_id: int,
+ text: str,
+ reply_params=None,
+ thread_kwargs: dict | None = None,
+ ) -> None:
+ """Send a plain text message with HTML fallback."""
+ try:
+ html = _markdown_to_telegram_html(text)
+ await self._app.bot.send_message(
+ chat_id=chat_id,
+ text=html,
+ parse_mode="HTML",
+ reply_parameters=reply_params,
+ **(thread_kwargs or {}),
+ )
+ except Exception as e:
+ logger.warning("HTML parse failed, falling back to plain text: {}", e)
+ # Let a plain-text failure propagate so the channel manager's
+ # retry policy applies (send contract: raise on delivery failure).
+ await self._app.bot.send_message(
+ chat_id=chat_id,
+ text=text,
+ reply_parameters=reply_params,
+ **(thread_kwargs or {}),
+ )
+
+ async def _send_with_streaming(
+ self,
+ chat_id: int,
+ text: str,
+ reply_params=None,
+ thread_kwargs: dict | None = None,
+ ) -> None:
+ """Simulate streaming via send_message_draft, then persist with send_message."""
+ draft_id = int(time.time() * 1000) % (2**31)
+ try:
+ step = max(len(text) // 8, 40)
+ for i in range(step, len(text), step):
+ await self._app.bot.send_message_draft(
+ chat_id=chat_id,
+ draft_id=draft_id,
+ text=text[:i],
+ )
+ await asyncio.sleep(0.04)
+ await self._app.bot.send_message_draft(
+ chat_id=chat_id,
+ draft_id=draft_id,
+ text=text,
+ )
+ await asyncio.sleep(0.15)
+ except Exception:
+ pass
+ await self._send_text(chat_id, text, reply_params, thread_kwargs)
+
+ async def _on_start(self, update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
+ """Handle /start command."""
+ if not update.message or not update.effective_user:
+ return
+
+ user = update.effective_user
+ await update.message.reply_text(
+ f"👋 Hi {user.first_name}! I'm TutorBot.\n\n"
+ "Send me a message and I'll respond!\n"
+ "Type /help to see available commands."
+ )
+
+ async def _on_help(self, update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
+ """Handle /help command, bypassing ACL so all users can access it."""
+ if not update.message:
+ return
+ await update.message.reply_text(
+ "🐈 TutorBot commands:\n"
+ "/new — Start a new conversation\n"
+ "/stop — Stop the current task\n"
+ "/restart — Restart the bot\n"
+ "/help — Show available commands"
+ )
+
+ @staticmethod
+ def _sender_id(user) -> str:
+ """Build sender_id with username for allowlist matching."""
+ sid = str(user.id)
+ return f"{sid}|{user.username}" if user.username else sid
+
+ @staticmethod
+ def _derive_topic_session_key(message) -> str | None:
+ """Derive topic-scoped session key for non-private Telegram chats."""
+ message_thread_id = getattr(message, "message_thread_id", None)
+ if message.chat.type == "private" or message_thread_id is None:
+ return None
+ return f"telegram:{message.chat_id}:topic:{message_thread_id}"
+
+ @staticmethod
+ def _build_message_metadata(message, user) -> dict:
+ """Build common Telegram inbound metadata payload."""
+ reply_to = getattr(message, "reply_to_message", None)
+ return {
+ "message_id": message.message_id,
+ "user_id": user.id,
+ "username": user.username,
+ "first_name": user.first_name,
+ "is_group": message.chat.type != "private",
+ "message_thread_id": getattr(message, "message_thread_id", None),
+ "is_forum": bool(getattr(message.chat, "is_forum", False)),
+ "reply_to_message_id": getattr(reply_to, "message_id", None) if reply_to else None,
+ }
+
+ @staticmethod
+ def _extract_reply_context(message) -> str | None:
+ """Extract text from the message being replied to, if any."""
+ reply = getattr(message, "reply_to_message", None)
+ if not reply:
+ return None
+ text = getattr(reply, "text", None) or getattr(reply, "caption", None) or ""
+ if len(text) > TELEGRAM_REPLY_CONTEXT_MAX_LEN:
+ text = text[:TELEGRAM_REPLY_CONTEXT_MAX_LEN] + "..."
+ return f"[Reply to: {text}]" if text else None
+
+ async def _download_message_media(
+ self, msg, *, add_failure_content: bool = False
+ ) -> tuple[list[str], list[str]]:
+ """Download media from a message (current or reply). Returns (media_paths, content_parts)."""
+ media_file = None
+ media_type = None
+ if getattr(msg, "photo", None):
+ media_file = msg.photo[-1]
+ media_type = "image"
+ elif getattr(msg, "voice", None):
+ media_file = msg.voice
+ media_type = "voice"
+ elif getattr(msg, "audio", None):
+ media_file = msg.audio
+ media_type = "audio"
+ elif getattr(msg, "document", None):
+ media_file = msg.document
+ media_type = "file"
+ elif getattr(msg, "video", None):
+ media_file = msg.video
+ media_type = "video"
+ elif getattr(msg, "video_note", None):
+ media_file = msg.video_note
+ media_type = "video"
+ elif getattr(msg, "animation", None):
+ media_file = msg.animation
+ media_type = "animation"
+ if not media_file or not self._app:
+ return [], []
+ try:
+ file = await self._app.bot.get_file(media_file.file_id)
+ ext = self._get_extension(
+ media_type,
+ getattr(media_file, "mime_type", None),
+ getattr(media_file, "file_name", None),
+ )
+ media_dir = get_media_dir("telegram")
+ unique_id = getattr(media_file, "file_unique_id", media_file.file_id)
+ file_path = media_dir / f"{unique_id}{ext}"
+ await file.download_to_drive(str(file_path))
+ path_str = str(file_path)
+ if media_type in ("voice", "audio"):
+ transcription = await self.transcribe_audio(file_path)
+ if transcription:
+ logger.info("Transcribed {}: {}...", media_type, transcription[:50])
+ return [path_str], [f"[transcription: {transcription}]"]
+ return [path_str], [f"[{media_type}: {path_str}]"]
+ return [path_str], [f"[{media_type}: {path_str}]"]
+ except Exception as e:
+ logger.warning("Failed to download message media: {}", e)
+ if add_failure_content:
+ return [], [f"[{media_type}: download failed]"]
+ return [], []
+
+ async def _ensure_bot_identity(self) -> tuple[int | None, str | None]:
+ """Load bot identity once and reuse it for mention/reply checks."""
+ if self._bot_user_id is not None or self._bot_username is not None:
+ return self._bot_user_id, self._bot_username
+ if not self._app:
+ return None, None
+ bot_info = await self._app.bot.get_me()
+ self._bot_user_id = getattr(bot_info, "id", None)
+ self._bot_username = getattr(bot_info, "username", None)
+ return self._bot_user_id, self._bot_username
+
+ @staticmethod
+ def _has_mention_entity(
+ text: str,
+ entities,
+ bot_username: str,
+ bot_id: int | None,
+ ) -> bool:
+ """Check Telegram mention entities against the bot username."""
+ handle = f"@{bot_username}".lower()
+ for entity in entities or []:
+ entity_type = getattr(entity, "type", None)
+ if entity_type == "text_mention":
+ user = getattr(entity, "user", None)
+ if user is not None and bot_id is not None and getattr(user, "id", None) == bot_id:
+ return True
+ continue
+ if entity_type != "mention":
+ continue
+ offset = getattr(entity, "offset", None)
+ length = getattr(entity, "length", None)
+ if offset is None or length is None:
+ continue
+ if text[offset : offset + length].lower() == handle:
+ return True
+ return handle in text.lower()
+
+ async def _is_group_message_for_bot(self, message) -> bool:
+ """Allow group messages when policy is open, @mentioned, or replying to the bot."""
+ if message.chat.type == "private" or self.config.group_policy == "open":
+ return True
+
+ bot_id, bot_username = await self._ensure_bot_identity()
+ if bot_username:
+ text = message.text or ""
+ caption = message.caption or ""
+ if self._has_mention_entity(
+ text,
+ getattr(message, "entities", None),
+ bot_username,
+ bot_id,
+ ):
+ return True
+ if self._has_mention_entity(
+ caption,
+ getattr(message, "caption_entities", None),
+ bot_username,
+ bot_id,
+ ):
+ return True
+
+ reply_user = getattr(getattr(message, "reply_to_message", None), "from_user", None)
+ return bool(bot_id and reply_user and reply_user.id == bot_id)
+
+ def _remember_thread_context(self, message) -> None:
+ """Cache topic thread id by chat/message id for follow-up replies."""
+ message_thread_id = getattr(message, "message_thread_id", None)
+ if message_thread_id is None:
+ return
+ key = (str(message.chat_id), message.message_id)
+ self._message_threads[key] = message_thread_id
+ if len(self._message_threads) > 1000:
+ self._message_threads.pop(next(iter(self._message_threads)))
+
+ async def _on_message(self, update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
+ """Handle incoming messages (text, photos, voice, documents)."""
+ if not update.message or not update.effective_user:
+ return
+
+ message = update.message
+ user = update.effective_user
+ chat_id = message.chat_id
+ sender_id = self._sender_id(user)
+ self._remember_thread_context(message)
+
+ # Store chat_id for replies
+ self._chat_ids[sender_id] = chat_id
+
+ if not await self._is_group_message_for_bot(message):
+ return
+
+ # Build content from text and/or media
+ content_parts = []
+ media_paths = []
+
+ # Text content
+ if message.text:
+ content_parts.append(message.text)
+ if message.caption:
+ content_parts.append(message.caption)
+
+ # Download current message media
+ current_media_paths, current_media_parts = await self._download_message_media(
+ message, add_failure_content=True
+ )
+ media_paths.extend(current_media_paths)
+ content_parts.extend(current_media_parts)
+ if current_media_paths:
+ logger.debug("Downloaded message media to {}", current_media_paths[0])
+
+ # Reply context: text and/or media from the replied-to message
+ reply = getattr(message, "reply_to_message", None)
+ if reply is not None:
+ reply_ctx = self._extract_reply_context(message)
+ reply_media, reply_media_parts = await self._download_message_media(reply)
+ if reply_media:
+ media_paths = reply_media + media_paths
+ logger.debug("Attached replied-to media: {}", reply_media[0])
+ tag = reply_ctx or (
+ f"[Reply to: {reply_media_parts[0]}]" if reply_media_parts else None
+ )
+ if tag:
+ content_parts.insert(0, tag)
+ content = "\n".join(content_parts) if content_parts else "[empty message]"
+
+ logger.debug("Telegram message from {}: {}...", sender_id, content[:50])
+
+ str_chat_id = str(chat_id)
+ metadata = self._build_message_metadata(message, user)
+ session_key = self._derive_topic_session_key(message)
+
+ # Telegram media groups: buffer briefly, forward as one aggregated turn.
+ if media_group_id := getattr(message, "media_group_id", None):
+ key = f"{str_chat_id}:{media_group_id}"
+ if key not in self._media_group_buffers:
+ self._media_group_buffers[key] = {
+ "sender_id": sender_id,
+ "chat_id": str_chat_id,
+ "contents": [],
+ "media": [],
+ "metadata": metadata,
+ "session_key": session_key,
+ }
+ self._start_typing(str_chat_id)
+ buf = self._media_group_buffers[key]
+ if content and content != "[empty message]":
+ buf["contents"].append(content)
+ buf["media"].extend(media_paths)
+ if key not in self._media_group_tasks:
+ self._media_group_tasks[key] = asyncio.create_task(self._flush_media_group(key))
+ return
+
+ # Start typing indicator before processing
+ self._start_typing(str_chat_id)
+
+ # Forward to the message bus
+ await self._handle_message(
+ sender_id=sender_id,
+ chat_id=str_chat_id,
+ content=content,
+ media=media_paths,
+ metadata=metadata,
+ session_key=session_key,
+ )
+
+ async def _flush_media_group(self, key: str) -> None:
+ """Wait briefly, then forward buffered media-group as one turn."""
+ try:
+ await asyncio.sleep(0.6)
+ if not (buf := self._media_group_buffers.pop(key, None)):
+ return
+ content = "\n".join(buf["contents"]) or "[empty message]"
+ await self._handle_message(
+ sender_id=buf["sender_id"],
+ chat_id=buf["chat_id"],
+ content=content,
+ media=list(dict.fromkeys(buf["media"])),
+ metadata=buf["metadata"],
+ session_key=buf.get("session_key"),
+ )
+ finally:
+ self._media_group_tasks.pop(key, None)
+
+ def _start_typing(self, chat_id: str) -> None:
+ """Start sending 'typing...' indicator for a chat."""
+ # Cancel any existing typing task for this chat
+ self._stop_typing(chat_id)
+ self._typing_tasks[chat_id] = asyncio.create_task(self._typing_loop(chat_id))
+
+ def _stop_typing(self, chat_id: str) -> None:
+ """Stop the typing indicator for a chat."""
+ task = self._typing_tasks.pop(chat_id, None)
+ if task and not task.done():
+ task.cancel()
+
+ async def _typing_loop(self, chat_id: str) -> None:
+ """Repeatedly send 'typing' action until cancelled."""
+ try:
+ while self._app:
+ await self._app.bot.send_chat_action(chat_id=int(chat_id), action="typing")
+ await asyncio.sleep(4)
+ except asyncio.CancelledError:
+ pass
+ except Exception as e:
+ logger.debug("Typing indicator stopped for {}: {}", chat_id, e)
+
+ async def _on_error(self, update: object, context: ContextTypes.DEFAULT_TYPE) -> None:
+ """Log polling / handler errors instead of silently swallowing them."""
+ logger.error("Telegram error: {}", context.error)
+
+ def _get_extension(
+ self,
+ media_type: str,
+ mime_type: str | None,
+ filename: str | None = None,
+ ) -> str:
+ """Get file extension based on media type or original filename."""
+ if mime_type:
+ ext_map = {
+ "image/jpeg": ".jpg",
+ "image/png": ".png",
+ "image/gif": ".gif",
+ "audio/ogg": ".ogg",
+ "audio/mpeg": ".mp3",
+ "audio/mp4": ".m4a",
+ }
+ if mime_type in ext_map:
+ return ext_map[mime_type]
+
+ type_map = {"image": ".jpg", "voice": ".ogg", "audio": ".mp3", "file": ""}
+ if ext := type_map.get(media_type, ""):
+ return ext
+
+ if filename:
+ from pathlib import Path
+
+ return "".join(Path(filename).suffixes)
+
+ return ""
diff --git a/deeptutor/partners/channels/wecom.py b/deeptutor/partners/channels/wecom.py
new file mode 100644
index 000000000..94a4286d4
--- /dev/null
+++ b/deeptutor/partners/channels/wecom.py
@@ -0,0 +1,383 @@
+"""WeCom (Enterprise WeChat) channel implementation using wecom_aibot_sdk."""
+
+import asyncio
+from collections import OrderedDict
+import importlib.util
+import os
+from typing import Any
+
+from loguru import logger
+from pydantic import Field
+
+from deeptutor.partners.bus.events import OutboundMessage
+from deeptutor.partners.bus.queue import MessageBus
+from deeptutor.partners.channels.base import BaseChannel
+from deeptutor.partners.config.paths import get_media_dir
+from deeptutor.partners.config.schema import Base, DeliveryOverrides
+
+WECOM_AVAILABLE = importlib.util.find_spec("wecom_aibot_sdk") is not None
+
+
+class WecomConfig(DeliveryOverrides):
+ """WeCom (Enterprise WeChat) AI Bot channel configuration."""
+
+ enabled: bool = False
+ bot_id: str = ""
+ secret: str = ""
+ allow_from: list[str] = Field(default_factory=list)
+ welcome_message: str = ""
+
+
+# Message type display mapping
+MSG_TYPE_MAP = {
+ "image": "[image]",
+ "voice": "[voice]",
+ "file": "[file]",
+ "mixed": "[mixed content]",
+}
+
+
+class WecomChannel(BaseChannel):
+ """
+ WeCom (Enterprise WeChat) channel using WebSocket long connection.
+
+ Uses WebSocket to receive events - no public IP or webhook required.
+
+ Requires:
+ - Bot ID and Secret from WeCom AI Bot platform
+ """
+
+ name = "wecom"
+ display_name = "WeCom"
+
+ @classmethod
+ def default_config(cls) -> dict[str, Any]:
+ return WecomConfig().model_dump(by_alias=True)
+
+ def __init__(self, config: Any, bus: MessageBus):
+ if isinstance(config, dict):
+ config = WecomConfig.model_validate(config)
+ super().__init__(config, bus)
+ self.config: WecomConfig = config
+ self._client: Any = None
+ self._processed_message_ids: OrderedDict[str, None] = OrderedDict()
+ self._loop: asyncio.AbstractEventLoop | None = None
+ self._generate_req_id = None
+ # Store frame headers for each chat to enable replies
+ self._chat_frames: dict[str, Any] = {}
+
+ async def start(self) -> None:
+ """Start the WeCom bot with WebSocket long connection."""
+ if not WECOM_AVAILABLE:
+ logger.error("WeCom SDK not installed. Run: pip install deeptutor[wecom]")
+ return
+
+ if not self.config.bot_id or not self.config.secret:
+ logger.error("WeCom bot_id and secret not configured")
+ return
+
+ from wecom_aibot_sdk import WSClient, generate_req_id
+
+ self._running = True
+ self._loop = asyncio.get_running_loop()
+ self._generate_req_id = generate_req_id
+
+ # Create WebSocket client
+ self._client = WSClient(
+ {
+ "bot_id": self.config.bot_id,
+ "secret": self.config.secret,
+ "reconnect_interval": 1000,
+ "max_reconnect_attempts": -1, # Infinite reconnect
+ "heartbeat_interval": 30000,
+ }
+ )
+
+ # Register event handlers
+ self._client.on("connected", self._on_connected)
+ self._client.on("authenticated", self._on_authenticated)
+ self._client.on("disconnected", self._on_disconnected)
+ self._client.on("error", self._on_error)
+ self._client.on("message.text", self._on_text_message)
+ self._client.on("message.image", self._on_image_message)
+ self._client.on("message.voice", self._on_voice_message)
+ self._client.on("message.file", self._on_file_message)
+ self._client.on("message.mixed", self._on_mixed_message)
+ self._client.on("event.enter_chat", self._on_enter_chat)
+
+ logger.info("WeCom bot starting with WebSocket long connection")
+ logger.info("No public IP required - using WebSocket to receive events")
+
+ # Connect
+ await self._client.connect_async()
+
+ # Keep running until stopped
+ while self._running:
+ await asyncio.sleep(1)
+
+ async def stop(self) -> None:
+ """Stop the WeCom bot."""
+ self._running = False
+ if self._client:
+ await self._client.disconnect()
+ logger.info("WeCom bot stopped")
+
+ async def _on_connected(self, frame: Any) -> None:
+ """Handle WebSocket connected event."""
+ logger.info("WeCom WebSocket connected")
+
+ async def _on_authenticated(self, frame: Any) -> None:
+ """Handle authentication success event."""
+ logger.info("WeCom authenticated successfully")
+
+ async def _on_disconnected(self, frame: Any) -> None:
+ """Handle WebSocket disconnected event."""
+ reason = frame.body if hasattr(frame, "body") else str(frame)
+ logger.warning("WeCom WebSocket disconnected: {}", reason)
+
+ async def _on_error(self, frame: Any) -> None:
+ """Handle error event."""
+ logger.error("WeCom error: {}", frame)
+
+ async def _on_text_message(self, frame: Any) -> None:
+ """Handle text message."""
+ await self._process_message(frame, "text")
+
+ async def _on_image_message(self, frame: Any) -> None:
+ """Handle image message."""
+ await self._process_message(frame, "image")
+
+ async def _on_voice_message(self, frame: Any) -> None:
+ """Handle voice message."""
+ await self._process_message(frame, "voice")
+
+ async def _on_file_message(self, frame: Any) -> None:
+ """Handle file message."""
+ await self._process_message(frame, "file")
+
+ async def _on_mixed_message(self, frame: Any) -> None:
+ """Handle mixed content message."""
+ await self._process_message(frame, "mixed")
+
+ async def _on_enter_chat(self, frame: Any) -> None:
+ """Handle enter_chat event (user opens chat with bot)."""
+ try:
+ # Extract body from WsFrame dataclass or dict
+ if hasattr(frame, "body"):
+ body = frame.body or {}
+ elif isinstance(frame, dict):
+ body = frame.get("body", frame)
+ else:
+ body = {}
+
+ chat_id = body.get("chatid", "") if isinstance(body, dict) else ""
+
+ if chat_id and self.config.welcome_message:
+ await self._client.reply_welcome(
+ frame,
+ {
+ "msgtype": "text",
+ "text": {"content": self.config.welcome_message},
+ },
+ )
+ except Exception as e:
+ logger.error("Error handling enter_chat: {}", e)
+
+ async def _process_message(self, frame: Any, msg_type: str) -> None:
+ """Process incoming message and forward to bus."""
+ try:
+ # Extract body from WsFrame dataclass or dict
+ if hasattr(frame, "body"):
+ body = frame.body or {}
+ elif isinstance(frame, dict):
+ body = frame.get("body", frame)
+ else:
+ body = {}
+
+ # Ensure body is a dict
+ if not isinstance(body, dict):
+ logger.warning("Invalid body type: {}", type(body))
+ return
+
+ # Extract message info
+ msg_id = body.get("msgid", "")
+ if not msg_id:
+ msg_id = f"{body.get('chatid', '')}_{body.get('sendertime', '')}"
+
+ # Deduplication check
+ if msg_id in self._processed_message_ids:
+ return
+ self._processed_message_ids[msg_id] = None
+
+ # Trim cache
+ while len(self._processed_message_ids) > 1000:
+ self._processed_message_ids.popitem(last=False)
+
+ # Extract sender info from "from" field (SDK format)
+ from_info = body.get("from", {})
+ sender_id = (
+ from_info.get("userid", "unknown") if isinstance(from_info, dict) else "unknown"
+ )
+
+ # For single chat, chatid is the sender's userid
+ # For group chat, chatid is provided in body
+ chat_type = body.get("chattype", "single")
+ chat_id = body.get("chatid", sender_id)
+
+ content_parts = []
+
+ if msg_type == "text":
+ text = body.get("text", {}).get("content", "")
+ if text:
+ content_parts.append(text)
+
+ elif msg_type == "image":
+ image_info = body.get("image", {})
+ file_url = image_info.get("url", "")
+ aes_key = image_info.get("aeskey", "")
+
+ if file_url and aes_key:
+ file_path = await self._download_and_save_media(file_url, aes_key, "image")
+ if file_path:
+ filename = os.path.basename(file_path)
+ content_parts.append(f"[image: {filename}]\n[Image: source: {file_path}]")
+ else:
+ content_parts.append("[image: download failed]")
+ else:
+ content_parts.append("[image: download failed]")
+
+ elif msg_type == "voice":
+ voice_info = body.get("voice", {})
+ # Voice message already contains transcribed content from WeCom
+ voice_content = voice_info.get("content", "")
+ if voice_content:
+ content_parts.append(f"[voice] {voice_content}")
+ else:
+ content_parts.append("[voice]")
+
+ elif msg_type == "file":
+ file_info = body.get("file", {})
+ file_url = file_info.get("url", "")
+ aes_key = file_info.get("aeskey", "")
+ file_name = file_info.get("name", "unknown")
+
+ if file_url and aes_key:
+ file_path = await self._download_and_save_media(
+ file_url, aes_key, "file", file_name
+ )
+ if file_path:
+ content_parts.append(f"[file: {file_name}]\n[File: source: {file_path}]")
+ else:
+ content_parts.append(f"[file: {file_name}: download failed]")
+ else:
+ content_parts.append(f"[file: {file_name}: download failed]")
+
+ elif msg_type == "mixed":
+ # Mixed content contains multiple message items
+ msg_items = body.get("mixed", {}).get("item", [])
+ for item in msg_items:
+ item_type = item.get("type", "")
+ if item_type == "text":
+ text = item.get("text", {}).get("content", "")
+ if text:
+ content_parts.append(text)
+ else:
+ content_parts.append(MSG_TYPE_MAP.get(item_type, f"[{item_type}]"))
+
+ else:
+ content_parts.append(MSG_TYPE_MAP.get(msg_type, f"[{msg_type}]"))
+
+ content = "\n".join(content_parts) if content_parts else ""
+
+ if not content:
+ return
+
+ # Store frame for this chat to enable replies
+ self._chat_frames[chat_id] = frame
+
+ # Forward to message bus
+ # Note: media paths are included in content for broader model compatibility
+ await self._handle_message(
+ sender_id=sender_id,
+ chat_id=chat_id,
+ content=content,
+ media=None,
+ metadata={
+ "message_id": msg_id,
+ "msg_type": msg_type,
+ "chat_type": chat_type,
+ },
+ )
+
+ except Exception as e:
+ logger.error("Error processing WeCom message: {}", e)
+
+ async def _download_and_save_media(
+ self,
+ file_url: str,
+ aes_key: str,
+ media_type: str,
+ filename: str | None = None,
+ ) -> str | None:
+ """
+ Download and decrypt media from WeCom.
+
+ Returns:
+ file_path or None if download failed
+ """
+ try:
+ data, fname = await self._client.download_file(file_url, aes_key)
+
+ if not data:
+ logger.warning("Failed to download media from WeCom")
+ return None
+
+ media_dir = get_media_dir("wecom")
+ if not filename:
+ filename = fname or f"{media_type}_{hash(file_url) % 100000}"
+ filename = os.path.basename(filename)
+
+ file_path = media_dir / filename
+ file_path.write_bytes(data)
+ logger.debug("Downloaded {} to {}", media_type, file_path)
+ return str(file_path)
+
+ except Exception as e:
+ logger.error("Error downloading media: {}", e)
+ return None
+
+ async def send(self, msg: OutboundMessage) -> None:
+ """Send a message through WeCom."""
+ if not self._client:
+ logger.warning("WeCom client not initialized")
+ return
+
+ try:
+ content = msg.content.strip()
+ if not content:
+ return
+ if self._generate_req_id is None:
+ logger.warning("WeCom request id generator not initialized")
+ return
+
+ # Get the stored frame for this chat
+ frame = self._chat_frames.get(msg.chat_id)
+ if not frame:
+ logger.warning("No frame found for chat {}, cannot reply", msg.chat_id)
+ return
+
+ # Use streaming reply for better UX
+ stream_id = self._generate_req_id("stream")
+
+ # Send as streaming message with finish=True
+ await self._client.reply_stream(
+ frame,
+ stream_id,
+ content,
+ finish=True,
+ )
+
+ logger.debug("WeCom message sent to {}", msg.chat_id)
+
+ except Exception as e:
+ logger.error("Error sending WeCom message: {}", e)
diff --git a/deeptutor/partners/channels/whatsapp.py b/deeptutor/partners/channels/whatsapp.py
new file mode 100644
index 000000000..86518ceb2
--- /dev/null
+++ b/deeptutor/partners/channels/whatsapp.py
@@ -0,0 +1,188 @@
+"""WhatsApp channel implementation using Node.js bridge."""
+
+import asyncio
+from collections import OrderedDict
+import json
+import mimetypes
+from typing import Any
+
+from loguru import logger
+from pydantic import Field
+
+from deeptutor.partners.bus.events import OutboundMessage
+from deeptutor.partners.bus.queue import MessageBus
+from deeptutor.partners.channels.base import BaseChannel
+from deeptutor.partners.config.schema import Base, DeliveryOverrides
+
+
+class WhatsAppConfig(DeliveryOverrides):
+ """WhatsApp channel configuration."""
+
+ enabled: bool = False
+ bridge_url: str = "ws://localhost:3001"
+ bridge_token: str = ""
+ allow_from: list[str] = Field(default_factory=list)
+
+
+class WhatsAppChannel(BaseChannel):
+ """
+ WhatsApp channel that connects to a Node.js bridge.
+
+ The bridge uses @whiskeysockets/baileys to handle the WhatsApp Web protocol.
+ Communication between Python and Node.js is via WebSocket.
+ """
+
+ name = "whatsapp"
+ display_name = "WhatsApp"
+
+ @classmethod
+ def default_config(cls) -> dict[str, Any]:
+ return WhatsAppConfig().model_dump(by_alias=True)
+
+ def __init__(self, config: Any, bus: MessageBus):
+ if isinstance(config, dict):
+ config = WhatsAppConfig.model_validate(config)
+ super().__init__(config, bus)
+ self._ws = None
+ self._connected = False
+ self._processed_message_ids: OrderedDict[str, None] = OrderedDict()
+
+ async def start(self) -> None:
+ """Start the WhatsApp channel by connecting to the bridge."""
+ import websockets
+
+ bridge_url = self.config.bridge_url
+
+ logger.info("Connecting to WhatsApp bridge at {}...", bridge_url)
+
+ self._running = True
+
+ while self._running:
+ try:
+ async with websockets.connect(bridge_url) as ws:
+ self._ws = ws
+ # Send auth token if configured
+ if self.config.bridge_token:
+ await ws.send(
+ json.dumps({"type": "auth", "token": self.config.bridge_token})
+ )
+ self._connected = True
+ logger.info("Connected to WhatsApp bridge")
+
+ # Listen for messages
+ async for message in ws:
+ try:
+ await self._handle_bridge_message(message)
+ except Exception as e:
+ logger.error("Error handling bridge message: {}", e)
+
+ except asyncio.CancelledError:
+ break
+ except Exception as e:
+ self._connected = False
+ self._ws = None
+ logger.warning("WhatsApp bridge connection error: {}", e)
+
+ if self._running:
+ logger.info("Reconnecting in 5 seconds...")
+ await asyncio.sleep(5)
+
+ async def stop(self) -> None:
+ """Stop the WhatsApp channel."""
+ self._running = False
+ self._connected = False
+
+ if self._ws:
+ await self._ws.close()
+ self._ws = None
+
+ async def send(self, msg: OutboundMessage) -> None:
+ """Send a message through WhatsApp."""
+ if not self._ws or not self._connected:
+ logger.warning("WhatsApp bridge not connected")
+ return
+
+ try:
+ payload = {"type": "send", "to": msg.chat_id, "text": msg.content}
+ await self._ws.send(json.dumps(payload, ensure_ascii=False))
+ except Exception as e:
+ logger.error("Error sending WhatsApp message: {}", e)
+
+ async def _handle_bridge_message(self, raw: str) -> None:
+ """Handle a message from the bridge."""
+ try:
+ data = json.loads(raw)
+ except json.JSONDecodeError:
+ logger.warning("Invalid JSON from bridge: {}", raw[:100])
+ return
+
+ msg_type = data.get("type")
+
+ if msg_type == "message":
+ # Incoming message from WhatsApp
+ # Deprecated by whatsapp: old phone number style typically: <phone>@s.whatspp.net
+ pn = data.get("pn", "")
+ # New LID sytle typically:
+ sender = data.get("sender", "")
+ content = data.get("content", "")
+ message_id = data.get("id", "")
+
+ if message_id:
+ if message_id in self._processed_message_ids:
+ return
+ self._processed_message_ids[message_id] = None
+ while len(self._processed_message_ids) > 1000:
+ self._processed_message_ids.popitem(last=False)
+
+ # Extract just the phone number or lid as chat_id
+ user_id = pn if pn else sender
+ sender_id = user_id.split("@")[0] if "@" in user_id else user_id
+ logger.info("Sender {}", sender)
+
+ # Handle voice transcription if it's a voice message
+ if content == "[Voice Message]":
+ logger.info(
+ "Voice message received from {}, but direct download from bridge is not yet supported.",
+ sender_id,
+ )
+ content = "[Voice Message: Transcription not available for WhatsApp yet]"
+
+ # Extract media paths (images/documents/videos downloaded by the bridge)
+ media_paths = data.get("media") or []
+
+ # Build content tags matching Telegram's pattern: [image: /path] or [file: /path]
+ if media_paths:
+ for p in media_paths:
+ mime, _ = mimetypes.guess_type(p)
+ media_type = "image" if mime and mime.startswith("image/") else "file"
+ media_tag = f"[{media_type}: {p}]"
+ content = f"{content}\n{media_tag}" if content else media_tag
+
+ await self._handle_message(
+ sender_id=sender_id,
+ chat_id=sender, # Use full LID for replies
+ content=content,
+ media=media_paths,
+ metadata={
+ "message_id": message_id,
+ "timestamp": data.get("timestamp"),
+ "is_group": data.get("isGroup", False),
+ },
+ )
+
+ elif msg_type == "status":
+ # Connection status update
+ status = data.get("status")
+ logger.info("WhatsApp status: {}", status)
+
+ if status == "connected":
+ self._connected = True
+ elif status == "disconnected":
+ self._connected = False
+
+ elif msg_type == "qr":
+ # QR code for authentication
+ logger.info("Scan QR code in the bridge terminal to connect WhatsApp")
+
+ elif msg_type == "error":
+ logger.error("WhatsApp bridge error: {}", data.get("error"))
diff --git a/deeptutor/partners/channels/zulip.py b/deeptutor/partners/channels/zulip.py
new file mode 100644
index 000000000..0d6cd4ce7
--- /dev/null
+++ b/deeptutor/partners/channels/zulip.py
@@ -0,0 +1,845 @@
+"""Zulip channel implementation using event queue API."""
+
+from __future__ import annotations
+
+import asyncio
+from collections import deque
+import hashlib
+from pathlib import Path
+import re
+import threading
+import time
+from typing import Any, Literal
+from urllib.parse import unquote
+
+from loguru import logger
+from pydantic import Field
+import requests
+
+from deeptutor.partners.bus.events import OutboundMessage
+from deeptutor.partners.bus.queue import MessageBus
+from deeptutor.partners.channels.base import BaseChannel
+from deeptutor.partners.config.paths import get_media_dir
+from deeptutor.partners.config.schema import Base, DeliveryOverrides
+from deeptutor.partners.helpers import split_message
+
+_UPLOAD_LINK_RE = re.compile(
+ r"\[([^\]]*)\]\((/user_uploads/[^)\s]+)\)"
+ r"|!\[([^\]]*)\]\((/user_uploads/[^)\s]+)\)",
+)
+
+_DISPLAY_MATH_RE = re.compile(
+ r"^\s*\$\$(.+?)\$\$\s*$",
+ re.MULTILINE | re.DOTALL,
+)
+_INLINE_MATH_RE = re.compile(
+ r"(?<!\$)\$(?!\$)(.+?)(?<!\$)\$(?!\$)",
+)
+_CODE_BLOCK_RE = re.compile(
+ r"(```(?!math)[\s\S]*?```|`[^`\n]+`)",
+)
+
+ZULIP_MAX_MESSAGE_LEN = 10000
+ZULIP_UPLOAD_PREFIX = "/user_uploads/"
+MENTION_FLAGS = frozenset(
+ {
+ "mentioned",
+ "wildcard_mentioned",
+ "stream_wildcard_mentioned",
+ "topic_wildcard_mentioned",
+ }
+)
+
+
+class ZulipConfig(DeliveryOverrides):
+ enabled: bool = False
+ site: str = ""
+ email: str = ""
+ api_key: str = Field(default="", repr=False)
+ allow_from: list[str] = Field(default_factory=list)
+ group_policy: Literal["mention", "open"] = "mention"
+ subscribe_streams: list[str] = Field(default_factory=list)
+ timeout: float = Field(default=60.0)
+
+
+class ZulipChannel(BaseChannel):
+ name = "zulip"
+ display_name = "Zulip"
+
+ @classmethod
+ def default_config(cls) -> dict[str, Any]:
+ return ZulipConfig().model_dump(by_alias=True)
+
+ def __init__(self, config: Any, bus: MessageBus):
+ if isinstance(config, dict):
+ config = ZulipConfig.model_validate(config)
+ super().__init__(config, bus)
+ self.config: ZulipConfig = config
+ self._client: Any = None
+ self._bot_email: str = ""
+ self._bot_user_id: int | None = None
+ self._bot_full_name: str = ""
+ self._queue_id: str | None = None
+ self._last_event_id: int = -1
+ self._max_message_id: int = 0
+ self._seen_ids: deque[int] = deque(maxlen=5000)
+ self._listener_thread: threading.Thread | None = None
+ self._loop: asyncio.AbstractEventLoop | None = None
+ self._typing_tasks: dict[str, asyncio.Task] = {}
+ self._recipient_map: dict[str, dict] = {}
+
+ def is_allowed(self, sender_id: str) -> bool:
+ if super().is_allowed(sender_id):
+ return True
+ allow_list = getattr(self.config, "allow_from", [])
+ if not allow_list or "*" in allow_list:
+ return False
+ sender_str = str(sender_id)
+ if sender_str.count("|") != 1:
+ return False
+ sid, email = sender_str.split("|", 1)
+ return sid in allow_list or email in allow_list
+
+ async def start(self) -> None:
+ if not self.config.site or not self.config.email or not self.config.api_key:
+ logger.error("Zulip site/email/apiKey not configured")
+ return
+
+ self._running = True
+ self._loop = asyncio.get_running_loop()
+
+ try:
+ import zulip
+
+ self._client = zulip.Client(
+ email=self.config.email,
+ api_key=self.config.api_key,
+ site=self.config.site,
+ )
+ except Exception as e:
+ logger.error("Failed to create Zulip client: {}", e)
+ self._running = False
+ return
+
+ profile = self._call_with_retry(self._client.get_profile)
+ if not profile or profile.get("result") != "success":
+ logger.error("Failed to get Zulip bot profile")
+ self._running = False
+ return
+
+ self._bot_email = profile.get("email", self.config.email)
+ self._bot_user_id = profile.get("user_id")
+ self._bot_full_name = profile.get("full_name", "")
+ logger.info(
+ "Zulip bot connected: {} (user_id={})",
+ self._bot_email,
+ self._bot_user_id,
+ )
+
+ self._subscribe_to_streams()
+
+ self._listener_thread = threading.Thread(
+ target=self._run_listener, daemon=True, name="zulip-listener"
+ )
+ self._listener_thread.start()
+
+ while self._running:
+ await asyncio.sleep(1)
+
+ async def stop(self) -> None:
+ self._running = False
+
+ for chat_id in list(self._typing_tasks):
+ self._stop_typing(chat_id)
+
+ if self._queue_id and self._client:
+ try:
+ self._client.deregister(self._queue_id)
+ except Exception:
+ pass
+
+ self._queue_id = None
+ self._client = None
+
+ if self._listener_thread and self._listener_thread.is_alive():
+ self._listener_thread.join(timeout=5)
+
+ self._listener_thread = None
+
+ async def send(self, msg: OutboundMessage) -> None:
+ if not self._client:
+ logger.warning("Zulip client not running")
+ return
+
+ metadata = self._metadata_for_send(msg)
+
+ if not metadata.get("_progress", False):
+ self._stop_typing(msg.chat_id)
+
+ try:
+ for media_path in msg.media or []:
+ await self._upload_and_send(msg.chat_id, media_path, metadata)
+
+ if msg.content and msg.content != "[empty message]":
+ converted = self._convert_latex_to_zulip(msg.content)
+ for chunk in split_message(converted, ZULIP_MAX_MESSAGE_LEN):
+ await self._send_text(msg.chat_id, chunk, metadata)
+ except Exception as e:
+ logger.error("Zulip send error: {}", e)
+
+ def _metadata_for_send(self, msg: OutboundMessage) -> dict:
+ metadata = msg.metadata or {}
+ if metadata.get("msg_type"):
+ return metadata
+
+ stored = self._recipient_map.get(msg.chat_id)
+ if not stored:
+ return metadata
+
+ msg.metadata = {**stored, **metadata}
+ return msg.metadata
+
+ def _call_with_retry(self, fn, *args, max_retries=3, **kwargs):
+ for attempt in range(max_retries):
+ try:
+ return fn(*args, **kwargs)
+ except Exception as e:
+ if attempt < max_retries - 1:
+ delay = 2**attempt
+ logger.warning(
+ "Zulip API call failed (attempt {}): {}, retrying in {}s",
+ attempt + 1,
+ e,
+ delay,
+ )
+ time.sleep(delay)
+ else:
+ logger.error("Zulip API call failed after {} retries: {}", max_retries, e)
+ raise
+
+ def _run_listener(self) -> None:
+ while self._running:
+ try:
+ self._register_queue()
+ if not self._queue_id:
+ logger.error("Failed to register Zulip event queue, retrying in 10s...")
+ time.sleep(10)
+ continue
+
+ while self._running:
+ try:
+ result = self._client.get_events(
+ queue_id=self._queue_id,
+ last_event_id=self._last_event_id,
+ )
+ except Exception as e:
+ logger.warning("Zulip get_events error: {}", e)
+ time.sleep(2)
+ break
+
+ if result.get("result") == "http-error":
+ logger.warning("Zulip HTTP error, retrying...")
+ time.sleep(2)
+ break
+
+ if result.get("code") == "BAD_EVENT_QUEUE_ID":
+ logger.warning("Zulip event queue expired, re-registering...")
+ self._queue_id = None
+ break
+
+ if result.get("result") != "success":
+ logger.warning(
+ "Zulip get_events unexpected result: {}",
+ result.get("msg", result.get("result")),
+ )
+ time.sleep(2)
+ continue
+
+ for event in result.get("events", []):
+ self._last_event_id = max(
+ self._last_event_id, event.get("id", self._last_event_id)
+ )
+ if event.get("type") == "message":
+ self._on_message(event.get("message", {}))
+
+ except Exception as e:
+ logger.error("Zulip listener error: {}", e)
+ time.sleep(5)
+
+ logger.info("Zulip listener stopped")
+
+ def _subscribe_to_streams(self) -> None:
+ stream_names = self._stream_names_to_subscribe()
+ if stream_names is None:
+ return
+ if not stream_names:
+ logger.info("No subscribe_streams configured, skipping auto-subscribe")
+ return
+
+ subscriptions = [{"name": name} for name in stream_names]
+ try:
+ result = self._call_with_retry(self._client.add_subscriptions, streams=subscriptions)
+ except Exception as e:
+ logger.error("Zulip auto-subscribe failed: {}", e)
+ return
+
+ self._log_subscription_result(result, set(stream_names))
+
+ def _stream_names_to_subscribe(self) -> list[str] | None:
+ streams = [s.strip() for s in self.config.subscribe_streams if s.strip()]
+ if not streams:
+ return []
+
+ if "*" not in streams:
+ return sorted(set(streams))
+
+ try:
+ result = self._call_with_retry(self._client.get_streams, include_all=True)
+ except Exception as e:
+ logger.error("Zulip get_streams failed during auto-subscribe: {}", e)
+ return None
+
+ if result.get("result") != "success":
+ logger.error("Failed to fetch streams for auto-subscribe: {}", result.get("msg"))
+ return None
+
+ fetched = {
+ stream.get("name")
+ for stream in result.get("streams", [])
+ if isinstance(stream, dict) and stream.get("name")
+ }
+ explicit = {stream for stream in streams if stream != "*"}
+ return sorted(fetched | explicit)
+
+ @staticmethod
+ def _already_subscribed_names(result: dict) -> set[str]:
+ already_subscribed = result.get("already_subscribed", {})
+ if isinstance(already_subscribed, list):
+ return {name for name in already_subscribed if isinstance(name, str)}
+ if not isinstance(already_subscribed, dict):
+ return set()
+
+ already_subscribed_names: set[str] = set()
+ for names in already_subscribed.values():
+ if isinstance(names, str):
+ already_subscribed_names.add(names)
+ elif isinstance(names, (list, tuple, set)):
+ already_subscribed_names.update(name for name in names if isinstance(name, str))
+ return already_subscribed_names
+
+ def _log_subscription_result(self, result: dict, stream_names: set[str]) -> None:
+ already_subscribed = self._already_subscribed_names(result) & stream_names
+ missing = stream_names - already_subscribed
+
+ if result.get("result") == "success":
+ if missing:
+ logger.info(
+ "Zulip bot subscribed to {} streams ({} new, {} already subscribed)",
+ len(stream_names),
+ len(missing),
+ len(already_subscribed),
+ )
+ else:
+ logger.info(
+ "Zulip bot already subscribed to {} streams (no new subscriptions)",
+ len(stream_names),
+ )
+ return
+
+ if not missing:
+ logger.debug(
+ "Zulip add_subscriptions returned non-success but all streams already subscribed: {}",
+ result.get("msg", "unknown"),
+ )
+ else:
+ logger.warning(
+ "Zulip auto-subscribe did not subscribe {} streams: {}",
+ len(missing),
+ result.get("msg", "unknown"),
+ )
+
+ def _register_queue(self) -> None:
+ try:
+ result = self._call_with_retry(
+ self._client.register,
+ event_types=["message"],
+ )
+ if result.get("result") == "success":
+ self._queue_id = result["queue_id"]
+ self._last_event_id = result.get("last_event_id", -1)
+ self._max_message_id = result.get("max_message_id", 0)
+ logger.info(
+ "Zulip event queue registered: queue_id={}, max_message_id={}",
+ self._queue_id,
+ self._max_message_id,
+ )
+ else:
+ logger.error("Zulip register failed: {}", result.get("msg", "unknown"))
+ self._queue_id = None
+ except Exception as e:
+ logger.error("Zulip register exception: {}", e)
+ self._queue_id = None
+
+ def _is_own_message(self, message: dict) -> bool:
+ sender_email = message.get("sender_email", "")
+ sender_id = message.get("sender_id")
+ if sender_email and sender_email == self._bot_email:
+ return True
+ if self._bot_user_id is not None and sender_id == self._bot_user_id:
+ return True
+ return False
+
+ def _is_duplicate(self, message: dict) -> bool:
+ msg_id = message.get("id")
+ if msg_id is None:
+ return False
+ if msg_id <= self._max_message_id:
+ return True
+ if msg_id in self._seen_ids:
+ return True
+ self._seen_ids.append(msg_id)
+ return False
+
+ def _on_message(self, message: dict) -> None:
+ if self._is_own_message(message):
+ return
+ if self._is_duplicate(message):
+ return
+
+ msg_type = message.get("type", "")
+ content = message.get("content", "")
+ logger.debug(
+ "Zulip message received: type={}, flags={}, sender={}, stream={}, topic={}",
+ msg_type,
+ message.get("flags", []),
+ message.get("sender_email", "?"),
+ message.get("display_recipient", "") if msg_type == "stream" else "N/A",
+ message.get("subject", ""),
+ )
+ content_type = message.get("content_type", "text/x-markdown")
+ if content_type == "text/x-markdown":
+ content = self._convert_zulip_latex_to_standard(content)
+ sender_id = message.get("sender_id", "")
+ sender_email = message.get("sender_email", "")
+ display_recipient = message.get("display_recipient", "")
+ subject = message.get("subject", "")
+
+ composite_sender = f"{sender_id}|{sender_email}" if sender_email else str(sender_id)
+
+ if msg_type == "stream":
+ stream_name = self._stream_name(display_recipient)
+ topic = self._topic_label(subject)
+ chat_id = self._stream_chat_id(stream_name, topic)
+ if self.config.group_policy == "mention":
+ if not self._is_mentioned(message):
+ logger.debug(
+ "Zulip stream message ignored (not mentioned): stream={}, topic={}, flags={}",
+ stream_name,
+ topic,
+ message.get("flags", []),
+ )
+ return
+ logger.debug(
+ "Zulip stream message will be processed: stream={}, topic={}",
+ stream_name,
+ topic,
+ )
+ content = f"**[{stream_name} > {topic}]** {content}"
+ elif msg_type == "private":
+ chat_id = f"pm:{sender_id}"
+ topic = ""
+ else:
+ return
+
+ metadata = {
+ "message_id": message.get("id"),
+ "msg_type": msg_type,
+ "sender_email": sender_email,
+ "sender_full_name": message.get("sender_full_name", ""),
+ "display_recipient": display_recipient,
+ "subject": subject,
+ }
+
+ if msg_type == "stream":
+ metadata["stream"] = self._stream_name(display_recipient)
+ metadata["topic"] = topic
+ else:
+ metadata["recipient_user_id"] = sender_id
+
+ self._recipient_map[chat_id] = metadata
+
+ media_paths = self._download_attachments(message)
+
+ if self._loop and not self._loop.is_closed():
+ asyncio.run_coroutine_threadsafe(self._start_typing_async(chat_id), self._loop)
+ asyncio.run_coroutine_threadsafe(
+ self._handle_message(
+ sender_id=composite_sender,
+ chat_id=chat_id,
+ content=content,
+ media=media_paths,
+ metadata=metadata,
+ session_key=self._session_key_for(chat_id),
+ ),
+ self._loop,
+ )
+
+ @staticmethod
+ def _stream_name(display_recipient: Any) -> str:
+ if isinstance(display_recipient, dict):
+ return display_recipient.get("name", str(display_recipient))
+ return str(display_recipient)
+
+ @staticmethod
+ def _topic_label(subject: Any) -> str:
+ topic = str(subject or "").strip()
+ return topic or "(no topic)"
+
+ @classmethod
+ def _stream_chat_id(cls, stream_name: str, topic: str) -> str:
+ return f"stream:{stream_name}:{cls._topic_label(topic)}"
+
+ def _session_key_for(self, chat_id: str) -> str | None:
+ if chat_id.startswith("stream:"):
+ return f"{self.name}:{chat_id}"
+ return None
+
+ def _is_mentioned(self, message: dict) -> bool:
+ """Check if the bot is mentioned in the message.
+
+ For Generic bot, Zulip server may not set 'mentioned' flag in the
+ event payload, so we also detect @mention by scanning the message
+ content for patterns like @**BotName** or @**BotName|UserID**.
+ """
+ if self._bot_user_id is None:
+ logger.debug("Zulip _is_mentioned: bot_user_id is None, cannot check mention")
+ return False
+
+ # 1. Mention flags — set by Outgoing webhook bots and some Generic bot
+ # configurations.
+ for flag in message.get("flags", []):
+ if isinstance(flag, str) and flag in MENTION_FLAGS:
+ logger.debug("Zulip _is_mentioned: found flag={}", flag)
+ return True
+
+ # 2. Content fallback — Generic bot + Event Queue API often returns an
+ # empty ``flags`` array, so scan the message body for the mention
+ # syntax Zulip renders: ``@**Bot Full Name**`` and, when names are
+ # ambiguous, the disambiguated ``@**Bot Full Name|user_id**``.
+ if self._bot_full_name:
+ content = message.get("content", "")
+ patterns = [f"@**{self._bot_full_name}**"]
+ if self._bot_user_id is not None:
+ patterns.append(f"@**{self._bot_full_name}|{self._bot_user_id}**")
+ for mention_pattern in patterns:
+ if mention_pattern in content:
+ logger.debug("Zulip _is_mentioned: matched content pattern {}", mention_pattern)
+ return True
+
+ logger.debug(
+ "Zulip _is_mentioned: no mention flags or content match, flags={}",
+ message.get("flags", []),
+ )
+ return False
+
+ def _download_attachments(self, message: dict) -> list[str]:
+ paths: list[str] = []
+ content = message.get("content", "")
+ content_type = message.get("content_type", "text/x-markdown")
+
+ upload_links = self._extract_upload_links(content, content_type)
+ if not upload_links:
+ return paths
+
+ media_dir = get_media_dir("zulip")
+
+ for name, path_id in upload_links:
+ local_path = self._download_upload_path(
+ path_id,
+ media_dir=media_dir,
+ name=name,
+ index=len(paths),
+ )
+ if local_path:
+ paths.append(local_path)
+
+ return paths
+
+ @staticmethod
+ def _safe_attachment_name(name: str, fallback: str) -> str:
+ raw_name = unquote(name or "").strip() or fallback
+ safe_name = re.sub(r"[^\w.\-]", "_", raw_name).strip("._")
+ return safe_name or fallback
+
+ @classmethod
+ def _attachment_destination(
+ cls,
+ media_dir: Path,
+ name: str,
+ path_id: str,
+ index: int,
+ ) -> Path:
+ fallback = f"attachment_{index}"
+ filename = cls._safe_attachment_name(name or Path(unquote(path_id)).name, fallback)
+ digest = hashlib.sha256(path_id.encode("utf-8")).hexdigest()[:12]
+ return media_dir / f"{digest}_{filename}"
+
+ @staticmethod
+ def _extract_upload_links(
+ content: str, content_type: str = "text/x-markdown"
+ ) -> list[tuple[str, str]]:
+ links: list[tuple[str, str]] = []
+ seen: set[str] = set()
+
+ if content_type == "text/html":
+ for match in re.finditer(r'href="(/user_uploads/[^"]+)"', content):
+ path_id = match.group(1)
+ if path_id not in seen:
+ seen.add(path_id)
+ name = Path(unquote(path_id)).name
+ links.append((name, path_id))
+ for match in re.finditer(r'src="(/user_uploads/[^"]+)"', content):
+ path_id = match.group(1)
+ if path_id not in seen:
+ seen.add(path_id)
+ name = Path(unquote(path_id)).name
+ links.append((name, path_id))
+ else:
+ for match in _UPLOAD_LINK_RE.finditer(content):
+ md_name = match.group(1) or match.group(3) or ""
+ path_id = match.group(2) or match.group(4) or ""
+ if path_id and path_id not in seen:
+ seen.add(path_id)
+ name = md_name if md_name else Path(unquote(path_id)).name
+ links.append((name, path_id))
+
+ return links
+
+ def _path_id_from_media(self, media_path: str) -> str | None:
+ if media_path.startswith(ZULIP_UPLOAD_PREFIX):
+ return media_path
+
+ site = self.config.site.rstrip("/")
+ if not site:
+ return None
+
+ prefix = f"{site}{ZULIP_UPLOAD_PREFIX}"
+ if media_path.startswith(prefix):
+ return f"{ZULIP_UPLOAD_PREFIX}{media_path[len(prefix) :]}"
+ return None
+
+ def _download_upload_path(
+ self,
+ path_id: str,
+ *,
+ media_dir: Path | None = None,
+ name: str | None = None,
+ index: int = 0,
+ ) -> str | None:
+ media_dir = media_dir or get_media_dir("zulip")
+ filename = name or Path(unquote(path_id)).name
+ dest = self._attachment_destination(media_dir, filename, path_id, index)
+
+ if dest.exists():
+ return str(dest)
+
+ url = f"{self.config.site.rstrip('/')}{path_id}"
+ try:
+ resp = requests.get(
+ url,
+ auth=(self.config.email, self.config.api_key),
+ timeout=self.config.timeout,
+ )
+ resp.raise_for_status()
+ dest.write_bytes(resp.content)
+ logger.debug("Downloaded Zulip attachment: {}", filename or path_id)
+ return str(dest)
+ except Exception as e:
+ logger.warning(
+ "Failed to download Zulip attachment {}: {}",
+ filename or path_id,
+ e,
+ )
+ return None
+
+ @staticmethod
+ def _convert_latex_to_zulip(text: str) -> str:
+ placeholders: list[str] = []
+
+ def _save_code(m: re.Match) -> str:
+ placeholders.append(m.group(0))
+ return f"\x00CODE{len(placeholders) - 1}\x00"
+
+ text = _CODE_BLOCK_RE.sub(_save_code, text)
+
+ def _display_math(m: re.Match) -> str:
+ body = m.group(1).strip()
+ return f"```math\n{body}\n```"
+
+ text = _DISPLAY_MATH_RE.sub(_display_math, text)
+
+ def _inline_math(m: re.Match) -> str:
+ body = m.group(1)
+ return f"$${body}$$"
+
+ text = _INLINE_MATH_RE.sub(_inline_math, text)
+
+ for i, code in enumerate(placeholders):
+ text = text.replace(f"\x00CODE{i}\x00", code)
+
+ return text
+
+ @staticmethod
+ def _convert_zulip_latex_to_standard(text: str) -> str:
+ placeholders: list[str] = []
+
+ def _save_code(m: re.Match) -> str:
+ placeholders.append(m.group(0))
+ return f"\x00CODE{len(placeholders) - 1}\x00"
+
+ text = _CODE_BLOCK_RE.sub(_save_code, text)
+
+ text = re.sub(
+ r"```math\s*\n(.*?)\n\s*```",
+ lambda m: f"$$\n{m.group(1).strip()}\n$$",
+ text,
+ flags=re.DOTALL,
+ )
+
+ text = re.sub(
+ r"(?<!\$)\$\$(?!\$)(.+?)(?<!\$)\$\$(?!\$)",
+ lambda m: f"${m.group(1)}$",
+ text,
+ )
+
+ for i, code in enumerate(placeholders):
+ text = text.replace(f"\x00CODE{i}\x00", code)
+
+ return text
+
+ async def _send_text(self, chat_id: str, text: str, metadata: dict) -> None:
+ client = self._client
+ if not client:
+ return
+ request = self._build_send_request(chat_id, text, metadata)
+ loop = asyncio.get_running_loop()
+ result = await loop.run_in_executor(
+ None,
+ lambda: self._call_with_retry(
+ client.call_endpoint,
+ url="messages",
+ request=request,
+ timeout=self.config.timeout,
+ ),
+ )
+ if result.get("result") != "success":
+ logger.error("Zulip send failed: {}", result.get("msg", "unknown"))
+
+ def _resolve_media_path(self, media_path: str) -> str | None:
+ if Path(media_path).exists():
+ return media_path
+
+ path_id = self._path_id_from_media(media_path)
+ if not path_id:
+ return None
+
+ return self._download_upload_path(path_id)
+
+ async def _upload_and_send(self, chat_id: str, media_path: str, metadata: dict) -> None:
+ client = self._client
+ if not client:
+ return
+
+ local_path = self._resolve_media_path(media_path)
+ if not local_path:
+ logger.error("Cannot resolve media path: {}", media_path)
+ return
+
+ loop = asyncio.get_running_loop()
+ with open(local_path, "rb") as f:
+ result = await loop.run_in_executor(
+ None,
+ lambda: self._call_with_retry(
+ client.call_endpoint,
+ url="user_uploads",
+ files=[f],
+ timeout=self.config.timeout,
+ ),
+ )
+ if result.get("result") != "success":
+ logger.error("Zulip upload failed: {}", result.get("msg", "unknown"))
+ return
+
+ uri = result.get("uri", "")
+ filename = Path(media_path).name
+ content = f"[{filename}]({self.config.site}{uri})"
+ await self._send_text(chat_id, content, metadata)
+
+ def _build_send_request(self, chat_id: str, content: str, metadata: dict) -> dict:
+ msg_type = metadata.get("msg_type", "private")
+
+ if msg_type == "stream":
+ stream = metadata.get("stream", metadata.get("display_recipient", ""))
+ topic = metadata.get("topic", metadata.get("subject", ""))
+ return {
+ "type": "stream",
+ "to": stream,
+ "subject": topic or "(no topic)",
+ "content": content,
+ }
+ else:
+ recipient = metadata.get("recipient_user_id") or metadata.get("sender_email", "")
+ return {
+ "type": "private",
+ "to": [recipient] if recipient else [],
+ "content": content,
+ }
+
+ async def _start_typing_async(self, chat_id: str) -> None:
+ self._start_typing(chat_id)
+
+ def _start_typing(self, chat_id: str) -> None:
+ self._stop_typing(chat_id)
+ self._typing_tasks[chat_id] = asyncio.create_task(self._typing_loop(chat_id))
+
+ def _stop_typing(self, chat_id: str) -> None:
+ task = self._typing_tasks.pop(chat_id, None)
+ if task and not task.done():
+ task.cancel()
+
+ async def _typing_loop(self, chat_id: str) -> None:
+ if not self._client or not self._bot_user_id:
+ return
+
+ if not chat_id.startswith("pm:"):
+ return
+
+ recipient_user_id = chat_id[3:]
+ if not recipient_user_id.isdigit():
+ return
+
+ try:
+ while self._running and self._client:
+ try:
+ self._client.set_typing_status(
+ {
+ "op": "start",
+ "to": [int(recipient_user_id)],
+ }
+ )
+ except Exception as e:
+ logger.debug("Zulip typing status error: {}", e)
+ await asyncio.sleep(4)
+ except asyncio.CancelledError:
+ pass
+ finally:
+ if self._client:
+ try:
+ self._client.set_typing_status(
+ {
+ "op": "stop",
+ "to": [int(recipient_user_id)],
+ }
+ )
+ except Exception:
+ pass
diff --git a/deeptutor/partners/config/__init__.py b/deeptutor/partners/config/__init__.py
new file mode 100644
index 000000000..4848444b1
--- /dev/null
+++ b/deeptutor/partners/config/__init__.py
@@ -0,0 +1,24 @@
+"""Configuration module for Partners channels."""
+
+from deeptutor.partners.config.paths import (
+ get_data_dir,
+ get_media_dir,
+ get_partner_dir,
+ get_partner_media_dir,
+ get_partner_sessions_dir,
+ get_partner_workspace,
+ get_runtime_subdir,
+)
+from deeptutor.partners.config.schema import Base, ChannelsConfig
+
+__all__ = [
+ "Base",
+ "ChannelsConfig",
+ "get_data_dir",
+ "get_media_dir",
+ "get_partner_dir",
+ "get_partner_media_dir",
+ "get_partner_sessions_dir",
+ "get_partner_workspace",
+ "get_runtime_subdir",
+]
diff --git a/deeptutor/partners/config/paths.py b/deeptutor/partners/config/paths.py
new file mode 100644
index 000000000..e7d8a3b60
--- /dev/null
+++ b/deeptutor/partners/config/paths.py
@@ -0,0 +1,53 @@
+"""Path helpers for the Partners data tree (``data/partners/``)."""
+
+from __future__ import annotations
+
+from pathlib import Path
+
+from deeptutor.partners.helpers import ensure_dir
+
+
+def _base_dir() -> Path:
+ # Anchored to the admin workspace root (data/partners), NOT the
+ # current-user path service: partner runtimes execute inside a synthetic
+ # partner scope whose workspace_root lives below this very tree, so
+ # resolving through the contextvar here would recurse the layout.
+ from deeptutor.multi_user.paths import get_admin_path_service
+
+ return ensure_dir(get_admin_path_service().workspace_root / "partners")
+
+
+def get_data_dir() -> Path:
+ return _base_dir()
+
+
+def get_runtime_subdir(name: str) -> Path:
+ return ensure_dir(_base_dir() / name)
+
+
+def get_media_dir(channel: str | None = None) -> Path:
+ """Shared media download dir used by channel implementations."""
+ base = get_runtime_subdir("media")
+ return ensure_dir(base / channel) if channel else base
+
+
+# ── Per-partner path helpers ──────────────────────────────────────
+
+
+def get_partner_dir(partner_id: str) -> Path:
+ """data/partners/{partner_id}/ — config, sessions, and workspace."""
+ return ensure_dir(_base_dir() / partner_id)
+
+
+def get_partner_workspace(partner_id: str) -> Path:
+ """The partner's scope root (chat user-workspace layout lives below it)."""
+ return ensure_dir(get_partner_dir(partner_id) / "workspace")
+
+
+def get_partner_sessions_dir(partner_id: str) -> Path:
+ return ensure_dir(get_partner_dir(partner_id) / "sessions")
+
+
+def get_partner_media_dir(partner_id: str, channel: str | None = None) -> Path:
+ base = ensure_dir(get_partner_dir(partner_id) / "media")
+ return ensure_dir(base / channel) if channel else base
diff --git a/deeptutor/partners/config/schema.py b/deeptutor/partners/config/schema.py
new file mode 100644
index 000000000..7a1dfd01d
--- /dev/null
+++ b/deeptutor/partners/config/schema.py
@@ -0,0 +1,60 @@
+"""Configuration schema — Pydantic models for partner channels."""
+
+from __future__ import annotations
+
+from pydantic import BaseModel, ConfigDict, Field
+from pydantic.alias_generators import to_camel
+
+
+class Base(BaseModel):
+ """Base model that accepts both camelCase and snake_case keys."""
+
+ model_config = ConfigDict(alias_generator=to_camel, populate_by_name=True)
+
+
+class DeliveryOverrides(Base):
+ """Per-channel delivery switches, ANDed with the partner-level flags.
+
+ A channel only receives progress / tool-hint messages when BOTH the
+ partner-level flag (ChannelsConfig) and the channel's own flag are on,
+ so the partner-level switches stay coarse master switches.
+ """
+
+ send_progress: bool = Field(
+ default=True,
+ description="Deliver agent narration progress to this channel (ANDed with the partner-level switch).",
+ )
+ send_tool_hints: bool = Field(
+ default=True,
+ description="Deliver one-line tool-call hints to this channel (ANDed with the partner-level switch).",
+ )
+
+
+class StreamingSupport(Base):
+ """Opt-in live streaming for channels that can edit messages in place."""
+
+ streaming: bool = Field(
+ default=False,
+ description=(
+ "Stream replies live by editing the message in place as text arrives. "
+ "Requires send_progress: narration rounds stream as they happen."
+ ),
+ )
+
+
+class ChannelsConfig(Base):
+ """Configuration for chat channels.
+
+ Built-in and plugin channel configs are stored as extra fields (dicts).
+ Each channel parses its own config in __init__.
+ """
+
+ model_config = ConfigDict(extra="allow")
+
+ # Both default ON so IM users see the partner's live working process
+ # (per-round narration text + one-line tool calls), mirroring the web
+ # chat's activity trace at IM-appropriate granularity.
+ send_progress: bool = True # stream agent narration to the channel
+ send_tool_hints: bool = True # stream tool-call hints (e.g. rag("…"))
+ # Outbound delivery failures retry with exponential backoff (1s/2s/4s…).
+ send_max_retries: int = 3
diff --git a/deeptutor/partners/helpers.py b/deeptutor/partners/helpers.py
new file mode 100644
index 000000000..f1a588b77
--- /dev/null
+++ b/deeptutor/partners/helpers.py
@@ -0,0 +1,69 @@
+"""Utility functions shared by the partner channel layer."""
+
+from datetime import datetime
+from pathlib import Path
+import re
+
+
+def detect_image_mime(data: bytes) -> str | None:
+ """Detect image MIME type from magic bytes, ignoring file extension."""
+ if data[:8] == b"\x89PNG\r\n\x1a\n":
+ return "image/png"
+ if data[:3] == b"\xff\xd8\xff":
+ return "image/jpeg"
+ if data[:6] in (b"GIF87a", b"GIF89a"):
+ return "image/gif"
+ if data[:4] == b"RIFF" and data[8:12] == b"WEBP":
+ return "image/webp"
+ return None
+
+
+def ensure_dir(path: Path) -> Path:
+ """Ensure directory exists, return it."""
+ path.mkdir(parents=True, exist_ok=True)
+ return path
+
+
+def timestamp() -> str:
+ """Current ISO timestamp."""
+ return datetime.now().isoformat()
+
+
+_UNSAFE_CHARS = re.compile(r'[<>:"/\\|?*]')
+
+
+def safe_filename(name: str) -> str:
+ """Replace unsafe path characters with underscores."""
+ return _UNSAFE_CHARS.sub("_", name).strip()
+
+
+def split_message(content: str, max_len: int = 2000) -> list[str]:
+ """
+ Split content into chunks within max_len, preferring line breaks.
+
+ Args:
+ content: The text content to split.
+ max_len: Maximum length per chunk (default 2000 for Discord compatibility).
+
+ Returns:
+ List of message chunks, each within max_len.
+ """
+ if not content:
+ return []
+ if len(content) <= max_len:
+ return [content]
+ chunks: list[str] = []
+ while content:
+ if len(content) <= max_len:
+ chunks.append(content)
+ break
+ cut = content[:max_len]
+ # Try to break at newline first, then space, then hard break
+ pos = cut.rfind("\n")
+ if pos <= 0:
+ pos = cut.rfind(" ")
+ if pos <= 0:
+ pos = max_len
+ chunks.append(content[:pos])
+ content = content[pos:].lstrip()
+ return chunks
diff --git a/deeptutor/partners/network.py b/deeptutor/partners/network.py
new file mode 100644
index 000000000..a9affff54
--- /dev/null
+++ b/deeptutor/partners/network.py
@@ -0,0 +1,101 @@
+"""Network security utilities for partner channels — SSRF protection.
+
+Stricter than ``deeptutor.services.mcp.network`` (which deliberately allows
+RFC1918 because MCP servers are often LAN-hosted): channel media URLs come
+from external IM platforms, so every private/internal range is blocked.
+
+Ported from nanobot's ``security/network.py``, trimmed to what channels use.
+"""
+
+from __future__ import annotations
+
+import ipaddress
+import socket
+from contextlib import suppress
+from urllib.parse import urlparse
+
+_BLOCKED_NETWORKS = [
+ ipaddress.ip_network("0.0.0.0/8"),
+ ipaddress.ip_network("10.0.0.0/8"),
+ ipaddress.ip_network("100.64.0.0/10"), # carrier-grade NAT
+ ipaddress.ip_network("127.0.0.0/8"),
+ ipaddress.ip_network("169.254.0.0/16"), # link-local / cloud metadata
+ ipaddress.ip_network("172.16.0.0/12"),
+ ipaddress.ip_network("192.168.0.0/16"),
+ ipaddress.ip_network("::1/128"),
+ ipaddress.ip_network("fc00::/7"), # unique local
+ ipaddress.ip_network("fe80::/10"), # link-local v6
+]
+
+
+def _normalize_addr(
+ addr: ipaddress.IPv4Address | ipaddress.IPv6Address,
+) -> ipaddress.IPv4Address | ipaddress.IPv6Address:
+ """Normalize IPv6-mapped IPv4 addresses (``::ffff:127.0.0.1``) to IPv4."""
+ if isinstance(addr, ipaddress.IPv6Address) and addr.ipv4_mapped is not None:
+ return addr.ipv4_mapped
+ return addr
+
+
+def _is_private(addr: ipaddress.IPv4Address | ipaddress.IPv6Address) -> bool:
+ normalized = _normalize_addr(addr)
+ return any(normalized in net for net in _BLOCKED_NETWORKS)
+
+
+def _is_allowed_loopback_target(
+ hostname: str,
+ addrs: list[ipaddress.IPv4Address | ipaddress.IPv6Address],
+) -> bool:
+ if not addrs or not all(_normalize_addr(addr).is_loopback for addr in addrs):
+ return False
+ normalized = hostname.rstrip(".").lower()
+ if normalized == "localhost":
+ return True
+ with suppress(ValueError):
+ return ipaddress.ip_address(hostname).is_loopback
+ return False
+
+
+def validate_url_target(url: str, *, allow_loopback: bool = False) -> tuple[bool, str]:
+ """Validate a URL is safe to fetch: scheme, hostname, and resolved IPs.
+
+ ``allow_loopback`` is intentionally narrow: it only permits literal
+ loopback hosts (localhost, 127.0.0.0/8, ::1) when every resolved address
+ is loopback. It does not allow RFC1918, link-local, metadata, or public
+ DNS names that happen to resolve to loopback.
+
+ Returns (ok, error_message). When ok is True, error_message is empty.
+ """
+ try:
+ p = urlparse(url)
+ except Exception as e:
+ return False, str(e)
+
+ if p.scheme not in ("http", "https"):
+ return False, f"Only http/https allowed, got '{p.scheme or 'none'}'"
+ if not p.netloc:
+ return False, "Missing domain"
+
+ hostname = p.hostname
+ if not hostname:
+ return False, "Missing hostname"
+
+ try:
+ infos = socket.getaddrinfo(hostname, None, socket.AF_UNSPEC, socket.SOCK_STREAM)
+ except socket.gaierror:
+ return False, f"Cannot resolve hostname: {hostname}"
+
+ addrs: list[ipaddress.IPv4Address | ipaddress.IPv6Address] = []
+ for info in infos:
+ try:
+ addr = ipaddress.ip_address(info[4][0])
+ except ValueError:
+ continue
+ addrs.append(addr)
+ if allow_loopback and _is_allowed_loopback_target(hostname, addrs):
+ return True, ""
+ for addr in addrs:
+ if _is_private(addr):
+ return False, f"Blocked: {hostname} resolves to private/internal address {addr}"
+
+ return True, ""
diff --git a/deeptutor/partners/transcription.py b/deeptutor/partners/transcription.py
new file mode 100644
index 000000000..670323de3
--- /dev/null
+++ b/deeptutor/partners/transcription.py
@@ -0,0 +1,61 @@
+"""Voice transcription provider using Groq."""
+
+import os
+from pathlib import Path
+
+import httpx
+from loguru import logger
+
+
+class GroqTranscriptionProvider:
+ """
+ Voice transcription provider using Groq's Whisper API.
+
+ Groq offers extremely fast transcription with a generous free tier.
+ """
+
+ def __init__(self, api_key: str | None = None):
+ self.api_key = api_key or os.environ.get("GROQ_API_KEY")
+ self.api_url = "https://api.groq.com/openai/v1/audio/transcriptions"
+
+ async def transcribe(self, file_path: str | Path) -> str:
+ """
+ Transcribe an audio file using Groq.
+
+ Args:
+ file_path: Path to the audio file.
+
+ Returns:
+ Transcribed text.
+ """
+ if not self.api_key:
+ logger.warning("Groq API key not configured for transcription")
+ return ""
+
+ path = Path(file_path)
+ if not path.exists():
+ logger.error("Audio file not found: {}", file_path)
+ return ""
+
+ try:
+ async with httpx.AsyncClient() as client:
+ with open(path, "rb") as f:
+ files = {
+ "file": (path.name, f),
+ "model": (None, "whisper-large-v3"),
+ }
+ headers = {
+ "Authorization": f"Bearer {self.api_key}",
+ }
+
+ response = await client.post(
+ self.api_url, headers=headers, files=files, timeout=60.0
+ )
+
+ response.raise_for_status()
+ data = response.json()
+ return data.get("text", "")
+
+ except Exception as e:
+ logger.error("Groq transcription error: {}", e)
+ return ""
diff --git a/deeptutor/services/partners/__init__.py b/deeptutor/services/partners/__init__.py
new file mode 100644
index 000000000..302868eb9
--- /dev/null
+++ b/deeptutor/services/partners/__init__.py
@@ -0,0 +1,23 @@
+"""Partner services — lifecycle, runtime, workspace, and sessions."""
+
+from deeptutor.services.partners.manager import (
+ PartnerConfig,
+ PartnerInstance,
+ PartnerManager,
+ get_partner_manager,
+ mask_channel_secrets,
+ slugify_partner_id,
+)
+from deeptutor.services.partners.runtime import PartnerRunner
+from deeptutor.services.partners.sessions import PartnerSessionStore
+
+__all__ = [
+ "PartnerConfig",
+ "PartnerInstance",
+ "PartnerManager",
+ "PartnerRunner",
+ "PartnerSessionStore",
+ "get_partner_manager",
+ "mask_channel_secrets",
+ "slugify_partner_id",
+]
diff --git a/deeptutor/services/partners/manager.py b/deeptutor/services/partners/manager.py
new file mode 100644
index 000000000..e9aa926ad
--- /dev/null
+++ b/deeptutor/services/partners/manager.py
@@ -0,0 +1,894 @@
+"""Partner Manager — create / start / stop / manage in-process partners.
+
+Each partner runs as a set of asyncio tasks within the DeepTutor server
+process: a ``PartnerRunner`` (chat-agent-loop driver), an outbound message
+router, and one listener task per enabled IM channel. Every partner owns an
+isolated chat-format workspace under ``data/partners/{partner_id}/``.
+"""
+
+from __future__ import annotations
+
+import asyncio
+from dataclasses import dataclass, field
+from datetime import datetime
+import logging
+from pathlib import Path
+import re
+import shutil
+from typing import Any, Awaitable, Callable
+
+import yaml
+
+from deeptutor.partners.config.paths import (
+ get_data_dir,
+ get_partner_dir,
+ get_partner_sessions_dir,
+)
+from deeptutor.services.partners.runtime import PartnerRunner
+from deeptutor.services.partners.sessions import PartnerSessionStore
+from deeptutor.services.partners.workspace import (
+ DEFAULT_SOUL,
+ ensure_partner_workspace,
+ read_soul,
+ write_soul,
+)
+
+logger = logging.getLogger(__name__)
+
+_RESERVED_NAMES = {"workspace", "media", "sessions", "_souls"}
+_ID_SAFE_RE = re.compile(r"[^a-z0-9-]+")
+
+# Substrings (case-insensitive) on channel field names that flag a value as a
+# secret which must be masked before being serialised in non-edit responses.
+# Matches existing channel configs: telegram.token, slack.bot_token /
+# slack.app_token, discord.token, matrix.access_token, whatsapp.bridge_token,
+# mochat.claw_token, feishu.app_secret / encrypt_key / verification_token,
+# wecom.secret, qq.secret, dingtalk.client_secret, email.imap_password /
+# smtp_password, etc.
+_SECRET_FIELD_HINTS: tuple[str, ...] = (
+ "token",
+ "secret",
+ "password",
+ "api_key",
+ "apikey",
+ "encrypt_key",
+)
+_SECRET_MASK = "***"
+
+
+def _is_secret_field(name: str) -> bool:
+ n = name.lower()
+ return any(hint in n for hint in _SECRET_FIELD_HINTS)
+
+
+def mask_channel_secrets(channels: dict[str, Any]) -> dict[str, Any]:
+ """Deep-copy ``channels`` and replace any secret-looking string field with ``***``."""
+
+ def _walk(value: Any, key_hint: str | None = None) -> Any:
+ if isinstance(value, dict):
+ return {k: _walk(v, key_hint=k) for k, v in value.items()}
+ if isinstance(value, list):
+ return [_walk(v, key_hint=key_hint) for v in value]
+ if isinstance(value, tuple):
+ return tuple(_walk(v, key_hint=key_hint) for v in value)
+ if key_hint is not None and _is_secret_field(key_hint) and isinstance(value, str) and value:
+ return _SECRET_MASK
+ return value
+
+ walked = _walk(channels)
+ if not isinstance(walked, dict): # defensive — should not happen
+ return {}
+ return walked
+
+
+def slugify_partner_id(name: str) -> str:
+ slug = _ID_SAFE_RE.sub("-", name.strip().lower()).strip("-")
+ return slug or "partner"
+
+
+def _optional_str_list(value: Any) -> list[str] | None:
+ """YAML field → ``None`` (absent / wrong type) or a list of strings."""
+ if isinstance(value, list):
+ return [str(item) for item in value]
+ return None
+
+
+@dataclass
+class PartnerConfig:
+ """Configuration for a single partner."""
+
+ name: str
+ description: str = ""
+ channels: dict[str, Any] = field(default_factory=dict)
+ llm_selection: dict[str, str] | None = None
+ # Fallback model: when a turn fails outright on the primary selection
+ # (LLM error, no output), the runner re-runs the turn once with this.
+ backup_llm_selection: dict[str, str] | None = None
+ model: str | None = None # legacy TutorBot model-string override
+ language: str = ""
+ emoji: str = ""
+ color: str = ""
+ # Custom avatar as a compact data URL (image/svg, client-resized) —
+ # kept inline in config so <img> rendering needs no authenticated
+ # file endpoint. Takes precedence over emoji/color when set.
+ avatar: str = ""
+ soul_origin: dict[str, str] = field(default_factory=dict) # {"type","id"} provenance
+ # User-toggleable system tools (same pool as the chat composer /
+ # /settings/tools). None = all of them; [] = none; list = whitelist.
+ enabled_tools: list[str] | None = None
+ # Configured MCP tools the partner may load. None = all; [] = MCP off.
+ mcp_tools: list[str] | None = None
+
+
+@dataclass
+class PartnerInstance:
+ """A running partner and its runtime objects."""
+
+ partner_id: str
+ config: PartnerConfig
+ started_at: datetime = field(default_factory=datetime.now)
+ tasks: list[asyncio.Task] = field(default_factory=list, repr=False)
+ runner: PartnerRunner | None = None
+ channel_manager: Any = None
+ notify_queue: asyncio.Queue = field(default_factory=asyncio.Queue)
+ channel_bindings: dict[str, str] = field(default_factory=dict)
+ reload_lock: asyncio.Lock = field(default_factory=asyncio.Lock, repr=False)
+ last_reload_error: str | None = None
+
+ @property
+ def running(self) -> bool:
+ return any(not t.done() for t in self.tasks)
+
+ def to_dict(
+ self,
+ *,
+ include_secrets: bool = False,
+ mask_secrets: bool = False,
+ ) -> dict[str, Any]:
+ """Serialise to a JSON-friendly dict (channel shapes as in TutorBot:
+ names-only by default, masked dict for detail views, raw only for the
+ explicitly-opt-in edit form)."""
+ if include_secrets:
+ channels: Any = self.config.channels
+ elif mask_secrets:
+ channels = mask_channel_secrets(self.config.channels)
+ else:
+ channels = list(self.config.channels.keys())
+
+ return {
+ "partner_id": self.partner_id,
+ "name": self.config.name,
+ "description": self.config.description,
+ "channels": channels,
+ "llm_selection": self.config.llm_selection,
+ "backup_llm_selection": self.config.backup_llm_selection,
+ "model": self.config.model,
+ "language": self.config.language,
+ "emoji": self.config.emoji,
+ "color": self.config.color,
+ "avatar": self.config.avatar,
+ "soul_origin": self.config.soul_origin,
+ "enabled_tools": self.config.enabled_tools,
+ "mcp_tools": self.config.mcp_tools,
+ "running": self.running,
+ "started_at": self.started_at.isoformat(),
+ "last_reload_error": self.last_reload_error,
+ }
+
+
+class PartnerManager:
+ """Manage partner instances running in-process."""
+
+ def __init__(self) -> None:
+ self._partners: dict[str, PartnerInstance] = {}
+ self._stores: dict[str, PartnerSessionStore] = {}
+ self._migrated_legacy = False
+
+ # ── Path helpers ──────────────────────────────────────────────
+
+ @property
+ def _partners_dir(self) -> Path:
+ return get_data_dir()
+
+ def _partner_dir(self, partner_id: str) -> Path:
+ return self._partners_dir / partner_id
+
+ def session_store(self, partner_id: str) -> PartnerSessionStore:
+ store = self._stores.get(partner_id)
+ if store is None:
+ store = PartnerSessionStore(get_partner_sessions_dir(partner_id))
+ self._stores[partner_id] = store
+ return store
+
+ def _ensure_partner_dirs(self, partner_id: str) -> None:
+ get_partner_dir(partner_id)
+ ensure_partner_workspace(partner_id)
+ get_partner_sessions_dir(partner_id)
+ if not read_soul(partner_id).strip():
+ write_soul(partner_id, DEFAULT_SOUL)
+
+ # ── Config persistence ────────────────────────────────────────
+
+ # Every PartnerConfig field must be listed here so merge_config can update
+ # it via the API; a field omitted here is silently un-updatable.
+ # auto_start is intentionally absent — lifecycle state, not config.
+ _MERGEABLE_FIELDS = (
+ "name",
+ "description",
+ "channels",
+ "llm_selection",
+ "backup_llm_selection",
+ "model",
+ "language",
+ "emoji",
+ "color",
+ "avatar",
+ "soul_origin",
+ "enabled_tools",
+ "mcp_tools",
+ )
+
+ def load_config(self, partner_id: str) -> PartnerConfig | None:
+ path = self._partner_dir(partner_id) / "config.yaml"
+ if not path.exists():
+ return None
+ try:
+ data = yaml.safe_load(path.read_text(encoding="utf-8")) or {}
+ return PartnerConfig(
+ name=data.get("name", partner_id),
+ description=data.get("description", ""),
+ channels=data.get("channels", {}) or {},
+ llm_selection=data.get("llm_selection"),
+ backup_llm_selection=data.get("backup_llm_selection"),
+ model=data.get("model"),
+ language=str(data.get("language", "") or ""),
+ emoji=str(data.get("emoji", "") or ""),
+ color=str(data.get("color", "") or ""),
+ avatar=str(data.get("avatar", "") or ""),
+ soul_origin=dict(data.get("soul_origin", {}) or {}),
+ enabled_tools=_optional_str_list(data.get("enabled_tools")),
+ mcp_tools=_optional_str_list(data.get("mcp_tools")),
+ )
+ except Exception:
+ logger.exception("Failed to load partner config %s", partner_id)
+ return None
+
+ def save_config(
+ self, partner_id: str, config: PartnerConfig, *, auto_start: bool | None = None
+ ) -> None:
+ """Persist atomically (write-temp + replace).
+
+ ``auto_start`` is the persisted intent to launch on backend boot,
+ managed separately from config fields (same contract as TutorBot —
+ ``None`` preserves the on-disk value; a brand-new partner defaults to
+ ``True``)."""
+ partner_dir = self._partner_dir(partner_id)
+ path = partner_dir / "config.yaml"
+ if auto_start is None:
+ auto_start = self._load_auto_start(partner_id, default=False) if path.exists() else True
+ partner_dir.mkdir(parents=True, exist_ok=True)
+ data: dict[str, Any] = {
+ "name": config.name,
+ "description": config.description,
+ "channels": config.channels,
+ "language": config.language,
+ "emoji": config.emoji,
+ "color": config.color,
+ "avatar": config.avatar,
+ "soul_origin": config.soul_origin,
+ "auto_start": auto_start,
+ }
+ if config.llm_selection:
+ data["llm_selection"] = config.llm_selection
+ if config.backup_llm_selection:
+ data["backup_llm_selection"] = config.backup_llm_selection
+ if config.model:
+ data["model"] = config.model
+ if config.enabled_tools is not None:
+ data["enabled_tools"] = list(config.enabled_tools)
+ if config.mcp_tools is not None:
+ data["mcp_tools"] = list(config.mcp_tools)
+
+ tmp_path = path.with_suffix(path.suffix + ".tmp")
+ tmp_path.write_text(yaml.dump(data, allow_unicode=True), encoding="utf-8")
+ tmp_path.replace(path)
+
+ def _load_auto_start(self, partner_id: str, *, default: bool = False) -> bool:
+ path = self._partner_dir(partner_id) / "config.yaml"
+ if not path.exists():
+ return default
+ try:
+ data = yaml.safe_load(path.read_text(encoding="utf-8")) or {}
+ return bool(data.get("auto_start", default))
+ except Exception:
+ logger.exception("Failed to load auto_start flag for partner '%s'", partner_id)
+ return default
+
+ def merge_config(self, partner_id: str, overrides: dict[str, Any]) -> PartnerConfig:
+ """Overlay non-``None`` overrides onto the on-disk config.
+
+ Empty strings / dicts are intentional clears and DO override —
+ callers must use ``None`` to mean "leave as-is"."""
+ existing = self.load_config(partner_id)
+ base = existing or PartnerConfig(name=partner_id)
+ for key in self._MERGEABLE_FIELDS:
+ if key in overrides and overrides[key] is not None:
+ setattr(base, key, overrides[key])
+ return base
+
+ # ── Lifecycle ─────────────────────────────────────────────────
+
+ async def start_partner(
+ self, partner_id: str, config: PartnerConfig | None = None
+ ) -> PartnerInstance:
+ if partner_id in self._partners and self._partners[partner_id].running:
+ return self._partners[partner_id]
+
+ self._ensure_partner_dirs(partner_id)
+
+ if config is None:
+ config = self.load_config(partner_id)
+ if config is None:
+ config = PartnerConfig(name=partner_id)
+ self.save_config(partner_id, config)
+
+ from deeptutor.partners.bus.queue import MessageBus
+
+ bus = MessageBus()
+ store = self.session_store(partner_id)
+ runner = PartnerRunner(partner_id, config, bus, store)
+
+ try:
+ channel_manager = self._build_channel_manager(config, bus, partner_id=partner_id)
+ except Exception:
+ logger.exception("Failed to initialise channels for partner '%s'", partner_id)
+ channel_manager = None
+
+ instance = PartnerInstance(
+ partner_id=partner_id,
+ config=config,
+ runner=runner,
+ channel_manager=channel_manager,
+ )
+
+ runner_task = asyncio.create_task(runner.run(), name=f"partner:{partner_id}:runner")
+ router_task = asyncio.create_task(
+ self._outbound_router(partner_id, bus, instance),
+ name=f"partner:{partner_id}:router",
+ )
+ instance.tasks.extend([runner_task, router_task])
+
+ if channel_manager:
+ for ch_name, ch in channel_manager.channels.items():
+ instance.tasks.append(
+ asyncio.create_task(ch.start(), name=f"partner:{partner_id}:ch:{ch_name}")
+ )
+
+ self._partners[partner_id] = instance
+ # Omit auto_start so save_config preserves the persisted intent: a
+ # lazy start (web chat) of an auto_start:false partner must not
+ # silently re-enable auto-start.
+ self.save_config(partner_id, config)
+ logger.info("Partner '%s' started", partner_id)
+ return instance
+
+ async def _outbound_router(self, partner_id: str, bus: Any, instance: PartnerInstance) -> None:
+ """Route outbound messages to channels, web notify_queue, and EventBus."""
+ try:
+ from deeptutor.events.event_bus import Event, EventType, get_event_bus
+ from deeptutor.partners.bus.events import OutboundMessage as _OMsg
+
+ event_bus = get_event_bus()
+ while True:
+ msg: _OMsg = await bus.consume_outbound()
+ is_progress = bool(msg.metadata and msg.metadata.get("_progress"))
+
+ if instance.channel_manager:
+ channel = instance.channel_manager.get_channel(msg.channel)
+ if channel:
+ try:
+ await channel.send(msg)
+ except Exception:
+ logger.exception(
+ "Failed to send to channel %s for partner %s",
+ msg.channel,
+ partner_id,
+ )
+ if not is_progress and msg.chat_id:
+ instance.channel_bindings[msg.channel] = msg.chat_id
+
+ if not is_progress:
+ await instance.notify_queue.put(msg.content or "")
+ await event_bus.publish(
+ Event(
+ type=EventType.CAPABILITY_COMPLETE,
+ task_id=f"partner:{partner_id}:{msg.channel}:{msg.chat_id}",
+ user_input="",
+ agent_output=msg.content or "",
+ metadata={
+ "source": "partner",
+ "partner_id": partner_id,
+ "channel": msg.channel,
+ "chat_id": msg.chat_id,
+ },
+ )
+ )
+ except asyncio.CancelledError:
+ return
+ except Exception:
+ logger.exception("Outbound router failed for partner %s", partner_id)
+
+ async def stop_partner(self, partner_id: str, *, preserve_auto_start: bool = False) -> bool:
+ """Stop a running partner.
+
+ Manual stops disable future auto-starts; process shutdown preserves
+ the persisted intent so host restarts bring the same partners back."""
+ instance = self._partners.get(partner_id)
+ if not instance:
+ return False
+ auto_start = (
+ self._load_auto_start(partner_id, default=True) if preserve_auto_start else False
+ )
+
+ for task in instance.tasks:
+ if not task.done():
+ task.cancel()
+ for task in instance.tasks:
+ try:
+ await asyncio.wait_for(asyncio.shield(task), timeout=5.0)
+ except (asyncio.CancelledError, asyncio.TimeoutError):
+ pass
+
+ if instance.channel_manager:
+ try:
+ await instance.channel_manager.stop_all()
+ except Exception:
+ logger.exception("Error stopping channels for partner '%s'", partner_id)
+
+ self.save_config(partner_id, instance.config, auto_start=auto_start)
+ del self._partners[partner_id]
+ logger.info("Partner '%s' stopped (auto_start=%s)", partner_id, auto_start)
+ return True
+
+ def _build_channel_manager(
+ self,
+ config: PartnerConfig,
+ bus: Any,
+ *,
+ partner_id: str,
+ ) -> Any | None:
+ """Construct a ``ChannelManager`` from ``config.channels`` or ``None``."""
+ if not config.channels:
+ return None
+ from deeptutor.partners.channels.manager import ChannelManager
+ from deeptutor.partners.config.schema import ChannelsConfig
+
+ channels_config = ChannelsConfig(**config.channels)
+ manager = ChannelManager(channels_config, bus)
+ if not manager.channels:
+ logger.info("No channels matched config for partner '%s'", partner_id)
+ return None
+ logger.info(
+ "Channels enabled for partner '%s': %s",
+ partner_id,
+ list(manager.channels.keys()),
+ )
+ return manager
+
+ async def reload_channels(self, partner_id: str) -> None:
+ """Restart channel listeners from ``instance.config.channels``.
+
+ Cancels only ``partner:{id}:ch:*`` tasks; runner and router keep
+ running. Serialised per partner via ``instance.reload_lock``. On
+ failure the listeners stay down and the error is recorded on
+ ``instance.last_reload_error`` for the UI."""
+ instance = self._partners.get(partner_id)
+ if not instance or not instance.running:
+ return
+
+ async with instance.reload_lock:
+ await self._teardown_channel_listeners(instance, partner_id)
+
+ try:
+ channel_manager = self._build_channel_manager(
+ instance.config,
+ instance.runner.bus if instance.runner else None,
+ partner_id=partner_id,
+ )
+ except Exception as exc:
+ logger.exception("Failed to reload channels for partner '%s'", partner_id)
+ instance.channel_manager = None
+ instance.last_reload_error = f"{type(exc).__name__}: {exc}"
+ raise
+
+ instance.channel_manager = channel_manager
+ instance.last_reload_error = None
+ if channel_manager:
+ for ch_name, ch in channel_manager.channels.items():
+ instance.tasks.append(
+ asyncio.create_task(ch.start(), name=f"partner:{partner_id}:ch:{ch_name}")
+ )
+ logger.info(
+ "Reloaded channels for partner '%s': %s",
+ partner_id,
+ list(channel_manager.channels.keys()),
+ )
+
+ async def _teardown_channel_listeners(
+ self,
+ instance: PartnerInstance,
+ partner_id: str,
+ ) -> None:
+ ch_prefix = f"partner:{partner_id}:ch:"
+ to_remove = [t for t in instance.tasks if (t.get_name() or "").startswith(ch_prefix)]
+ for t in to_remove:
+ if not t.done():
+ t.cancel()
+ for t in to_remove:
+ try:
+ await asyncio.wait_for(asyncio.shield(t), timeout=5.0)
+ except (asyncio.CancelledError, asyncio.TimeoutError):
+ pass
+ instance.tasks = [t for t in instance.tasks if t not in to_remove]
+
+ if instance.channel_manager:
+ try:
+ await instance.channel_manager.stop_all()
+ except Exception:
+ logger.exception(
+ "Error stopping channels before reload for partner '%s'", partner_id
+ )
+
+ instance.channel_manager = None
+ instance.channel_bindings.clear()
+
+ # ── Listing & discovery ───────────────────────────────────────
+
+ def _discover_partner_ids(self) -> set[str]:
+ self._migrate_legacy_tutorbot()
+ ids: set[str] = set()
+ if not self._partners_dir.exists():
+ return ids
+ for entry in self._partners_dir.iterdir():
+ if entry.name in _RESERVED_NAMES or entry.name.startswith((".", "_")):
+ continue
+ if entry.is_dir() and (entry / "config.yaml").exists():
+ ids.add(entry.name)
+ return ids
+
+ def list_partners(self) -> list[dict[str, Any]]:
+ """All known partners (running + configured on disk); channels keys-only."""
+ result: dict[str, dict[str, Any]] = {}
+
+ for inst in self._partners.values():
+ result[inst.partner_id] = inst.to_dict()
+
+ for pid in self._discover_partner_ids():
+ if pid in result:
+ continue
+ cfg = self.load_config(pid)
+ result[pid] = {
+ "partner_id": pid,
+ "name": cfg.name if cfg else pid,
+ "description": cfg.description if cfg else "",
+ "channels": list(cfg.channels.keys()) if cfg else [],
+ "llm_selection": cfg.llm_selection if cfg else None,
+ "backup_llm_selection": cfg.backup_llm_selection if cfg else None,
+ "model": cfg.model if cfg else None,
+ "language": cfg.language if cfg else "",
+ "emoji": cfg.emoji if cfg else "",
+ "color": cfg.color if cfg else "",
+ "avatar": cfg.avatar if cfg else "",
+ "soul_origin": cfg.soul_origin if cfg else {},
+ "enabled_tools": cfg.enabled_tools if cfg else None,
+ "mcp_tools": cfg.mcp_tools if cfg else None,
+ "running": False,
+ "started_at": None,
+ }
+
+ return list(result.values())
+
+ def get_partner(self, partner_id: str) -> PartnerInstance | None:
+ return self._partners.get(partner_id)
+
+ def partner_exists(self, partner_id: str) -> bool:
+ return (self._partner_dir(partner_id) / "config.yaml").exists()
+
+ @staticmethod
+ def web_session_key(
+ partner_id: str, *, chat_id: str = "web", session_id: str | None = None
+ ) -> str:
+ normalized_session = str(session_id or "").strip()
+ if normalized_session:
+ return f"web:{normalized_session}"
+ normalized_chat = str(chat_id or "web").strip() or "web"
+ if normalized_chat != "web":
+ return f"web:{normalized_chat}"
+ return f"partner:{partner_id}"
+
+ def get_history(
+ self, partner_id: str, *, session_key: str | None = None, limit: int = 100
+ ) -> list[dict[str, Any]]:
+ store = self.session_store(partner_id)
+ if session_key:
+ return store.messages(session_key, limit=limit)
+ return store.merged_messages(limit=limit)
+
+ def get_recent_active_partners(self, limit: int = 3) -> list[dict[str, Any]]:
+ activity: list[tuple[str, dict[str, Any]]] = []
+ for pid in self._discover_partner_ids():
+ sessions = self.session_store(pid).list_sessions()
+ if not sessions:
+ continue
+ newest = sessions[0]
+ cfg = self.load_config(pid)
+ instance = self._partners.get(pid)
+ activity.append(
+ (
+ str(newest.get("updated_at", "")),
+ {
+ "partner_id": pid,
+ "name": cfg.name if cfg else pid,
+ "running": instance.running if instance else False,
+ "last_message": newest.get("last_message", ""),
+ "updated_at": newest.get("updated_at", ""),
+ },
+ )
+ )
+ activity.sort(key=lambda item: item[0], reverse=True)
+ return [item[1] for item in activity[:limit]]
+
+ # ── Messaging (web entry point) ───────────────────────────────
+
+ async def send_message(
+ self,
+ partner_id: str,
+ content: str,
+ chat_id: str = "web",
+ session_id: str | None = None,
+ on_event: Callable[[Any], Awaitable[None]] | None = None,
+ ) -> str:
+ """Send a web message to a running partner and return the reply."""
+ instance = self._partners.get(partner_id)
+ if not instance or not instance.running or not instance.runner:
+ raise RuntimeError(f"Partner '{partner_id}' is not running")
+
+ from deeptutor.partners.bus.events import InboundMessage
+
+ session_key = self.web_session_key(partner_id, chat_id=chat_id, session_id=session_id)
+ msg = InboundMessage(
+ channel="web",
+ sender_id="web",
+ chat_id=session_id or chat_id,
+ content=content,
+ session_key_override=session_key,
+ )
+ return await instance.runner.process_message(msg, on_event=on_event)
+
+ # ── Boot / shutdown ───────────────────────────────────────────
+
+ async def auto_start_partners(self) -> None:
+ for pid in self._discover_partner_ids():
+ if pid in self._partners and self._partners[pid].running:
+ continue
+ try:
+ if not self._load_auto_start(pid, default=False):
+ continue
+ config = self.load_config(pid)
+ if config is None:
+ continue
+ await self.start_partner(pid, config)
+ logger.info("Auto-started partner '%s'", pid)
+ except Exception:
+ logger.exception("Failed to auto-start partner '%s'", pid)
+
+ async def stop_all(self, *, preserve_auto_start: bool = True) -> None:
+ for partner_id in list(self._partners.keys()):
+ await self.stop_partner(partner_id, preserve_auto_start=preserve_auto_start)
+
+ async def destroy_partner(self, partner_id: str) -> bool:
+ await self.stop_partner(partner_id, preserve_auto_start=False)
+ self._stores.pop(partner_id, None)
+ try:
+ from deeptutor.services.cron import get_cron_service
+
+ get_cron_service().remove_owner_jobs(f"partner:{partner_id}")
+ except Exception:
+ logger.warning("Failed to clear cron jobs for '%s'", partner_id, exc_info=True)
+ partner_dir = self._partner_dir(partner_id)
+ if not partner_dir.exists():
+ return False
+ shutil.rmtree(partner_dir)
+ logger.info("Partner '%s' destroyed (data deleted)", partner_id)
+ return True
+
+ # ── Legacy TutorBot migration ─────────────────────────────────
+
+ def _migrate_legacy_tutorbot(self) -> None:
+ """One-shot migration of ``data/tutorbot/`` bots into partners.
+
+ Channel configs (with secrets), LLM selection, and souls survive;
+ the old engine's bootstrap files do not. ``persona`` becomes the
+ partner's SOUL.md. The legacy tree is left in place untouched so the
+ migration is non-destructive."""
+ if self._migrated_legacy:
+ return
+ self._migrated_legacy = True
+
+ legacy_root = self._partners_dir.parent / "tutorbot"
+ if not legacy_root.is_dir():
+ return
+
+ legacy_souls = legacy_root / "_souls.yaml"
+ new_souls = self._souls_file
+ if legacy_souls.is_file() and not new_souls.exists():
+ try:
+ self._partners_dir.mkdir(parents=True, exist_ok=True)
+ shutil.copy2(legacy_souls, new_souls)
+ except OSError:
+ logger.exception("Failed to migrate TutorBot souls library")
+
+ for entry in legacy_root.iterdir():
+ if not entry.is_dir() or entry.name in _RESERVED_NAMES | {"bots"}:
+ continue
+ legacy_config = entry / "config.yaml"
+ if not legacy_config.is_file():
+ continue
+ partner_id = entry.name
+ if (self._partner_dir(partner_id) / "config.yaml").exists():
+ continue
+ try:
+ data = yaml.safe_load(legacy_config.read_text(encoding="utf-8")) or {}
+ config = PartnerConfig(
+ name=data.get("name", partner_id),
+ description=data.get("description", ""),
+ channels=data.get("channels", {}) or {},
+ llm_selection=data.get("llm_selection"),
+ model=data.get("model"),
+ soul_origin={"type": "tutorbot", "id": partner_id},
+ )
+ self._ensure_partner_dirs(partner_id)
+ persona = str(data.get("persona", "") or "").strip()
+ if persona:
+ write_soul(partner_id, persona)
+ self.save_config(partner_id, config, auto_start=bool(data.get("auto_start", False)))
+ legacy_sessions = entry / "workspace" / "sessions"
+ if legacy_sessions.is_dir():
+ dst = get_partner_sessions_dir(partner_id)
+ for jsonl in legacy_sessions.glob("*.jsonl"):
+ target = dst / jsonl.name
+ if not target.exists():
+ shutil.copy2(jsonl, target)
+ logger.info("Migrated TutorBot '%s' to partner", partner_id)
+ except Exception:
+ logger.exception("Failed to migrate TutorBot '%s'", partner_id)
+
+ # ── Soul template library ─────────────────────────────────────
+
+ @property
+ def _souls_file(self) -> Path:
+ return self._partners_dir / "_souls.yaml"
+
+ def _load_souls(self) -> list[dict[str, str]]:
+ path = self._souls_file
+ if not path.exists():
+ self._seed_default_souls()
+ try:
+ data = yaml.safe_load(path.read_text(encoding="utf-8"))
+ return data if isinstance(data, list) else []
+ except Exception:
+ return []
+
+ def _save_souls(self, souls: list[dict[str, str]]) -> None:
+ self._partners_dir.mkdir(parents=True, exist_ok=True)
+ self._souls_file.write_text(
+ yaml.dump(souls, allow_unicode=True, default_flow_style=False),
+ encoding="utf-8",
+ )
+
+ def _seed_default_souls(self) -> None:
+ defaults = [
+ {
+ "id": "companion",
+ "name": "Learning Companion",
+ "content": (
+ "# Soul\n\nI am a personal learning companion.\n\n"
+ "## Personality\n\n- Helpful and friendly\n- Clear, encouraging, and patient\n"
+ "- Adapts explanations to the user's level\n\n"
+ "## Values\n\n- Accuracy over speed\n- User privacy and safety\n- Transparency in actions"
+ ),
+ },
+ {
+ "id": "math-tutor",
+ "name": "Math Tutor",
+ "content": (
+ "# Soul\n\nI am a math tutor specializing in clear, step-by-step problem solving.\n\n"
+ "## Personality\n\n- Patient and methodical\n- Encourages showing work\n"
+ "- Celebrates progress on hard problems\n\n"
+ "## Teaching Style\n\n- Break complex problems into small steps\n"
+ "- Use visual representations when possible\n- Always verify final answers"
+ ),
+ },
+ {
+ "id": "coding-assistant",
+ "name": "Coding Assistant",
+ "content": (
+ "# Soul\n\nI am a coding assistant focused on helping developers write better software.\n\n"
+ "## Personality\n\n- Precise and detail-oriented\n"
+ "- Pragmatic — working code over perfect code\n- Explains trade-offs clearly\n\n"
+ "## Approach\n\n- Read before writing; understand context first\n"
+ "- Suggest tests alongside implementations\n- Prefer standard patterns over clever tricks"
+ ),
+ },
+ {
+ "id": "research-helper",
+ "name": "Research Helper",
+ "content": (
+ "# Soul\n\nI am a research assistant helping users explore academic topics in depth.\n\n"
+ "## Personality\n\n- Curious and thorough\n"
+ "- Balanced — presents multiple perspectives\n- Cites sources when possible\n\n"
+ "## Approach\n\n- Decompose broad questions into focused sub-questions\n"
+ "- Distinguish established facts from open questions\n- Suggest further reading"
+ ),
+ },
+ {
+ "id": "language-tutor",
+ "name": "Language Tutor",
+ "content": (
+ "# Soul\n\nI am a language learning companion helping users practice and improve.\n\n"
+ "## Personality\n\n- Encouraging and patient\n"
+ "- Adapts difficulty to learner level\n- Makes learning fun with examples\n\n"
+ "## Teaching Style\n\n- Correct mistakes gently with explanations\n"
+ "- Use contextual examples over abstract rules\n- Encourage speaking/writing practice"
+ ),
+ },
+ ]
+ self._save_souls(defaults)
+
+ def list_souls(self) -> list[dict[str, str]]:
+ return self._load_souls()
+
+ def get_soul(self, soul_id: str) -> dict[str, str] | None:
+ for s in self._load_souls():
+ if s.get("id") == soul_id:
+ return s
+ return None
+
+ def create_soul(self, soul_id: str, name: str, content: str) -> dict[str, str]:
+ souls = self._load_souls()
+ entry = {"id": soul_id, "name": name, "content": content}
+ souls.append(entry)
+ self._save_souls(souls)
+ return entry
+
+ def update_soul(
+ self, soul_id: str, name: str | None, content: str | None
+ ) -> dict[str, str] | None:
+ souls = self._load_souls()
+ for s in souls:
+ if s.get("id") == soul_id:
+ if name is not None:
+ s["name"] = name
+ if content is not None:
+ s["content"] = content
+ self._save_souls(souls)
+ return s
+ return None
+
+ def delete_soul(self, soul_id: str) -> bool:
+ souls = self._load_souls()
+ new = [s for s in souls if s.get("id") != soul_id]
+ if len(new) == len(souls):
+ return False
+ self._save_souls(new)
+ return True
+
+
+_manager: PartnerManager | None = None
+
+
+def get_partner_manager() -> PartnerManager:
+ global _manager
+ if _manager is None:
+ _manager = PartnerManager()
+ return _manager
diff --git a/deeptutor/services/partners/model_runtime.py b/deeptutor/services/partners/model_runtime.py
new file mode 100644
index 000000000..f5aba3333
--- /dev/null
+++ b/deeptutor/services/partners/model_runtime.py
@@ -0,0 +1,36 @@
+"""Helpers for resolving per-partner LLM model selection."""
+
+from __future__ import annotations
+
+from typing import Any
+
+from deeptutor.services.llm.config import LLMConfig
+from deeptutor.services.model_selection import LLMSelection
+from deeptutor.services.model_selection.runtime import resolve_llm_config_for_selection
+
+
+def normalize_partner_llm_selection(value: Any) -> dict[str, str] | None:
+ """Return a validated selection dict, or ``None`` for system default."""
+ selection = LLMSelection.from_payload(value)
+ return selection.to_dict() if selection else None
+
+
+def resolve_partner_llm_config(partner_config: Any) -> LLMConfig:
+ """Resolve the effective LLM config for a partner config object.
+
+ Configs store ``llm_selection`` as a stable catalog reference. Configs
+ migrated from TutorBot may still carry a raw ``model`` string, which is
+ applied as a model-only override on top of the system default provider.
+ """
+ selection = normalize_partner_llm_selection(getattr(partner_config, "llm_selection", None))
+ if selection:
+ return resolve_llm_config_for_selection(selection)
+
+ base = resolve_llm_config_for_selection(None)
+ legacy_model = str(getattr(partner_config, "model", "") or "").strip()
+ if legacy_model:
+ return base.model_copy(update={"model": legacy_model})
+ return base
+
+
+__all__ = ["normalize_partner_llm_selection", "resolve_partner_llm_config"]
diff --git a/deeptutor/services/partners/runtime.py b/deeptutor/services/partners/runtime.py
new file mode 100644
index 000000000..eb40b6167
--- /dev/null
+++ b/deeptutor/services/partners/runtime.py
@@ -0,0 +1,467 @@
+"""Partner agent runtime — drives the chat agent loop from IM messages.
+
+This replaces the deleted TutorBot engine. A partner has NO engine of its
+own: every inbound message becomes one chat turn executed by
+``ChatOrchestrator`` → ``AgenticChatPipeline`` (the exact loop the product
+chat uses), run inside the partner's synthetic user scope so rag / skills /
+notebook tools read the partner workspace natively.
+
+Event → IM mapping:
+
+* ``RESULT`` (``metadata.response``) → the reply message
+* ``CONTENT`` with ``call_kind=llm_final_response`` → terminator/ask_user
+ text (the loop's RESULT is empty for an unresolved ask_user pause — the
+ pending question IS the reply, and the user's next IM message simply
+ starts the next turn)
+* narration rounds (``call_role=narration``) → optional ``_progress``
+ messages (``send_progress`` channel flag)
+* ``TOOL_CALL`` → optional ``_tool_hint``
+"""
+
+from __future__ import annotations
+
+import asyncio
+import base64
+import logging
+from typing import Any, Awaitable, Callable
+import uuid
+
+from deeptutor.core.context import Attachment, UnifiedContext
+from deeptutor.core.stream import StreamEvent, StreamEventType
+from deeptutor.multi_user.paths import user_context
+from deeptutor.partners.bus.events import InboundMessage, OutboundMessage
+from deeptutor.partners.bus.queue import MessageBus
+from deeptutor.partners.helpers import detect_image_mime
+from deeptutor.services.partners.scope import partner_user
+from deeptutor.services.partners.sessions import PartnerSessionStore
+from deeptutor.services.partners.workspace import ensure_partner_workspace, read_soul
+
+logger = logging.getLogger(__name__)
+
+EventCallback = Callable[[StreamEvent], Awaitable[None]]
+
+_MAX_IMAGE_BYTES = 8 * 1024 * 1024
+_TOOL_HINT_MAX_CHARS = 120
+
+
+def _format_tool_hint(tool_name: str, args: Any) -> str:
+ """One-line IM rendering of a tool call: ``⚙ rag(query="…")``."""
+ rendered = ""
+ if isinstance(args, dict) and args:
+ parts = []
+ for key, value in args.items():
+ if str(key).startswith("_"):
+ continue
+ text = str(value)
+ if len(text) > 40:
+ text = text[:37] + "…"
+ parts.append(f"{key}={text!r}" if isinstance(value, str) else f"{key}={text}")
+ rendered = ", ".join(parts)
+ hint = f"⚙ {tool_name}({rendered})"
+ if len(hint) > _TOOL_HINT_MAX_CHARS:
+ hint = hint[: _TOOL_HINT_MAX_CHARS - 1] + "…"
+ return hint
+
+
+class PartnerRunner:
+ """Consume a partner's inbound bus and answer with the chat agent loop."""
+
+ def __init__(
+ self,
+ partner_id: str,
+ config: Any,
+ bus: MessageBus,
+ store: PartnerSessionStore,
+ ) -> None:
+ self.partner_id = partner_id
+ self.config = config
+ self.bus = bus
+ self.store = store
+ self._session_locks: dict[str, asyncio.Lock] = {}
+ self._tasks: set[asyncio.Task] = set()
+
+ # ── inbound loop ──────────────────────────────────────────────
+
+ async def run(self) -> None:
+ """Long-running consumer: one task per message, serialised per session."""
+ try:
+ while True:
+ msg = await self.bus.consume_inbound()
+ task = asyncio.create_task(
+ self._handle_inbound(msg),
+ name=f"partner:{self.partner_id}:turn",
+ )
+ self._tasks.add(task)
+ task.add_done_callback(self._tasks.discard)
+ except asyncio.CancelledError:
+ for task in list(self._tasks):
+ task.cancel()
+ raise
+
+ async def _handle_inbound(self, msg: InboundMessage) -> None:
+ delivery_meta: dict[str, Any] = {}
+ try:
+ final = await self.process_message(msg, delivery_meta=delivery_meta)
+ except Exception as exc:
+ logger.exception(
+ "Partner %s failed to process message on %s", self.partner_id, msg.channel
+ )
+ final = f"Sorry, something went wrong while processing your message: {exc}"
+ if final:
+ await self.bus.publish_outbound(
+ OutboundMessage(
+ channel=msg.channel,
+ chat_id=msg.chat_id,
+ content=final,
+ metadata=delivery_meta,
+ )
+ )
+
+ # ── one turn ──────────────────────────────────────────────────
+
+ def _lock_for(self, session_key: str) -> asyncio.Lock:
+ lock = self._session_locks.get(session_key)
+ if lock is None:
+ lock = asyncio.Lock()
+ self._session_locks[session_key] = lock
+ return lock
+
+ async def process_message(
+ self,
+ msg: InboundMessage,
+ *,
+ on_event: EventCallback | None = None,
+ delivery_meta: dict[str, Any] | None = None,
+ ) -> str:
+ """Run one chat turn for *msg* and return the final reply text.
+
+ *delivery_meta*, when given, is filled with metadata the caller
+ should attach to the final outbound message (e.g. ``_streamed``
+ when the reply was already delivered live via stream deltas).
+ """
+ session_key = msg.session_key
+ async with self._lock_for(session_key):
+ final = await self._run_turn(msg, on_event=on_event, delivery_meta=delivery_meta)
+ self.store.append(
+ session_key,
+ "user",
+ msg.content,
+ channel=msg.channel,
+ sender_id=msg.sender_id,
+ )
+ if final:
+ self.store.append(session_key, "assistant", final, channel=msg.channel)
+ return final
+
+ async def _run_turn(
+ self,
+ msg: InboundMessage,
+ *,
+ on_event: EventCallback | None = None,
+ delivery_meta: dict[str, Any] | None = None,
+ ) -> str:
+ ensure_partner_workspace(self.partner_id)
+ primary = getattr(self.config, "llm_selection", None) or None
+ backup = getattr(self.config, "backup_llm_selection", None) or None
+
+ final_text, errors = await self._execute_turn(
+ msg, selection=primary, on_event=on_event, delivery_meta=delivery_meta
+ )
+ if not final_text and errors and backup and backup != primary:
+ logger.warning(
+ "Partner %s turn failed on primary model (%s); retrying with backup",
+ self.partner_id,
+ errors[-1][:200],
+ )
+ if delivery_meta is not None:
+ delivery_meta.pop("_streamed", None)
+ final_text, errors = await self._execute_turn(
+ msg, selection=backup, on_event=on_event, delivery_meta=delivery_meta
+ )
+
+ if not final_text and errors:
+ final_text = f"Sorry, the turn failed: {errors[-1]}"
+ return final_text
+
+ async def _execute_turn(
+ self,
+ msg: InboundMessage,
+ *,
+ selection: dict[str, str] | None,
+ on_event: EventCallback | None = None,
+ delivery_meta: dict[str, Any] | None = None,
+ ) -> tuple[str, list[str]]:
+ """Run one chat turn with *selection* active; returns (final, errors).
+
+ A failed turn is ``("", [error, …])`` — the caller decides whether a
+ backup model gets a second attempt. Exceptions are folded into the
+ error list so the retry policy sees them too.
+
+ When the inbound message asks for streaming (``_wants_stream``, set
+ by channels whose config enables it), every loop round's text is
+ published live as ``_stream_delta`` messages keyed by
+ ``_stream_id = {turn_id}:{call_id}`` — narration rounds freeze into
+ their own IM message when they complete, and the finish round
+ becomes the reply (the final outbound is then marked ``_streamed``
+ so the channel doesn't send it twice).
+ """
+ from deeptutor.runtime.orchestrator import ChatOrchestrator
+ from deeptutor.services.model_selection.runtime import (
+ activate_llm_selection,
+ reset_llm_selection,
+ )
+
+ context = self._build_context(msg)
+ turn_id = str(context.metadata.get("turn_id") or "")
+ send_progress = self._channels_flag("send_progress", default=True)
+ send_tool_hints = self._channels_flag("send_tool_hints", default=True)
+ is_im = msg.channel != "web"
+ # Streaming requires send_progress: narration rounds stream live as
+ # they happen, so with progress muted we keep buffered delivery.
+ wants_stream = is_im and send_progress and bool(msg.metadata.get("_wants_stream"))
+
+ final_text = ""
+ terminator_text = ""
+ round_buffers: dict[str, list[str]] = {}
+ streamed_rounds: dict[str, str] = {} # call_id → accumulated streamed text
+ ended_rounds: set[str] = set()
+ errors: list[str] = []
+
+ # Resolve the partner's LLM selection BEFORE entering the partner
+ # scope: the model catalog lives in the admin workspace. The scoped
+ # config rides the same async context into the orchestrator task.
+ _config, llm_token = activate_llm_selection(selection)
+ try:
+ with user_context(partner_user(self.partner_id, name=self.config.name)):
+ orchestrator = ChatOrchestrator()
+ async for event in orchestrator.handle(context):
+ if on_event is not None:
+ await on_event(event)
+ meta = event.metadata or {}
+
+ if event.type == StreamEventType.CONTENT:
+ call_id = str(meta.get("call_id") or "")
+ round_buffers.setdefault(call_id, []).append(event.content or "")
+ if meta.get("call_kind") == "llm_final_response":
+ terminator_text += event.content or ""
+ if wants_stream and event.content:
+ streamed_rounds[call_id] = (
+ streamed_rounds.get(call_id, "") + event.content
+ )
+ await self._publish_stream_delta(msg, turn_id, call_id, event.content)
+
+ elif event.type == StreamEventType.TOOL_CALL:
+ if is_im and send_tool_hints and event.content:
+ hint = _format_tool_hint(event.content, meta.get("args"))
+ await self._publish_hint(msg, hint, tool_hint=True)
+
+ elif event.type == StreamEventType.PROGRESS:
+ if (
+ meta.get("trace_kind") == "call_status"
+ and meta.get("call_state") == "complete"
+ and meta.get("call_role") == "narration"
+ ):
+ call_id = str(meta.get("call_id") or "")
+ text = "".join(round_buffers.pop(call_id, [])).strip()
+ if call_id in streamed_rounds:
+ # Already streamed live — freeze the segment.
+ ended_rounds.add(call_id)
+ await self._publish_stream_end(msg, turn_id, call_id)
+ elif is_im and send_progress and text:
+ await self._publish_hint(msg, text, tool_hint=False)
+
+ elif event.type == StreamEventType.RESULT and event.source == "chat":
+ final_text = str(meta.get("response") or "")
+
+ elif event.type == StreamEventType.ERROR and event.content:
+ errors.append(event.content)
+ except Exception as exc:
+ logger.exception("Partner %s turn crashed", self.partner_id)
+ errors.append(f"{type(exc).__name__}: {exc}")
+ finally:
+ reset_llm_selection(llm_token)
+
+ if not final_text.strip():
+ final_text = terminator_text.strip()
+ final_text = final_text.strip()
+
+ # Close any stream segments still open (the finish round, or partial
+ # rounds after a crash) so channels can flush their edit buffers.
+ for call_id in streamed_rounds:
+ if call_id not in ended_rounds:
+ await self._publish_stream_end(msg, turn_id, call_id)
+ # The reply is "already delivered" only when the live-streamed
+ # text matches what the caller is about to send.
+ if (
+ delivery_meta is not None
+ and final_text
+ and streamed_rounds[call_id].strip() == final_text
+ ):
+ delivery_meta["_streamed"] = True
+
+ return final_text, errors
+
+ # ── context assembly ──────────────────────────────────────────
+
+ def _build_context(self, msg: InboundMessage) -> UnifiedContext:
+ session_key = msg.session_key
+ turn_id = f"partner-{self.partner_id}-{uuid.uuid4().hex[:12]}"
+ history = self.store.conversation_history(session_key)
+ attachments = self._attachments_from_media(msg.media)
+
+ # Partner-scope context blocks (soul / skills / KBs) are assembled
+ # inside the partner scope so the same service locators the chat
+ # turn-runtime uses resolve to the partner workspace.
+ with user_context(partner_user(self.partner_id, name=self.config.name)):
+ skills_manifest = self._build_skills_manifest()
+ kb_names = self._list_kb_names()
+
+ metadata: dict[str, Any] = {
+ "turn_id": turn_id,
+ "source": "partner",
+ "partner_id": self.partner_id,
+ "channel": msg.channel,
+ "chat_id": msg.chat_id,
+ "sender_id": msg.sender_id,
+ "session_key": session_key,
+ # Swaps the system prompt's product identity ("You are DeepTutor")
+ # for the partner's user-given identity; the Soul does the rest.
+ "agent_identity": {
+ "name": self.config.name,
+ "description": getattr(self.config, "description", "") or "",
+ },
+ # NOTE: no ``wait_for_user_reply`` — an ask_user pause makes
+ # the pending question the turn's reply (IM semantics).
+ }
+ mcp_tools = getattr(self.config, "mcp_tools", None)
+ if isinstance(mcp_tools, list):
+ metadata["mcp_tools_filter"] = [str(name) for name in mcp_tools]
+
+ return UnifiedContext(
+ session_id=f"partner:{self.partner_id}:{session_key}",
+ user_message=msg.content,
+ conversation_history=history,
+ enabled_tools=self._resolved_enabled_tools(),
+ active_capability="chat",
+ knowledge_bases=kb_names,
+ attachments=attachments,
+ language=self._language(),
+ persona_context=read_soul(self.partner_id).strip(),
+ skills_manifest=skills_manifest,
+ metadata=metadata,
+ )
+
+ def _resolved_enabled_tools(self) -> list[str]:
+ """The partner's user-toggleable tool whitelist.
+
+ ``None`` in config means "everything the user could toggle on in
+ chat" — partners default to fully equipped; an explicit list (or
+ ``[]``) is the owner's selection.
+ """
+ configured = getattr(self.config, "enabled_tools", None)
+ if configured is None:
+ from deeptutor.agents._shared.tool_composition import default_optional_tools
+
+ return default_optional_tools()
+ return [str(name) for name in configured]
+
+ def _build_skills_manifest(self) -> str:
+ try:
+ from deeptutor.services.skill.service import (
+ get_skill_service,
+ render_skills_manifest,
+ )
+
+ service = get_skill_service()
+ entries = service.summary_entries()
+ always_block = service.load_always_for_context()
+ return "\n\n".join(
+ part for part in (always_block, render_skills_manifest(entries)) if part
+ )
+ except Exception:
+ logger.warning(
+ "Failed to build skills manifest for partner %s", self.partner_id, exc_info=True
+ )
+ return ""
+
+ def _list_kb_names(self) -> list[str]:
+ try:
+ from deeptutor.knowledge.manager import KnowledgeBaseManager
+ from deeptutor.services.path_service import get_path_service
+
+ kb_root = get_path_service().get_knowledge_bases_root()
+ if not kb_root.is_dir():
+ return []
+ return KnowledgeBaseManager(base_dir=str(kb_root)).list_knowledge_bases()
+ except Exception:
+ logger.warning("Failed to list KBs for partner %s", self.partner_id, exc_info=True)
+ return []
+
+ def _language(self) -> str:
+ lang = str(getattr(self.config, "language", "") or "").strip().lower()
+ return "zh" if lang.startswith("zh") else "en"
+
+ def _channels_flag(self, name: str, *, default: bool) -> bool:
+ channels = getattr(self.config, "channels", None) or {}
+ value = channels.get(name, default) if isinstance(channels, dict) else default
+ return bool(value)
+
+ def _attachments_from_media(self, media: list[str]) -> list[Attachment]:
+ attachments: list[Attachment] = []
+ for raw_path in media or []:
+ try:
+ from pathlib import Path
+
+ path = Path(raw_path)
+ if not path.is_file() or path.stat().st_size > _MAX_IMAGE_BYTES:
+ continue
+ data = path.read_bytes()
+ mime = detect_image_mime(data)
+ if not mime:
+ continue
+ attachments.append(
+ Attachment(
+ type="image",
+ base64=base64.b64encode(data).decode("ascii"),
+ filename=path.name,
+ mime_type=mime,
+ )
+ )
+ except OSError:
+ logger.warning("Skipping unreadable media file: %s", raw_path, exc_info=True)
+ return attachments
+
+ async def _publish_hint(self, msg: InboundMessage, text: str, *, tool_hint: bool) -> None:
+ await self.bus.publish_outbound(
+ OutboundMessage(
+ channel=msg.channel,
+ chat_id=msg.chat_id,
+ content=text,
+ metadata={"_progress": True, "_tool_hint": tool_hint},
+ )
+ )
+
+ async def _publish_stream_delta(
+ self, msg: InboundMessage, turn_id: str, call_id: str, delta: str
+ ) -> None:
+ await self.bus.publish_outbound(
+ OutboundMessage(
+ channel=msg.channel,
+ chat_id=msg.chat_id,
+ content=delta,
+ metadata={"_stream_delta": True, "_stream_id": f"{turn_id}:{call_id}"},
+ )
+ )
+
+ async def _publish_stream_end(self, msg: InboundMessage, turn_id: str, call_id: str) -> None:
+ await self.bus.publish_outbound(
+ OutboundMessage(
+ channel=msg.channel,
+ chat_id=msg.chat_id,
+ content="",
+ metadata={"_stream_end": True, "_stream_id": f"{turn_id}:{call_id}"},
+ )
+ )
+
+
+__all__ = ["PartnerRunner"]
diff --git a/deeptutor/services/partners/scope.py b/deeptutor/services/partners/scope.py
new file mode 100644
index 000000000..2e162dadf
--- /dev/null
+++ b/deeptutor/services/partners/scope.py
@@ -0,0 +1,42 @@
+"""Synthetic user scope for partner runtimes.
+
+A partner is executed as a *synthetic user*: its workspace
+(``data/partners/<id>/workspace``) is laid out exactly like a chat user
+workspace, and every service that resolves paths through
+``get_current_path_service()`` (rag, skills, notebooks, memory, task
+workspaces) transparently reads the partner's own assets once the partner
+scope is installed via ``user_context(...)``.
+"""
+
+from __future__ import annotations
+
+from deeptutor.multi_user.models import CurrentUser, UserScope
+from deeptutor.partners.config.paths import get_partner_workspace
+
+PARTNER_USER_PREFIX = "partner_"
+
+
+def partner_user_id(partner_id: str) -> str:
+ return f"{PARTNER_USER_PREFIX}{partner_id}"
+
+
+def partner_scope(partner_id: str) -> UserScope:
+ workspace = get_partner_workspace(partner_id)
+ return UserScope(
+ kind="user",
+ user_id=partner_user_id(partner_id),
+ root=workspace.resolve(),
+ )
+
+
+def partner_user(partner_id: str, *, name: str = "") -> CurrentUser:
+ scope = partner_scope(partner_id)
+ return CurrentUser(
+ id=scope.user_id,
+ username=name or partner_id,
+ role="user",
+ scope=scope,
+ )
+
+
+__all__ = ["PARTNER_USER_PREFIX", "partner_scope", "partner_user", "partner_user_id"]
diff --git a/deeptutor/services/partners/sessions.py b/deeptutor/services/partners/sessions.py
new file mode 100644
index 000000000..b72a52779
--- /dev/null
+++ b/deeptutor/services/partners/sessions.py
@@ -0,0 +1,154 @@
+"""Lightweight JSONL conversation store for partner sessions.
+
+One JSONL file per session key (``telegram:12345``, ``web:<session_id>``,
+``partner:<id>`` …) under ``data/partners/<id>/sessions/``. This is the
+partner-side replacement for the deleted engine's SessionManager: it only
+has to hand the chat agent loop an OpenAI-format ``conversation_history``
+and back the history API, so a flat append-only file per session is enough.
+"""
+
+from __future__ import annotations
+
+from datetime import datetime
+import json
+import logging
+from pathlib import Path
+import threading
+from typing import Any
+
+from deeptutor.partners.helpers import safe_filename
+
+logger = logging.getLogger(__name__)
+
+_HISTORY_MAX_MESSAGES = 40
+_HISTORY_MAX_CHARS = 24_000
+
+
+class PartnerSessionStore:
+ """Append-only JSONL persistence for one partner's conversations."""
+
+ def __init__(self, sessions_dir: Path) -> None:
+ self._dir = sessions_dir
+ self._dir.mkdir(parents=True, exist_ok=True)
+ self._write_lock = threading.Lock()
+
+ def _path(self, session_key: str) -> Path:
+ return self._dir / f"{safe_filename(session_key) or 'default'}.jsonl"
+
+ # ── write ─────────────────────────────────────────────────────
+
+ def append(
+ self,
+ session_key: str,
+ role: str,
+ content: str,
+ *,
+ channel: str = "",
+ sender_id: str = "",
+ metadata: dict[str, Any] | None = None,
+ ) -> None:
+ record = {
+ "role": role,
+ "content": content,
+ "timestamp": datetime.now().isoformat(),
+ }
+ if channel:
+ record["channel"] = channel
+ if sender_id:
+ record["sender_id"] = sender_id
+ if metadata:
+ record["metadata"] = metadata
+ line = json.dumps(record, ensure_ascii=False)
+ with self._write_lock:
+ with open(self._path(session_key), "a", encoding="utf-8") as f:
+ f.write(line + "\n")
+
+ def clear(self, session_key: str) -> bool:
+ path = self._path(session_key)
+ if not path.exists():
+ return False
+ path.unlink()
+ return True
+
+ # ── read ──────────────────────────────────────────────────────
+
+ def _read_records(self, session_key: str) -> list[dict[str, Any]]:
+ path = self._path(session_key)
+ if not path.exists():
+ return []
+ records: list[dict[str, Any]] = []
+ try:
+ with open(path, encoding="utf-8") as f:
+ for line in f:
+ line = line.strip()
+ if not line:
+ continue
+ try:
+ data = json.loads(line)
+ except json.JSONDecodeError:
+ continue
+ if isinstance(data, dict) and data.get("role") and data.get("content"):
+ records.append(data)
+ except OSError:
+ logger.exception("Failed to read partner session %s", session_key)
+ return records
+
+ def conversation_history(
+ self,
+ session_key: str,
+ *,
+ max_messages: int = _HISTORY_MAX_MESSAGES,
+ max_chars: int = _HISTORY_MAX_CHARS,
+ ) -> list[dict[str, str]]:
+ """Return trailing history in OpenAI message format, budget-capped."""
+ records = self._read_records(session_key)
+ window = [
+ {"role": str(r["role"]), "content": str(r["content"])}
+ for r in records[-max_messages:]
+ if r.get("role") in {"user", "assistant"}
+ ]
+ total = 0
+ kept: list[dict[str, str]] = []
+ for message in reversed(window):
+ total += len(message["content"])
+ if kept and total > max_chars:
+ break
+ kept.append(message)
+ kept.reverse()
+ return kept
+
+ def messages(self, session_key: str, *, limit: int = 100) -> list[dict[str, Any]]:
+ """Raw records (role/content/timestamp/...) for the history API."""
+ return self._read_records(session_key)[-limit:]
+
+ def merged_messages(self, *, limit: int = 100) -> list[dict[str, Any]]:
+ """All sessions' records merged chronologically (recent-activity view)."""
+ merged: list[tuple[str, int, dict[str, Any]]] = []
+ sequence = 0
+ for path in sorted(self._dir.glob("*.jsonl"), key=lambda p: p.stat().st_mtime):
+ key = path.stem
+ for record in self._read_records(key):
+ merged.append((str(record.get("timestamp", "")), sequence, record))
+ sequence += 1
+ merged.sort(key=lambda item: (item[0], item[1]))
+ return [item[2] for item in merged[-limit:]]
+
+ def list_sessions(self) -> list[dict[str, Any]]:
+ sessions: list[dict[str, Any]] = []
+ for path in sorted(
+ self._dir.glob("*.jsonl"), key=lambda p: p.stat().st_mtime, reverse=True
+ ):
+ records = self._read_records(path.stem)
+ last = records[-1] if records else {}
+ sessions.append(
+ {
+ "session_key": path.stem,
+ "message_count": len(records),
+ "updated_at": datetime.fromtimestamp(path.stat().st_mtime).isoformat(),
+ "last_message": str(last.get("content", ""))[:200],
+ }
+ )
+ return sessions
+
+
+__all__ = ["PartnerSessionStore"]
diff --git a/deeptutor/services/partners/workspace.py b/deeptutor/services/partners/workspace.py
new file mode 100644
index 000000000..0126b658e
--- /dev/null
+++ b/deeptutor/services/partners/workspace.py
@@ -0,0 +1,388 @@
+"""Partner workspace layout + asset provisioning.
+
+The partner workspace is a verbatim clone of the chat user-workspace format
+(``PathService`` layout), so the chat agent loop's tools read it natively:
+
+ data/partners/<id>/workspace/ ← synthetic scope root
+ ├── knowledge_bases/<kb>/ ← copied KBs (rag)
+ └── user/
+ ├── workspace/
+ │ ├── SOUL.md ← the partner's persona
+ │ ├── skills/<name>/SKILL.md ← copied skills (read_skill)
+ │ ├── notebook/… ← copied notebooks (list_notebook/write_note)
+ │ └── memory/…
+ └── settings/ …
+
+Provisioning runs in the *requesting user's* context: sources are resolved
+with that user's permissions (``resolve_kb`` / assigned-skill grants), then
+copied into the partner scope as plain files. All three asset classes are
+self-contained on disk, so a copy is a complete transfer:
+
+* KB: the whole ``<kb>/`` tree (raw + LlamaIndex ``version-N`` dirs); the
+ partner-side ``KnowledgeBaseManager`` auto-registers it on first list.
+* Skill: the whole ``<name>/`` dir (SKILL.md + references).
+* Notebook: ``<id>.json`` plus its ``notebooks_index.json`` entry.
+"""
+
+from __future__ import annotations
+
+import json
+import logging
+from pathlib import Path
+import shutil
+from typing import Any
+
+from deeptutor.multi_user.paths import (
+ ensure_scope_workspace,
+ get_admin_path_service,
+ get_path_service_for_scope,
+)
+from deeptutor.services.partners.scope import partner_scope
+from deeptutor.services.path_service import PathService
+
+logger = logging.getLogger(__name__)
+
+
+def _requester_path_service() -> PathService:
+ """Path service for the user driving this provisioning call.
+
+ Resolved through ``get_current_user()`` (which falls back to the local
+ admin) rather than ``get_path_service()`` — the latter short-circuits to
+ the process-default instance when no user contextvar is set, bypassing
+ scope resolution entirely.
+ """
+ from deeptutor.multi_user.context import get_current_user
+
+ return get_path_service_for_scope(get_current_user().scope)
+
+
+SOUL_FILENAME = "SOUL.md"
+
+DEFAULT_SOUL = """# Soul
+
+I am a learning companion. I help with questions patiently and clearly,
+adapt to the user's level, and value accuracy over speed.
+"""
+
+
+def ensure_partner_workspace(partner_id: str) -> Path:
+ """Create the full chat-format workspace tree; returns the scope root."""
+ return ensure_scope_workspace(partner_scope(partner_id))
+
+
+def strip_frontmatter(text: str) -> str:
+ """Drop a leading YAML frontmatter block (``---`` … ``---``) if present.
+
+ Used when cloning a chat persona (PERSONA.md carries name/description
+ frontmatter) into a partner SOUL.md, which is plain markdown.
+ """
+ raw = (text or "").lstrip()
+ if not raw.startswith("---"):
+ return text or ""
+ end = raw.find("\n---", 3)
+ if end == -1:
+ return text or ""
+ return raw[end + 4 :].lstrip("\n")
+
+
+def _partner_path_service(partner_id: str) -> PathService:
+ return PathService(workspace_root=ensure_partner_workspace(partner_id))
+
+
+# ── Soul ──────────────────────────────────────────────────────────
+
+
+def soul_path(partner_id: str) -> Path:
+ return _partner_path_service(partner_id).get_workspace_dir() / SOUL_FILENAME
+
+
+def read_soul(partner_id: str) -> str:
+ path = soul_path(partner_id)
+ if not path.exists():
+ return ""
+ try:
+ return path.read_text(encoding="utf-8")
+ except OSError:
+ logger.exception("Failed to read SOUL.md for partner %s", partner_id)
+ return ""
+
+
+def write_soul(partner_id: str, content: str) -> None:
+ path = soul_path(partner_id)
+ path.parent.mkdir(parents=True, exist_ok=True)
+ path.write_text(content or "", encoding="utf-8")
+
+
+# ── Asset provisioning (runs in the requesting user's context) ────
+
+
+def provision_assets(
+ partner_id: str,
+ *,
+ knowledge_bases: list[str] | None = None,
+ skills: list[str] | None = None,
+ notebooks: list[str] | None = None,
+) -> dict[str, Any]:
+ """Copy the requested assets into the partner workspace.
+
+ Source resolution honours the calling user's permissions. Returns a
+ report dict: ``{"copied": {...}, "errors": [{"type","name","error"}]}``.
+ """
+ root = ensure_partner_workspace(partner_id)
+ copied: dict[str, list[str]] = {"knowledge_bases": [], "skills": [], "notebooks": []}
+ errors: list[dict[str, str]] = []
+
+ for kb_ref in knowledge_bases or []:
+ try:
+ copied["knowledge_bases"].append(_copy_knowledge_base(kb_ref, root))
+ except Exception as exc:
+ logger.exception("KB provisioning failed for %s", kb_ref)
+ errors.append({"type": "knowledge_base", "name": kb_ref, "error": _err(exc)})
+
+ for skill_name in skills or []:
+ try:
+ copied["skills"].append(_copy_skill(skill_name, partner_id))
+ except Exception as exc:
+ logger.exception("Skill provisioning failed for %s", skill_name)
+ errors.append({"type": "skill", "name": skill_name, "error": _err(exc)})
+
+ for notebook_id in notebooks or []:
+ try:
+ copied["notebooks"].append(_copy_notebook(notebook_id, partner_id))
+ except Exception as exc:
+ logger.exception("Notebook provisioning failed for %s", notebook_id)
+ errors.append({"type": "notebook", "name": notebook_id, "error": _err(exc)})
+
+ return {"copied": copied, "errors": errors}
+
+
+def _err(exc: Exception) -> str:
+ detail = getattr(exc, "detail", None)
+ return str(detail) if detail else f"{type(exc).__name__}: {exc}"
+
+
+def _copy_knowledge_base(kb_ref: str, partner_root: Path) -> str:
+ from deeptutor.multi_user.knowledge_access import resolve_kb
+
+ resource = resolve_kb(kb_ref)
+ src = Path(resource.base_dir) / resource.name
+ if not src.is_dir():
+ raise FileNotFoundError(f"Knowledge base directory missing: {resource.name}")
+ dst = partner_root / "knowledge_bases" / resource.name
+ if dst.exists():
+ return resource.name # already provisioned
+ shutil.copytree(src, dst)
+ return resource.name
+
+
+def _skill_source_dir(skill_name: str) -> Path:
+ """Resolve a skill the calling user may read.
+
+ Resolution order mirrors SkillService visibility: the user's own
+ workspace shadows the packaged builtin set; non-admins may also copy
+ admin-assigned skills. (Builtins are visible to every partner anyway —
+ copying one just pins a workspace-local snapshot.)
+ """
+ from deeptutor.multi_user.context import get_current_user
+ from deeptutor.services.skill.service import BUILTIN_SKILLS_ROOT
+
+ own = _requester_path_service().get_workspace_dir() / "skills" / skill_name
+ if (own / "SKILL.md").exists():
+ return own
+
+ builtin = BUILTIN_SKILLS_ROOT / skill_name
+ if (builtin / "SKILL.md").exists():
+ return builtin
+
+ user = get_current_user()
+ if not user.is_admin:
+ from deeptutor.multi_user.skill_access import assigned_skill_ids
+
+ if skill_name in assigned_skill_ids(user.id):
+ assigned = get_admin_path_service().get_workspace_dir() / "skills" / skill_name
+ if (assigned / "SKILL.md").exists():
+ return assigned
+ raise FileNotFoundError(f"Skill '{skill_name}' not found or not accessible")
+
+
+def _copy_skill(skill_name: str, partner_id: str) -> str:
+ src = _skill_source_dir(skill_name)
+ dst = _partner_path_service(partner_id).get_workspace_dir() / "skills" / skill_name
+ if dst.exists():
+ return skill_name
+ dst.parent.mkdir(parents=True, exist_ok=True)
+ shutil.copytree(src, dst)
+ return skill_name
+
+
+def _copy_notebook(notebook_id: str, partner_id: str) -> str:
+ src_dir = _requester_path_service().get_notebook_dir()
+ src_file = src_dir / f"{notebook_id}.json"
+ if not src_file.exists():
+ raise FileNotFoundError(f"Notebook '{notebook_id}' not found")
+
+ dst_dir = _partner_path_service(partner_id).get_notebook_dir()
+ dst_dir.mkdir(parents=True, exist_ok=True)
+ dst_file = dst_dir / f"{notebook_id}.json"
+ if not dst_file.exists():
+ shutil.copy2(src_file, dst_file)
+
+ entry = _index_entry(src_dir / "notebooks_index.json", notebook_id)
+ if entry is None:
+ # Fall back to a minimal entry derived from the notebook payload.
+ try:
+ payload = json.loads(src_file.read_text(encoding="utf-8"))
+ except (OSError, json.JSONDecodeError):
+ payload = {}
+ entry = {
+ "id": notebook_id,
+ "name": str(payload.get("name") or notebook_id),
+ "description": str(payload.get("description") or ""),
+ "created_at": payload.get("created_at") or 0,
+ "updated_at": payload.get("updated_at") or 0,
+ "record_count": len(payload.get("records") or []),
+ "color": payload.get("color") or "#3B82F6",
+ "icon": payload.get("icon") or "book",
+ }
+ _merge_index_entry(dst_dir / "notebooks_index.json", entry)
+ return notebook_id
+
+
+def _index_entry(index_path: Path, notebook_id: str) -> dict[str, Any] | None:
+ if not index_path.exists():
+ return None
+ try:
+ data = json.loads(index_path.read_text(encoding="utf-8"))
+ except (OSError, json.JSONDecodeError):
+ return None
+ for entry in data.get("notebooks", []) or []:
+ if str(entry.get("id")) == notebook_id:
+ return dict(entry)
+ return None
+
+
+def _merge_index_entry(index_path: Path, entry: dict[str, Any]) -> None:
+ data: dict[str, Any] = {"notebooks": []}
+ if index_path.exists():
+ try:
+ loaded = json.loads(index_path.read_text(encoding="utf-8"))
+ if isinstance(loaded, dict) and isinstance(loaded.get("notebooks"), list):
+ data = loaded
+ except (OSError, json.JSONDecodeError):
+ pass
+ notebooks = [n for n in data["notebooks"] if str(n.get("id")) != str(entry.get("id"))]
+ notebooks.append(entry)
+ data["notebooks"] = notebooks
+ index_path.parent.mkdir(parents=True, exist_ok=True)
+ index_path.write_text(json.dumps(data, ensure_ascii=False, indent=2), encoding="utf-8")
+
+
+# ── Asset inventory / removal (partner-side, no user context needed) ──
+
+
+def list_assets(partner_id: str) -> dict[str, list[dict[str, Any]]]:
+ root = ensure_partner_workspace(partner_id)
+ service = _partner_path_service(partner_id)
+
+ kbs: list[dict[str, Any]] = []
+ kb_root = root / "knowledge_bases"
+ if kb_root.is_dir():
+ for entry in sorted(kb_root.iterdir()):
+ if entry.is_dir() and not entry.name.startswith((".", "_")):
+ raw_count = sum(1 for f in (entry / "raw").glob("*") if f.is_file())
+ kbs.append({"name": entry.name, "documents": raw_count})
+
+ skills: list[dict[str, Any]] = []
+ skills_root = service.get_workspace_dir() / "skills"
+ if skills_root.is_dir():
+ for entry in sorted(skills_root.iterdir()):
+ if entry.is_dir() and (entry / "SKILL.md").exists():
+ skills.append({"name": entry.name})
+
+ notebooks: list[dict[str, Any]] = []
+ index_path = service.get_notebook_dir() / "notebooks_index.json"
+ if index_path.exists():
+ try:
+ data = json.loads(index_path.read_text(encoding="utf-8"))
+ for entry in data.get("notebooks", []) or []:
+ notebooks.append(
+ {
+ "id": str(entry.get("id", "")),
+ "name": str(entry.get("name", "")),
+ "record_count": entry.get("record_count", 0),
+ }
+ )
+ except (OSError, json.JSONDecodeError):
+ pass
+
+ return {"knowledge_bases": kbs, "skills": skills, "notebooks": notebooks}
+
+
+def remove_asset(partner_id: str, asset_type: str, name: str) -> bool:
+ root = ensure_partner_workspace(partner_id)
+ service = _partner_path_service(partner_id)
+ if "/" in name or "\\" in name or name.startswith("."):
+ raise ValueError("Invalid asset name")
+
+ if asset_type == "knowledge_base":
+ target = root / "knowledge_bases" / name
+ if not target.is_dir():
+ return False
+ shutil.rmtree(target)
+ config_file = root / "knowledge_bases" / "kb_config.json"
+ if config_file.exists():
+ try:
+ config = json.loads(config_file.read_text(encoding="utf-8"))
+ if name in config.get("knowledge_bases", {}):
+ config["knowledge_bases"].pop(name, None)
+ config_file.write_text(
+ json.dumps(config, ensure_ascii=False, indent=2), encoding="utf-8"
+ )
+ except (OSError, json.JSONDecodeError):
+ logger.warning("Could not prune kb_config entry for %s", name, exc_info=True)
+ return True
+
+ if asset_type == "skill":
+ target = service.get_workspace_dir() / "skills" / name
+ if not target.is_dir():
+ return False
+ shutil.rmtree(target)
+ return True
+
+ if asset_type == "notebook":
+ notebook_dir = service.get_notebook_dir()
+ target = notebook_dir / f"{name}.json"
+ removed = False
+ if target.exists():
+ target.unlink()
+ removed = True
+ index_path = notebook_dir / "notebooks_index.json"
+ if index_path.exists():
+ try:
+ data = json.loads(index_path.read_text(encoding="utf-8"))
+ before = len(data.get("notebooks", []) or [])
+ data["notebooks"] = [
+ n for n in data.get("notebooks", []) or [] if str(n.get("id")) != name
+ ]
+ if len(data["notebooks"]) != before:
+ removed = True
+ index_path.write_text(
+ json.dumps(data, ensure_ascii=False, indent=2), encoding="utf-8"
+ )
+ except (OSError, json.JSONDecodeError):
+ pass
+ return removed
+
+ raise ValueError(f"Unknown asset type: {asset_type}")
+
+
+__all__ = [
+ "DEFAULT_SOUL",
+ "ensure_partner_workspace",
+ "list_assets",
+ "provision_assets",
+ "read_soul",
+ "remove_asset",
+ "soul_path",
+ "write_soul",
+]
diff --git a/deeptutor_cli/bot.py b/deeptutor_cli/partner.py
similarity index 100%
rename from deeptutor_cli/bot.py
rename to deeptutor_cli/partner.py
diff --git a/pyproject.toml b/pyproject.toml
index fbb0c7803..476f7fc66 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -44,6 +44,8 @@ dependencies = [
"openpyxl>=3.1.0",
"python-pptx>=1.0.0",
"pypdf>=4.0.0",
+ "pdfplumber>=0.11.0,<0.11.8", # 0.11.8+ pins pdfminer.six==20251230, conflicts with mineru (via raganything)
+ "reportlab>=4.0.0",
"defusedxml>=0.7.1",
"fastapi>=0.100.0",
"uvicorn[standard]>=0.24.0",
@@ -75,11 +77,13 @@ cli = [
"PyMuPDF>=1.26.0",
"numpy>=1.24.0,<3.0.0",
"arxiv>=2.0.0",
- # Document text extraction (chat attachments)
+ # Document text extraction (chat attachments) + office-skill authoring libs
"python-docx>=1.1.0",
"openpyxl>=3.1.0",
"python-pptx>=1.0.0",
"pypdf>=4.0.0",
+ "pdfplumber>=0.11.0,<0.11.8", # 0.11.8+ pins pdfminer.six==20251230, conflicts with mineru (via raganything)
+ "reportlab>=4.0.0",
"defusedxml>=0.7.1",
]
@@ -96,16 +100,15 @@ server = [
"pocketbase>=0.12.0",
"loguru>=0.7.3,<1.0.0",
"json-repair>=0.57.0,<1.0.0",
+ "croniter>=6.0.0,<7.0.0",
]
-# TutorBot agent engine + channel SDKs. Mirrors requirements/tutorbot.txt.
-tutorbot = [
+# Partner channel SDKs + MCP client. Mirrors requirements/partners.txt.
+# Partners run on the chat agent loop, so there is no engine here — just the
+# IM platform SDKs and the MCP client used for deferred tools.
+partners = [
"deeptutor[server]",
- "croniter>=6.0.0,<7.0.0",
- "tiktoken>=0.12.0,<1.0.0",
- "chardet>=3.0.2,<6.0.0",
"mcp>=1.26.0,<2.0.0",
- "readability-lxml>=0.8.4,<1.0.0",
"python-telegram-bot[socks]>=22.6,<23.0",
"lark-oapi>=1.5.0,<2.0.0",
"dingtalk-stream>=0.24.0,<1.0.0",
@@ -118,9 +121,21 @@ tutorbot = [
"socksio>=1.0.0,<2.0.0",
"websocket-client>=1.9.0,<2.0.0",
"zulip>=0.8.0,<1.0.0",
+ # slack-sdk Socket Mode + napcat need the async `websockets` lib — pin it
+ # explicitly instead of relying on dingtalk-stream/lark-oapi transitives.
+ "websockets>=12.0",
+ # napcat (OneBot v11) media downloads
+ "aiohttp>=3.10.0,<4.0.0",
+ # msteams Bot Framework token validation
+ "PyJWT[crypto]>=2.8.0,<3.0.0",
+ # weixin QR-code login
+ "qrcode>=7.4.0,<9.0.0",
]
-# Matrix (Element) channel for TutorBot. Mirrors requirements/matrix.txt.
+# Legacy alias kept for one release: `pip install deeptutor[tutorbot]`.
+tutorbot = ["deeptutor[partners]"]
+
+# Matrix (Element) channel for partners. Mirrors requirements/matrix.txt.
# Default Matrix install is non-E2EE so it works without libolm/python-olm.
matrix = [
"matrix-nio>=0.25.2,<1.0.0",
@@ -155,9 +170,9 @@ dev = [
"defusedxml>=0.7.1",
]
-# Everything: server + tutorbot + non-E2EE matrix + math-animator + dev tools.
+# Everything: server + partners + non-E2EE matrix + math-animator + dev tools.
all = [
- "deeptutor[tutorbot]",
+ "deeptutor[partners]",
"deeptutor[matrix]",
"deeptutor[math-animator]",
"deeptutor[dev]",
@@ -176,9 +191,9 @@ include = ["deeptutor*", "deeptutor_cli*"]
[tool.setuptools.package-data]
# Runtime data shipped inside the deeptutor package: prompt YAMLs (loaded by
# PromptManager from PACKAGE_ROOT/deeptutor/.../prompts/*.yaml), markdown
-# templates (tutorbot SKILL.md, vision_solver prompts), and helper shell
-# scripts (tutorbot tmux skill). Without these, ``pip install deeptutor`` ships
-# a wheel missing every agent prompt and capability fails at first use.
+# templates (builtin SKILL.md files, vision_solver prompts), and helper shell
+# scripts. Without these, ``pip install deeptutor`` ships a wheel missing
+# every agent prompt and capability fails at first use.
deeptutor = [
"**/*.yaml",
"**/*.yml",
@@ -342,7 +357,7 @@ max-complexity = 10
# Pytest configuration
# ============================================
[tool.pytest.ini_options]
-testpaths = ["tests"]
+testpaths = ["tests", "deeptutor/learning/tests"]
pythonpath = ["."]
markers = [
"asyncio: mark async tests that require pytest-asyncio",
@@ -352,7 +367,8 @@ addopts = [
"--strict-markers",
"--strict-config",
"--disable-warnings",
- "--tb=short"
+ "--tb=short",
+ "--import-mode=importlib",
]
# ============================================
diff --git a/requirements/partners.txt b/requirements/partners.txt
new file mode 100644
index 000000000..3abfe69de
--- /dev/null
+++ b/requirements/partners.txt
@@ -0,0 +1,39 @@
+# ============================================
+# DeepTutor Partners — Channel SDK Dependencies
+# ============================================
+# Mirrors pyproject.toml `[project.optional-dependencies].partners`.
+# Keep in sync with pyproject.toml when adding/updating dependencies.
+#
+# Partners run on the chat agent loop (no separate engine), so this set is
+# the IM channel SDKs plus MCP client support.
+#
+# Preferred install (from a source clone): pip install -e ".[partners]"
+# Use this file for Docker/CI when pyproject.toml/source code aren't yet available.
+
+-r server.txt
+
+# --- MCP client (deferred tools for chat + partners) ---
+mcp>=1.26.0,<2.0.0
+
+# --- Channel SDKs ---
+python-telegram-bot[socks]>=22.6,<23.0
+lark-oapi>=1.5.0,<2.0.0
+dingtalk-stream>=0.24.0,<1.0.0
+slack-sdk>=3.39.0,<4.0.0
+slackify-markdown>=0.2.0,<1.0.0
+qq-botpy>=1.2.0,<2.0.0
+python-socketio>=5.16.0,<6.0.0
+msgpack>=1.1.0,<2.0.0
+python-socks[asyncio]>=2.8.0,<3.0.0
+socksio>=1.0.0,<2.0.0
+websocket-client>=1.9.0,<2.0.0
+zulip>=0.8.0,<1.0.0
+# slack-sdk Socket Mode + napcat need the async `websockets` lib — pin it
+# explicitly instead of relying on dingtalk-stream/lark-oapi transitives.
+websockets>=12.0
+# napcat (OneBot v11) media downloads
+aiohttp>=3.10.0,<4.0.0
+# msteams Bot Framework token validation
+PyJWT[crypto]>=2.8.0,<3.0.0
+# weixin QR-code login
+qrcode>=7.4.0,<9.0.0
diff --git a/requirements/tutorbot.txt b/requirements/tutorbot.txt
deleted file mode 100644
index cc97f913f..000000000
--- a/requirements/tutorbot.txt
+++ /dev/null
@@ -1,34 +0,0 @@
-# ============================================
-# DeepTutor TutorBot — Agent Engine Dependencies
-# ============================================
-# Mirrors pyproject.toml `[project.optional-dependencies].tutorbot`.
-# Keep in sync with pyproject.toml when adding/updating dependencies.
-#
-# Preferred install (from a source clone): pip install -e ".[tutorbot]"
-# Use this file for Docker/CI when pyproject.toml/source code aren't yet available.
-
--r server.txt
-
-# --- Agent core ---
-# (loguru and json-repair are pulled in transitively via server.txt — used by provider_core.)
-croniter>=6.0.0,<7.0.0
-tiktoken>=0.12.0,<1.0.0
-chardet>=3.0.2,<6.0.0
-mcp>=1.26.0,<2.0.0
-
-# --- Web tools ---
-readability-lxml>=0.8.4,<1.0.0
-
-# --- Channel SDKs ---
-python-telegram-bot[socks]>=22.6,<23.0
-lark-oapi>=1.5.0,<2.0.0
-dingtalk-stream>=0.24.0,<1.0.0
-slack-sdk>=3.39.0,<4.0.0
-slackify-markdown>=0.2.0,<1.0.0
-qq-botpy>=1.2.0,<2.0.0
-python-socketio>=5.16.0,<6.0.0
-msgpack>=1.1.0,<2.0.0
-python-socks[asyncio]>=2.8.0,<3.0.0
-socksio>=1.0.0,<2.0.0
-websocket-client>=1.9.0,<2.0.0
-zulip>=0.8.0,<1.0.0
diff --git a/tests/api/test_partners_channel_schema.py b/tests/api/test_partners_channel_schema.py
new file mode 100644
index 000000000..21d47fdd6
--- /dev/null
+++ b/tests/api/test_partners_channel_schema.py
@@ -0,0 +1,191 @@
+"""Tests for the schema-driven channels endpoint helpers.
+
+Covers:
+* ``resolve_config_model``: maps each ``XxxChannel`` to its ``XxxConfig``.
+* ``inline_refs``: flattens nested model ``$ref``s (slack ``dm`` subtree).
+* ``collect_secret_fields``: only flags **string-typed** secret-looking keys
+ (so e.g. ``user_token_read_only: bool`` is excluded).
+* ``GET /api/v1/partners/channels/schema`` integration: shape, snake_case
+ property names, and that telegram/slack/discord schemas survive the trip.
+"""
+
+from __future__ import annotations
+
+from fastapi.testclient import TestClient
+import pytest
+
+from deeptutor.api.routers._partners_channel_schema import (
+ all_channel_schemas,
+ channel_schema_payload,
+ collect_secret_fields,
+ inline_refs,
+ resolve_config_model,
+)
+
+
+class TestResolveConfigModel:
+ def test_telegram_pairs_with_telegram_config(self) -> None:
+ from deeptutor.partners.channels.telegram import TelegramChannel, TelegramConfig
+
+ assert resolve_config_model(TelegramChannel) is TelegramConfig
+
+ def test_slack_pairs_with_slack_config(self) -> None:
+ from deeptutor.partners.channels.slack import SlackChannel, SlackConfig
+
+ assert resolve_config_model(SlackChannel) is SlackConfig
+
+ def test_discord_pairs_with_discord_config(self) -> None:
+ from deeptutor.partners.channels.discord import DiscordChannel, DiscordConfig
+
+ assert resolve_config_model(DiscordChannel) is DiscordConfig
+
+
+class TestInlineRefs:
+ def test_inlines_simple_def(self) -> None:
+ schema = {
+ "type": "object",
+ "properties": {"dm": {"$ref": "#/$defs/SlackDMConfig"}},
+ "$defs": {
+ "SlackDMConfig": {
+ "type": "object",
+ "properties": {"enabled": {"type": "boolean"}},
+ }
+ },
+ }
+ out = inline_refs(schema)
+ assert "$defs" not in out
+ assert out["properties"]["dm"]["type"] == "object"
+ assert out["properties"]["dm"]["properties"]["enabled"]["type"] == "boolean"
+
+ def test_per_field_overrides_take_precedence(self) -> None:
+ # Pydantic sometimes emits {"$ref": "...", "description": "..."}; the
+ # description should override the referenced model's description.
+ schema = {
+ "type": "object",
+ "properties": {
+ "child": {"$ref": "#/$defs/Foo", "description": "override"},
+ },
+ "$defs": {
+ "Foo": {"type": "object", "description": "original"},
+ },
+ }
+ out = inline_refs(schema)
+ assert out["properties"]["child"]["description"] == "override"
+
+
+class TestCollectSecretFields:
+ def test_flags_string_token_field(self) -> None:
+ schema = {
+ "properties": {
+ "token": {"type": "string"},
+ "enabled": {"type": "boolean"},
+ }
+ }
+ assert collect_secret_fields(schema) == ["token"]
+
+ def test_skips_boolean_with_secret_substring(self) -> None:
+ # Slack's ``user_token_read_only`` is a flag, not a secret.
+ schema = {
+ "properties": {
+ "user_token_read_only": {"type": "boolean"},
+ "bot_token": {"type": "string"},
+ }
+ }
+ assert collect_secret_fields(schema) == ["bot_token"]
+
+ def test_walks_nested_objects(self) -> None:
+ schema = {
+ "properties": {
+ "dm": {
+ "type": "object",
+ "properties": {"webhook_secret": {"type": "string"}},
+ },
+ }
+ }
+ assert collect_secret_fields(schema) == ["dm.webhook_secret"]
+
+ def test_handles_nullable_strings(self) -> None:
+ # Pydantic's ``Optional[str]`` becomes ``anyOf: [{type: string}, {type: null}]``.
+ schema = {
+ "properties": {
+ "encrypt_key": {"anyOf": [{"type": "string"}, {"type": "null"}]},
+ }
+ }
+ assert collect_secret_fields(schema) == ["encrypt_key"]
+
+
+class TestChannelSchemaPayload:
+ def test_telegram_payload_shape(self) -> None:
+ from deeptutor.partners.channels.telegram import TelegramChannel
+
+ payload = channel_schema_payload(TelegramChannel)
+ assert payload is not None
+ assert payload["name"] == "telegram"
+ assert payload["display_name"] == "Telegram"
+ assert payload["secret_fields"] == ["token"]
+ # Snake_case wire format (matches the storage form).
+ props = payload["json_schema"]["properties"]
+ assert "allow_from" in props and "allowFrom" not in props
+ assert payload["default_config"]["enabled"] is False
+
+ def test_slack_dm_subtree_inlined(self) -> None:
+ from deeptutor.partners.channels.slack import SlackChannel
+
+ payload = channel_schema_payload(SlackChannel)
+ assert payload is not None
+ dm = payload["json_schema"]["properties"]["dm"]
+ assert dm["type"] == "object"
+ assert "enabled" in dm["properties"]
+ # Bool flags whose names contain "token" must NOT be flagged secret.
+ assert "user_token_read_only" not in payload["secret_fields"]
+ assert "bot_token" in payload["secret_fields"]
+
+
+class TestEndpoint:
+ @pytest.fixture
+ def client(self) -> TestClient:
+ # Build a minimal FastAPI app with just the partners router; the
+ # ``/channels/schema`` endpoint doesn't touch the manager so no
+ # fixturing of ``get_partner_manager`` is needed.
+ from fastapi import FastAPI
+
+ from deeptutor.api.routers import partners as partners_router
+
+ app = FastAPI()
+ app.include_router(partners_router.router, prefix="/api/v1/partners")
+ return TestClient(app)
+
+ def test_returns_channels_and_global(self, client: TestClient) -> None:
+ res = client.get("/api/v1/partners/channels/schema")
+ assert res.status_code == 200
+ body = res.json()
+ assert set(body.keys()) >= {"channels", "global"}
+ # Telegram is always installed (no extra deps).
+ assert "telegram" in body["channels"]
+
+ def test_telegram_entry_has_secret_fields(self, client: TestClient) -> None:
+ res = client.get("/api/v1/partners/channels/schema")
+ tg = res.json()["channels"]["telegram"]
+ assert tg["secret_fields"] == ["token"]
+ assert "token" in tg["json_schema"]["properties"]
+
+ def test_global_schema_uses_snake_case(self, client: TestClient) -> None:
+ res = client.get("/api/v1/partners/channels/schema")
+ global_props = res.json()["global"]["json_schema"]["properties"]
+ assert "send_progress" in global_props
+ assert "send_tool_hints" in global_props
+
+
+class TestAllChannelSchemas:
+ def test_returns_at_least_telegram(self) -> None:
+ out = all_channel_schemas()
+ assert "telegram" in out
+ # Every payload has the four documented keys.
+ for entry in out.values():
+ assert {
+ "name",
+ "display_name",
+ "default_config",
+ "secret_fields",
+ "json_schema",
+ } <= entry.keys()
diff --git a/tests/api/test_plugins_api_partner.py b/tests/api/test_plugins_api_partner.py
new file mode 100644
index 000000000..6d70cb244
--- /dev/null
+++ b/tests/api/test_plugins_api_partner.py
@@ -0,0 +1,126 @@
+"""Regression tests for partner-compatible plugin capability streaming."""
+
+from __future__ import annotations
+
+import importlib
+import json
+import re
+from typing import Any
+
+import pytest
+
+try:
+ from fastapi import FastAPI
+ from fastapi.testclient import TestClient
+except Exception: # pragma: no cover
+ FastAPI = None
+ TestClient = None
+
+pytestmark = pytest.mark.skipif(
+ FastAPI is None or TestClient is None, reason="fastapi not installed"
+)
+
+
+def _events(text: str) -> list[tuple[str, dict[str, Any]]]:
+ events: list[tuple[str, dict[str, Any]]] = []
+ for block in text.strip().split("\n\n"):
+ event = ""
+ data = "{}"
+ for line in block.splitlines():
+ if line.startswith("event: "):
+ event = line[len("event: ") :]
+ elif line.startswith("data: "):
+ data = line[len("data: ") :]
+ if event:
+ events.append((event, json.loads(data)))
+ return events
+
+
+def _client_with_fake_partner(monkeypatch):
+ from deeptutor.core.stream import StreamEvent, StreamEventType
+ from deeptutor.services.partners.manager import PartnerConfig
+
+ class FakeInstance:
+ running = True
+
+ class FakeMgr:
+ def __init__(self):
+ self.calls: list[dict[str, Any]] = []
+
+ def get_partner(self, partner_id: str):
+ return FakeInstance()
+
+ def load_config(self, partner_id: str):
+ return PartnerConfig(name=partner_id)
+
+ async def start_partner(self, partner_id: str, config: PartnerConfig):
+ return FakeInstance()
+
+ async def send_message(self, partner_id: str, content: str, **kwargs):
+ self.calls.append({"partner_id": partner_id, "content": content, **kwargs})
+ on_event = kwargs.get("on_event")
+ if on_event:
+ await on_event(
+ StreamEvent(type=StreamEventType.THINKING, content="thinking")
+ )
+ return "streamed answer"
+
+ mgr = FakeMgr()
+ partners_router_mod = importlib.import_module("deeptutor.api.routers.partners")
+ plugins_router_mod = importlib.import_module("deeptutor.api.routers.plugins_api")
+ monkeypatch.setattr(partners_router_mod, "get_partner_manager", lambda: mgr)
+ partners_router_mod._start_locks.clear()
+
+ app = FastAPI()
+ app.include_router(plugins_router_mod.router, prefix="/api/v1/plugins")
+ return TestClient(app), mgr
+
+
+def test_plugin_chat_stream_routes_to_specified_partner_session(monkeypatch):
+ client, mgr = _client_with_fake_partner(monkeypatch)
+
+ response = client.post(
+ "/api/v1/plugins/capabilities/chat/execute-stream",
+ json={
+ "content": "hi",
+ # Legacy TutorBot HTTP API field name still addresses a partner.
+ "bot_id": "math-bot",
+ "session_id": "lesson-1",
+ "enabledTools": [],
+ "knowledgeBases": [],
+ "language": "zh",
+ "llmSelection": {"profile_id": "p-alt", "model_id": "m-alt"},
+ },
+ )
+
+ assert response.status_code == 200
+ events = _events(response.text)
+ assert ("session", {"partner_id": "math-bot", "session_id": "lesson-1"}) in events
+ assert ("thinking", {"content": "thinking"}) in events
+ assert ("content", {"content": "streamed answer"}) in events
+ assert ("done", {"partner_id": "math-bot", "session_id": "lesson-1"}) in events
+ assert len(mgr.calls) == 1
+ call = mgr.calls[0]
+ assert call["partner_id"] == "math-bot"
+ assert call["content"] == "hi"
+ assert call["chat_id"] == "lesson-1"
+ assert call["session_id"] == "lesson-1"
+ assert callable(call["on_event"])
+
+
+def test_plugin_chat_stream_creates_session_when_missing(monkeypatch):
+ client, mgr = _client_with_fake_partner(monkeypatch)
+
+ response = client.post(
+ "/api/v1/plugins/capabilities/chat/execute-stream",
+ json={"content": "first message", "bot_id": "math-bot"},
+ )
+
+ assert response.status_code == 200
+ assert "event: done" in response.text
+ match = re.search(r'"session_id": "([^"]+)"', response.text)
+ assert match is not None
+ session_id = match.group(1)
+ assert session_id != "web"
+ assert mgr.calls[0]["session_id"] == session_id
+ assert mgr.calls[0]["chat_id"] == session_id
diff --git a/tests/services/partners/__init__.py b/tests/services/partners/__init__.py
new file mode 100644
index 000000000..e69de29bb
diff --git a/tests/services/partners/conftest.py b/tests/services/partners/conftest.py
new file mode 100644
index 000000000..5de95ef2b
--- /dev/null
+++ b/tests/services/partners/conftest.py
@@ -0,0 +1,30 @@
+"""Fixtures for the partners service suite — isolate all paths under tmp_path."""
+
+from __future__ import annotations
+
+from pathlib import Path
+
+import pytest
+
+
+def partners_root(tmp_path, monkeypatch) -> Path:
+ """Redirect the admin workspace (and multi-user roots) under ``tmp_path``.
+
+ Everything the partners layer touches resolves through
+ ``deeptutor.multi_user.paths`` — the partners data dir is anchored at the
+ admin workspace root and partner scopes are synthetic ``UserScope``s — so
+ patching that module is sufficient to keep tests off the real ``data/``.
+ """
+ from deeptutor.multi_user import paths
+
+ project_root = tmp_path
+ admin_root = (project_root / "data").resolve()
+ monkeypatch.setattr(paths, "PROJECT_ROOT", project_root)
+ monkeypatch.setattr(paths, "ADMIN_WORKSPACE_ROOT", admin_root)
+ monkeypatch.setattr(paths, "USERS_ROOT", admin_root / "users")
+ monkeypatch.setattr(paths, "SYSTEM_ROOT", admin_root / "system")
+ monkeypatch.setattr(paths, "_path_services", {})
+
+ admin_root.mkdir(parents=True, exist_ok=True)
+ return admin_root / "partners"
diff --git a/tests/services/partners/test_channel_manager.py b/tests/services/partners/test_channel_manager.py
new file mode 100644
index 000000000..5ed9a9760
--- /dev/null
+++ b/tests/services/partners/test_channel_manager.py
@@ -0,0 +1,85 @@
+"""Unit tests for TutorBot channel dispatch behavior."""
+
+from __future__ import annotations
+
+import asyncio
+from unittest.mock import AsyncMock
+
+import pytest
+
+from deeptutor.partners.bus.events import OutboundMessage
+from deeptutor.partners.channels.manager import ChannelManager
+from deeptutor.partners.config.schema import ChannelsConfig
+
+
+class _OneShotBus:
+ def __init__(self, msg: OutboundMessage):
+ self._msg = msg
+ self._calls = 0
+
+ async def consume_outbound(self) -> OutboundMessage:
+ self._calls += 1
+ if self._calls == 1:
+ return self._msg
+ raise asyncio.CancelledError
+
+
+class _DummyChannel:
+ def __init__(self):
+ self.send = AsyncMock()
+ self.send_delta = AsyncMock()
+ # Effective flags normally set by ChannelManager._init_channels
+ # (partner-level AND per-channel override).
+ self.send_progress = True
+ self.send_tool_hints = True
+
+
+async def _dispatch_one(msg: OutboundMessage, config: ChannelsConfig) -> _DummyChannel:
+ channel = _DummyChannel()
+ channel.send_progress = config.send_progress
+ channel.send_tool_hints = config.send_tool_hints
+ manager = ChannelManager(config, _OneShotBus(msg)) # type: ignore[arg-type]
+ manager.channels = {msg.channel: channel} # type: ignore[dict-item]
+
+ await manager._dispatch_outbound()
+ return channel
+
+
+class TestChannelManagerToolHints:
+ @pytest.mark.asyncio
+ async def test_tool_hint_progress_skipped_by_default(self):
+ msg = OutboundMessage(
+ channel="zulip",
+ chat_id="pm:42",
+ content='message("Hello")',
+ metadata={"_progress": True, "_tool_hint": True},
+ )
+
+ channel = await _dispatch_one(msg, ChannelsConfig(send_tool_hints=False))
+
+ channel.send.assert_not_awaited()
+
+ @pytest.mark.asyncio
+ async def test_tool_hint_progress_dispatched_when_enabled(self):
+ msg = OutboundMessage(
+ channel="zulip",
+ chat_id="pm:42",
+ content='message("Hello")',
+ metadata={"_progress": True, "_tool_hint": True},
+ )
+
+ channel = await _dispatch_one(msg, ChannelsConfig(send_tool_hints=True))
+
+ channel.send.assert_awaited_once_with(msg)
+
+
+def test_channel_registry_discovers_builtin_channels() -> None:
+ from deeptutor.partners.channels.base import BaseChannel
+ from deeptutor.partners.channels.registry import discover_all, discover_channel_names
+
+ names = set(discover_channel_names())
+ assert {"telegram", "slack", "discord", "zulip"} <= names
+
+ channels = discover_all()
+ assert {"telegram", "slack", "discord", "zulip"} <= set(channels)
+ assert all(issubclass(cls, BaseChannel) for cls in channels.values())
diff --git a/tests/services/partners/test_channel_secrets.py b/tests/services/partners/test_channel_secrets.py
new file mode 100644
index 000000000..8e0a56243
--- /dev/null
+++ b/tests/services/partners/test_channel_secrets.py
@@ -0,0 +1,216 @@
+"""Unit tests for channel-secret handling in the partner manager layer.
+
+These guard the contract that secret-looking fields (token, password, api_key,
+…) are NEVER serialised into responses unless the caller explicitly opts into
+``include_secrets=True``. A regression here would re-introduce the token-leak
+fixed alongside PR #338.
+"""
+
+from __future__ import annotations
+
+import pytest
+
+from deeptutor.services.partners.manager import (
+ PartnerConfig,
+ PartnerInstance,
+ mask_channel_secrets,
+)
+
+# ---------------------------------------------------------------------------
+# mask_channel_secrets
+# ---------------------------------------------------------------------------
+
+
+class TestMaskChannelSecrets:
+ def test_masks_top_level_token(self):
+ out = mask_channel_secrets({"telegram": {"token": "123:abc"}})
+ assert out["telegram"]["token"] == "***"
+
+ def test_masks_nested_password_in_email_section(self):
+ out = mask_channel_secrets(
+ {
+ "email": {
+ "imap_username": "me",
+ "imap_password": "supersecret",
+ "smtp_password": "another",
+ }
+ }
+ )
+ assert out["email"]["imap_username"] == "me"
+ assert out["email"]["imap_password"] == "***"
+ assert out["email"]["smtp_password"] == "***"
+
+ def test_masks_diverse_secret_keys(self):
+ out = mask_channel_secrets(
+ {
+ "slack": {"bot_token": "xoxb-…", "app_token": "xapp-…"},
+ "matrix": {"access_token": "syt_…"},
+ "feishu": {
+ "app_id": "cli_…",
+ "app_secret": "shh",
+ "encrypt_key": "k",
+ "verification_token": "vt",
+ },
+ "wecom": {"secret": "s"},
+ }
+ )
+ assert out["slack"]["bot_token"] == "***"
+ assert out["slack"]["app_token"] == "***"
+ assert out["matrix"]["access_token"] == "***"
+ assert out["feishu"]["app_id"] == "cli_…" # not a secret hint
+ assert out["feishu"]["app_secret"] == "***"
+ assert out["feishu"]["encrypt_key"] == "***"
+ assert out["feishu"]["verification_token"] == "***"
+ assert out["wecom"]["secret"] == "***"
+
+ def test_preserves_non_string_values(self):
+ out = mask_channel_secrets(
+ {"telegram": {"token": "", "enabled": True, "allow_from": ["1", "2"]}}
+ )
+ # Empty string is left as-is (nothing to hide; helps the UI distinguish
+ # "unset" from "redacted").
+ assert out["telegram"]["token"] == ""
+ assert out["telegram"]["enabled"] is True
+ assert out["telegram"]["allow_from"] == ["1", "2"]
+
+ def test_does_not_mutate_input(self):
+ original = {"telegram": {"token": "abc"}}
+ out = mask_channel_secrets(original)
+ assert original["telegram"]["token"] == "abc"
+ assert out is not original
+
+
+# ---------------------------------------------------------------------------
+# PartnerInstance.to_dict contract
+# ---------------------------------------------------------------------------
+
+
+def _make_instance() -> PartnerInstance:
+ return PartnerInstance(
+ partner_id="p",
+ config=PartnerConfig(
+ name="partner",
+ channels={
+ "telegram": {"enabled": True, "token": "123:ABC"},
+ "send_progress": True,
+ },
+ ),
+ )
+
+
+class TestToDictDefaultsAreSafe:
+ def test_default_returns_keys_only(self):
+ inst = _make_instance()
+ d = inst.to_dict()
+ assert set(d["channels"]) == {"telegram", "send_progress"}
+ # last_reload_error is always present for the UI to consume
+ assert "last_reload_error" in d
+ assert d["last_reload_error"] is None
+
+ def test_mask_secrets_returns_full_dict_with_token_masked(self):
+ inst = _make_instance()
+ d = inst.to_dict(mask_secrets=True)
+ assert d["channels"]["telegram"]["enabled"] is True
+ assert d["channels"]["telegram"]["token"] == "***"
+ assert d["channels"]["send_progress"] is True
+
+ def test_include_secrets_returns_raw_token(self):
+ inst = _make_instance()
+ d = inst.to_dict(include_secrets=True)
+ assert d["channels"]["telegram"]["token"] == "123:ABC"
+
+ def test_include_secrets_takes_precedence_over_mask(self):
+ inst = _make_instance()
+ d = inst.to_dict(include_secrets=True, mask_secrets=True)
+ assert d["channels"]["telegram"]["token"] == "123:ABC"
+
+
+# ---------------------------------------------------------------------------
+# reload_lock + last_reload_error wiring
+# ---------------------------------------------------------------------------
+
+
+async def test_reload_lock_serialises_concurrent_calls(monkeypatch):
+ """Two concurrent reload_channels calls must not run their bodies in parallel."""
+ import asyncio
+
+ from deeptutor.services.partners.manager import PartnerManager
+
+ mgr = PartnerManager()
+ inst = _make_instance()
+
+ class _FakeRunner:
+ bus = object()
+
+ inst.runner = _FakeRunner()
+ # Mark the instance as running by giving it a not-done sentinel task.
+ sentinel = asyncio.create_task(asyncio.sleep(60))
+ inst.tasks = [sentinel]
+ mgr._partners["p"] = inst
+
+ overlap_count = 0
+ max_overlap = 0
+ in_flight = 0
+
+ async def fake_teardown(instance, partner_id):
+ nonlocal in_flight, overlap_count, max_overlap
+ in_flight += 1
+ max_overlap = max(max_overlap, in_flight)
+ overlap_count += 1
+ await asyncio.sleep(0.05)
+ in_flight -= 1
+
+ monkeypatch.setattr(mgr, "_teardown_channel_listeners", fake_teardown)
+ monkeypatch.setattr(mgr, "_build_channel_manager", lambda config, bus, *, partner_id: None)
+
+ try:
+ await asyncio.gather(mgr.reload_channels("p"), mgr.reload_channels("p"))
+ assert overlap_count == 2
+ assert max_overlap == 1, "reload_channels must be serialised per partner"
+ finally:
+ sentinel.cancel()
+ try:
+ await sentinel
+ except asyncio.CancelledError:
+ pass
+
+
+async def test_reload_failure_records_last_reload_error(monkeypatch):
+ import asyncio
+
+ from deeptutor.services.partners.manager import PartnerManager
+
+ mgr = PartnerManager()
+ inst = _make_instance()
+
+ class _FakeRunner:
+ bus = object()
+
+ inst.runner = _FakeRunner()
+ sentinel = asyncio.create_task(asyncio.sleep(60))
+ inst.tasks = [sentinel]
+ mgr._partners["p"] = inst
+
+ async def fake_teardown(instance, partner_id):
+ return None
+
+ def boom(*args, **kwargs):
+ raise ValueError("invalid telegram token format")
+
+ monkeypatch.setattr(mgr, "_teardown_channel_listeners", fake_teardown)
+ monkeypatch.setattr(mgr, "_build_channel_manager", boom)
+
+ try:
+ with pytest.raises(ValueError):
+ await mgr.reload_channels("p")
+ assert inst.last_reload_error is not None
+ assert "invalid telegram token format" in inst.last_reload_error
+ assert inst.channel_manager is None
+ finally:
+ sentinel.cancel()
+ try:
+ await sentinel
+ except asyncio.CancelledError:
+ pass
diff --git a/tests/services/partners/test_partner_manager_config.py b/tests/services/partners/test_partner_manager_config.py
new file mode 100644
index 000000000..17366e41b
--- /dev/null
+++ b/tests/services/partners/test_partner_manager_config.py
@@ -0,0 +1,166 @@
+"""PartnerManager config persistence, merge semantics, and legacy migration."""
+
+from __future__ import annotations
+
+import dataclasses
+
+import yaml
+
+from deeptutor.services.partners.manager import PartnerConfig, PartnerManager
+from deeptutor.services.partners.workspace import DEFAULT_SOUL, read_soul
+
+
+def _mgr() -> PartnerManager:
+ return PartnerManager()
+
+
+class TestConfigRoundTrip:
+ def test_save_and_load(self, partners_root):
+ mgr = _mgr()
+ config = PartnerConfig(
+ name="Ada",
+ description="study partner",
+ channels={"telegram": {"enabled": True, "token": "t"}},
+ llm_selection={"profile_id": "p", "model_id": "m"},
+ language="zh",
+ emoji="🦊",
+ color="#aabbcc",
+ soul_origin={"type": "library", "id": "math-tutor"},
+ enabled_tools=["web_search"],
+ mcp_tools=[],
+ )
+ mgr.save_config("ada", config)
+ loaded = mgr.load_config("ada")
+ assert loaded is not None
+ assert dataclasses.asdict(loaded) == dataclasses.asdict(config)
+
+ def test_missing_returns_none(self, partners_root):
+ assert _mgr().load_config("nope") is None
+
+ def test_none_tool_fields_stay_none(self, partners_root):
+ mgr = _mgr()
+ mgr.save_config("p1", PartnerConfig(name="P1"))
+ loaded = mgr.load_config("p1")
+ assert loaded.enabled_tools is None
+ assert loaded.mcp_tools is None
+
+
+class TestMergeSemantics:
+ def test_none_values_preserve_existing(self, partners_root):
+ mgr = _mgr()
+ mgr.save_config(
+ "p1",
+ PartnerConfig(name="Keep", description="keep me", enabled_tools=["rag"]),
+ )
+ merged = mgr.merge_config("p1", {"name": None, "description": None})
+ assert merged.name == "Keep"
+ assert merged.description == "keep me"
+ assert merged.enabled_tools == ["rag"]
+
+ def test_empty_values_are_intentional_clears(self, partners_root):
+ mgr = _mgr()
+ mgr.save_config("p1", PartnerConfig(name="Keep", description="old"))
+ merged = mgr.merge_config("p1", {"description": "", "channels": {}})
+ assert merged.description == ""
+ assert merged.channels == {}
+
+ def test_unknown_keys_ignored(self, partners_root):
+ merged = _mgr().merge_config("new", {"bogus": 1, "name": "X"})
+ assert merged.name == "X"
+ assert not hasattr(merged, "bogus")
+
+ def test_mergeable_fields_match_partnerconfig_fields(self):
+ """Every config field must be mergeable via the API (anti-drift pin)."""
+ field_names = {f.name for f in dataclasses.fields(PartnerConfig)}
+ assert set(PartnerManager._MERGEABLE_FIELDS) == field_names
+
+
+class TestAutoStart:
+ def test_new_partner_defaults_to_auto_start(self, partners_root):
+ mgr = _mgr()
+ mgr.save_config("p1", PartnerConfig(name="P1"))
+ assert mgr._load_auto_start("p1", default=False) is True
+
+ def test_routine_save_preserves_disabled_intent(self, partners_root):
+ mgr = _mgr()
+ mgr.save_config("p1", PartnerConfig(name="P1"), auto_start=False)
+ # Routine save (auto_start omitted) must not silently flip it back on.
+ mgr.save_config("p1", PartnerConfig(name="P1 renamed"))
+ assert mgr._load_auto_start("p1", default=True) is False
+
+
+class TestWorkspaceSeeding:
+ def test_ensure_dirs_seeds_default_soul(self, partners_root):
+ mgr = _mgr()
+ mgr._ensure_partner_dirs("p1")
+ assert read_soul("p1") == DEFAULT_SOUL
+ ws = partners_root / "p1" / "workspace"
+ assert (ws / "user" / "workspace").is_dir()
+ assert (ws / "knowledge_bases").is_dir()
+
+ def test_existing_soul_not_overwritten(self, partners_root):
+ from deeptutor.services.partners.workspace import write_soul
+
+ mgr = _mgr()
+ mgr._ensure_partner_dirs("p1")
+ write_soul("p1", "# Custom")
+ mgr._ensure_partner_dirs("p1")
+ assert read_soul("p1") == "# Custom"
+
+
+class TestLegacyTutorBotMigration:
+ def _seed_legacy_bot(self, admin_root, bot_id="old-bot", **overrides):
+ legacy = admin_root / "tutorbot" / bot_id
+ legacy.mkdir(parents=True)
+ data = {
+ "name": "Old Bot",
+ "description": "from tutorbot",
+ "persona": "# Soul\nLegacy persona text",
+ "channels": {"telegram": {"enabled": True, "token": "tok"}},
+ "llm_selection": {"profile_id": "p", "model_id": "m"},
+ "auto_start": True,
+ **overrides,
+ }
+ (legacy / "config.yaml").write_text(yaml.dump(data), encoding="utf-8")
+ sessions = legacy / "workspace" / "sessions"
+ sessions.mkdir(parents=True)
+ (sessions / "telegram_1.jsonl").write_text(
+ '{"role": "user", "content": "hi", "timestamp": "2026-01-01T00:00:00"}\n',
+ encoding="utf-8",
+ )
+ return legacy
+
+ def test_migrates_config_soul_and_sessions(self, partners_root):
+ admin_root = partners_root.parent
+ self._seed_legacy_bot(admin_root)
+
+ mgr = _mgr()
+ ids = mgr._discover_partner_ids()
+ assert "old-bot" in ids
+
+ cfg = mgr.load_config("old-bot")
+ assert cfg.name == "Old Bot"
+ assert cfg.channels["telegram"]["token"] == "tok"
+ assert cfg.llm_selection == {"profile_id": "p", "model_id": "m"}
+ assert cfg.soul_origin == {"type": "tutorbot", "id": "old-bot"}
+ assert read_soul("old-bot") == "# Soul\nLegacy persona text"
+ assert mgr._load_auto_start("old-bot", default=False) is True
+
+ history = mgr.get_history("old-bot")
+ assert history and history[0]["content"] == "hi"
+
+ def test_migration_is_idempotent_and_non_destructive(self, partners_root):
+ admin_root = partners_root.parent
+ legacy = self._seed_legacy_bot(admin_root)
+
+ mgr = _mgr()
+ mgr._discover_partner_ids()
+ # Tweak the migrated partner, then re-discover with a fresh manager.
+ from deeptutor.services.partners.workspace import write_soul
+
+ write_soul("old-bot", "# Edited after migration")
+ mgr2 = _mgr()
+ mgr2._discover_partner_ids()
+ assert read_soul("old-bot") == "# Edited after migration"
+ # Legacy tree untouched.
+ assert (legacy / "config.yaml").exists()
diff --git a/tests/services/partners/test_partner_runtime.py b/tests/services/partners/test_partner_runtime.py
new file mode 100644
index 000000000..c1b324754
--- /dev/null
+++ b/tests/services/partners/test_partner_runtime.py
@@ -0,0 +1,302 @@
+"""PartnerRunner: chat-loop event mapping, tool config, session persistence."""
+
+from __future__ import annotations
+
+from typing import Any
+
+import pytest
+
+from deeptutor.core.stream import StreamEvent, StreamEventType
+from deeptutor.partners.bus.events import InboundMessage
+from deeptutor.partners.bus.queue import MessageBus
+from deeptutor.services.partners.manager import PartnerConfig
+from deeptutor.services.partners.runtime import PartnerRunner
+from deeptutor.services.partners.sessions import PartnerSessionStore
+
+
+def _event(
+ event_type: StreamEventType,
+ *,
+ content: str = "",
+ source: str = "chat",
+ metadata: dict[str, Any] | None = None,
+) -> StreamEvent:
+ return StreamEvent(type=event_type, source=source, content=content, metadata=metadata or {})
+
+
+def _narration_round(call_id: str, text: str) -> list[StreamEvent]:
+ return [
+ _event(StreamEventType.CONTENT, content=text, metadata={"call_id": call_id}),
+ _event(
+ StreamEventType.PROGRESS,
+ metadata={
+ "trace_kind": "call_status",
+ "call_state": "complete",
+ "call_role": "narration",
+ "call_id": call_id,
+ },
+ ),
+ ]
+
+
+def _finish(text: str) -> list[StreamEvent]:
+ return [
+ _event(StreamEventType.CONTENT, content=text, metadata={"call_id": "c-finish"}),
+ _event(StreamEventType.RESULT, metadata={"response": text}),
+ _event(StreamEventType.DONE),
+ ]
+
+
+class _FakeOrchestrator:
+ """Yields a scripted event sequence instead of running the chat loop."""
+
+ script: list[StreamEvent] = []
+ # Optional queue of per-turn scripts; when non-empty, each handle() call
+ # pops the next one (lets tests model a failed turn + a backup retry).
+ scripts: list[list[StreamEvent]] = []
+ seen_contexts: list[Any] = []
+ activated_selections: list[Any] = []
+
+ def __init__(self) -> None:
+ pass
+
+ async def handle(self, context):
+ type(self).seen_contexts.append(context)
+ script = type(self).scripts.pop(0) if type(self).scripts else type(self).script
+ for event in script:
+ yield event
+
+
+def fake_orchestrator(monkeypatch):
+ import deeptutor.runtime.orchestrator as orch_mod
+ from deeptutor.services.model_selection import runtime as selection_runtime
+
+ _FakeOrchestrator.script = []
+ _FakeOrchestrator.scripts = []
+ _FakeOrchestrator.seen_contexts = []
+ _FakeOrchestrator.activated_selections = []
+ monkeypatch.setattr(orch_mod, "ChatOrchestrator", _FakeOrchestrator)
+
+ def _record_activate(selection):
+ _FakeOrchestrator.activated_selections.append(selection)
+ return (None, None)
+
+ monkeypatch.setattr(selection_runtime, "activate_llm_selection", _record_activate)
+ monkeypatch.setattr(selection_runtime, "reset_llm_selection", lambda token: None)
+ return _FakeOrchestrator
+
+
+def _runner(partners_root, config: PartnerConfig | None = None) -> PartnerRunner:
+ from deeptutor.partners.config.paths import get_partner_sessions_dir
+
+ config = config or PartnerConfig(name="Ada")
+ bus = MessageBus()
+ store = PartnerSessionStore(get_partner_sessions_dir("ada"))
+ return PartnerRunner("ada", config, bus, store)
+
+
+def _msg(content: str = "hello", channel: str = "telegram") -> InboundMessage:
+ return InboundMessage(channel=channel, sender_id="42", chat_id="42", content=content)
+
+
+class TestTurnExecution:
+ @pytest.mark.asyncio
+ async def test_returns_finish_text_and_persists_session(self, partners_root, fake_orchestrator):
+ fake_orchestrator.script = _narration_round("c1", "let me check") + _finish(
+ "The answer is 4."
+ )
+ runner = _runner(partners_root)
+
+ final = await runner.process_message(_msg("what is 2+2?"))
+ assert final == "The answer is 4."
+
+ history = runner.store.conversation_history("telegram:42")
+ assert history == [
+ {"role": "user", "content": "what is 2+2?"},
+ {"role": "assistant", "content": "The answer is 4."},
+ ]
+
+ @pytest.mark.asyncio
+ async def test_narration_streams_as_progress_outbound(self, partners_root, fake_orchestrator):
+ fake_orchestrator.script = _narration_round("c1", "exploring…") + _finish("done")
+ runner = _runner(partners_root)
+
+ await runner.process_message(_msg())
+ progress = await runner.bus.outbound.get()
+ assert progress.content == "exploring…"
+ assert progress.metadata["_progress"] is True
+ assert progress.metadata["_tool_hint"] is False
+
+ @pytest.mark.asyncio
+ async def test_tool_calls_stream_as_hints_by_default(self, partners_root, fake_orchestrator):
+ fake_orchestrator.script = [
+ _event(
+ StreamEventType.TOOL_CALL,
+ content="rag",
+ metadata={"args": {"query": "hello world", "_internal": "x"}},
+ ),
+ *_finish("done"),
+ ]
+ runner = _runner(partners_root)
+
+ await runner.process_message(_msg())
+ hint = await runner.bus.outbound.get()
+ assert hint.metadata["_tool_hint"] is True
+ assert hint.content.startswith("⚙ rag(")
+ assert "hello world" in hint.content
+ assert "_internal" not in hint.content
+
+ @pytest.mark.asyncio
+ async def test_send_progress_flag_off_suppresses_narration(
+ self, partners_root, fake_orchestrator
+ ):
+ fake_orchestrator.script = _narration_round("c1", "exploring…") + _finish("done")
+ config = PartnerConfig(name="Ada", channels={"send_progress": False})
+ runner = _runner(partners_root, config)
+
+ await runner.process_message(_msg())
+ assert runner.bus.outbound.empty()
+
+ @pytest.mark.asyncio
+ async def test_web_channel_never_emits_progress_outbound(
+ self, partners_root, fake_orchestrator
+ ):
+ fake_orchestrator.script = _narration_round("c1", "exploring…") + _finish("done")
+ runner = _runner(partners_root)
+
+ await runner.process_message(_msg(channel="web"))
+ assert runner.bus.outbound.empty()
+
+ @pytest.mark.asyncio
+ async def test_unresolved_ask_user_question_becomes_reply(
+ self, partners_root, fake_orchestrator
+ ):
+ # An unresolved ask_user pause emits the question as a final-response
+ # CONTENT event while RESULT carries an empty response.
+ fake_orchestrator.script = [
+ _event(
+ StreamEventType.CONTENT,
+ content="Which topic do you mean?",
+ metadata={"call_id": "f1", "call_kind": "llm_final_response"},
+ ),
+ _event(StreamEventType.RESULT, metadata={"response": ""}),
+ _event(StreamEventType.DONE),
+ ]
+ runner = _runner(partners_root)
+
+ final = await runner.process_message(_msg())
+ assert final == "Which topic do you mean?"
+
+ @pytest.mark.asyncio
+ async def test_backup_model_retries_failed_turn(self, partners_root, fake_orchestrator):
+ primary = {"profile_id": "p1", "model_id": "m1"}
+ backup = {"profile_id": "p2", "model_id": "m2"}
+ fake_orchestrator.scripts = [
+ # Turn 1 (primary): hard failure, no answer.
+ [
+ _event(StreamEventType.ERROR, content="rate limited"),
+ _event(StreamEventType.RESULT, metadata={"response": ""}),
+ _event(StreamEventType.DONE),
+ ],
+ # Turn 2 (backup): succeeds.
+ _finish("backup answer"),
+ ]
+ config = PartnerConfig(name="Ada", llm_selection=primary, backup_llm_selection=backup)
+ runner = _runner(partners_root, config)
+
+ final = await runner.process_message(_msg())
+ assert final == "backup answer"
+ assert fake_orchestrator.activated_selections == [primary, backup]
+
+ @pytest.mark.asyncio
+ async def test_no_backup_returns_error_text(self, partners_root, fake_orchestrator):
+ fake_orchestrator.script = [
+ _event(StreamEventType.ERROR, content="rate limited"),
+ _event(StreamEventType.RESULT, metadata={"response": ""}),
+ _event(StreamEventType.DONE),
+ ]
+ runner = _runner(partners_root)
+
+ final = await runner.process_message(_msg())
+ assert "rate limited" in final
+ assert len(fake_orchestrator.seen_contexts) == 1
+
+ @pytest.mark.asyncio
+ async def test_successful_turn_never_touches_backup(self, partners_root, fake_orchestrator):
+ backup = {"profile_id": "p2", "model_id": "m2"}
+ fake_orchestrator.script = _finish("first try works")
+ config = PartnerConfig(name="Ada", backup_llm_selection=backup)
+ runner = _runner(partners_root, config)
+
+ final = await runner.process_message(_msg())
+ assert final == "first try works"
+ assert fake_orchestrator.activated_selections == [None]
+
+ @pytest.mark.asyncio
+ async def test_inbound_handler_publishes_reply_outbound(self, partners_root, fake_orchestrator):
+ fake_orchestrator.script = _finish("reply text")
+ runner = _runner(partners_root)
+
+ await runner._handle_inbound(_msg())
+ out = await runner.bus.outbound.get()
+ assert out.channel == "telegram"
+ assert out.chat_id == "42"
+ assert out.content == "reply text"
+
+
+class TestContextAssembly:
+ @pytest.mark.asyncio
+ async def test_context_carries_soul_tools_and_metadata(self, partners_root, fake_orchestrator):
+ from deeptutor.services.partners.workspace import write_soul
+
+ write_soul("ada", "# Soul\nBe kind.")
+ fake_orchestrator.script = _finish("ok")
+ config = PartnerConfig(
+ name="Ada",
+ language="zh",
+ enabled_tools=["web_search"],
+ mcp_tools=["mcp_github_search"],
+ )
+ runner = _runner(partners_root, config)
+
+ await runner.process_message(_msg())
+ context = fake_orchestrator.seen_contexts[0]
+ assert context.persona_context == "# Soul\nBe kind."
+ assert context.enabled_tools == ["web_search"]
+ assert context.metadata["mcp_tools_filter"] == ["mcp_github_search"]
+ assert context.language == "zh"
+ assert context.active_capability == "chat"
+ assert context.metadata["partner_id"] == "ada"
+ assert context.metadata["agent_identity"]["name"] == "Ada"
+ assert "wait_for_user_reply" not in context.metadata
+
+ @pytest.mark.asyncio
+ async def test_default_tools_resolve_to_full_toggleable_set(
+ self, partners_root, fake_orchestrator
+ ):
+ from deeptutor.agents._shared.tool_composition import default_optional_tools
+
+ fake_orchestrator.script = _finish("ok")
+ runner = _runner(partners_root) # enabled_tools=None
+
+ await runner.process_message(_msg())
+ context = fake_orchestrator.seen_contexts[0]
+ assert context.enabled_tools == default_optional_tools()
+ assert "mcp_tools_filter" not in context.metadata
+
+ @pytest.mark.asyncio
+ async def test_history_feeds_next_turn(self, partners_root, fake_orchestrator):
+ fake_orchestrator.script = _finish("first reply")
+ runner = _runner(partners_root)
+ await runner.process_message(_msg("first question"))
+
+ fake_orchestrator.script = _finish("second reply")
+ await runner.process_message(_msg("second question"))
+
+ context = fake_orchestrator.seen_contexts[-1]
+ assert {"role": "user", "content": "first question"} in context.conversation_history
+ assert {
+ "role": "assistant",
+ "content": "first reply",
+ } in context.conversation_history
diff --git a/tests/services/partners/test_partner_workspace.py b/tests/services/partners/test_partner_workspace.py
new file mode 100644
index 000000000..ebb7324ba
--- /dev/null
+++ b/tests/services/partners/test_partner_workspace.py
@@ -0,0 +1,171 @@
+"""Asset provisioning: copy KB / skill / notebook into the partner workspace."""
+
+from __future__ import annotations
+
+import json
+
+from deeptutor.services.partners.workspace import (
+ ensure_partner_workspace,
+ list_assets,
+ provision_assets,
+ remove_asset,
+ strip_frontmatter,
+)
+
+
+def _seed_admin_kb(admin_root, name="physics"):
+ kb = admin_root / "knowledge_bases" / name
+ (kb / "raw").mkdir(parents=True)
+ (kb / "raw" / "doc.pdf").write_bytes(b"%PDF-fake")
+ (kb / "version-1").mkdir()
+ (kb / "version-1" / "docstore.json").write_text("{}", encoding="utf-8")
+ (kb / "metadata.json").write_text(
+ json.dumps({"name": name, "rag_provider": "llamaindex"}), encoding="utf-8"
+ )
+ return kb
+
+
+def _seed_admin_skill(admin_root, name="research-mode"):
+ skill = admin_root / "user" / "workspace" / "skills" / name
+ skill.mkdir(parents=True)
+ (skill / "SKILL.md").write_text(
+ f"---\nname: {name}\ndescription: test skill\n---\n\nBody.", encoding="utf-8"
+ )
+ (skill / "references").mkdir()
+ (skill / "references" / "ref.md").write_text("ref", encoding="utf-8")
+ return skill
+
+
+def _seed_admin_notebook(admin_root, notebook_id="nb1"):
+ nb_dir = admin_root / "user" / "workspace" / "notebook"
+ nb_dir.mkdir(parents=True)
+ (nb_dir / f"{notebook_id}.json").write_text(
+ json.dumps(
+ {
+ "id": notebook_id,
+ "name": "My Notes",
+ "records": [{"id": "r1", "type": "chat", "title": "t"}],
+ }
+ ),
+ encoding="utf-8",
+ )
+ (nb_dir / "notebooks_index.json").write_text(
+ json.dumps({"notebooks": [{"id": notebook_id, "name": "My Notes", "record_count": 1}]}),
+ encoding="utf-8",
+ )
+ return nb_dir
+
+
+class TestProvisioning:
+ def test_copies_all_three_asset_classes(self, partners_root):
+ admin_root = partners_root.parent
+ _seed_admin_kb(admin_root)
+ _seed_admin_skill(admin_root)
+ _seed_admin_notebook(admin_root)
+
+ report = provision_assets(
+ "ada",
+ knowledge_bases=["physics"],
+ skills=["research-mode"],
+ notebooks=["nb1"],
+ )
+ assert report["errors"] == []
+ assert report["copied"] == {
+ "knowledge_bases": ["physics"],
+ "skills": ["research-mode"],
+ "notebooks": ["nb1"],
+ }
+
+ ws = partners_root / "ada" / "workspace"
+ assert (ws / "knowledge_bases" / "physics" / "raw" / "doc.pdf").exists()
+ assert (ws / "knowledge_bases" / "physics" / "version-1" / "docstore.json").exists()
+ assert (ws / "user" / "workspace" / "skills" / "research-mode" / "SKILL.md").exists()
+ assert (
+ ws / "user" / "workspace" / "skills" / "research-mode" / "references" / "ref.md"
+ ).exists()
+ assert (ws / "user" / "workspace" / "notebook" / "nb1.json").exists()
+ index = json.loads(
+ (ws / "user" / "workspace" / "notebook" / "notebooks_index.json").read_text()
+ )
+ assert index["notebooks"][0]["id"] == "nb1"
+
+ def test_unknown_assets_reported_not_raised(self, partners_root):
+ report = provision_assets(
+ "ada",
+ knowledge_bases=["ghost-kb"],
+ skills=["ghost-skill"],
+ notebooks=["ghost-nb"],
+ )
+ assert len(report["errors"]) == 3
+ types = {e["type"] for e in report["errors"]}
+ assert types == {"knowledge_base", "skill", "notebook"}
+
+ def test_builtin_skill_copies_from_package(self, partners_root):
+ # skill-creator ships inside the package (deeptutor/skills/builtin);
+ # provisioning must fall back to it when the user workspace has no
+ # skill of that name. Regression: builtin picks from the wizard's
+ # default-all selection used to fail with "not accessible".
+ from deeptutor.services.skill.service import BUILTIN_SKILLS_ROOT
+
+ builtin_names = [
+ entry.name
+ for entry in BUILTIN_SKILLS_ROOT.iterdir()
+ if (entry / "SKILL.md").exists()
+ ]
+ assert builtin_names, "expected packaged builtin skills"
+ target = builtin_names[0]
+
+ report = provision_assets("ada", skills=[target])
+ assert report["errors"] == []
+ ws = partners_root / "ada" / "workspace"
+ assert (ws / "user" / "workspace" / "skills" / target / "SKILL.md").exists()
+
+ def test_provisioning_is_idempotent(self, partners_root):
+ admin_root = partners_root.parent
+ _seed_admin_kb(admin_root)
+ provision_assets("ada", knowledge_bases=["physics"])
+ report = provision_assets("ada", knowledge_bases=["physics"])
+ assert report["errors"] == []
+ assert report["copied"]["knowledge_bases"] == ["physics"]
+
+
+class TestInventoryAndRemoval:
+ def test_list_and_remove(self, partners_root):
+ admin_root = partners_root.parent
+ _seed_admin_kb(admin_root)
+ _seed_admin_skill(admin_root)
+ _seed_admin_notebook(admin_root)
+ provision_assets(
+ "ada",
+ knowledge_bases=["physics"],
+ skills=["research-mode"],
+ notebooks=["nb1"],
+ )
+
+ assets = list_assets("ada")
+ assert [kb["name"] for kb in assets["knowledge_bases"]] == ["physics"]
+ assert [s["name"] for s in assets["skills"]] == ["research-mode"]
+ assert [n["id"] for n in assets["notebooks"]] == ["nb1"]
+
+ assert remove_asset("ada", "knowledge_base", "physics") is True
+ assert remove_asset("ada", "skill", "research-mode") is True
+ assert remove_asset("ada", "notebook", "nb1") is True
+
+ assets = list_assets("ada")
+ assert assets == {"knowledge_bases": [], "skills": [], "notebooks": []}
+
+ def test_remove_rejects_path_traversal(self, partners_root):
+ ensure_partner_workspace("ada")
+ import pytest
+
+ with pytest.raises(ValueError):
+ remove_asset("ada", "skill", "../escape")
+
+
+class TestStripFrontmatter:
+ def test_strips_yaml_block(self):
+ text = "---\nname: x\ndescription: y\n---\n\n# Body\ncontent"
+ assert strip_frontmatter(text) == "# Body\ncontent"
+
+ def test_passthrough_without_frontmatter(self):
+ assert strip_frontmatter("# Plain") == "# Plain"
diff --git a/tests/services/partners/test_zulip_channel.py b/tests/services/partners/test_zulip_channel.py
new file mode 100644
index 000000000..785aa505c
--- /dev/null
+++ b/tests/services/partners/test_zulip_channel.py
@@ -0,0 +1,1261 @@
+"""Unit tests for the Zulip channel implementation."""
+
+from __future__ import annotations
+
+import asyncio
+from collections import deque
+from pathlib import Path
+import sys
+from types import SimpleNamespace
+from unittest.mock import AsyncMock, MagicMock, patch
+
+import pytest
+
+from deeptutor.partners.bus.queue import MessageBus
+from deeptutor.partners.channels.zulip import ZulipChannel, ZulipConfig
+
+
+def _make_channel(**overrides) -> ZulipChannel:
+ defaults = {
+ "enabled": True,
+ "site": "https://example.zulipchat.com",
+ "email": "[email protected]",
+ "api_key": "secret-key-123",
+ "allow_from": ["*"],
+ "group_policy": "mention",
+ "timeout": 60.0,
+ }
+ defaults.update(overrides)
+ config = ZulipConfig.model_validate(defaults)
+ bus = MagicMock(spec=MessageBus)
+ bus.publish_inbound = AsyncMock()
+ return ZulipChannel(config, bus)
+
+
+class TestZulipConfig:
+ def test_default_values(self):
+ cfg = ZulipConfig()
+ assert cfg.enabled is False
+ assert cfg.site == ""
+ assert cfg.email == ""
+ assert cfg.api_key == ""
+ assert cfg.allow_from == []
+ assert cfg.group_policy == "mention"
+ assert cfg.subscribe_streams == []
+ assert cfg.timeout == 60.0
+
+ def test_api_key_repr_false(self):
+ cfg = ZulipConfig(api_key="super-secret")
+ dumped = cfg.model_dump()
+ assert dumped["api_key"] == "super-secret"
+ r = repr(cfg)
+ assert "super-secret" not in r
+
+ def test_camel_case_alias(self):
+ cfg = ZulipConfig(site="https://example.zulipchat.com", api_key="k")
+ d = cfg.model_dump(by_alias=True)
+ assert "apiKey" in d
+ assert "groupPolicy" in d
+
+ def test_from_camel_case_dict(self):
+ d = {
+ "enabled": True,
+ "site": "https://example.zulipchat.com",
+ "email": "[email protected]",
+ "apiKey": "secret",
+ "allowFrom": ["*"],
+ "groupPolicy": "open",
+ }
+ cfg = ZulipConfig.model_validate(d)
+ assert cfg.api_key == "secret"
+ assert cfg.group_policy == "open"
+ assert cfg.allow_from == ["*"]
+
+
+class TestDefaultConfig:
+ def test_default_config_returns_dict(self):
+ cfg = ZulipChannel.default_config()
+ assert isinstance(cfg, dict)
+ assert cfg["enabled"] is False
+ assert "site" in cfg
+ assert "apiKey" in cfg
+
+
+class TestIsAllowed:
+ def test_wildcard_allows_all(self):
+ ch = _make_channel(allow_from=["*"])
+ assert ch.is_allowed("42") is True
+
+ def test_empty_list_denies_all(self):
+ ch = _make_channel(allow_from=[])
+ assert ch.is_allowed("42") is False
+
+ def test_sender_id_match(self):
+ ch = _make_channel(allow_from=["42"])
+ assert ch.is_allowed("42") is True
+ assert ch.is_allowed("99") is False
+
+ def test_composite_sender_id_email_match(self):
+ ch = _make_channel(allow_from=["[email protected]"])
+ assert ch.is_allowed("42|[email protected]") is True
+ assert ch.is_allowed("42|[email protected]") is False
+
+ def test_composite_sender_id_numeric_match(self):
+ ch = _make_channel(allow_from=["42"])
+ assert ch.is_allowed("42|[email protected]") is True
+
+ def test_composite_sender_id_no_pipe(self):
+ ch = _make_channel(allow_from=["42"])
+ assert ch.is_allowed("42") is True
+
+
+class TestIsOwnMessage:
+ def test_matches_by_email(self):
+ ch = _make_channel()
+ ch._bot_email = "[email protected]"
+ ch._bot_user_id = 100
+ assert ch._is_own_message({"sender_email": "[email protected]", "sender_id": 200}) is True
+
+ def test_matches_by_user_id(self):
+ ch = _make_channel()
+ ch._bot_email = "[email protected]"
+ ch._bot_user_id = 100
+ assert ch._is_own_message({"sender_email": "[email protected]", "sender_id": 100}) is True
+
+ def test_not_own_message(self):
+ ch = _make_channel()
+ ch._bot_email = "[email protected]"
+ ch._bot_user_id = 100
+ assert ch._is_own_message({"sender_email": "[email protected]", "sender_id": 200}) is False
+
+
+class TestIsDuplicate:
+ def test_skips_messages_below_max_message_id(self):
+ ch = _make_channel()
+ ch._max_message_id = 100
+ assert ch._is_duplicate({"id": 50}) is True
+
+ def test_allows_new_messages(self):
+ ch = _make_channel()
+ ch._max_message_id = 100
+ assert ch._is_duplicate({"id": 101}) is False
+
+ def test_detects_duplicate_in_seen_ids(self):
+ ch = _make_channel()
+ ch._max_message_id = 0
+ ch._seen_ids = deque([101, 102, 103], maxlen=5000)
+ assert ch._is_duplicate({"id": 102}) is True
+
+ def test_adds_new_id_to_seen(self):
+ ch = _make_channel()
+ ch._max_message_id = 0
+ ch._is_duplicate({"id": 200})
+ assert 200 in ch._seen_ids
+
+ def test_none_id_not_duplicate(self):
+ ch = _make_channel()
+ assert ch._is_duplicate({}) is False
+
+
+class TestIsMentioned:
+ def test_mentioned_flag(self):
+ ch = _make_channel()
+ ch._bot_user_id = 100
+ assert ch._is_mentioned({"flags": ["mentioned"]}) is True
+
+ def test_no_flags(self):
+ ch = _make_channel()
+ ch._bot_user_id = 100
+ assert ch._is_mentioned({"flags": []}) is False
+
+ def test_other_flags(self):
+ ch = _make_channel()
+ ch._bot_user_id = 100
+ assert ch._is_mentioned({"flags": ["has_alert_word"]}) is False
+
+ def test_no_bot_user_id(self):
+ ch = _make_channel()
+ ch._bot_user_id = None
+ assert ch._is_mentioned({"flags": ["mentioned"]}) is False
+
+ def test_wildcard_mentioned_flag(self):
+ ch = _make_channel()
+ ch._bot_user_id = 100
+ assert ch._is_mentioned({"flags": ["wildcard_mentioned"]}) is True
+
+ def test_stream_wildcard_mentioned_flag(self):
+ ch = _make_channel()
+ ch._bot_user_id = 100
+ assert ch._is_mentioned({"flags": ["stream_wildcard_mentioned"]}) is True
+
+ def test_topic_wildcard_mentioned_flag(self):
+ ch = _make_channel()
+ ch._bot_user_id = 100
+ assert ch._is_mentioned({"flags": ["topic_wildcard_mentioned"]}) is True
+
+ def test_mentioned_with_other_flags(self):
+ ch = _make_channel()
+ ch._bot_user_id = 100
+ assert ch._is_mentioned({"flags": ["read", "mentioned", "starred"]}) is True
+
+ def test_missing_flags_field(self):
+ ch = _make_channel()
+ ch._bot_user_id = 100
+ assert ch._is_mentioned({}) is False
+
+ def test_flags_with_non_string_elements(self):
+ ch = _make_channel()
+ ch._bot_user_id = 100
+ assert ch._is_mentioned({"flags": ["mentioned", 123, None]}) is True
+
+ def test_multiple_mention_flags(self):
+ ch = _make_channel()
+ ch._bot_user_id = 100
+ assert ch._is_mentioned({"flags": ["mentioned", "wildcard_mentioned"]}) is True
+
+ def test_content_fallback_when_flags_empty(self):
+ # Generic bot + Event Queue API returns empty flags; detect the mention
+ # from the rendered ``@**Bot Name**`` syntax in the message body.
+ ch = _make_channel()
+ ch._bot_user_id = 100
+ ch._bot_full_name = "DeepTutor Bot"
+ assert ch._is_mentioned({"flags": [], "content": "hi @**DeepTutor Bot** help"}) is True
+
+ def test_content_fallback_requires_full_name(self):
+ ch = _make_channel()
+ ch._bot_user_id = 100
+ ch._bot_full_name = ""
+ assert ch._is_mentioned({"flags": [], "content": "hi @**DeepTutor Bot**"}) is False
+
+ def test_content_fallback_no_match(self):
+ ch = _make_channel()
+ ch._bot_user_id = 100
+ ch._bot_full_name = "DeepTutor Bot"
+ assert ch._is_mentioned({"flags": [], "content": "no mention here"}) is False
+
+ def test_content_fallback_disambiguated_mention(self):
+ # Zulip renders @**Name|user_id** when names are ambiguous; this string
+ # does not contain @**Name** as a substring, so it needs its own pattern.
+ ch = _make_channel()
+ ch._bot_user_id = 100
+ ch._bot_full_name = "DeepTutor Bot"
+ assert ch._is_mentioned({"flags": [], "content": "hi @**DeepTutor Bot|100** help"}) is True
+
+
+class TestExtractUploadLinks:
+ def test_markdown_image(self):
+ content = "Check this: ![photo.png](/user_uploads/2/ce/abc123/photo.png)"
+ links = ZulipChannel._extract_upload_links(content)
+ assert len(links) == 1
+ assert links[0][0] == "photo.png"
+ assert links[0][1] == "/user_uploads/2/ce/abc123/photo.png"
+
+ def test_markdown_file_link(self):
+ content = "Here is [report.pdf](/user_uploads/2/ce/def456/report.pdf)"
+ links = ZulipChannel._extract_upload_links(content)
+ assert len(links) == 1
+ assert links[0][0] == "report.pdf"
+ assert links[0][1] == "/user_uploads/2/ce/def456/report.pdf"
+
+ def test_html_img_src(self):
+ content = '<p><img src="/user_uploads/2/ce/abc123/photo.png"></p>'
+ links = ZulipChannel._extract_upload_links(content, content_type="text/html")
+ assert len(links) == 1
+ assert links[0][1] == "/user_uploads/2/ce/abc123/photo.png"
+
+ def test_html_a_href(self):
+ content = '<a href="/user_uploads/2/ce/def456/report.pdf">report.pdf</a>'
+ links = ZulipChannel._extract_upload_links(content, content_type="text/html")
+ assert len(links) == 1
+ assert links[0][1] == "/user_uploads/2/ce/def456/report.pdf"
+
+ def test_multiple_links(self):
+ content = (
+ "See ![img.png](/user_uploads/2/ce/aaa/img.png) "
+ "and [doc.pdf](/user_uploads/2/ce/bbb/doc.pdf)"
+ )
+ links = ZulipChannel._extract_upload_links(content)
+ assert len(links) == 2
+
+ def test_dedup_same_path(self):
+ content = (
+ "![img.png](/user_uploads/2/ce/aaa/img.png) "
+ "again [img.png](/user_uploads/2/ce/aaa/img.png)"
+ )
+ links = ZulipChannel._extract_upload_links(content)
+ assert len(links) == 1
+
+ def test_no_uploads(self):
+ content = "Just a plain message with no attachments"
+ links = ZulipChannel._extract_upload_links(content)
+ assert links == []
+
+ def test_non_upload_link_ignored(self):
+ content = "[Zulip](https://zulip.com) and [docs](/help/)"
+ links = ZulipChannel._extract_upload_links(content)
+ assert links == []
+
+ def test_empty_name_uses_path(self):
+ content = "![](/user_uploads/2/ce/abc123/photo.png)"
+ links = ZulipChannel._extract_upload_links(content)
+ assert len(links) == 1
+ assert links[0][0] == "photo.png"
+
+
+class TestDownloadAttachments:
+ def test_extracts_from_markdown_content(self, tmp_path: Path):
+ ch = _make_channel()
+ message = {
+ "content": "Check ![img.png](/user_uploads/2/ce/abc/img.png)",
+ "content_type": "text/x-markdown",
+ }
+ with (
+ patch.object(
+ ch,
+ "_extract_upload_links",
+ return_value=[("img.png", "/user_uploads/2/ce/abc/img.png")],
+ ),
+ patch(
+ "deeptutor.partners.channels.zulip.get_media_dir",
+ return_value=tmp_path,
+ ),
+ patch("deeptutor.partners.channels.zulip.requests.get") as mock_get,
+ ):
+ mock_resp = MagicMock()
+ mock_resp.raise_for_status = MagicMock()
+ mock_resp.content = b"fake-image-data"
+ mock_get.return_value = mock_resp
+ with patch.object(Path, "exists", return_value=False):
+ with patch.object(Path, "write_bytes"):
+ paths = ch._download_attachments(message)
+ assert len(paths) == 1
+ mock_get.assert_called_once()
+ call_url = mock_get.call_args[0][0]
+ assert call_url == "https://example.zulipchat.com/user_uploads/2/ce/abc/img.png"
+
+ def test_no_uploads_returns_empty(self):
+ ch = _make_channel()
+ message = {"content": "No attachments here", "content_type": "text/x-markdown"}
+ with patch.object(ch, "_extract_upload_links", return_value=[]):
+ paths = ch._download_attachments(message)
+ assert paths == []
+
+ def test_caches_existing_file(self, tmp_path: Path):
+ ch = _make_channel()
+ message = {
+ "content": "![img.png](/user_uploads/2/ce/abc/img.png)",
+ "content_type": "text/x-markdown",
+ }
+ with (
+ patch.object(
+ ch,
+ "_extract_upload_links",
+ return_value=[("img.png", "/user_uploads/2/ce/abc/img.png")],
+ ),
+ patch(
+ "deeptutor.partners.channels.zulip.get_media_dir",
+ return_value=tmp_path,
+ ),
+ ):
+ from pathlib import Path as RealPath
+
+ with patch.object(RealPath, "exists", return_value=True):
+ paths = ch._download_attachments(message)
+ assert len(paths) == 1
+
+ def test_attachment_destination_uses_upload_path_digest(self, tmp_path: Path):
+ first = ZulipChannel._attachment_destination(
+ tmp_path,
+ "image.png",
+ "/user_uploads/2/aa/first/image.png",
+ 0,
+ )
+ second = ZulipChannel._attachment_destination(
+ tmp_path,
+ "image.png",
+ "/user_uploads/2/bb/second/image.png",
+ 0,
+ )
+
+ assert first != second
+ assert first.name.endswith("_image.png")
+ assert second.name.endswith("_image.png")
+
+
+class TestConvertLatexToZulip:
+ def test_inline_math(self):
+ result = ZulipChannel._convert_latex_to_zulip("The value $x^2$ is positive")
+ assert result == "The value $$x^2$$ is positive"
+
+ def test_display_math(self):
+ result = ZulipChannel._convert_latex_to_zulip("$$\n\\int_a^b f(x) dx\n$$")
+ assert "```math" in result
+ assert "\\int_a^b f(x) dx" in result
+ assert "$$" not in result
+
+ def test_display_math_single_line(self):
+ result = ZulipChannel._convert_latex_to_zulip("$$E = mc^2$$")
+ assert "```math" in result
+ assert "E = mc^2" in result
+
+ def test_mixed_inline_and_display(self):
+ result = ZulipChannel._convert_latex_to_zulip("Inline $a+b$ and display:\n$$c+d$$")
+ assert "$$a+b$$" in result
+ assert "```math" in result
+ assert "c+d" in result
+
+ def test_code_block_preserved(self):
+ result = ZulipChannel._convert_latex_to_zulip("```python\nx = $1 + $2\n```")
+ assert "```python" in result
+ assert "$1 + $2" in result
+
+ def test_inline_code_preserved(self):
+ result = ZulipChannel._convert_latex_to_zulip("Use `$x$` variable")
+ assert "`$x$`" in result
+
+ def test_no_math_unchanged(self):
+ text = "Just plain text without any math"
+ assert ZulipChannel._convert_latex_to_zulip(text) == text
+
+ def test_already_double_dollar_preserved_as_display(self):
+ result = ZulipChannel._convert_latex_to_zulip("$$x^2$$")
+ assert "```math" in result
+
+ def test_multiple_inline(self):
+ result = ZulipChannel._convert_latex_to_zulip("$a$ and $b$ and $c$")
+ assert result == "$$a$$ and $$b$$ and $$c$$"
+
+
+class TestConvertZulipLatexToStandard:
+ def test_inline_math(self):
+ result = ZulipChannel._convert_zulip_latex_to_standard("The value $$x^2$$ is positive")
+ assert result == "The value $x^2$ is positive"
+
+ def test_display_math(self):
+ result = ZulipChannel._convert_zulip_latex_to_standard("```math\n\\int_a^b f(x) dx\n```")
+ assert "$$" in result
+ assert "\\int_a^b f(x) dx" in result
+ assert "```math" not in result
+
+ def test_mixed(self):
+ result = ZulipChannel._convert_zulip_latex_to_standard(
+ "Inline $$a+b$$ and display:\n```math\nc+d\n```"
+ )
+ assert "$a+b$" in result
+ assert "$$" in result
+ assert "c+d" in result
+
+ def test_code_block_preserved(self):
+ result = ZulipChannel._convert_zulip_latex_to_standard("```python\nx = $$1 + $$2\n```")
+ assert "```python" in result
+ assert "$$1 + $$2" in result
+
+ def test_no_math_unchanged(self):
+ text = "Just plain text"
+ assert ZulipChannel._convert_zulip_latex_to_standard(text) == text
+
+ def test_roundtrip_inline(self):
+ original = "The value $x^2$ is positive"
+ zulip_fmt = ZulipChannel._convert_latex_to_zulip(original)
+ restored = ZulipChannel._convert_zulip_latex_to_standard(zulip_fmt)
+ assert restored == original
+
+ def test_roundtrip_display(self):
+ original = "$$\n\\int_a^b f(x) dx\n$$"
+ zulip_fmt = ZulipChannel._convert_latex_to_zulip(original)
+ restored = ZulipChannel._convert_zulip_latex_to_standard(zulip_fmt)
+ assert "\\int_a^b f(x) dx" in restored
+
+
+class TestBuildSendRequest:
+ def test_stream_message(self):
+ ch = _make_channel()
+ metadata = {
+ "msg_type": "stream",
+ "stream": "general",
+ "topic": "hello",
+ }
+ req = ch._build_send_request("stream:general:hello", "Hello world", metadata)
+ assert req["type"] == "stream"
+ assert req["to"] == "general"
+ assert req["subject"] == "hello"
+ assert req["content"] == "Hello world"
+
+ def test_stream_message_no_topic(self):
+ ch = _make_channel()
+ metadata = {"msg_type": "stream", "stream": "general", "topic": ""}
+ req = ch._build_send_request("stream:general", "Hi", metadata)
+ assert req["subject"] == "(no topic)"
+
+ def test_private_message(self):
+ ch = _make_channel()
+ metadata = {
+ "msg_type": "private",
+ "recipient_user_id": "42",
+ }
+ req = ch._build_send_request("pm:42", "Hello", metadata)
+ assert req["type"] == "private"
+ assert req["to"] == ["42"]
+
+ def test_private_message_fallback_to_email(self):
+ ch = _make_channel()
+ metadata = {
+ "msg_type": "private",
+ "sender_email": "[email protected]",
+ }
+ req = ch._build_send_request("pm:42", "Hello", metadata)
+ assert req["to"] == ["[email protected]"]
+
+
+class TestOnMessage:
+ def _make_msg(self, **overrides) -> dict:
+ base = {
+ "id": 200,
+ "type": "private",
+ "content": "Hello bot",
+ "sender_id": 42,
+ "sender_email": "[email protected]",
+ "sender_full_name": "Test User",
+ "display_recipient": [
+ {"id": 42, "email": "[email protected]"},
+ {"id": 100, "email": "[email protected]"},
+ ],
+ "subject": "",
+ "flags": [],
+ "attachments": [],
+ }
+ base.update(overrides)
+ return base
+
+ @pytest.mark.asyncio
+ async def test_private_message_dispatched(self):
+ ch = _make_channel()
+ ch._bot_email = "[email protected]"
+ ch._bot_user_id = 100
+ ch._max_message_id = 0
+ ch._loop = asyncio.get_running_loop()
+
+ msg = self._make_msg()
+ ch._on_message(msg)
+
+ await asyncio.sleep(0.1)
+ ch.bus.publish_inbound.assert_awaited_once()
+ call_args = ch.bus.publish_inbound.call_args[0][0]
+ assert call_args.channel == "zulip"
+ assert call_args.sender_id == "42|[email protected]"
+ assert call_args.chat_id == "pm:42"
+ assert call_args.content == "Hello bot"
+
+ @pytest.mark.asyncio
+ async def test_own_message_filtered(self):
+ ch = _make_channel()
+ ch._bot_email = "[email protected]"
+ ch._bot_user_id = 100
+ ch._max_message_id = 0
+ ch._loop = asyncio.get_running_loop()
+
+ msg = self._make_msg(sender_email="[email protected]", sender_id=100)
+ ch._on_message(msg)
+
+ await asyncio.sleep(0.1)
+ ch.bus.publish_inbound.assert_not_awaited()
+
+ @pytest.mark.asyncio
+ async def test_duplicate_message_filtered(self):
+ ch = _make_channel()
+ ch._bot_email = "[email protected]"
+ ch._bot_user_id = 100
+ ch._max_message_id = 0
+ ch._loop = asyncio.get_running_loop()
+
+ msg = self._make_msg(id=200)
+ ch._on_message(msg)
+ await asyncio.sleep(0.1)
+
+ ch.bus.publish_inbound.reset_mock()
+ ch._on_message(msg)
+ await asyncio.sleep(0.1)
+ ch.bus.publish_inbound.assert_not_awaited()
+
+ @pytest.mark.asyncio
+ async def test_stream_mention_policy_rejects_unmentioned(self):
+ ch = _make_channel(group_policy="mention")
+ ch._bot_email = "[email protected]"
+ ch._bot_user_id = 100
+ ch._max_message_id = 0
+ ch._loop = asyncio.get_running_loop()
+
+ msg = self._make_msg(
+ type="stream",
+ display_recipient="general",
+ subject="test",
+ flags=[],
+ )
+ ch._on_message(msg)
+
+ await asyncio.sleep(0.1)
+ ch.bus.publish_inbound.assert_not_awaited()
+
+ @pytest.mark.asyncio
+ async def test_stream_mention_policy_allows_mentioned(self):
+ ch = _make_channel(group_policy="mention")
+ ch._bot_email = "[email protected]"
+ ch._bot_user_id = 100
+ ch._max_message_id = 0
+ ch._loop = asyncio.get_running_loop()
+
+ msg = self._make_msg(
+ type="stream",
+ display_recipient="general",
+ subject="test",
+ flags=["mentioned"],
+ )
+ ch._on_message(msg)
+
+ await asyncio.sleep(0.1)
+ ch.bus.publish_inbound.assert_awaited_once()
+
+ @pytest.mark.asyncio
+ async def test_stream_open_policy_allows_all(self):
+ ch = _make_channel(group_policy="open")
+ ch._bot_email = "[email protected]"
+ ch._bot_user_id = 100
+ ch._max_message_id = 0
+ ch._loop = asyncio.get_running_loop()
+
+ msg = self._make_msg(
+ type="stream",
+ display_recipient="general",
+ subject="test",
+ flags=[],
+ )
+ ch._on_message(msg)
+
+ await asyncio.sleep(0.1)
+ ch.bus.publish_inbound.assert_awaited_once()
+
+ @pytest.mark.asyncio
+ async def test_stream_message_includes_prefix(self):
+ ch = _make_channel(group_policy="open")
+ ch._bot_email = "[email protected]"
+ ch._bot_user_id = 100
+ ch._max_message_id = 0
+ ch._loop = asyncio.get_running_loop()
+
+ msg = self._make_msg(
+ type="stream",
+ display_recipient="general",
+ subject="test topic",
+ content="Hello",
+ flags=[],
+ )
+ ch._on_message(msg)
+
+ await asyncio.sleep(0.1)
+ call_args = ch.bus.publish_inbound.call_args[0][0]
+ assert call_args.chat_id == "stream:general:test topic"
+ assert call_args.session_key_override == "zulip:stream:general:test topic"
+ assert "**[general > test topic]**" in call_args.content
+
+ @pytest.mark.asyncio
+ async def test_empty_stream_topic_gets_stable_no_topic_scope(self):
+ ch = _make_channel(group_policy="open")
+ ch._bot_email = "[email protected]"
+ ch._bot_user_id = 100
+ ch._max_message_id = 0
+ ch._loop = asyncio.get_running_loop()
+
+ msg = self._make_msg(
+ type="stream",
+ display_recipient="general",
+ subject="",
+ content="Hello",
+ flags=[],
+ )
+ ch._on_message(msg)
+
+ await asyncio.sleep(0.1)
+ call_args = ch.bus.publish_inbound.call_args[0][0]
+ assert call_args.chat_id == "stream:general:(no topic)"
+ assert call_args.session_key_override == "zulip:stream:general:(no topic)"
+
+
+class TestSend:
+ @pytest.mark.asyncio
+ async def test_send_text_uses_call_endpoint(self):
+ ch = _make_channel()
+ mock_client = MagicMock()
+ mock_client.call_endpoint.return_value = {"result": "success"}
+ ch._client = mock_client
+
+ from deeptutor.partners.bus.events import OutboundMessage
+
+ msg = OutboundMessage(
+ channel="zulip",
+ chat_id="pm:42",
+ content="Hello",
+ metadata={"msg_type": "private", "recipient_user_id": "42"},
+ )
+ await ch.send(msg)
+
+ mock_client.call_endpoint.assert_called_once()
+ call_kwargs = mock_client.call_endpoint.call_args
+ assert call_kwargs.kwargs["url"] == "messages"
+ assert call_kwargs.kwargs["timeout"] == 60.0
+
+ @pytest.mark.asyncio
+ async def test_send_stops_typing_on_final_response(self):
+ ch = _make_channel()
+ mock_client = MagicMock()
+ mock_client.call_endpoint.return_value = {"result": "success"}
+ ch._client = mock_client
+
+ typing_task = asyncio.create_task(asyncio.sleep(100))
+ ch._typing_tasks["pm:42"] = typing_task
+
+ from deeptutor.partners.bus.events import OutboundMessage
+
+ msg = OutboundMessage(
+ channel="zulip",
+ chat_id="pm:42",
+ content="Hello",
+ metadata={},
+ )
+ await ch.send(msg)
+ assert "pm:42" not in ch._typing_tasks
+
+ @pytest.mark.asyncio
+ async def test_send_keeps_typing_on_progress(self):
+ ch = _make_channel()
+ mock_client = MagicMock()
+ mock_client.call_endpoint.return_value = {"result": "success"}
+ ch._client = mock_client
+
+ typing_task = asyncio.create_task(asyncio.sleep(100))
+ ch._typing_tasks["pm:42"] = typing_task
+
+ from deeptutor.partners.bus.events import OutboundMessage
+
+ msg = OutboundMessage(
+ channel="zulip",
+ chat_id="pm:42",
+ content="Thinking...",
+ metadata={"_progress": True},
+ )
+ await ch.send(msg)
+ assert "pm:42" in ch._typing_tasks
+
+ @pytest.mark.asyncio
+ async def test_send_no_client_returns_early(self):
+ ch = _make_channel()
+ ch._client = None
+
+ from deeptutor.partners.bus.events import OutboundMessage
+
+ msg = OutboundMessage(
+ channel="zulip",
+ chat_id="pm:42",
+ content="Hello",
+ metadata={},
+ )
+ await ch.send(msg)
+
+
+class TestUploadAndSend:
+ @pytest.mark.asyncio
+ async def test_upload_uses_call_endpoint(self, tmp_path: Path):
+ test_file = tmp_path / "test.png"
+ test_file.write_bytes(b"fake-image")
+
+ ch = _make_channel()
+ mock_client = MagicMock()
+
+ def fake_call_endpoint(**kwargs):
+ if kwargs.get("url") == "user_uploads":
+ return {"result": "success", "uri": "/user_uploads/img.png"}
+ return {"result": "success"}
+
+ mock_client.call_endpoint.side_effect = fake_call_endpoint
+ ch._client = mock_client
+
+ from deeptutor.partners.bus.events import OutboundMessage
+
+ msg = OutboundMessage(
+ channel="zulip",
+ chat_id="pm:42",
+ content="",
+ media=[str(test_file)],
+ metadata={"msg_type": "private", "recipient_user_id": "42"},
+ )
+ await ch.send(msg)
+
+ upload_calls = [
+ c
+ for c in mock_client.call_endpoint.call_args_list
+ if c.kwargs.get("url") == "user_uploads"
+ ]
+ assert len(upload_calls) == 1
+ assert upload_calls[0].kwargs["timeout"] == 60.0
+ files_arg = upload_calls[0].kwargs["files"]
+ assert len(files_arg) == 1
+ assert hasattr(files_arg[0], "read")
+
+ @pytest.mark.asyncio
+ async def test_upload_passes_file_object_not_string(self, tmp_path: Path):
+ test_file = tmp_path / "test.png"
+ test_file.write_bytes(b"fake-image")
+
+ ch = _make_channel()
+ mock_client = MagicMock()
+ mock_client.call_endpoint.return_value = {
+ "result": "success",
+ "uri": "/user_uploads/img.png",
+ }
+ ch._client = mock_client
+
+ await ch._upload_and_send(
+ "pm:42",
+ str(test_file),
+ {"msg_type": "private", "recipient_user_id": "42"},
+ )
+
+ upload_calls = [
+ c
+ for c in mock_client.call_endpoint.call_args_list
+ if c.kwargs.get("url") == "user_uploads"
+ ]
+ assert len(upload_calls) == 1
+ files_arg = upload_calls[0].kwargs["files"]
+ assert len(files_arg) == 1
+ f = files_arg[0]
+ assert hasattr(f, "name")
+ assert hasattr(f, "read")
+
+ @pytest.mark.asyncio
+ async def test_upload_skips_unresolvable_path(self):
+ ch = _make_channel()
+ mock_client = MagicMock()
+ ch._client = mock_client
+
+ with patch.object(ch, "_resolve_media_path", return_value=None):
+ await ch._upload_and_send(
+ "pm:42",
+ "/nonexistent/file.png",
+ {"msg_type": "private", "recipient_user_id": "42"},
+ )
+
+ mock_client.call_endpoint.assert_not_called()
+
+
+class TestResolveMediaPath:
+ def test_existing_local_path_returned_directly(self, tmp_path: Path):
+ test_file = tmp_path / "image.png"
+ test_file.write_bytes(b"data")
+
+ ch = _make_channel()
+ result = ch._resolve_media_path(str(test_file))
+ assert result == str(test_file)
+
+ def test_zulip_upload_path_finds_cached_file(self, tmp_path: Path):
+ ch = _make_channel()
+ path_id = "/user_uploads/2/ce/abc123/photo.png"
+
+ with patch(
+ "deeptutor.partners.channels.zulip.get_media_dir",
+ return_value=tmp_path,
+ ):
+ dest = ZulipChannel._attachment_destination(tmp_path, "photo.png", path_id, 0)
+ dest.write_bytes(b"cached-data")
+
+ result = ch._resolve_media_path(path_id)
+ assert result is not None
+ assert result == str(dest)
+
+ def test_zulip_upload_path_downloads_if_not_cached(self, tmp_path: Path):
+ ch = _make_channel()
+ path_id = "/user_uploads/2/ce/abc123/photo.png"
+
+ with (
+ patch(
+ "deeptutor.partners.channels.zulip.get_media_dir",
+ return_value=tmp_path,
+ ),
+ patch("deeptutor.partners.channels.zulip.requests.get") as mock_get,
+ ):
+ mock_resp = MagicMock()
+ mock_resp.raise_for_status = MagicMock()
+ mock_resp.content = b"downloaded-data"
+ mock_get.return_value = mock_resp
+
+ result = ch._resolve_media_path(path_id)
+ assert result is not None
+ assert Path(result).read_bytes() == b"downloaded-data"
+ mock_get.assert_called_once()
+
+ def test_full_url_resolved_to_zulip_path(self, tmp_path: Path):
+ ch = _make_channel()
+ url = "https://example.zulipchat.com/user_uploads/2/ce/abc/photo.png"
+
+ with (
+ patch(
+ "deeptutor.partners.channels.zulip.get_media_dir",
+ return_value=tmp_path,
+ ),
+ patch("deeptutor.partners.channels.zulip.requests.get") as mock_get,
+ ):
+ mock_resp = MagicMock()
+ mock_resp.raise_for_status = MagicMock()
+ mock_resp.content = b"data"
+ mock_get.return_value = mock_resp
+
+ result = ch._resolve_media_path(url)
+ assert result is not None
+
+ def test_full_url_resolved_when_config_site_has_trailing_slash(self, tmp_path: Path):
+ ch = _make_channel(site="https://example.zulipchat.com/")
+ url = "https://example.zulipchat.com/user_uploads/2/ce/abc/photo.png"
+
+ with (
+ patch(
+ "deeptutor.partners.channels.zulip.get_media_dir",
+ return_value=tmp_path,
+ ),
+ patch("deeptutor.partners.channels.zulip.requests.get") as mock_get,
+ ):
+ mock_resp = MagicMock()
+ mock_resp.raise_for_status = MagicMock()
+ mock_resp.content = b"data"
+ mock_get.return_value = mock_resp
+
+ result = ch._resolve_media_path(url)
+ assert result is not None
+ assert Path(result).read_bytes() == b"data"
+
+ def test_non_zulip_nonexistent_path_returns_none(self):
+ ch = _make_channel()
+ result = ch._resolve_media_path("/some/random/path.png")
+ assert result is None
+
+
+class TestSendMetadataEnrichment:
+ @pytest.mark.asyncio
+ async def test_send_enriches_metadata_from_recipient_map(self, tmp_path: Path):
+ ch = _make_channel()
+ mock_client = MagicMock()
+ mock_client.call_endpoint.return_value = {"result": "success"}
+ ch._client = mock_client
+
+ ch._recipient_map["pm:42"] = {
+ "msg_type": "private",
+ "recipient_user_id": "42",
+ "sender_email": "[email protected]",
+ }
+
+ from deeptutor.partners.bus.events import OutboundMessage
+
+ msg = OutboundMessage(
+ channel="zulip",
+ chat_id="pm:42",
+ content="Hello",
+ metadata={"message_id": "200"},
+ )
+ await ch.send(msg)
+
+ assert msg.metadata["msg_type"] == "private"
+ assert msg.metadata["recipient_user_id"] == "42"
+ assert msg.metadata["message_id"] == "200"
+
+ @pytest.mark.asyncio
+ async def test_send_preserves_existing_metadata(self):
+ ch = _make_channel()
+ mock_client = MagicMock()
+ mock_client.call_endpoint.return_value = {"result": "success"}
+ ch._client = mock_client
+
+ ch._recipient_map["pm:42"] = {
+ "msg_type": "private",
+ "recipient_user_id": "42",
+ }
+
+ from deeptutor.partners.bus.events import OutboundMessage
+
+ msg = OutboundMessage(
+ channel="zulip",
+ chat_id="pm:42",
+ content="Hello",
+ metadata={"msg_type": "stream", "stream": "general", "topic": "test"},
+ )
+ await ch.send(msg)
+
+ assert msg.metadata["msg_type"] == "stream"
+ assert msg.metadata["stream"] == "general"
+
+
+class TestSendToolHints:
+ @pytest.mark.asyncio
+ async def test_tool_hint_message_sent_when_dispatched(self):
+ ch = _make_channel()
+ mock_client = MagicMock()
+ mock_client.call_endpoint.return_value = {"result": "success"}
+ ch._client = mock_client
+
+ from deeptutor.partners.bus.events import OutboundMessage
+
+ msg = OutboundMessage(
+ channel="zulip",
+ chat_id="pm:42",
+ content='message("Hello")',
+ metadata={
+ "_progress": True,
+ "_tool_hint": True,
+ "msg_type": "private",
+ "recipient_user_id": "42",
+ },
+ )
+ await ch.send(msg)
+
+ mock_client.call_endpoint.assert_called_once()
+
+ @pytest.mark.asyncio
+ async def test_progress_message_without_tool_hint_sent(self):
+ ch = _make_channel()
+ mock_client = MagicMock()
+ mock_client.call_endpoint.return_value = {"result": "success"}
+ ch._client = mock_client
+
+ from deeptutor.partners.bus.events import OutboundMessage
+
+ msg = OutboundMessage(
+ channel="zulip",
+ chat_id="pm:42",
+ content="Thinking...",
+ metadata={"_progress": True, "msg_type": "private", "recipient_user_id": "42"},
+ )
+ await ch.send(msg)
+
+ mock_client.call_endpoint.assert_called()
+
+
+class TestStop:
+ @pytest.mark.asyncio
+ async def test_stop_deregisters_queue(self):
+ ch = _make_channel()
+ mock_client = MagicMock()
+ ch._client = mock_client
+ ch._queue_id = "test-queue-123"
+ ch._running = True
+
+ saved_client = ch._client
+ await ch.stop()
+
+ saved_client.deregister.assert_called_once_with("test-queue-123")
+ assert ch._queue_id is None
+ assert ch._client is None
+ assert ch._running is False
+
+ @pytest.mark.asyncio
+ async def test_stop_cancels_typing_tasks(self):
+ ch = _make_channel()
+ mock_client = MagicMock()
+ ch._client = mock_client
+ ch._running = True
+
+ task = asyncio.create_task(asyncio.sleep(100))
+ ch._typing_tasks["pm:42"] = task
+
+ await ch.stop()
+ await asyncio.sleep(0)
+ assert task.cancelled() or task.done()
+ assert len(ch._typing_tasks) == 0
+
+
+class TestSubscribeStreams:
+ def test_no_streams_configured_skips(self):
+ ch = _make_channel(subscribe_streams=[])
+ mock_client = MagicMock()
+ ch._client = mock_client
+ ch._subscribe_to_streams()
+ mock_client.add_subscriptions.assert_not_called()
+ mock_client.get_streams.assert_not_called()
+
+ def test_explicit_stream_names(self):
+ ch = _make_channel(subscribe_streams=["general", "dev"])
+ mock_client = MagicMock()
+ mock_client.add_subscriptions.return_value = {
+ "result": "success",
+ "already_subscribed": {},
+ }
+ ch._client = mock_client
+ ch._subscribe_to_streams()
+ mock_client.add_subscriptions.assert_called_once()
+ call_kwargs = mock_client.add_subscriptions.call_args
+ streams_arg = call_kwargs.kwargs["streams"]
+ names = [s["name"] for s in streams_arg]
+ assert "general" in names
+ assert "dev" in names
+
+ def test_explicit_stream_names_are_deduplicated_and_sorted(self):
+ ch = _make_channel(subscribe_streams=["general", "dev", "general", " "])
+ mock_client = MagicMock()
+ mock_client.add_subscriptions.return_value = {
+ "result": "success",
+ "already_subscribed": {},
+ }
+ ch._client = mock_client
+
+ ch._subscribe_to_streams()
+
+ streams_arg = mock_client.add_subscriptions.call_args.kwargs["streams"]
+ assert [s["name"] for s in streams_arg] == ["dev", "general"]
+
+ def test_wildcard_subscribes_all_public_streams(self):
+ ch = _make_channel(subscribe_streams=["*"])
+ mock_client = MagicMock()
+ mock_client.get_streams.return_value = {
+ "result": "success",
+ "streams": [
+ {"name": "general"},
+ {"name": "dev"},
+ {"name": "announce"},
+ ],
+ }
+ mock_client.add_subscriptions.return_value = {
+ "result": "success",
+ "already_subscribed": {},
+ }
+ ch._client = mock_client
+ ch._subscribe_to_streams()
+ mock_client.get_streams.assert_called_once_with(include_all=True)
+ call_kwargs = mock_client.add_subscriptions.call_args
+ streams_arg = call_kwargs.kwargs["streams"]
+ names = {s["name"] for s in streams_arg}
+ assert names == {"general", "dev", "announce"}
+
+ def test_wildcard_fetch_failure_skips_subscribe(self):
+ ch = _make_channel(subscribe_streams=["*"])
+ mock_client = MagicMock()
+ mock_client.get_streams.return_value = {"result": "error", "msg": "forbidden"}
+ ch._client = mock_client
+ ch._subscribe_to_streams()
+ mock_client.add_subscriptions.assert_not_called()
+
+ def test_subscribe_partial_failure_logs_warning(self):
+ ch = _make_channel(subscribe_streams=["general"])
+ mock_client = MagicMock()
+ mock_client.add_subscriptions.return_value = {
+ "result": "error",
+ "msg": "some error",
+ }
+ ch._client = mock_client
+
+ with patch("deeptutor.partners.channels.zulip.logger.warning") as mock_warning:
+ ch._subscribe_to_streams()
+
+ mock_client.add_subscriptions.assert_called_once()
+ mock_warning.assert_called_once()
+
+ def test_subscribe_non_success_all_already_subscribed_is_debug_only(self):
+ ch = _make_channel(subscribe_streams=["general"])
+ mock_client = MagicMock()
+ mock_client.add_subscriptions.return_value = {
+ "result": "error",
+ "msg": "already subscribed",
+ "already_subscribed": {"[email protected]": ["general"]},
+ }
+ ch._client = mock_client
+
+ with (
+ patch("deeptutor.partners.channels.zulip.logger.warning") as mock_warning,
+ patch("deeptutor.partners.channels.zulip.logger.debug") as mock_debug,
+ ):
+ ch._subscribe_to_streams()
+
+ mock_warning.assert_not_called()
+ mock_debug.assert_called_once()
+
+ def test_subscribe_logs_already_subscribed(self):
+ ch = _make_channel(subscribe_streams=["general", "dev"])
+ mock_client = MagicMock()
+ mock_client.add_subscriptions.return_value = {
+ "result": "success",
+ "already_subscribed": {"[email protected]": ["general"]},
+ }
+ ch._client = mock_client
+ ch._subscribe_to_streams()
+ mock_client.add_subscriptions.assert_called_once()
+
+
+class TestRegisterQueue:
+ def test_register_success(self):
+ ch = _make_channel()
+ mock_client = MagicMock()
+ mock_client.register.return_value = {
+ "result": "success",
+ "queue_id": "q-123",
+ "last_event_id": 10,
+ "max_message_id": 500,
+ }
+ ch._client = mock_client
+
+ ch._register_queue()
+ assert ch._queue_id == "q-123"
+ assert ch._last_event_id == 10
+ assert ch._max_message_id == 500
+
+ def test_register_failure(self):
+ ch = _make_channel()
+ mock_client = MagicMock()
+ mock_client.register.return_value = {
+ "result": "error",
+ "msg": "bad request",
+ }
+ ch._client = mock_client
+
+ ch._register_queue()
+ assert ch._queue_id is None
+
+
+class TestCallWithRetry:
+ def test_succeeds_on_first_attempt(self):
+ ch = _make_channel()
+ fn = MagicMock(return_value={"result": "success"})
+ result = ch._call_with_retry(fn)
+ assert result == {"result": "success"}
+ assert fn.call_count == 1
+
+ def test_retries_on_failure(self):
+ ch = _make_channel()
+ fn = MagicMock(
+ side_effect=[Exception("fail"), Exception("fail again"), {"result": "success"}]
+ )
+ with patch("time.sleep"):
+ result = ch._call_with_retry(fn)
+ assert result == {"result": "success"}
+ assert fn.call_count == 3
+
+ def test_raises_after_max_retries(self):
+ ch = _make_channel()
+ fn = MagicMock(side_effect=Exception("persistent failure"))
+ with patch("time.sleep"):
+ with pytest.raises(Exception, match="persistent failure"):
+ ch._call_with_retry(fn)
+ assert fn.call_count == 3
+
+
+class TestStart:
+ @pytest.mark.asyncio
+ async def test_start_without_config_returns_early(self):
+ ch = _make_channel(site="", email="", api_key="")
+ await ch.start()
+ assert ch._running is False
+
+ @pytest.mark.asyncio
+ async def test_start_profile_failure(self, monkeypatch):
+ ch = _make_channel()
+ fake_zulip = SimpleNamespace(Client=MagicMock())
+ monkeypatch.setitem(sys.modules, "zulip", fake_zulip)
+ with patch("deeptutor.partners.channels.zulip.ZulipChannel._call_with_retry") as mock_retry:
+ mock_retry.return_value = {"result": "error"}
+ await ch.start()
+
+ assert ch._running is False
diff --git a/web/app/(workspace)/agents/[botId]/chat/page.tsx b/web/app/(workspace)/agents/[botId]/chat/page.tsx
deleted file mode 100644
index 7a04d0cd6..000000000
--- a/web/app/(workspace)/agents/[botId]/chat/page.tsx
+++ /dev/null
@@ -1,397 +0,0 @@
-"use client";
-
-import { useCallback, useEffect, useMemo, useRef, useState } from "react";
-import dynamic from "next/dynamic";
-import { useParams, useRouter } from "next/navigation";
-import { useTranslation } from "react-i18next";
-import { ArrowLeft, Bot, Loader2, Send } from "lucide-react";
-import { apiFetch, apiUrl, wsUrl } from "@/lib/api";
-import { firstParam } from "@/lib/route-params";
-import AssistantResponse from "@/components/common/AssistantResponse";
-import { SimpleComposerInput } from "@/components/chat/home/SimpleComposerInput";
-import { downloadChatMarkdown } from "@/lib/chat-export";
-import {
- normalizeMessageContent,
- type RawMessageContent,
-} from "@/lib/message-content";
-import type { MessageItem } from "@/context/UnifiedChatContext";
-import type {
- NotebookSaveMessage,
- NotebookSavePayload,
-} from "@/components/notebook/SaveToNotebookModal";
-
-const SaveToNotebookModal = dynamic(
- () => import("@/components/notebook/SaveToNotebookModal"),
- { ssr: false },
-);
-
-interface BotInfo {
- bot_id: string;
- name: string;
- running: boolean;
-}
-
-interface ChatMsg {
- role: "user" | "assistant";
- content: string;
- thinking?: string[];
-}
-
-export default function BotChatPage() {
- const params = useParams<{ botId?: string | string[] }>();
- const botId = firstParam(params?.botId);
- const router = useRouter();
- const { t } = useTranslation();
-
- const [bot, setBot] = useState<BotInfo | null>(null);
- const [messages, setMessages] = useState<ChatMsg[]>([]);
- const [streaming, setStreaming] = useState(false);
- const [thinking, setThinking] = useState<string[]>([]);
- const thinkingRef = useRef<string[]>([]);
-
- const wsRef = useRef<WebSocket | null>(null);
- const scrollRef = useRef<HTMLDivElement>(null);
- const inputRef = useRef<HTMLTextAreaElement>(null);
-
- const [showSaveModal, setShowSaveModal] = useState(false);
-
- const exportTitle = useMemo(() => {
- const firstUser = messages
- .find((m) => m.role === "user")
- ?.content.trim()
- .slice(0, 80);
- return firstUser || bot?.name || botId || "Bot Chat";
- }, [bot?.name, botId, messages]);
-
- const exportMessages = useMemo<MessageItem[]>(
- () =>
- messages.map((m) => ({
- role: m.role,
- content: m.content,
- })),
- [messages],
- );
-
- const notebookSaveMessages = useMemo<NotebookSaveMessage[]>(
- () =>
- messages.map((m) => ({
- role: m.role,
- content: m.content,
- })),
- [messages],
- );
-
- const notebookSavePayload = useMemo<NotebookSavePayload | null>(() => {
- if (!messages.length) return null;
- return {
- recordType: "tutorbot",
- title: exportTitle,
- // SaveToNotebookModal rebuilds userQuery / output from the user's
- // selected message subset; we just need a non-null payload here.
- userQuery: "",
- output: "",
- metadata: {
- source: "agent_chat",
- bot_id: botId ?? null,
- bot_name: bot?.name ?? null,
- total_message_count: messages.length,
- },
- };
- }, [bot?.name, botId, exportTitle, messages.length]);
-
- const handleDownloadMarkdown = useCallback(() => {
- if (!exportMessages.length) return;
- downloadChatMarkdown(exportMessages, { title: exportTitle });
- }, [exportMessages, exportTitle]);
-
- const handleCloseSaveModal = useCallback(() => setShowSaveModal(false), []);
-
- const scrollToBottom = useCallback((behavior: ScrollBehavior = "smooth") => {
- requestAnimationFrame(() => {
- scrollRef.current?.scrollTo({
- top: scrollRef.current.scrollHeight,
- behavior,
- });
- });
- }, []);
-
- useEffect(() => {
- if (!botId) {
- return;
- }
- let cancelled = false;
- // Clear stale transcript immediately when navigating between bots.
- // eslint-disable-next-line react-hooks/set-state-in-effect
- setMessages([]);
- setThinking([]);
- thinkingRef.current = [];
- setStreaming(false);
-
- apiFetch(apiUrl(`/api/v1/tutorbot/${botId}`))
- .then((r) => (r.ok ? r.json() : null))
- .then((data) => {
- if (!cancelled) setBot(data);
- })
- .catch(() => {
- if (!cancelled) setBot(null);
- });
-
- apiFetch(apiUrl(`/api/v1/tutorbot/${botId}/history`))
- .then((r) => (r.ok ? r.json() : []))
- .then(
- (
- history: {
- role: string;
- content: RawMessageContent;
- reasoning_content?: unknown;
- }[],
- ) => {
- const restored: ChatMsg[] = history
- .filter((m) => m.role === "user" || m.role === "assistant")
- .map((m) => ({
- role: m.role as "user" | "assistant",
- content: normalizeMessageContent(m.content),
- }));
- if (cancelled) return;
- setMessages(restored);
- if (restored.length) {
- requestAnimationFrame(() => scrollToBottom("instant"));
- window.setTimeout(() => scrollToBottom("instant"), 80);
- window.setTimeout(() => scrollToBottom("instant"), 250);
- }
- },
- )
- .catch(() => {});
- return () => {
- cancelled = true;
- };
- }, [botId, scrollToBottom]);
-
- useEffect(() => {
- if (!botId) {
- return;
- }
- const ws = new WebSocket(wsUrl(`/api/v1/tutorbot/${botId}/ws`));
- wsRef.current = ws;
-
- ws.onmessage = (e) => {
- const data = JSON.parse(e.data);
- if (data.type === "thinking") {
- thinkingRef.current = [...thinkingRef.current, data.content];
- setThinking(thinkingRef.current);
- scrollToBottom();
- } else if (data.type === "content") {
- const snap = thinkingRef.current;
- setMessages((msgs) => [
- ...msgs,
- {
- role: "assistant",
- content: data.content,
- thinking: snap.length ? [...snap] : undefined,
- },
- ]);
- thinkingRef.current = [];
- setThinking([]);
- scrollToBottom();
- } else if (data.type === "done") {
- setStreaming(false);
- setTimeout(() => inputRef.current?.focus(), 50);
- } else if (data.type === "proactive") {
- setMessages((msgs) => [
- ...msgs,
- { role: "assistant", content: data.content },
- ]);
- scrollToBottom();
- } else if (data.type === "error") {
- setMessages((msgs) => [
- ...msgs,
- { role: "assistant", content: `Error: ${data.content}` },
- ]);
- thinkingRef.current = [];
- setThinking([]);
- setStreaming(false);
- }
- };
-
- ws.onclose = () => {
- setStreaming(false);
- };
-
- return () => {
- ws.close();
- wsRef.current = null;
- };
- }, [botId, scrollToBottom]);
-
- const handleSend = useCallback(
- (content: string) => {
- if (
- !botId ||
- streaming ||
- !wsRef.current ||
- wsRef.current.readyState !== WebSocket.OPEN
- )
- return;
-
- setMessages((msgs) => [...msgs, { role: "user", content }]);
- setStreaming(true);
- setThinking([]);
- wsRef.current.send(JSON.stringify({ content }));
- scrollToBottom();
- },
- [botId, streaming, scrollToBottom],
- );
-
- const handleManualSend = useCallback(() => {
- const content = inputRef.current?.value.trim();
- if (content) {
- handleSend(content);
- if (inputRef.current) inputRef.current.value = "";
- }
- }, [handleSend]);
-
- return (
- <div className="flex h-full flex-col">
- {/* Header */}
- <div className="flex items-center gap-3 border-b border-[var(--border)] px-5 py-3">
- <button
- onClick={() => router.push("/agents")}
- className="rounded-lg p-1.5 text-[var(--muted-foreground)] transition-colors hover:bg-[var(--muted)] hover:text-[var(--foreground)]"
- >
- <ArrowLeft className="h-4 w-4" />
- </button>
- <Bot className="h-4 w-4 text-[var(--muted-foreground)]" />
- <span className="text-[14px] font-medium text-[var(--foreground)]">
- {bot?.name ?? botId}
- </span>
- {bot?.running && (
- <span className="h-2 w-2 rounded-full bg-emerald-500" />
- )}
- <div className="ml-auto flex items-center gap-2">
- <button
- onClick={() => setShowSaveModal(true)}
- disabled={!notebookSavePayload}
- className="rounded-lg border border-[var(--border)]/50 px-3 py-1.5 text-[12px] font-medium text-[var(--muted-foreground)] transition-colors hover:border-[var(--border)] hover:text-[var(--foreground)] disabled:cursor-not-allowed disabled:opacity-40 disabled:hover:border-[var(--border)]/50 disabled:hover:text-[var(--muted-foreground)]"
- >
- {t("Save to Notebook")}
- </button>
- <button
- onClick={handleDownloadMarkdown}
- disabled={!messages.length}
- title={t("Download chat history as Markdown")}
- className="rounded-lg border border-[var(--border)]/50 px-3 py-1.5 text-[12px] font-medium text-[var(--muted-foreground)] transition-colors hover:border-[var(--border)] hover:text-[var(--foreground)] disabled:cursor-not-allowed disabled:opacity-40 disabled:hover:border-[var(--border)]/50 disabled:hover:text-[var(--muted-foreground)]"
- >
- {t("Download Markdown")}
- </button>
- </div>
- </div>
-
- {/* Messages */}
- <div
- ref={scrollRef}
- className="flex-1 overflow-y-auto px-5 py-6 [scrollbar-gutter:stable]"
- >
- <div className="mx-auto max-w-[720px] space-y-5">
- {messages.length === 0 && !streaming && (
- <div className="flex flex-col items-center justify-center pt-24 text-center">
- <div className="mb-3 rounded-xl bg-[var(--muted)] p-3 text-[var(--muted-foreground)]">
- <Bot size={22} />
- </div>
- <p className="text-[14px] font-medium text-[var(--foreground)]">
- {t("Chat with {{name}}", { name: bot?.name ?? botId })}
- </p>
- <p className="mt-1 text-[13px] text-[var(--muted-foreground)]">
- {t("Send a message to start the conversation.")}
- </p>
- </div>
- )}
-
- {messages.map((msg, i) => (
- <div
- key={i}
- className={msg.role === "user" ? "flex justify-end" : ""}
- >
- {msg.role === "user" ? (
- <div className="max-w-[80%] rounded-2xl rounded-br-md bg-[var(--primary)] px-4 py-2.5 text-[14px] text-[var(--primary-foreground)]">
- {msg.content}
- </div>
- ) : (
- <div className="max-w-full">
- {msg.thinking && msg.thinking.length > 0 && (
- <details className="mb-2">
- <summary className="cursor-pointer text-[12px] text-[var(--muted-foreground)] hover:text-[var(--foreground)]">
- {t("Thinking ({{count}} steps)", {
- count: msg.thinking.length,
- })}
- </summary>
- <div className="mt-1 space-y-1 border-l-2 border-[var(--border)] pl-3">
- {msg.thinking.map((th, j) => (
- <p
- key={j}
- className="text-[12px] text-[var(--muted-foreground)]"
- >
- {th}
- </p>
- ))}
- </div>
- </details>
- )}
- <AssistantResponse content={msg.content} />
- </div>
- )}
- </div>
- ))}
-
- {/* Streaming indicator */}
- {streaming && (
- <div className="space-y-2">
- {thinking.length > 0 && (
- <div className="space-y-1 border-l-2 border-[var(--border)] pl-3">
- {thinking.map((th, i) => (
- <p
- key={i}
- className="text-[12px] text-[var(--muted-foreground)]"
- >
- {th}
- </p>
- ))}
- </div>
- )}
- <div className="flex items-center gap-2 text-[13px] text-[var(--muted-foreground)]">
- <Loader2 className="h-3.5 w-3.5 animate-spin" />
- <span>
- {thinking.length > 0 ? t("Working...") : t("Thinking...")}
- </span>
- </div>
- </div>
- )}
- </div>
- </div>
-
- {/* Input */}
- <div className="border-t border-[var(--border)] px-5 py-3">
- <div className="mx-auto flex max-w-[720px] items-end gap-2">
- <SimpleComposerInput
- textareaRef={inputRef}
- onSend={handleSend}
- disabled={streaming}
- />
- <button
- onClick={handleManualSend}
- disabled={streaming}
- className="flex h-[42px] w-[42px] items-center justify-center rounded-xl bg-[var(--primary)] text-[var(--primary-foreground)] transition-opacity hover:opacity-90 disabled:opacity-30"
- >
- <Send className="h-4 w-4" />
- </button>
- </div>
- </div>
-
- <SaveToNotebookModal
- open={showSaveModal}
- payload={notebookSavePayload}
- messages={notebookSaveMessages}
- onClose={handleCloseSaveModal}
- />
- </div>
- );
-}
diff --git a/web/app/(workspace)/agents/page.tsx b/web/app/(workspace)/agents/page.tsx
deleted file mode 100644
index 8ec1631f7..000000000
--- a/web/app/(workspace)/agents/page.tsx
+++ /dev/null
@@ -1,2202 +0,0 @@
-"use client";
-
-import { useCallback, useEffect, useMemo, useState } from "react";
-import {
- Bot,
- Eye,
- EyeOff,
- FileText,
- Heart,
- Loader2,
- MessageCircle,
- Pencil,
- Play,
- Plus,
- Save,
- Settings2,
- Square,
- Trash2,
- X,
-} from "lucide-react";
-import { useRouter } from "next/navigation";
-import { useTranslation } from "react-i18next";
-import dynamic from "next/dynamic";
-import { apiFetch, apiUrl } from "@/lib/api";
-import ModelSelector from "@/components/chat/home/ModelSelector";
-import {
- listLLMOptions,
- sameLLMSelection,
- type LLMOption,
-} from "@/lib/llm-options";
-import type { LLMSelection } from "@/lib/unified-ws";
-
-const MarkdownRenderer = dynamic(
- () => import("@/components/common/MarkdownRenderer"),
- {
- ssr: false,
- },
-);
-
-/* ── Types ──────────────────────────────────────────────── */
-
-interface BotInfo {
- bot_id: string;
- name: string;
- description: string;
- persona: string;
- /**
- * From `GET /tutorbot` (list): channel name keys only — never carries secrets.
- * The single-bot detail endpoint returns a richer dict; ChannelsTab fetches
- * it explicitly via `?include_secrets=true` and works with that shape directly,
- * so this list-shape type is sufficient here.
- */
- channels: string[];
- model: string | null;
- llm_selection?: LLMSelection | null;
- running: boolean;
- started_at: string | null;
- /** Set when a previous PATCH succeeded but `reload_channels` failed. */
- last_reload_error?: string | null;
-}
-
-interface SoulTemplate {
- id: string;
- name: string;
- content: string;
-}
-
-type Tab = "bots" | "profiles" | "channels" | "souls";
-
-const BOT_FILES = [
- "SOUL.md",
- "USER.md",
- "TOOLS.md",
- "AGENTS.md",
- "HEARTBEAT.md",
-] as const;
-type BotFile = (typeof BOT_FILES)[number];
-
-/* ── Main Page ──────────────────────────────────────────── */
-
-export default function AgentsPage() {
- const router = useRouter();
- const { t } = useTranslation();
- const [bots, setBots] = useState<BotInfo[]>([]);
- const [souls, setSouls] = useState<SoulTemplate[]>([]);
- const [loading, setLoading] = useState(true);
- const [activeTab, setActiveTab] = useState<Tab>("bots");
- const [toast, setToast] = useState("");
- const [llmOptions, setLLMOptions] = useState<LLMOption[]>([]);
- const [activeLLMDefault, setActiveLLMDefault] = useState<LLMSelection | null>(
- null,
- );
- const [llmOptionsLoading, setLLMOptionsLoading] = useState(true);
- const [llmOptionsError, setLLMOptionsError] = useState(false);
-
- useEffect(() => {
- if (!toast) return;
- const timer = setTimeout(() => setToast(""), 3500);
- return () => clearTimeout(timer);
- }, [toast]);
-
- const loadBots = useCallback(async () => {
- setLoading(true);
- try {
- const res = await apiFetch(apiUrl("/api/v1/tutorbot"));
- const data = await res.json();
- setBots(Array.isArray(data) ? data : (data.bots ?? []));
- } finally {
- setLoading(false);
- }
- }, []);
-
- const loadSouls = useCallback(async () => {
- try {
- const res = await apiFetch(apiUrl("/api/v1/tutorbot/souls"));
- if (res.ok) setSouls(await res.json());
- } catch {
- /* ignore */
- }
- }, []);
-
- const loadLLMOptions = useCallback(async () => {
- setLLMOptionsLoading(true);
- try {
- const payload = await listLLMOptions();
- setLLMOptions(payload.options);
- setActiveLLMDefault(payload.active);
- setLLMOptionsError(false);
- } catch {
- setLLMOptions([]);
- setActiveLLMDefault(null);
- setLLMOptionsError(true);
- } finally {
- setLLMOptionsLoading(false);
- }
- }, []);
-
- useEffect(() => {
- void loadBots();
- void loadSouls();
- void loadLLMOptions();
- }, [loadBots, loadSouls, loadLLMOptions]);
-
- return (
- <div className="h-full overflow-y-auto [scrollbar-gutter:stable]">
- <div className="mx-auto max-w-[960px] px-6 py-8">
- {/* Header */}
- <div className="mb-6">
- <h1 className="text-[24px] font-semibold tracking-tight text-[var(--foreground)]">
- {t("TutorBot Agents")}
- </h1>
- {toast ? (
- <p className="mt-1 text-[13px] text-[var(--primary)] animate-fade-in">
- {toast}
- </p>
- ) : (
- <p className="mt-1 text-[13px] text-[var(--muted-foreground)]">
- {t("Manage your in-process TutorBot instances")}
- </p>
- )}
- </div>
-
- {/* Tabs */}
- <div className="mb-6 flex items-center gap-1 border-b border-[var(--border)]/50 pb-3">
- {[
- { key: "bots" as Tab, label: t("Bots"), icon: Bot },
- { key: "profiles" as Tab, label: t("Profiles"), icon: FileText },
- { key: "channels" as Tab, label: t("Channels"), icon: Settings2 },
- { key: "souls" as Tab, label: t("Soul Templates"), icon: Heart },
- ].map((tab) => {
- const Icon = tab.icon;
- const active = activeTab === tab.key;
- return (
- <button
- key={tab.key}
- onClick={() => setActiveTab(tab.key)}
- className={`inline-flex items-center gap-1.5 rounded-lg px-3 py-1.5 text-[13px] transition-colors ${
- active
- ? "bg-[var(--muted)] font-medium text-[var(--foreground)]"
- : "text-[var(--muted-foreground)] hover:text-[var(--foreground)]"
- }`}
- >
- <Icon className="h-3.5 w-3.5" />
- {tab.label}
- </button>
- );
- })}
- </div>
-
- {activeTab === "bots" ? (
- <BotsTab
- bots={bots}
- souls={souls}
- loading={loading}
- llmOptions={llmOptions}
- activeLLMDefault={activeLLMDefault}
- llmOptionsLoading={llmOptionsLoading}
- llmOptionsError={llmOptionsError}
- onReload={loadBots}
- onToast={setToast}
- router={router}
- />
- ) : activeTab === "profiles" ? (
- <ProfilesTab
- bots={bots}
- souls={souls}
- loading={loading}
- onToast={setToast}
- onReloadSouls={loadSouls}
- />
- ) : activeTab === "channels" ? (
- <ChannelsTab
- bots={bots}
- loading={loading}
- onToast={setToast}
- onReload={loadBots}
- />
- ) : (
- <SoulsTab souls={souls} onReload={loadSouls} onToast={setToast} />
- )}
- </div>
- </div>
- );
-}
-
-/* ── Channels tab (schema-driven, all channels) ─────────── */
-
-/**
- * JSON-Schema fragment subset we actually consume. Pydantic emits richer
- * shapes (allOf / examples / formats) that we ignore — the form gracefully
- * falls back to a text input for anything it doesn't recognise.
- */
-type JsonSchema = {
- type?: string | string[];
- title?: string;
- description?: string;
- default?: unknown;
- enum?: unknown[];
- properties?: Record<string, JsonSchema>;
- items?: JsonSchema;
- anyOf?: JsonSchema[];
-};
-
-interface ChannelSchemaEntry {
- name: string;
- display_name: string;
- default_config: Record<string, unknown>;
- secret_fields: string[];
- json_schema: JsonSchema;
-}
-
-interface ChannelsSchemaResponse {
- channels: Record<string, ChannelSchemaEntry>;
- global: { json_schema: JsonSchema; secret_fields: string[] };
-}
-
-/** Pick the first non-null variant of an `anyOf` and merge its meta. */
-function resolveSchemaVariant(s: JsonSchema): JsonSchema {
- if (!s.anyOf) return s;
- const first = s.anyOf.find((v) => v.type !== "null") ?? s.anyOf[0];
- return {
- ...first,
- title: s.title ?? first.title,
- description: s.description ?? first.description,
- };
-}
-
-/** True iff this schema's value can be `null` (e.g. `Optional[str]`). */
-function isNullable(s: JsonSchema): boolean {
- if (Array.isArray(s.type) && s.type.includes("null")) return true;
- if (s.anyOf?.some((v) => v.type === "null")) return true;
- return false;
-}
-
-/** Default value for a property when the live config doesn't set it. */
-function defaultFor(s: JsonSchema): unknown {
- if (s.default !== undefined) return s.default;
- const v = resolveSchemaVariant(s);
- switch (v.type) {
- case "boolean":
- return false;
- case "integer":
- case "number":
- return 0;
- case "array":
- return [];
- case "object":
- return {};
- case "string":
- default:
- return "";
- }
-}
-
-/** Title-case a snake_case key when no `title` is provided. */
-function humaniseKey(k: string): string {
- return k.replace(/_/g, " ").replace(/\b\w/g, (c) => c.toUpperCase());
-}
-
-/** Generic field renderer — recursive for nested objects. */
-function SchemaField({
- fieldKey,
- schema,
- value,
- onChange,
- secretFields,
- path,
- showSecretFor,
- toggleSecret,
-}: {
- fieldKey: string;
- schema: JsonSchema;
- value: unknown;
- onChange: (next: unknown) => void;
- secretFields: Set<string>;
- path: string;
- showSecretFor: Set<string>;
- toggleSecret: (path: string) => void;
-}) {
- const v = resolveSchemaVariant(schema);
- const label = schema.title || v.title || humaniseKey(fieldKey);
- const description = schema.description || v.description;
- const isSecret = secretFields.has(path);
- const enumValues = (v.enum ?? schema.enum) as unknown[] | undefined;
-
- // Boolean → checkbox row (label inline).
- if (v.type === "boolean") {
- return (
- <label className="flex items-start gap-2 text-[13px]">
- <input
- type="checkbox"
- checked={!!value}
- onChange={(e) => onChange(e.target.checked)}
- className="mt-0.5"
- />
- <span>
- {label}
- {description && (
- <span className="ml-1 text-[11px] text-[var(--muted-foreground)]">
- — {description}
- </span>
- )}
- </span>
- </label>
- );
- }
-
- // Enum / Literal → select.
- if (Array.isArray(enumValues) && enumValues.length > 0) {
- return (
- <div>
- <FieldLabel label={label} description={description} />
- <select
- value={String(value ?? "")}
- onChange={(e) => onChange(e.target.value)}
- className="rounded-lg border border-[var(--border)] bg-transparent px-3 py-1.5 text-[13px] outline-none focus:border-[var(--ring)]"
- >
- {enumValues.map((opt) => (
- <option key={String(opt)} value={String(opt)}>
- {String(opt)}
- </option>
- ))}
- </select>
- </div>
- );
- }
-
- // Array of strings → textarea (one per line). For non-string arrays we
- // fall through to JSON editing below.
- if (v.type === "array" && (v.items?.type === "string" || !v.items)) {
- const lines = Array.isArray(value) ? (value as unknown[]).map(String) : [];
- return (
- <div>
- <FieldLabel
- label={label}
- description={description ?? "One value per line"}
- />
- <textarea
- value={lines.join("\n")}
- onChange={(e) =>
- onChange(
- e.target.value
- .split("\n")
- .map((s) => s.trim())
- .filter(Boolean),
- )
- }
- rows={Math.max(3, Math.min(8, lines.length + 1))}
- className="w-full rounded-lg border border-[var(--border)] bg-transparent px-3 py-2 font-mono text-[13px] outline-none focus:border-[var(--ring)]"
- />
- </div>
- );
- }
-
- // Nested object → recursive fieldset.
- if (v.type === "object" && v.properties) {
- const obj = (value && typeof value === "object" ? value : {}) as Record<
- string,
- unknown
- >;
- return (
- <fieldset className="rounded-lg border border-[var(--border)]/60 px-3 py-2.5 space-y-2.5">
- <legend className="px-1 text-[12px] font-medium text-[var(--muted-foreground)]">
- {label}
- </legend>
- {description && (
- <p className="text-[11px] text-[var(--muted-foreground)]">
- {description}
- </p>
- )}
- {Object.entries(v.properties).map(([k, child]) => (
- <SchemaField
- key={k}
- fieldKey={k}
- schema={child}
- value={obj[k] ?? defaultFor(child)}
- onChange={(next) => onChange({ ...obj, [k]: next })}
- secretFields={secretFields}
- path={path ? `${path}.${k}` : k}
- showSecretFor={showSecretFor}
- toggleSecret={toggleSecret}
- />
- ))}
- </fieldset>
- );
- }
-
- // Integer/number → number input.
- if (v.type === "integer" || v.type === "number") {
- return (
- <div>
- <FieldLabel label={label} description={description} />
- <input
- type="number"
- value={typeof value === "number" ? value : ""}
- onChange={(e) => {
- const raw = e.target.value;
- if (raw === "") onChange(isNullable(schema) ? null : 0);
- else
- onChange(
- v.type === "integer" ? parseInt(raw, 10) : parseFloat(raw),
- );
- }}
- className="w-40 rounded-lg border border-[var(--border)] bg-transparent px-3 py-1.5 text-[13px] outline-none focus:border-[var(--ring)]"
- />
- </div>
- );
- }
-
- // Default: string input (with secret reveal handling).
- const reveal = showSecretFor.has(path);
- const strVal = value == null ? "" : String(value);
- return (
- <div>
- <FieldLabel label={label} description={description} />
- <div className="relative">
- <input
- type={isSecret && !reveal ? "password" : "text"}
- autoComplete={isSecret ? "new-password" : "off"}
- spellCheck={!isSecret}
- value={strVal}
- onChange={(e) => {
- const next = e.target.value;
- // Empty optional strings persist as null (matches Pydantic's
- // `Optional[str]` default and avoids "" sneaking past validators).
- onChange(next === "" && isNullable(schema) ? null : next);
- }}
- className={`w-full rounded-lg border border-[var(--border)] bg-transparent py-2 pl-3 ${isSecret ? "pr-10 font-mono" : "pr-3"} text-[13px] outline-none focus:border-[var(--ring)]`}
- />
- {isSecret && (
- <button
- type="button"
- onClick={() => toggleSecret(path)}
- className="absolute right-1 top-1/2 -translate-y-1/2 rounded-md p-1.5 text-[var(--muted-foreground)] hover:bg-[var(--muted)] hover:text-[var(--foreground)]"
- aria-label={reveal ? "Hide secret" : "Show secret"}
- title={reveal ? "Hide secret" : "Show secret"}
- >
- {reveal ? (
- <EyeOff className="h-4 w-4" />
- ) : (
- <Eye className="h-4 w-4" />
- )}
- </button>
- )}
- </div>
- </div>
- );
-}
-
-function FieldLabel({
- label,
- description,
-}: {
- label: string;
- description?: string;
-}) {
- return (
- <label className="mb-1 block text-[12px] font-medium text-[var(--muted-foreground)]">
- {label}
- {description && (
- <span className="ml-1 font-normal opacity-70">— {description}</span>
- )}
- </label>
- );
-}
-
-function ChannelsTab({
- bots,
- loading,
- onToast,
- onReload,
-}: {
- bots: BotInfo[];
- loading: boolean;
- onToast: (msg: string) => void;
- onReload: () => Promise<void>;
-}) {
- const { t } = useTranslation();
- const [selectedBot, setSelectedBot] = useState("");
- const [schemaCatalog, setSchemaCatalog] =
- useState<ChannelsSchemaResponse | null>(null);
- const [channels, setChannels] = useState<Record<string, unknown>>({});
- const [activeChannel, setActiveChannel] = useState<string | null>(null);
- const [reloadError, setReloadError] = useState<string | null>(null);
- const [loadingDetail, setLoadingDetail] = useState(false);
- const [saving, setSaving] = useState(false);
- /** dot-paths of secrets the user has explicitly toggled to plaintext. */
- const [revealed, setRevealed] = useState<Set<string>>(new Set());
-
- // One-time fetch of the channel schema catalog. Cheap and never changes
- // at runtime (channels are discovered at process start).
- useEffect(() => {
- void (async () => {
- try {
- const res = await apiFetch(apiUrl("/api/v1/tutorbot/channels/schema"));
- if (res.ok) setSchemaCatalog(await res.json());
- } catch {
- /* leave catalog null → renders fallback message */
- }
- })();
- }, []);
-
- useEffect(() => {
- if (bots.length > 0 && !selectedBot) setSelectedBot(bots[0].bot_id);
- }, [bots, selectedBot]);
-
- useEffect(() => {
- setRevealed(new Set());
- setReloadError(null);
- }, [selectedBot]);
-
- const loadDetail = useCallback(async (bid: string) => {
- if (!bid) return;
- setLoadingDetail(true);
- try {
- // Edit form needs raw secrets to populate fields. Default GET masks them.
- const res = await apiFetch(
- apiUrl(`/api/v1/tutorbot/${bid}?include_secrets=true`),
- );
- if (!res.ok) return;
- const data = await res.json();
- const raw = (data.channels ?? {}) as Record<string, unknown>;
- // Surface globals as-is; per-channel dicts are passed straight to the
- // SchemaForm which handles per-field defaults from the JSON schema.
- setChannels({
- send_progress: raw.send_progress !== false,
- send_tool_hints: !!raw.send_tool_hints,
- ...Object.fromEntries(
- Object.entries(raw).filter(
- ([k]) => k !== "send_progress" && k !== "send_tool_hints",
- ),
- ),
- });
- setReloadError(
- typeof data.last_reload_error === "string"
- ? data.last_reload_error
- : null,
- );
- } finally {
- setLoadingDetail(false);
- }
- }, []);
-
- useEffect(() => {
- if (selectedBot) void loadDetail(selectedBot);
- }, [selectedBot, loadDetail]);
-
- // Pick a sensible default active channel: prefer one already enabled,
- // otherwise the first channel in the catalog.
- useEffect(() => {
- if (activeChannel || !schemaCatalog) return;
- const names = Object.keys(schemaCatalog.channels);
- const enabled = names.find((n) => {
- const cfg = channels[n];
- return (
- cfg &&
- typeof cfg === "object" &&
- (cfg as Record<string, unknown>).enabled === true
- );
- });
- setActiveChannel(enabled ?? names[0] ?? null);
- }, [schemaCatalog, channels, activeChannel]);
-
- const toggleSecret = useCallback((path: string) => {
- setRevealed((prev) => {
- const next = new Set(prev);
- if (next.has(path)) next.delete(path);
- else next.add(path);
- return next;
- });
- }, []);
-
- const setActiveChannelConfig = (next: unknown) => {
- if (!activeChannel) return;
- setChannels((prev) => ({ ...prev, [activeChannel]: next }));
- };
-
- const save = async () => {
- if (!selectedBot) return;
- setSaving(true);
- try {
- const res = await apiFetch(apiUrl(`/api/v1/tutorbot/${selectedBot}`), {
- method: "PATCH",
- headers: { "Content-Type": "application/json" },
- body: JSON.stringify({ channels }),
- });
- if (res.ok) {
- onToast(t("Channels saved"));
- await Promise.all([onReload(), loadDetail(selectedBot)]);
- } else if (res.status === 422) {
- const err = (await res.json().catch(() => ({}))) as {
- detail?: { message?: string; errors?: unknown } | string;
- };
- const detail = err.detail;
- const msg =
- typeof detail === "string"
- ? detail
- : (detail?.message ?? t("Invalid channel configuration"));
- onToast(msg);
- } else {
- const err = (await res.json().catch(() => ({}))) as { detail?: string };
- onToast(err.detail ?? t("Save failed"));
- }
- } finally {
- setSaving(false);
- }
- };
-
- if (loading) {
- return (
- <div className="flex min-h-[320px] items-center justify-center">
- <Loader2 className="h-5 w-5 animate-spin text-[var(--muted-foreground)]" />
- </div>
- );
- }
-
- if (bots.length === 0) {
- return (
- <div className="flex min-h-[320px] flex-col items-center justify-center rounded-xl border border-dashed border-[var(--border)] text-center">
- <p className="text-[14px] font-medium text-[var(--foreground)]">
- {t("No bots to configure")}
- </p>
- <p className="mt-1.5 max-w-xs text-[13px] text-[var(--muted-foreground)]">
- {t("Create a bot first in the Bots tab.")}
- </p>
- </div>
- );
- }
-
- const channelEntries = schemaCatalog
- ? Object.entries(schemaCatalog.channels).sort(([, a], [, b]) =>
- a.display_name.localeCompare(b.display_name),
- )
- : [];
- const activeEntry = activeChannel
- ? schemaCatalog?.channels[activeChannel]
- : undefined;
- const activeValue =
- activeChannel &&
- channels[activeChannel] &&
- typeof channels[activeChannel] === "object"
- ? (channels[activeChannel] as Record<string, unknown>)
- : (activeEntry?.default_config ?? {});
- const activeSecretSet = new Set(activeEntry?.secret_fields ?? []);
-
- return (
- <div className="space-y-5">
- <div className="flex flex-wrap items-center gap-3">
- <label className="text-[12px] font-medium text-[var(--muted-foreground)] shrink-0">
- {t("Bot")}
- </label>
- <select
- value={selectedBot}
- onChange={(e) => setSelectedBot(e.target.value)}
- className="rounded-lg border border-[var(--border)] bg-transparent px-3 py-1.5 text-[13px] text-[var(--foreground)] outline-none focus:border-[var(--ring)]"
- >
- {bots.map((b) => (
- <option key={b.bot_id} value={b.bot_id}>
- {b.name} ({b.bot_id})
- </option>
- ))}
- </select>
- <button
- type="button"
- onClick={() => void save()}
- disabled={saving || loadingDetail}
- className="inline-flex items-center gap-1.5 rounded-lg bg-[var(--primary)] px-3 py-1.5 text-[12px] font-medium text-[var(--primary-foreground)] disabled:opacity-40"
- >
- {saving ? (
- <Loader2 className="h-3.5 w-3.5 animate-spin" />
- ) : (
- <Save className="h-3.5 w-3.5" />
- )}
- {t("Save")}
- </button>
- </div>
-
- {reloadError && (
- <div className="rounded-lg border border-amber-500/40 bg-amber-500/10 px-3 py-2 text-[12px] text-amber-700 dark:text-amber-300">
- <strong className="font-medium">
- {t("Channel listeners failed to restart:")}
- </strong>{" "}
- <span className="font-mono">{reloadError}</span>{" "}
- <span className="opacity-80">
- {t("Config is saved on disk; stop and start the bot to apply.")}
- </span>
- </div>
- )}
-
- {loadingDetail || !schemaCatalog ? (
- <div className="flex justify-center py-8">
- <Loader2 className="h-5 w-5 animate-spin text-[var(--muted-foreground)]" />
- </div>
- ) : (
- <>
- {/* Globals (Delivery) */}
- <div className="rounded-xl border border-[var(--border)] p-4 space-y-3">
- <h3 className="text-[13px] font-medium text-[var(--foreground)]">
- {t("Delivery")}
- </h3>
- <label className="flex items-center gap-2 text-[13px]">
- <input
- type="checkbox"
- checked={!!channels.send_progress}
- onChange={(e) =>
- setChannels((c) => ({
- ...c,
- send_progress: e.target.checked,
- }))
- }
- />
- {t("Stream progress text to channels")}
- </label>
- <label className="flex items-center gap-2 text-[13px]">
- <input
- type="checkbox"
- checked={!!channels.send_tool_hints}
- onChange={(e) =>
- setChannels((c) => ({
- ...c,
- send_tool_hints: e.target.checked,
- }))
- }
- />
- {t("Stream tool hints to channels")}
- </label>
- </div>
-
- {/* Channel master-detail */}
- <div className="grid grid-cols-1 gap-4 md:grid-cols-[180px_1fr]">
- <aside className="rounded-xl border border-[var(--border)] p-2 h-fit">
- <ul className="space-y-0.5">
- {channelEntries.map(([name, entry]) => {
- const cfg = channels[name] as
- | Record<string, unknown>
- | undefined;
- const enabled = cfg?.enabled === true;
- const isActive = activeChannel === name;
- return (
- <li key={name}>
- <button
- type="button"
- onClick={() => setActiveChannel(name)}
- className={`group flex w-full items-center justify-between rounded-md px-2.5 py-1.5 text-left text-[13px] transition-colors ${
- isActive
- ? "bg-[var(--muted)] font-medium text-[var(--foreground)]"
- : "text-[var(--muted-foreground)] hover:text-[var(--foreground)]"
- }`}
- >
- <span className="truncate">{entry.display_name}</span>
- {enabled && (
- <span
- aria-label={t("Enabled")}
- title={t("Enabled")}
- className="ml-2 h-1.5 w-1.5 shrink-0 rounded-full bg-emerald-500"
- />
- )}
- </button>
- </li>
- );
- })}
- </ul>
- </aside>
-
- <section className="rounded-xl border border-[var(--border)] p-4 space-y-3">
- {!activeEntry ? (
- <p className="text-[13px] text-[var(--muted-foreground)]">
- {t("Select a channel.")}
- </p>
- ) : (
- <>
- <div className="flex items-baseline justify-between">
- <h3 className="text-[14px] font-medium text-[var(--foreground)]">
- {activeEntry.display_name}
- </h3>
- <code className="text-[11px] text-[var(--muted-foreground)]">
- {activeEntry.name}
- </code>
- </div>
- {activeEntry.json_schema.description && (
- <p className="text-[11px] text-[var(--muted-foreground)]">
- {activeEntry.json_schema.description}
- </p>
- )}
- {Object.entries(activeEntry.json_schema.properties ?? {}).map(
- ([k, child]) => (
- <SchemaField
- key={k}
- fieldKey={k}
- schema={child}
- value={activeValue[k] ?? defaultFor(child)}
- onChange={(next) =>
- setActiveChannelConfig({ ...activeValue, [k]: next })
- }
- secretFields={activeSecretSet}
- path={k}
- showSecretFor={revealed}
- toggleSecret={toggleSecret}
- />
- ),
- )}
- </>
- )}
- </section>
- </div>
- </>
- )}
- </div>
- );
-}
-
-/* ── Bots Tab ───────────────────────────────────────────── */
-
-function BotsTab({
- bots,
- souls,
- loading,
- llmOptions,
- activeLLMDefault,
- llmOptionsLoading,
- llmOptionsError,
- onReload,
- onToast,
- router,
-}: {
- bots: BotInfo[];
- souls: SoulTemplate[];
- loading: boolean;
- llmOptions: LLMOption[];
- activeLLMDefault: LLMSelection | null;
- llmOptionsLoading: boolean;
- llmOptionsError: boolean;
- onReload: () => Promise<void>;
- onToast: (msg: string) => void;
- router: ReturnType<typeof useRouter>;
-}) {
- const { t } = useTranslation();
- const [showCreate, setShowCreate] = useState(false);
- const [creating, setCreating] = useState(false);
-
- const [formName, setFormName] = useState("");
- const [formDesc, setFormDesc] = useState("");
- const [formSoulId, setFormSoulId] = useState("_custom");
- const [formSoul, setFormSoul] = useState("");
- const [formLLMSelection, setFormLLMSelection] = useState<LLMSelection | null>(
- null,
- );
- const [updatingModelBot, setUpdatingModelBot] = useState<string | null>(null);
-
- const resetForm = () => {
- setFormName("");
- setFormDesc("");
- setFormSoulId("_custom");
- setFormSoul("");
- setFormLLMSelection(null);
- };
-
- const botId = useMemo(() => {
- const trimmed = formName.trim();
- if (!trimmed) return "";
- const slug = trimmed
- .toLowerCase()
- .replace(/[^a-z0-9]+/g, "-")
- .replace(/^-|-$/g, "");
- if (slug) return slug;
- // Name has no ASCII alphanumerics (e.g. pure Chinese / Japanese).
- // Derive a deterministic ASCII fallback so the bot ID stays
- // filesystem- and URL-safe while the display name keeps its CJK form.
- let h = 0;
- for (let i = 0; i < trimmed.length; i++) {
- h = (h << 5) - h + trimmed.charCodeAt(i);
- h |= 0;
- }
- return `bot-${Math.abs(h).toString(36).padStart(6, "0").slice(0, 8)}`;
- }, [formName]);
-
- const selectSoul = (id: string) => {
- setFormSoulId(id);
- if (id !== "_custom") {
- const soul = souls.find((s) => s.id === id);
- if (soul) setFormSoul(soul.content);
- }
- };
-
- const createBot = useCallback(async () => {
- if (!botId) return;
- setCreating(true);
- try {
- const res = await apiFetch(apiUrl("/api/v1/tutorbot"), {
- method: "POST",
- headers: { "Content-Type": "application/json" },
- body: JSON.stringify({
- bot_id: botId,
- name: formName.trim(),
- description: formDesc.trim(),
- persona: formSoul.trim(),
- llm_selection: formLLMSelection,
- }),
- });
- if (res.ok) {
- onToast(`${formName.trim()} created`);
- setShowCreate(false);
- resetForm();
- await onReload();
- } else {
- const err = (await res.json().catch(() => ({}))) as {
- detail?: string | { message?: string };
- };
- const detail =
- typeof err.detail === "string"
- ? err.detail
- : (err.detail?.message ?? t("Failed to create bot"));
- onToast(detail);
- }
- } catch {
- onToast(t("Failed to create bot"));
- } finally {
- setCreating(false);
- }
- }, [
- botId,
- formName,
- formDesc,
- formSoul,
- formLLMSelection,
- onReload,
- onToast,
- t,
- ]);
-
- const updateBotModel = useCallback(
- async (bid: string, selection: LLMSelection | null) => {
- setUpdatingModelBot(bid);
- try {
- const res = await apiFetch(apiUrl(`/api/v1/tutorbot/${bid}`), {
- method: "PATCH",
- headers: { "Content-Type": "application/json" },
- body: JSON.stringify({
- llm_selection: selection,
- ...(selection ? {} : { model: "" }),
- }),
- });
- if (res.ok) {
- onToast(t("Model saved"));
- await onReload();
- } else {
- const err = (await res.json().catch(() => ({}))) as {
- detail?: string;
- };
- onToast(err.detail ?? t("Failed to save model"));
- }
- } catch {
- onToast(t("Failed to save model"));
- } finally {
- setUpdatingModelBot(null);
- }
- },
- [onReload, onToast, t],
- );
-
- const modelLabelFor = useCallback(
- (bot: BotInfo) => {
- const selected = bot.llm_selection
- ? llmOptions.find((option) =>
- sameLLMSelection(option, bot.llm_selection),
- )
- : null;
- if (selected) return selected.model_name || selected.model;
- if (bot.llm_selection) return t("Selected model");
- if (bot.model) return bot.model;
- return t("System default");
- },
- [llmOptions, t],
- );
-
- const startBot = useCallback(
- async (bid: string) => {
- const res = await apiFetch(apiUrl("/api/v1/tutorbot"), {
- method: "POST",
- headers: { "Content-Type": "application/json" },
- body: JSON.stringify({ bot_id: bid }),
- });
- if (res.ok) {
- onToast(`${bid} started`);
- await onReload();
- }
- },
- [onReload, onToast],
- );
-
- const stopBot = useCallback(
- async (bid: string) => {
- const res = await apiFetch(apiUrl(`/api/v1/tutorbot/${bid}`), {
- method: "DELETE",
- });
- if (res.ok) {
- onToast(`${bid} stopped`);
- await onReload();
- }
- },
- [onReload, onToast],
- );
-
- const destroyBot = useCallback(
- async (bid: string, name: string) => {
- if (
- !window.confirm(
- t('Permanently delete "{{name}}" ({{id}})? This cannot be undone.', {
- name,
- id: bid,
- }),
- )
- )
- return;
- const res = await apiFetch(apiUrl(`/api/v1/tutorbot/${bid}/destroy`), {
- method: "DELETE",
- });
- if (res.ok) {
- onToast(`${name} deleted`);
- await onReload();
- }
- },
- [onReload, onToast, t],
- );
-
- return (
- <>
- {/* New Bot button */}
- <div className="mb-4 flex justify-end">
- <button
- onClick={() => setShowCreate(true)}
- className="inline-flex items-center gap-1.5 rounded-lg border border-[var(--border)]/50 px-3 py-1.5 text-[12px] font-medium text-[var(--muted-foreground)] transition-colors hover:border-[var(--border)] hover:text-[var(--foreground)]"
- >
- <Plus className="h-3 w-3" />
- {t("New Bot")}
- </button>
- </div>
-
- {/* Create form */}
- {showCreate && (
- <div className="mb-6 rounded-xl border border-[var(--border)] p-5">
- <div className="mb-4 flex items-center justify-between">
- <h2 className="text-[15px] font-medium text-[var(--foreground)]">
- {t("Create TutorBot")}
- </h2>
- <button
- onClick={() => {
- setShowCreate(false);
- resetForm();
- }}
- className="text-[var(--muted-foreground)] hover:text-[var(--foreground)]"
- >
- <X className="h-4 w-4" />
- </button>
- </div>
- <div className="grid gap-3">
- <div>
- <label className="mb-1 block text-[12px] font-medium text-[var(--muted-foreground)]">
- {t("Name")}
- </label>
- <input
- value={formName}
- onChange={(e) => setFormName(e.target.value)}
- placeholder={t("e.g. Math Tutor")}
- className="w-full rounded-lg border border-[var(--border)] bg-transparent px-3 py-2 text-[13px] text-[var(--foreground)] outline-none focus:border-[var(--ring)] placeholder:text-[var(--muted-foreground)]/40"
- />
- {botId && (
- <p className="mt-1 text-[11px] text-[var(--muted-foreground)]">
- ID: {botId}
- </p>
- )}
- </div>
- <div>
- <label className="mb-1 block text-[12px] font-medium text-[var(--muted-foreground)]">
- {t("Description")}{" "}
- <span className="font-normal opacity-60">
- {t("(optional)")}
- </span>
- </label>
- <input
- value={formDesc}
- onChange={(e) => setFormDesc(e.target.value)}
- placeholder={t("A brief description of what this bot does")}
- className="w-full rounded-lg border border-[var(--border)] bg-transparent px-3 py-2 text-[13px] text-[var(--foreground)] outline-none focus:border-[var(--ring)] placeholder:text-[var(--muted-foreground)]/40"
- />
- </div>
- <div>
- <label className="mb-1 block text-[12px] font-medium text-[var(--muted-foreground)]">
- {t("Soul")}
- </label>
- <div className="flex flex-wrap gap-1.5 mb-2">
- <button
- onClick={() => selectSoul("_custom")}
- className={`rounded-md px-2.5 py-1 text-[12px] transition-colors ${
- formSoulId === "_custom"
- ? "bg-[var(--primary)] text-[var(--primary-foreground)]"
- : "bg-[var(--muted)] text-[var(--muted-foreground)] hover:text-[var(--foreground)]"
- }`}
- >
- {t("Custom")}
- </button>
- {souls.map((s) => (
- <button
- key={s.id}
- onClick={() => selectSoul(s.id)}
- className={`rounded-md px-2.5 py-1 text-[12px] transition-colors ${
- formSoulId === s.id
- ? "bg-[var(--primary)] text-[var(--primary-foreground)]"
- : "bg-[var(--muted)] text-[var(--muted-foreground)] hover:text-[var(--foreground)]"
- }`}
- >
- {s.name}
- </button>
- ))}
- </div>
- <textarea
- value={formSoul}
- onChange={(e) => {
- setFormSoul(e.target.value);
- setFormSoulId("_custom");
- }}
- placeholder={t(
- "Define the bot's personality, values, and communication style in markdown...",
- )}
- rows={8}
- className="w-full rounded-lg border border-[var(--border)] bg-transparent px-3 py-2 font-mono text-[13px] leading-6 text-[var(--foreground)] outline-none focus:border-[var(--ring)] placeholder:text-[var(--muted-foreground)]/40"
- />
- <p className="mt-1 text-[11px] text-[var(--muted-foreground)]/60">
- {t(
- "Pick a soul from the library above, or write your own. Manage the library in the Souls tab.",
- )}
- </p>
- </div>
- <div>
- <label className="mb-1 block text-[12px] font-medium text-[var(--muted-foreground)]">
- {t("Model")}{" "}
- <span className="font-normal opacity-60">
- {t("(optional)")}
- </span>
- </label>
- <ModelSelector
- options={llmOptions}
- activeDefault={activeLLMDefault}
- value={formLLMSelection}
- loading={llmOptionsLoading}
- error={llmOptionsError}
- allowSystemDefault
- helperText={t("Applies to this TutorBot")}
- placement="bottom"
- onChange={setFormLLMSelection}
- />
- <p className="mt-1 text-[11px] text-[var(--muted-foreground)]/60">
- {t(
- "Choose a configured Settings model, or keep the system default.",
- )}
- </p>
- </div>
- <div className="flex justify-end">
- <button
- onClick={createBot}
- disabled={creating || !botId}
- className="inline-flex items-center gap-1.5 rounded-lg bg-[var(--primary)] px-4 py-2 text-[13px] font-medium text-[var(--primary-foreground)] transition-opacity hover:opacity-90 disabled:opacity-40"
- >
- {creating ? (
- <Loader2 className="h-3.5 w-3.5 animate-spin" />
- ) : (
- <Play className="h-3.5 w-3.5" />
- )}
- {t("Create & Start")}
- </button>
- </div>
- </div>
- </div>
- )}
-
- {/* Bot list */}
- {loading ? (
- <div className="flex min-h-[320px] items-center justify-center">
- <Loader2 className="h-5 w-5 animate-spin text-[var(--muted-foreground)]" />
- </div>
- ) : bots.length === 0 ? (
- <div className="flex min-h-[320px] flex-col items-center justify-center rounded-xl border border-dashed border-[var(--border)] text-center">
- <div className="mb-3 rounded-xl bg-[var(--muted)] p-2.5 text-[var(--muted-foreground)]">
- <Bot size={18} />
- </div>
- <p className="text-[14px] font-medium text-[var(--foreground)]">
- {t("No TutorBots yet")}
- </p>
- <p className="mt-1.5 max-w-xs text-[13px] text-[var(--muted-foreground)]">
- {t("Create your first TutorBot to get started.")}
- </p>
- </div>
- ) : (
- <div className="grid gap-3">
- {bots.map((bot) => (
- <div
- key={bot.bot_id}
- className="flex items-center justify-between rounded-xl border border-[var(--border)] px-5 py-4 transition-colors hover:border-[var(--border)]"
- >
- <div className="flex items-center gap-4 min-w-0">
- <div
- className={`h-2 w-2 shrink-0 rounded-full ${bot.running ? "bg-emerald-500" : "bg-[var(--muted-foreground)]/30"}`}
- />
- <div className="min-w-0">
- <p className="text-[14px] font-medium text-[var(--foreground)] truncate">
- {bot.name}
- </p>
- <div className="mt-0.5 flex items-center gap-3 text-[12px] text-[var(--muted-foreground)]">
- {bot.description ? (
- <span className="truncate max-w-[300px]">
- {bot.description}
- </span>
- ) : (
- <span>{bot.bot_id}</span>
- )}
- <span>· {modelLabelFor(bot)}</span>
- {bot.started_at && (
- <span>
- ·{" "}
- {t("started {{time}}", {
- time: new Date(bot.started_at).toLocaleString(),
- })}
- </span>
- )}
- </div>
- </div>
- </div>
- <div className="flex items-center gap-2 shrink-0">
- <ModelSelector
- options={llmOptions}
- activeDefault={activeLLMDefault}
- value={bot.llm_selection ?? null}
- loading={llmOptionsLoading || updatingModelBot === bot.bot_id}
- error={llmOptionsError}
- allowSystemDefault
- helperText={t("Applies to this TutorBot")}
- placement="bottom"
- onChange={(selection) =>
- updateBotModel(bot.bot_id, selection)
- }
- />
- {bot.running ? (
- <>
- <button
- onClick={() => router.push(`/agents/${bot.bot_id}/chat`)}
- className="inline-flex items-center gap-1.5 rounded-lg border border-[var(--border)]/50 px-3 py-1.5 text-[12px] font-medium text-[var(--primary)] transition-colors hover:border-[var(--primary)]/50"
- >
- <MessageCircle className="h-3 w-3" />
- {t("Chat")}
- </button>
- <button
- onClick={() => stopBot(bot.bot_id)}
- className="inline-flex items-center gap-1.5 rounded-lg border border-[var(--border)]/50 px-3 py-1.5 text-[12px] font-medium text-red-400 transition-colors hover:border-red-400/50"
- >
- <Square className="h-3 w-3" />
- {t("Stop")}
- </button>
- </>
- ) : (
- <button
- onClick={() => startBot(bot.bot_id)}
- className="inline-flex items-center gap-1.5 rounded-lg border border-[var(--border)]/50 px-3 py-1.5 text-[12px] font-medium text-[var(--muted-foreground)] transition-colors hover:border-[var(--border)] hover:text-[var(--foreground)]"
- >
- <Play className="h-3 w-3" />
- {t("Start")}
- </button>
- )}
- <button
- onClick={() => destroyBot(bot.bot_id, bot.name)}
- className="inline-flex items-center justify-center rounded-lg border border-[var(--border)]/50 p-1.5 text-[var(--muted-foreground)]/50 transition-colors hover:border-red-400/50 hover:text-red-400"
- >
- <Trash2 className="h-3 w-3" />
- </button>
- </div>
- </div>
- ))}
- </div>
- )}
- </>
- );
-}
-
-/* ── Profiles Tab ───────────────────────────────────────── */
-
-function ProfilesTab({
- bots,
- souls,
- loading,
- onToast,
- onReloadSouls,
-}: {
- bots: BotInfo[];
- souls: SoulTemplate[];
- loading: boolean;
- onToast: (msg: string) => void;
- onReloadSouls: () => Promise<void>;
-}) {
- const { t } = useTranslation();
- const [selectedBot, setSelectedBot] = useState<string>("");
- const [activeFile, setActiveFile] = useState<BotFile>("SOUL.md");
- const [files, setFiles] = useState<Record<string, string>>({});
- const [editor, setEditor] = useState("");
- const [selectedSoulId, setSelectedSoulId] = useState("_custom");
- const [sourceSoulId, setSourceSoulId] = useState<string | null>(null);
- const [loadingFiles, setLoadingFiles] = useState(false);
- const [saving, setSaving] = useState(false);
- const [saveModalOpen, setSaveModalOpen] = useState(false);
- const [saveMode, setSaveMode] = useState<
- "file_only" | "update_template" | "new_template"
- >("file_only");
- const [newTemplateName, setNewTemplateName] = useState("");
- const [replaceModalOpen, setReplaceModalOpen] = useState(false);
- const [pendingSoulId, setPendingSoulId] = useState<string | null>(null);
- const [activeView, setActiveView] = useState<"edit" | "preview">("edit");
-
- const hasChanges = editor !== (files[activeFile] ?? "");
- const activeSoulTemplate = useMemo(
- () => souls.find((s) => s.id === selectedSoulId) ?? null,
- [souls, selectedSoulId],
- );
- const sourceSoulTemplate = useMemo(
- () => souls.find((s) => s.id === sourceSoulId) ?? null,
- [souls, sourceSoulId],
- );
-
- const matchSoulId = useCallback(
- (content: string): string =>
- souls.find((s) => s.content === content)?.id ?? "_custom",
- [souls],
- );
-
- useEffect(() => {
- if (bots.length > 0 && !selectedBot) {
- setSelectedBot(bots[0].bot_id);
- }
- }, [bots, selectedBot]);
-
- const loadFiles = useCallback(
- async (bid: string) => {
- if (!bid) return;
- setLoadingFiles(true);
- try {
- const res = await apiFetch(apiUrl(`/api/v1/tutorbot/${bid}/files`));
- const data: Record<string, string> = await res.json();
- setFiles(data);
- setEditor(data[activeFile] ?? "");
- const matched = matchSoulId(data["SOUL.md"] ?? "");
- setSelectedSoulId(matched);
- setSourceSoulId(matched === "_custom" ? null : matched);
- } finally {
- setLoadingFiles(false);
- }
- },
- [activeFile, matchSoulId],
- );
-
- useEffect(() => {
- if (selectedBot) void loadFiles(selectedBot);
- }, [selectedBot, loadFiles]);
-
- useEffect(() => {
- setEditor(files[activeFile] ?? "");
- if (activeFile === "SOUL.md") {
- const matched = matchSoulId(files["SOUL.md"] ?? "");
- setSelectedSoulId(matched);
- setSourceSoulId(matched === "_custom" ? null : matched);
- }
- setActiveView("edit");
- }, [activeFile, files, matchSoulId]);
-
- const applySoulSelection = useCallback(
- (nextId: string) => {
- if (nextId === "_custom") {
- setSelectedSoulId("_custom");
- setSourceSoulId(null);
- return;
- }
- const soul = souls.find((s) => s.id === nextId);
- if (!soul) return;
- setSelectedSoulId(nextId);
- setSourceSoulId(nextId);
- setEditor(soul.content);
- },
- [souls],
- );
-
- const handleSoulSelect = useCallback(
- (nextId: string) => {
- if (hasChanges) {
- setPendingSoulId(nextId);
- setReplaceModalOpen(true);
- return;
- }
- applySoulSelection(nextId);
- },
- [applySoulSelection, hasChanges],
- );
-
- const saveFile = useCallback(
- async (
- mode: "file_only" | "update_template" | "new_template",
- createTemplateName?: string,
- ) => {
- if (!selectedBot) return false;
- setSaving(true);
- try {
- if (activeFile === "SOUL.md") {
- const content = editor.trim();
- if (!content) {
- onToast(t("SOUL.md is empty"));
- return false;
- }
- if (mode === "update_template") {
- if (!sourceSoulTemplate) {
- onToast(t("No template selected to update"));
- return false;
- }
- const tplRes = await apiFetch(
- apiUrl(`/api/v1/tutorbot/souls/${sourceSoulTemplate.id}`),
- {
- method: "PUT",
- headers: { "Content-Type": "application/json" },
- body: JSON.stringify({
- name: sourceSoulTemplate.name,
- content: editor,
- }),
- },
- );
- if (!tplRes.ok) {
- onToast(t("Failed to update soul template"));
- return false;
- }
- await onReloadSouls();
- setSelectedSoulId(sourceSoulTemplate.id);
- setSourceSoulId(sourceSoulTemplate.id);
- } else if (mode === "new_template") {
- const rawName = (createTemplateName ?? "").trim();
- if (!rawName) {
- onToast(t("Template name is required"));
- return false;
- }
- const baseId = rawName
- .toLowerCase()
- .replace(/[^a-z0-9]+/g, "-")
- .replace(/^-|-$/g, "");
- if (!baseId) {
- onToast(t("Please choose a name with letters or numbers"));
- return false;
- }
- const existing = new Set(souls.map((s) => s.id));
- let soulId = baseId;
- let n = 2;
- while (existing.has(soulId)) {
- soulId = `${baseId}-${n}`;
- n += 1;
- }
- const tplRes = await apiFetch(apiUrl("/api/v1/tutorbot/souls"), {
- method: "POST",
- headers: { "Content-Type": "application/json" },
- body: JSON.stringify({
- id: soulId,
- name: rawName,
- content: editor,
- }),
- });
- if (tplRes.status === 409) {
- onToast(
- t("A soul with this id already exists, try another name"),
- );
- return false;
- }
- if (!tplRes.ok) {
- onToast(t("Failed to save soul template"));
- return false;
- }
- await onReloadSouls();
- setSelectedSoulId(soulId);
- setSourceSoulId(soulId);
- }
- }
-
- const res = await apiFetch(
- apiUrl(`/api/v1/tutorbot/${selectedBot}/files/${activeFile}`),
- {
- method: "PUT",
- headers: { "Content-Type": "application/json" },
- body: JSON.stringify({ content: editor }),
- },
- );
- if (res.ok) {
- setFiles((prev) => ({ ...prev, [activeFile]: editor }));
- if (activeFile === "SOUL.md") {
- const personaRes = await apiFetch(
- apiUrl(`/api/v1/tutorbot/${selectedBot}`),
- {
- method: "PATCH",
- headers: { "Content-Type": "application/json" },
- body: JSON.stringify({ persona: editor }),
- },
- );
- if (!personaRes.ok) {
- onToast(t("SOUL.md saved, but persona sync failed"));
- return false;
- }
- }
- onToast(`${activeFile} saved`);
- return true;
- }
- return false;
- } finally {
- setSaving(false);
- }
- },
- [
- selectedBot,
- activeFile,
- editor,
- onToast,
- onReloadSouls,
- sourceSoulTemplate,
- souls,
- t,
- ],
- );
-
- const handleSaveClick = useCallback(() => {
- if (activeFile !== "SOUL.md") {
- void saveFile("file_only");
- return;
- }
- setSaveMode(sourceSoulTemplate ? "update_template" : "file_only");
- setNewTemplateName(`${selectedBot || "custom"} soul`);
- setSaveModalOpen(true);
- }, [activeFile, saveFile, selectedBot, sourceSoulTemplate]);
-
- const handleConfirmSave = useCallback(async () => {
- const ok = await saveFile(saveMode, newTemplateName);
- if (ok) setSaveModalOpen(false);
- }, [newTemplateName, saveFile, saveMode]);
-
- const handleKeyDown = useCallback(
- (e: React.KeyboardEvent<HTMLTextAreaElement>) => {
- if ((e.metaKey || e.ctrlKey) && e.key === "s") {
- e.preventDefault();
- handleSaveClick();
- }
- },
- [handleSaveClick],
- );
-
- if (loading) {
- return (
- <div className="flex min-h-[320px] items-center justify-center">
- <Loader2 className="h-5 w-5 animate-spin text-[var(--muted-foreground)]" />
- </div>
- );
- }
-
- if (bots.length === 0) {
- return (
- <div className="flex min-h-[320px] flex-col items-center justify-center rounded-xl border border-dashed border-[var(--border)] text-center">
- <div className="mb-3 rounded-xl bg-[var(--muted)] p-2.5 text-[var(--muted-foreground)]">
- <FileText size={18} />
- </div>
- <p className="text-[14px] font-medium text-[var(--foreground)]">
- {t("No bots to configure")}
- </p>
- <p className="mt-1.5 max-w-xs text-[13px] text-[var(--muted-foreground)]">
- {t("Create a bot first in the Bots tab.")}
- </p>
- </div>
- );
- }
-
- return (
- <div className="space-y-4">
- {/* Bot selector */}
- <div className="flex items-center gap-3">
- <label className="text-[12px] font-medium text-[var(--muted-foreground)] shrink-0">
- {t("Bot")}
- </label>
- <select
- value={selectedBot}
- onChange={(e) => setSelectedBot(e.target.value)}
- className="rounded-lg border border-[var(--border)] bg-transparent px-3 py-1.5 text-[13px] text-[var(--foreground)] outline-none focus:border-[var(--ring)]"
- >
- {bots.map((b) => (
- <option key={b.bot_id} value={b.bot_id}>
- {b.name} ({b.bot_id})
- </option>
- ))}
- </select>
- </div>
-
- {/* File tabs */}
- <div className="flex items-center gap-1 border-b border-[var(--border)]/50 pb-2">
- {BOT_FILES.map((fn) => (
- <button
- key={fn}
- onClick={() => setActiveFile(fn)}
- className={`rounded-lg px-2.5 py-1 text-[12px] transition-colors ${
- activeFile === fn
- ? "bg-[var(--muted)] font-medium text-[var(--foreground)]"
- : "text-[var(--muted-foreground)] hover:text-[var(--foreground)]"
- }`}
- >
- {fn.replace(".md", "")}
- </button>
- ))}
- </div>
-
- {/* Toolbar */}
- <div className="flex items-center justify-between">
- <div className="flex items-center gap-2">
- {(["edit", "preview"] as const).map((v) => (
- <button
- key={v}
- onClick={() => setActiveView(v)}
- className={`rounded-lg px-3 py-1.5 text-[12px] transition-colors ${
- activeView === v
- ? "bg-[var(--muted)] font-medium text-[var(--foreground)]"
- : "text-[var(--muted-foreground)] hover:text-[var(--foreground)]"
- }`}
- >
- {v === "edit" ? t("Edit") : t("Preview")}
- </button>
- ))}
- {activeFile === "SOUL.md" && (
- <>
- <select
- value={selectedSoulId}
- onChange={(e) => handleSoulSelect(e.target.value)}
- className="rounded-lg border border-[var(--border)] bg-transparent px-2.5 py-1.5 text-[12px] text-[var(--foreground)] outline-none focus:border-[var(--ring)]"
- >
- <option value="_custom">{t("Custom")}</option>
- {souls.map((soul) => (
- <option key={soul.id} value={soul.id}>
- {soul.name}
- </option>
- ))}
- </select>
- {activeSoulTemplate && (
- <span className="text-[11px] text-[var(--muted-foreground)]/70">
- {hasChanges
- ? t('Editing template "{{name}}"', {
- name: activeSoulTemplate.name,
- })
- : t('Using "{{name}}"', { name: activeSoulTemplate.name })}
- </span>
- )}
- {!activeSoulTemplate && (
- <span className="text-[11px] text-[var(--muted-foreground)]/70">
- {t("Custom soul")}
- </span>
- )}
- </>
- )}
- </div>
- <button
- onClick={handleSaveClick}
- disabled={saving || !hasChanges}
- className={`inline-flex items-center gap-1.5 rounded-lg px-3 py-1.5 text-[12px] font-medium transition-colors disabled:opacity-40 ${
- hasChanges
- ? "bg-[var(--primary)] text-[var(--primary-foreground)] hover:opacity-90"
- : "border border-[var(--border)]/50 text-[var(--muted-foreground)]"
- }`}
- >
- {saving ? (
- <Loader2 className="h-3 w-3 animate-spin" />
- ) : (
- <Save className="h-3 w-3" />
- )}
- {t("Save")}
- </button>
- </div>
-
- {/* Editor / Preview */}
- {loadingFiles ? (
- <div className="flex min-h-[400px] items-center justify-center">
- <Loader2 className="h-5 w-5 animate-spin text-[var(--muted-foreground)]" />
- </div>
- ) : activeView === "edit" ? (
- <div>
- <textarea
- value={editor}
- onChange={(e) => {
- const next = e.target.value;
- setEditor(next);
- }}
- onKeyDown={handleKeyDown}
- spellCheck={false}
- className="min-h-[420px] w-full resize-none rounded-xl border border-[var(--border)] bg-transparent px-5 py-4 font-mono text-[13px] leading-7 text-[var(--foreground)] outline-none transition-colors focus:border-[var(--ring)] placeholder:text-[var(--muted-foreground)]/40"
- placeholder={t("Edit {{file}}...", { file: activeFile })}
- />
- <p className="mt-2 text-[11px] text-[var(--muted-foreground)]/40">
- {t("Cmd+S to save · Markdown supported")}
- {hasChanges && ` · ${t("Unsaved changes")}`}
- </p>
- </div>
- ) : editor.trim() ? (
- <div className="rounded-xl border border-[var(--border)] px-6 py-5">
- <MarkdownRenderer
- content={editor}
- variant="prose"
- className="text-[14px] leading-relaxed"
- />
- </div>
- ) : (
- <div className="flex min-h-[300px] flex-col items-center justify-center rounded-xl border border-dashed border-[var(--border)] text-center">
- <p className="text-[14px] font-medium text-[var(--foreground)]">
- {t("{{file}} is empty", { file: activeFile })}
- </p>
- <p className="mt-1 text-[13px] text-[var(--muted-foreground)]">
- {t("Switch to Edit to add content.")}
- </p>
- </div>
- )}
- {saveModalOpen && activeFile === "SOUL.md" && (
- <div className="fixed inset-0 z-50 flex items-center justify-center bg-[var(--overlay)] px-4">
- <div className="w-full max-w-md rounded-xl border border-[var(--border)] bg-[var(--background)] p-5 shadow-xl">
- <h3 className="text-[15px] font-medium text-[var(--foreground)]">
- {t("Save SOUL.md")}
- </h3>
- <p className="mt-1 text-[12px] text-[var(--muted-foreground)]">
- {t(
- "Choose whether to only save this bot profile, overwrite the selected template, or save your edits as a new template.",
- )}
- </p>
-
- <div className="mt-4 space-y-2">
- <label className="flex items-center gap-2 text-[12px] text-[var(--foreground)]">
- <input
- type="radio"
- name="save-mode"
- checked={saveMode === "file_only"}
- onChange={() => setSaveMode("file_only")}
- />
- {t("Save profile only")}
- </label>
- {sourceSoulTemplate && (
- <label className="flex items-center gap-2 text-[12px] text-[var(--foreground)]">
- <input
- type="radio"
- name="save-mode"
- checked={saveMode === "update_template"}
- onChange={() => setSaveMode("update_template")}
- />
- {t('Save and overwrite template "{{name}}"', {
- name: sourceSoulTemplate.name,
- })}
- </label>
- )}
- <label className="flex items-center gap-2 text-[12px] text-[var(--foreground)]">
- <input
- type="radio"
- name="save-mode"
- checked={saveMode === "new_template"}
- onChange={() => setSaveMode("new_template")}
- />
- {t("Save and create new template")}
- </label>
- </div>
-
- {saveMode === "new_template" && (
- <div className="mt-4">
- <label className="mb-1 block text-[12px] font-medium text-[var(--muted-foreground)]">
- {t("Template name")}
- </label>
- <input
- value={newTemplateName}
- onChange={(e) => setNewTemplateName(e.target.value)}
- placeholder={t("e.g. IELTS Mentor")}
- className="w-full rounded-lg border border-[var(--border)] bg-transparent px-3 py-2 text-[13px] text-[var(--foreground)] outline-none focus:border-[var(--ring)] placeholder:text-[var(--muted-foreground)]/40"
- />
- </div>
- )}
-
- <div className="mt-5 flex items-center justify-end gap-2">
- <button
- onClick={() => setSaveModalOpen(false)}
- disabled={saving}
- className="rounded-lg border border-[var(--border)]/50 px-3 py-1.5 text-[12px] text-[var(--muted-foreground)] transition-colors hover:text-[var(--foreground)] disabled:opacity-40"
- >
- {t("Cancel")}
- </button>
- <button
- onClick={handleConfirmSave}
- disabled={
- saving ||
- (saveMode === "new_template" && !newTemplateName.trim())
- }
- className="inline-flex items-center gap-1.5 rounded-lg bg-[var(--primary)] px-3 py-1.5 text-[12px] font-medium text-[var(--primary-foreground)] transition-opacity hover:opacity-90 disabled:opacity-40"
- >
- {saving ? (
- <Loader2 className="h-3 w-3 animate-spin" />
- ) : (
- <Save className="h-3 w-3" />
- )}
- {saveMode === "update_template"
- ? t("Save and overwrite")
- : saveMode === "new_template"
- ? t("Save and create")
- : t("Save profile")}
- </button>
- </div>
- </div>
- </div>
- )}
- {replaceModalOpen && activeFile === "SOUL.md" && (
- <div className="fixed inset-0 z-50 flex items-center justify-center bg-[var(--overlay)] px-4">
- <div className="w-full max-w-md rounded-xl border border-[var(--border)] bg-[var(--background)] p-5 shadow-xl">
- <h3 className="text-[15px] font-medium text-[var(--foreground)]">
- {t("Replace SOUL.md content?")}
- </h3>
- <p className="mt-1 text-[12px] text-[var(--muted-foreground)]">
- {t(
- "You have unsaved changes. Switching templates will replace the current editor content.",
- )}
- </p>
- <div className="mt-5 flex items-center justify-end gap-2">
- <button
- onClick={() => {
- setReplaceModalOpen(false);
- setPendingSoulId(null);
- }}
- className="rounded-lg border border-[var(--border)]/50 px-3 py-1.5 text-[12px] text-[var(--muted-foreground)] transition-colors hover:text-[var(--foreground)]"
- >
- {t("Cancel")}
- </button>
- <button
- onClick={() => {
- if (pendingSoulId) applySoulSelection(pendingSoulId);
- setReplaceModalOpen(false);
- setPendingSoulId(null);
- }}
- className="inline-flex items-center gap-1.5 rounded-lg bg-[var(--primary)] px-3 py-1.5 text-[12px] font-medium text-[var(--primary-foreground)] transition-opacity hover:opacity-90"
- >
- {t("Replace")}
- </button>
- </div>
- </div>
- </div>
- )}
- </div>
- );
-}
-
-/* ── Souls Tab ──────────────────────────────────────────── */
-
-function SoulsTab({
- souls,
- onReload,
- onToast,
-}: {
- souls: SoulTemplate[];
- onReload: () => Promise<void>;
- onToast: (msg: string) => void;
-}) {
- const { t } = useTranslation();
- const [editing, setEditing] = useState<string | null>(null);
- const [creating, setCreating] = useState(false);
- const [saving, setSaving] = useState(false);
-
- const [editName, setEditName] = useState("");
- const [editContent, setEditContent] = useState("");
- const [newName, setNewName] = useState("");
- const [newContent, setNewContent] = useState("");
-
- const startEdit = (soul: SoulTemplate) => {
- setEditing(soul.id);
- setEditName(soul.name);
- setEditContent(soul.content);
- setCreating(false);
- };
-
- const cancelEdit = () => {
- setEditing(null);
- setEditName("");
- setEditContent("");
- };
-
- const startCreate = () => {
- setCreating(true);
- setEditing(null);
- setNewName("");
- setNewContent("");
- };
-
- const saveSoul = useCallback(async () => {
- if (!editing) return;
- setSaving(true);
- try {
- const res = await apiFetch(apiUrl(`/api/v1/tutorbot/souls/${editing}`), {
- method: "PUT",
- headers: { "Content-Type": "application/json" },
- body: JSON.stringify({ name: editName.trim(), content: editContent }),
- });
- if (res.ok) {
- onToast(`"${editName.trim()}" updated`);
- cancelEdit();
- await onReload();
- }
- } finally {
- setSaving(false);
- }
- }, [editing, editName, editContent, onReload, onToast]);
-
- const createSoul = useCallback(async () => {
- const name = newName.trim();
- if (!name) return;
- const id = name
- .toLowerCase()
- .replace(/[^a-z0-9]+/g, "-")
- .replace(/^-|-$/g, "");
- if (!id) return;
- setSaving(true);
- try {
- const res = await apiFetch(apiUrl("/api/v1/tutorbot/souls"), {
- method: "POST",
- headers: { "Content-Type": "application/json" },
- body: JSON.stringify({ id, name, content: newContent }),
- });
- if (res.ok) {
- onToast(`"${name}" created`);
- setCreating(false);
- setNewName("");
- setNewContent("");
- await onReload();
- } else if (res.status === 409) {
- onToast(`Soul ID "${id}" already exists`);
- }
- } finally {
- setSaving(false);
- }
- }, [newName, newContent, onReload, onToast]);
-
- const deleteSoul = useCallback(
- async (soul: SoulTemplate) => {
- if (!window.confirm(t('Delete soul "{{name}}"?', { name: soul.name })))
- return;
- const res = await apiFetch(apiUrl(`/api/v1/tutorbot/souls/${soul.id}`), {
- method: "DELETE",
- });
- if (res.ok) {
- if (editing === soul.id) cancelEdit();
- onToast(`"${soul.name}" deleted`);
- await onReload();
- }
- },
- [editing, onReload, onToast, t],
- );
-
- const handleKeyDown = useCallback(
- (e: React.KeyboardEvent<HTMLTextAreaElement>, save: () => void) => {
- if ((e.metaKey || e.ctrlKey) && e.key === "s") {
- e.preventDefault();
- save();
- }
- },
- [],
- );
-
- return (
- <div className="space-y-4">
- {/* Header */}
- <div className="flex items-center justify-between">
- <p className="text-[13px] text-[var(--muted-foreground)]">
- {t("Reusable soul templates for creating TutorBots.")}
- </p>
- <button
- onClick={startCreate}
- className="inline-flex items-center gap-1.5 rounded-lg border border-[var(--border)]/50 px-3 py-1.5 text-[12px] font-medium text-[var(--muted-foreground)] transition-colors hover:border-[var(--border)] hover:text-[var(--foreground)]"
- >
- <Plus className="h-3 w-3" />
- {t("New Soul")}
- </button>
- </div>
-
- {/* Create form */}
- {creating && (
- <div className="rounded-xl border border-[var(--border)] p-5">
- <div className="mb-4 flex items-center justify-between">
- <h2 className="text-[15px] font-medium text-[var(--foreground)]">
- {t("New Soul")}
- </h2>
- <button
- onClick={() => setCreating(false)}
- className="text-[var(--muted-foreground)] hover:text-[var(--foreground)]"
- >
- <X className="h-4 w-4" />
- </button>
- </div>
- <div className="grid gap-3">
- <div>
- <label className="mb-1 block text-[12px] font-medium text-[var(--muted-foreground)]">
- {t("Name")}
- </label>
- <input
- value={newName}
- onChange={(e) => setNewName(e.target.value)}
- placeholder={t("e.g. Creative Writer")}
- className="w-full rounded-lg border border-[var(--border)] bg-transparent px-3 py-2 text-[13px] text-[var(--foreground)] outline-none focus:border-[var(--ring)] placeholder:text-[var(--muted-foreground)]/40"
- />
- {newName.trim() && (
- <p className="mt-1 text-[11px] text-[var(--muted-foreground)]">
- ID:{" "}
- {newName
- .trim()
- .toLowerCase()
- .replace(/[^a-z0-9]+/g, "-")
- .replace(/^-|-$/g, "")}
- </p>
- )}
- </div>
- <div>
- <label className="mb-1 block text-[12px] font-medium text-[var(--muted-foreground)]">
- {t("Content")}
- </label>
- <textarea
- value={newContent}
- onChange={(e) => setNewContent(e.target.value)}
- onKeyDown={(e) => handleKeyDown(e, createSoul)}
- placeholder={t("Define the soul in markdown...")}
- rows={10}
- spellCheck={false}
- className="w-full rounded-lg border border-[var(--border)] bg-transparent px-3 py-2 font-mono text-[13px] leading-6 text-[var(--foreground)] outline-none focus:border-[var(--ring)] placeholder:text-[var(--muted-foreground)]/40"
- />
- </div>
- <div className="flex justify-end gap-2">
- <button
- onClick={() => setCreating(false)}
- className="rounded-lg px-3 py-1.5 text-[12px] text-[var(--muted-foreground)] hover:text-[var(--foreground)]"
- >
- {t("Cancel")}
- </button>
- <button
- onClick={createSoul}
- disabled={saving || !newName.trim()}
- className="inline-flex items-center gap-1.5 rounded-lg bg-[var(--primary)] px-4 py-2 text-[13px] font-medium text-[var(--primary-foreground)] transition-opacity hover:opacity-90 disabled:opacity-40"
- >
- {saving ? (
- <Loader2 className="h-3.5 w-3.5 animate-spin" />
- ) : (
- <Plus className="h-3.5 w-3.5" />
- )}
- {t("Create")}
- </button>
- </div>
- </div>
- </div>
- )}
-
- {/* Soul list */}
- {souls.length === 0 && !creating ? (
- <div className="flex min-h-[320px] flex-col items-center justify-center rounded-xl border border-dashed border-[var(--border)] text-center">
- <div className="mb-3 rounded-xl bg-[var(--muted)] p-2.5 text-[var(--muted-foreground)]">
- <Heart size={18} />
- </div>
- <p className="text-[14px] font-medium text-[var(--foreground)]">
- {t("No souls yet")}
- </p>
- <p className="mt-1.5 max-w-xs text-[13px] text-[var(--muted-foreground)]">
- {t(
- "Create your first soul template. Default presets will be seeded automatically on next server restart.",
- )}
- </p>
- </div>
- ) : (
- <div className="grid gap-3">
- {souls.map((soul) =>
- editing === soul.id ? (
- <div
- key={soul.id}
- className="rounded-xl border border-[var(--ring)] p-5"
- >
- <div className="grid gap-3">
- <div>
- <label className="mb-1 block text-[12px] font-medium text-[var(--muted-foreground)]">
- {t("Name")}
- </label>
- <input
- value={editName}
- onChange={(e) => setEditName(e.target.value)}
- className="w-full rounded-lg border border-[var(--border)] bg-transparent px-3 py-2 text-[13px] text-[var(--foreground)] outline-none focus:border-[var(--ring)]"
- />
- </div>
- <div>
- <label className="mb-1 block text-[12px] font-medium text-[var(--muted-foreground)]">
- {t("Content")}
- </label>
- <textarea
- value={editContent}
- onChange={(e) => setEditContent(e.target.value)}
- onKeyDown={(e) => handleKeyDown(e, saveSoul)}
- rows={12}
- spellCheck={false}
- className="w-full rounded-lg border border-[var(--border)] bg-transparent px-3 py-2 font-mono text-[13px] leading-6 text-[var(--foreground)] outline-none focus:border-[var(--ring)]"
- />
- </div>
- <div className="flex justify-end gap-2">
- <button
- onClick={cancelEdit}
- className="rounded-lg px-3 py-1.5 text-[12px] text-[var(--muted-foreground)] hover:text-[var(--foreground)]"
- >
- {t("Cancel")}
- </button>
- <button
- onClick={saveSoul}
- disabled={saving || !editName.trim()}
- className="inline-flex items-center gap-1.5 rounded-lg bg-[var(--primary)] px-4 py-2 text-[13px] font-medium text-[var(--primary-foreground)] transition-opacity hover:opacity-90 disabled:opacity-40"
- >
- {saving ? (
- <Loader2 className="h-3.5 w-3.5 animate-spin" />
- ) : (
- <Save className="h-3.5 w-3.5" />
- )}
- {t("Save")}
- </button>
- </div>
- </div>
- </div>
- ) : (
- <div
- key={soul.id}
- className="group flex items-start justify-between rounded-xl border border-[var(--border)] px-5 py-4 transition-colors hover:border-[var(--border)]"
- >
- <div className="min-w-0 flex-1">
- <div className="flex items-center gap-2">
- <Heart className="h-3.5 w-3.5 shrink-0 text-[var(--muted-foreground)]" />
- <p className="text-[14px] font-medium text-[var(--foreground)]">
- {soul.name}
- </p>
- <span className="text-[11px] text-[var(--muted-foreground)]/60">
- {soul.id}
- </span>
- </div>
- <p className="mt-1.5 line-clamp-2 text-[12px] leading-5 text-[var(--muted-foreground)] pl-5.5">
- {soul.content.replace(/^#.*\n+/g, "").slice(0, 200)}
- </p>
- </div>
- <div className="flex shrink-0 items-center gap-1 ml-4 opacity-0 group-hover:opacity-100 transition-opacity">
- <button
- onClick={() => startEdit(soul)}
- className="inline-flex items-center justify-center rounded-lg border border-[var(--border)]/50 p-1.5 text-[var(--muted-foreground)] transition-colors hover:border-[var(--border)] hover:text-[var(--foreground)]"
- >
- <Pencil className="h-3 w-3" />
- </button>
- <button
- onClick={() => deleteSoul(soul)}
- className="inline-flex items-center justify-center rounded-lg border border-[var(--border)]/50 p-1.5 text-[var(--muted-foreground)] transition-colors hover:border-red-400/50 hover:text-red-400"
- >
- <Trash2 className="h-3 w-3" />
- </button>
- </div>
- </div>
- ),
- )}
- </div>
- )}
- </div>
- );
-}
diff --git a/web/components/partners/ChannelIcon.tsx b/web/components/partners/ChannelIcon.tsx
new file mode 100644
index 000000000..c614f20fa
--- /dev/null
+++ b/web/components/partners/ChannelIcon.tsx
@@ -0,0 +1,213 @@
+"use client";
+
+/**
+ * Per-channel brand icons for the partner Channels UI.
+ *
+ * Sources: simple-icons (CC0) for most brands; Feishu/Lark comes from
+ * ByteDance's own IconPark set (`new-lark`, Apache-2.0), DingTalk from
+ * Ant Design Icons (MIT), and WeCom from Tencent's TDesign icons
+ * (`logo-wecom`, MIT) recolored per subpath to the official brand palette
+ * (sampled from work.weixin.qq.com's logo) — the vendors' official icon
+ * libraries. Brands with no clean vector source (Slack, MoChat) render as
+ * brand-colored letter badges. Unknown channels fall back to a neutral
+ * radio mark; email uses a neutral envelope.
+ */
+
+import { Mail, Radio } from "lucide-react";
+
+const BRAND_PATHS: Record<string, { hex: string; path: string }> = {
+ discord: {
+ hex: "#5865F2",
+ path: "M20.317 4.3698a19.7913 19.7913 0 00-4.8851-1.5152.0741.0741 0 00-.0785.0371c-.211.3753-.4447.8648-.6083 1.2495-1.8447-.2762-3.68-.2762-5.4868 0-.1636-.3933-.4058-.8742-.6177-1.2495a.077.077 0 00-.0785-.037 19.7363 19.7363 0 00-4.8852 1.515.0699.0699 0 00-.0321.0277C.5334 9.0458-.319 13.5799.0992 18.0578a.0824.0824 0 00.0312.0561c2.0528 1.5076 4.0413 2.4228 5.9929 3.0294a.0777.0777 0 00.0842-.0276c.4616-.6304.8731-1.2952 1.226-1.9942a.076.076 0 00-.0416-.1057c-.6528-.2476-1.2743-.5495-1.8722-.8923a.077.077 0 01-.0076-.1277c.1258-.0943.2517-.1923.3718-.2914a.0743.0743 0 01.0776-.0105c3.9278 1.7933 8.18 1.7933 12.0614 0a.0739.0739 0 01.0785.0095c.1202.099.246.1981.3728.2924a.077.077 0 01-.0066.1276 12.2986 12.2986 0 01-1.873.8914.0766.0766 0 00-.0407.1067c.3604.698.7719 1.3628 1.225 1.9932a.076.076 0 00.0842.0286c1.961-.6067 3.9495-1.5219 6.0023-3.0294a.077.077 0 00.0313-.0552c.5004-5.177-.8382-9.6739-3.5485-13.6604a.061.061 0 00-.0312-.0286zM8.02 15.3312c-1.1825 0-2.1569-1.0857-2.1569-2.419 0-1.3332.9555-2.4189 2.157-2.4189 1.2108 0 2.1757 1.0952 2.1568 2.419 0 1.3332-.9555 2.4189-2.1569 2.4189zm7.9748 0c-1.1825 0-2.1569-1.0857-2.1569-2.419 0-1.3332.9554-2.4189 2.1569-2.4189 1.2108 0 2.1757 1.0952 2.1568 2.419 0 1.3332-.946 2.4189-2.1568 2.4189Z",
+ },
+ matrix: {
+ hex: "#000000",
+ path: "M.632.55v22.9H2.28V24H0V0h2.28v.55zm7.043 7.26v1.157h.033c.309-.443.683-.784 1.117-1.024.433-.245.936-.365 1.5-.365.54 0 1.033.107 1.481.314.448.208.785.582 1.02 1.108.254-.374.6-.706 1.034-.992.434-.287.95-.43 1.546-.43.453 0 .872.056 1.26.167.388.11.716.286.993.53.276.245.489.559.646.951.152.392.23.863.23 1.417v5.728h-2.349V11.52c0-.286-.01-.559-.032-.812a1.755 1.755 0 0 0-.18-.66 1.106 1.106 0 0 0-.438-.448c-.194-.11-.457-.166-.785-.166-.332 0-.6.064-.803.189a1.38 1.38 0 0 0-.48.499 1.946 1.946 0 0 0-.231.696 5.56 5.56 0 0 0-.06.785v4.768h-2.35v-4.8c0-.254-.004-.503-.018-.752a2.074 2.074 0 0 0-.143-.688 1.052 1.052 0 0 0-.415-.503c-.194-.125-.476-.19-.854-.19-.111 0-.259.024-.439.074-.18.051-.36.143-.53.282-.171.138-.319.337-.439.595-.12.259-.18.6-.18 1.02v4.966H5.46V7.81zm15.693 15.64V.55H21.72V0H24v24h-2.28v-.55z",
+ },
+ qq: {
+ hex: "#1EBAFC",
+ path: "M21.395 15.035a40 40 0 0 0-.803-2.264l-1.079-2.695c.001-.032.014-.562.014-.836C19.526 4.632 17.351 0 12 0S4.474 4.632 4.474 9.241c0 .274.013.804.014.836l-1.08 2.695a39 39 0 0 0-.802 2.264c-1.021 3.283-.69 4.643-.438 4.673.54.065 2.103-2.472 2.103-2.472 0 1.469.756 3.387 2.394 4.771-.612.188-1.363.479-1.845.835-.434.32-.379.646-.301.778.343.578 5.883.369 7.482.189 1.6.18 7.14.389 7.483-.189.078-.132.132-.458-.301-.778-.483-.356-1.233-.646-1.846-.836 1.637-1.384 2.393-3.302 2.393-4.771 0 0 1.563 2.537 2.103 2.472.251-.03.581-1.39-.438-4.673",
+ },
+ telegram: {
+ hex: "#26A5E4",
+ path: "M11.944 0A12 12 0 0 0 0 12a12 12 0 0 0 12 12 12 12 0 0 0 12-12A12 12 0 0 0 12 0a12 12 0 0 0-.056 0zm4.962 7.224c.1-.002.321.023.465.14a.506.506 0 0 1 .171.325c.016.093.036.306.02.472-.18 1.898-.962 6.502-1.36 8.627-.168.9-.499 1.201-.82 1.23-.696.065-1.225-.46-1.9-.902-1.056-.693-1.653-1.124-2.678-1.8-1.185-.78-.417-1.21.258-1.91.177-.184 3.247-2.977 3.307-3.23.007-.032.014-.15-.056-.212s-.174-.041-.249-.024c-.106.024-1.793 1.14-5.061 3.345-.48.33-.913.49-1.302.48-.428-.008-1.252-.241-1.865-.44-.752-.245-1.349-.374-1.297-.789.027-.216.325-.437.893-.663 3.498-1.524 5.83-2.529 6.998-3.014 3.332-1.386 4.025-1.627 4.476-1.635z",
+ },
+ whatsapp: {
+ hex: "#25D366",
+ path: "M17.472 14.382c-.297-.149-1.758-.867-2.03-.967-.273-.099-.471-.148-.67.15-.197.297-.767.966-.94 1.164-.173.199-.347.223-.644.075-.297-.15-1.255-.463-2.39-1.475-.883-.788-1.48-1.761-1.653-2.059-.173-.297-.018-.458.13-.606.134-.133.298-.347.446-.52.149-.174.198-.298.298-.497.099-.198.05-.371-.025-.52-.075-.149-.669-1.612-.916-2.207-.242-.579-.487-.5-.669-.51-.173-.008-.371-.01-.57-.01-.198 0-.52.074-.792.372-.272.297-1.04 1.016-1.04 2.479 0 1.462 1.065 2.875 1.213 3.074.149.198 2.096 3.2 5.077 4.487.709.306 1.262.489 1.694.625.712.227 1.36.195 1.871.118.571-.085 1.758-.719 2.006-1.413.248-.694.248-1.289.173-1.413-.074-.124-.272-.198-.57-.347m-5.421 7.403h-.004a9.87 9.87 0 01-5.031-1.378l-.361-.214-3.741.982.998-3.648-.235-.374a9.86 9.86 0 01-1.51-5.26c.001-5.45 4.436-9.884 9.888-9.884 2.64 0 5.122 1.03 6.988 2.898a9.825 9.825 0 012.893 6.994c-.003 5.45-4.437 9.884-9.885 9.884m8.413-18.297A11.815 11.815 0 0012.05 0C5.495 0 .16 5.335.157 11.892c0 2.096.547 4.142 1.588 5.945L.057 24l6.305-1.654a11.882 11.882 0 005.683 1.448h.005c6.554 0 11.89-5.335 11.893-11.893a11.821 11.821 0 00-3.48-8.413Z",
+ },
+ zulip: {
+ hex: "#6492FE",
+ path: "M22.767 3.589c0 1.209-.543 2.283-1.37 2.934l-8.034 7.174c-.149.128-.343-.078-.235-.25l2.946-5.9c.083-.165-.024-.368-.194-.368H4.452c-1.77 0-3.219-1.615-3.219-3.59C1.233 1.616 2.682 0 4.452 0h15.096c1.77-.001 3.219 1.614 3.219 3.589zM4.452 24h15.096c1.77 0 3.219-1.616 3.219-3.59 0-1.974-1.449-3.59-3.219-3.59H8.12c-.17 0-.277-.202-.194-.367l2.946-5.9c.108-.172-.086-.378-.235-.25l-8.033 7.173c-.828.65-1.37 1.725-1.37 2.934 0 1.974 1.448 3.59 3.218 3.59z",
+ },
+};
+
+const LETTER_BADGES: Record<string, { label: string; hex: string }> = {
+ slack: { label: "S", hex: "#4A154B" },
+ mochat: { label: "M", hex: "#07C160" },
+};
+
+/** Feishu's bird mark — ByteDance IconPark `new-lark` (stroke style). */
+function FeishuIcon({ size, className }: { size: number; className: string }) {
+ const blue = "#3370FF";
+ return (
+ <svg
+ viewBox="0 0 48 48"
+ width={size}
+ height={size}
+ className={`shrink-0 ${className}`}
+ fill="none"
+ aria-hidden
+ >
+ <path
+ stroke={blue}
+ strokeLinecap="round"
+ strokeLinejoin="round"
+ strokeWidth="4"
+ d="M17 29C21 29 25 26.9339 28 23.4065C36 14 41.4242 16.8166 44 17.9998C38.5 20.9998 40.5 29.6233 33 35.9998C28.382 39.9259 23.4945 41.014 19 41C12.5231 40.9799 6.86226 37.7637 4 35.4063V16.9998"
+ />
+ <path
+ fill={blue}
+ d="M5.64808 15.8669C5.02231 14.9567 3.77715 14.7261 2.86694 15.3519C1.95673 15.9777 1.72615 17.2228 2.35192 18.1331L5.64808 15.8669ZM36.0021 35.7309C36.958 35.1774 37.2843 33.9539 36.7309 32.9979C36.1774 32.042 34.9539 31.7157 33.9979 32.2691L36.0021 35.7309ZM2.35192 18.1331C5.2435 22.339 10.7992 28.144 16.8865 32.2239C19.9345 34.2667 23.217 35.946 26.449 36.7324C29.6946 37.522 33.0451 37.4428 36.0021 35.7309L33.9979 32.2691C32.2049 33.3072 29.9929 33.478 27.3947 32.8458C24.783 32.2103 21.9405 30.7958 19.1135 28.9011C13.4508 25.106 8.2565 19.661 5.64808 15.8669L2.35192 18.1331Z"
+ />
+ <path
+ stroke={blue}
+ strokeLinecap="round"
+ strokeLinejoin="round"
+ strokeWidth="4"
+ d="M33.5947 17C32.84 14.7027 30.8551 9.94054 27.5947 7H11.5947C15.2174 10.6757 23.0002 16 27.0002 24"
+ />
+ </svg>
+ );
+}
+
+/**
+ * WeCom's bubble + pinwheel mark — TDesign `logo-wecom` outline split into
+ * its five subpaths (bubble, then top/right/bottom/left petals) so each can
+ * carry the official brand color.
+ */
+const WECOM_PARTS: Array<{ hex: string; path: string }> = [
+ {
+ // Speech bubble
+ hex: "#0082EF",
+ path: "M17.326 8.158l-.003-.007a6.6 6.6 0 0 0-1.178-1.674c-1.266-1.307-3.067-2.19-5.102-2.417a9.3 9.3 0 0 0-2.124 0h-.001c-2.061.228-3.882 1.107-5.14 2.405a6.7 6.7 0 0 0-1.194 1.682A5.7 5.7 0 0 0 2 10.657c0 1.106.332 2.218.988 3.201l.006.01c.391.594 1.092 1.39 1.637 1.83l.983.793l-.208.875l.527-.267l.708-.358l.761.225c.467.137.955.227 1.517.29h.005q.515.06 1.026.059c.355 0 .724-.02 1.095-.06a9 9 0 0 0 1.346-.258c.095.7.43 1.337.932 1.81c-.658.208-1.352.358-2.061.436c-.442.048-.883.072-1.312.072q-.627 0-1.253-.072a10.7 10.7 0 0 1-1.861-.36l-2.84 1.438s-.29.131-.44.131c-.418 0-.702-.285-.702-.704c0-.252.067-.598.128-.84l.394-1.653c-.728-.586-1.563-1.544-2.052-2.287A7.76 7.76 0 0 1 0 10.658a7.7 7.7 0 0 1 .787-3.39a8.7 8.7 0 0 1 1.551-2.19c1.61-1.665 3.878-2.73 6.359-3.006a11.3 11.3 0 0 1 2.565 0c2.47.275 4.712 1.353 6.323 3.017a8.6 8.6 0 0 1 1.539 2.192c.466.945.769 1.937.769 2.978a3.06 3.06 0 0 0-2-.005c-.001-.644-.189-1.329-.564-2.09z",
+ },
+ {
+ // Top petal
+ hex: "#2CB800",
+ path: "M21.451 15.135l-.024-.024l-.024-.018l-.024-.018l-.096-.095a4.24 4.24 0 0 1-1.169-2.192q0-.038-.006-.075l-.006-.056l-.035-.144a1.3 1.3 0 0 0-.358-.61a1.386 1.386 0 0 0-1.957 0a1.4 1.4 0 0 0 0 1.963c.191.191.418.311.668.371c.024.012.06.012.084.012q.019 0 .041.006q.023.005.042.006a4.24 4.24 0 0 1 2.231 1.186c.048.048.096.095.131.143a.323.323 0 0 0 .466 0a.35.35 0 0 0 .036-.455",
+ },
+ {
+ // Right petal
+ hex: "#0081EE",
+ path: "M20.401 19.505l-.025.025c-.119.096-.31.096-.453-.036a.326.326 0 0 1 0-.467c.047-.036.094-.083.141-.13l.002-.002a4.27 4.27 0 0 0 1.187-2.28q.005-.024.006-.043c0-.024 0-.06.012-.084a1.386 1.386 0 0 1 2.326-.67a1.4 1.4 0 0 1 0 1.964c-.167.18-.382.299-.608.359l-.143.036l-.057.005q-.035.006-.075.007a4.2 4.2 0 0 0-2.183 1.173l-.095.096q-.009.01-.018.024t-.018.024",
+ },
+ {
+ // Bottom petal
+ hex: "#FB6500",
+ path: "M16.008 18.453l.024.024l.024.018q.015.009.024.018l.096.096a4.25 4.25 0 0 1 1.169 2.19q0 .04.006.076q.005.03.006.057l.035.143c.06.228.18.443.358.611c.537.539 1.42.539 1.957 0a1.4 1.4 0 0 0 0-1.964a1.4 1.4 0 0 0-.668-.371c-.024-.012-.06-.012-.084-.012q-.018 0-.041-.006l-.042-.006a4.25 4.25 0 0 1-2.231-1.185a1.4 1.4 0 0 1-.131-.144a.323.323 0 0 0-.466 0a.325.325 0 0 0-.036.455",
+ },
+ {
+ // Left petal
+ hex: "#FFCC00",
+ path: "M17.047 14.095l.024-.024a.32.32 0 0 1 .453.035a.326.326 0 0 1 0 .467c-.047.036-.094.083-.141.13l-.002.002a4.27 4.27 0 0 0-1.187 2.281l-.006.042c0 .024 0 .06-.012.084a1.386 1.386 0 0 1-2.326.67a1.4 1.4 0 0 1 0-1.963c.166-.18.381-.3.608-.36l.143-.035q.026 0 .056-.006q.037-.005.075-.006a4.2 4.2 0 0 0 2.183-1.174l.096-.095l.018-.025z",
+ },
+];
+
+function WeComIcon({ size, className }: { size: number; className: string }) {
+ return (
+ <svg
+ viewBox="0 0 24 24"
+ width={size}
+ height={size}
+ className={`shrink-0 ${className}`}
+ aria-hidden
+ >
+ {WECOM_PARTS.map((part, i) => (
+ <path key={i} fill={part.hex} d={part.path} />
+ ))}
+ </svg>
+ );
+}
+
+/** DingTalk's wing mark — Ant Design Icons `dingtalk`. */
+function DingTalkIcon({ size, className }: { size: number; className: string }) {
+ return (
+ <svg
+ viewBox="0 0 1024 1024"
+ width={size}
+ height={size}
+ className={`shrink-0 ${className}`}
+ fill="#0089FF"
+ aria-hidden
+ >
+ <path d="M573.7 252.5C422.5 197.4 201.3 96.7 201.3 96.7c-15.7-4.1-17.9 11.1-17.9 11.1c-5 61.1 33.6 160.5 53.6 182.8c19.9 22.3 319.1 113.7 319.1 113.7S326 357.9 270.5 341.9c-55.6-16-37.9 17.8-37.9 17.8c11.4 61.7 64.9 131.8 107.2 138.4c42.2 6.6 220.1 4 220.1 4s-35.5 4.1-93.2 11.9c-42.7 5.8-97 12.5-111.1 17.8c-33.1 12.5 24 62.6 24 62.6c84.7 76.8 129.7 50.5 129.7 50.5c33.3-10.7 61.4-18.5 85.2-24.2L565 743.1h84.6L603 928l205.3-271.9H700.8l22.3-38.7c.3.5.4.8.4.8S799.8 496.1 829 433.8l.6-1h-.1c5-10.8 8.6-19.7 10-25.8c17-71.3-114.5-99.4-265.8-154.5" />
+ </svg>
+ );
+}
+
+export default function ChannelIcon({
+ name,
+ size = 16,
+ className = "",
+}: {
+ name: string;
+ size?: number;
+ className?: string;
+}) {
+ const key = name.toLowerCase();
+ if (key === "feishu") return <FeishuIcon size={size} className={className} />;
+ if (key === "dingtalk") return <DingTalkIcon size={size} className={className} />;
+ if (key === "wecom") return <WeComIcon size={size} className={className} />;
+ const brand = BRAND_PATHS[key];
+ if (brand) {
+ return (
+ <svg
+ viewBox="0 0 24 24"
+ width={size}
+ height={size}
+ className={`shrink-0 ${className}`}
+ // Pure-black brand marks (Matrix) would vanish on the dark theme.
+ fill={brand.hex === "#000000" ? "currentColor" : brand.hex}
+ aria-hidden
+ >
+ <path d={brand.path} />
+ </svg>
+ );
+ }
+ const badge = LETTER_BADGES[key];
+ if (badge) {
+ return (
+ <span
+ aria-hidden
+ className={`flex shrink-0 select-none items-center justify-center rounded-[5px] font-semibold text-white ${className}`}
+ style={{
+ width: size,
+ height: size,
+ background: badge.hex,
+ fontSize: size * 0.58,
+ }}
+ >
+ {badge.label}
+ </span>
+ );
+ }
+ if (key === "email") {
+ return (
+ <Mail
+ width={size}
+ height={size}
+ className={`shrink-0 text-[var(--muted-foreground)] ${className}`}
+ aria-hidden
+ />
+ );
+ }
+ return (
+ <Radio
+ width={size}
+ height={size}
+ className={`shrink-0 text-[var(--muted-foreground)] ${className}`}
+ aria-hidden
+ />
+ );
+}