Build and run agents you can see, understand and trust.
Python agentchatbotlarge-language-modelsllmllm-agentmcpmulti-agentmulti-modalreact-agentrealtime-agentvoice-agentvoice-assistant
feat(channel): add DingTalk channel in agent service (#2285)
DiegoCluv7da00849f2c3d
diff --git a/examples/agent_service/main.py b/examples/agent_service/main.pyindex 9a6a0bbf3..2c47a481c 100644--- a/examples/agent_service/main.py+++ b/examples/agent_service/main.py@@ -7,7 +7,11 @@ from fastapi.middleware import Middlewarefrom fastapi.middleware.cors import CORSMiddlewarefrom agentscope.app import create_app, SubAgentTemplate-from agentscope.app.channel import DiscordChannel, FeishuChannel+from agentscope.app.channel import (+ DingTalkChannel,+ DiscordChannel,+ FeishuChannel,+)from agentscope.app.hub import ClawSkillHub, GitHubMCPHubfrom agentscope.app.message_bus import InMemoryMessageBusfrom agentscope.app.rag.knowledge_base_manager import CollectionPerKbManager@@ -153,6 +157,7 @@ so anything you want them to see MUST be sent through `TeamSay`.""",),],channels=[+ DingTalkChannel,DiscordChannel,FeishuChannel,],diff --git a/pyproject.toml b/pyproject.tomlindex 581cf397f..4c0327202 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -81,6 +81,7 @@ storage-s3 = ["aioboto3"]channel = ["lark-oapi>=1.4.0","discord.py>=2.3",+ "dingtalk-stream>=0.24.3",]# ------------ Workspace (sandbox backends) ------------workspace-docker = ["aiodocker"]diff --git a/src/agentscope/app/_app.py b/src/agentscope/app/_app.pyindex 60e319d5d..46df69ce6 100644--- a/src/agentscope/app/_app.py+++ b/src/agentscope/app/_app.py@@ -251,7 +251,7 @@ def create_app(preserves the historical owner-isolated behavior.channels (`list[Type[ChannelBase]] | None`, optional):Channel adapter classes this service allows (e.g.- ``[FeishuChannel, DiscordChannel]``). Each class+ ``[DingTalkChannel, FeishuChannel, DiscordChannel]``). Each classself-describes its ``channel_type``, credentials and config,so the service registers it without a separate table; pass acustom :class:`~agentscope.app.channel.ChannelBase` subclassdiff --git a/src/agentscope/app/channel/__init__.py b/src/agentscope/app/channel/__init__.pyindex 80d71481f..c17b7ffc5 100644--- a/src/agentscope/app/channel/__init__.py+++ b/src/agentscope/app/channel/__init__.py@@ -1,7 +1,8 @@# -*- coding: utf-8 -*-"""Channel module — connect AgentScope agents to IM platforms.-Channels translate a platform (Feishu, ...) to/from normalised events;+Channels translate a platform (DingTalk, Feishu, ...) to/from normalised+events;the stateless :class:`ChannelGateway` orchestrates each event;:class:`~agentscope.app._service.ChannelService` owns CRUD;:class:`ChannelLifecycleDispatcher` keeps this node's live instances@@ -21,6 +22,7 @@ from ._dispatcher import ChannelLifecycleDispatcherfrom ._errors import ChannelErrorfrom ._gateway import ChannelGatewayfrom ._registry import ChannelTypeRegistry, ChannelTypeSchema+from ._dingtalk import DingTalkChannelfrom ._discord import DiscordChannelfrom ._feishu import FeishuChannel@@ -38,6 +40,7 @@ __all__ = ["ChannelLifecycleDispatcher","ChannelTypeRegistry","ChannelTypeSchema",+ "DingTalkChannel","DiscordChannel","FeishuChannel",]diff --git a/src/agentscope/app/channel/_dingtalk/__init__.py b/src/agentscope/app/channel/_dingtalk/__init__.pynew file mode 100644index 000000000..2ac6b1b89--- /dev/null+++ b/src/agentscope/app/channel/_dingtalk/__init__.py@@ -0,0 +1,6 @@+# -*- coding: utf-8 -*-+"""DingTalk channel."""++from ._channel import DingTalkChannel++__all__ = ["DingTalkChannel"]diff --git a/src/agentscope/app/channel/_dingtalk/_card.py b/src/agentscope/app/channel/_dingtalk/_card.pynew file mode 100644index 000000000..2b80f0847--- /dev/null+++ b/src/agentscope/app/channel/_dingtalk/_card.py@@ -0,0 +1,155 @@+# -*- coding: utf-8 -*-+"""DingTalk interactive-card helpers for tool approval.++DingTalk cards use a template created in the Card Platform. The template+round-trips the lookup keys defined here as callback parameters. Session+state remains authoritative; none of the tool input is trusted on callback.+"""++import json+from dataclasses import dataclass+from typing import Any++_APPROVE_ACTIONS = frozenset({"allow", "approve", "accept", "agree"})+_DENY_ACTIONS = frozenset({"deny", "reject"})+++@dataclass(frozen=True, slots=True)+class _ApprovalDecision:+ """A validated decision parsed from a DingTalk card callback."""++ out_track_id: str+ user_id: str+ approver_id: str+ tool_call_id: str+ chat_id: str+ agent_id: str+ session_id: str+ approved: bool+++def _approval_card_data(+ tool_call_id: str,+ chat_id: str,+ tool_name: str,+ summary: str,+ approver_id: str,+ agent_id: str = "",+ session_id: str = "",+) -> dict[str, str]:+ """Build the parameter map consumed by the configured card template.++ Args:+ tool_call_id (`str`): Awaiting tool call answered by the card.+ chat_id (`str`): Encoded DingTalk chat used for session routing.+ tool_name (`str`): Tool name displayed to the user.+ summary (`str`): Truncated tool arguments displayed to the user.+ approver_id (`str`): Optional user permitted to decide the request.+ agent_id (`str`): Resolved agent id, echoed through the callback.+ session_id (`str`): Resolved session id, echoed through the callback.++ Returns:+ `dict[str, str]`: DingTalk card template parameter map.+ """+ shown = summary if len(summary) <= 800 else summary[:799] + "…"+ return {+ "title": "Tool execution needs approval",+ "markdown": f"**Tool:** `{tool_name}`\n**Arguments:** {shown}",+ "status": "pending",+ "toolCallId": tool_call_id,+ "chatId": chat_id,+ "agentId": agent_id,+ "sessionId": session_id,+ "approverId": approver_id,+ }+++def _resolved_card_data(approved: bool) -> dict[str, str]:+ """Build card parameters used after a decision.++ Args:+ approved (`bool`): Whether the tool call was approved.++ Returns:+ `dict[str, str]`: Replacement values for the card template.+ """+ return {+ "title": "Tool execution approved" if approved else "Tool denied",+ "markdown": (+ "The tool was approved and will continue."+ if approved+ else "The tool was denied."+ ),+ "status": "approved" if approved else "denied",+ }+++def _parse_card_callback(payload: Any) -> _ApprovalDecision | None:+ """Parse and validate one advanced-card action callback.++ The configured allow and deny buttons must return ``action`` plus the+ routing fields from :func:`_approval_card_data` in+ ``cardPrivateData.params``.++ Args:+ payload (`Any`): Callback data supplied by the Stream SDK.++ Returns:+ `_ApprovalDecision | None`: Parsed decision, or ``None`` for a+ malformed or unrelated callback.+ """+ if not isinstance(payload, dict):+ return None+ if payload.get("type") not in (None, "", "actionCallback"):+ return None+ content = _json_object(payload.get("content"))+ private_data = _json_object(content.get("cardPrivateData"))+ params = _json_object(private_data.get("params"))++ action = str(params.get("action") or "").strip().lower()+ if action in _APPROVE_ACTIONS:+ approved = True+ elif action in _DENY_ACTIONS:+ approved = False+ else:+ return None++ tool_call_id = _field(params, "toolCallId", "tool_call_id")+ chat_id = _field(params, "chatId", "chat_id")+ approver_id = _field(params, "approverId", "approver_id")+ user_id = _field(payload, "userId", "user_id")+ out_track_id = _field(payload, "outTrackId", "out_track_id")+ if not all((tool_call_id, chat_id, user_id, out_track_id)):+ return None+ return _ApprovalDecision(+ out_track_id=out_track_id,+ user_id=user_id,+ approver_id=approver_id,+ tool_call_id=tool_call_id,+ chat_id=chat_id,+ agent_id=_field(params, "agentId", "agent_id"),+ session_id=_field(params, "sessionId", "session_id"),+ approved=approved,+ )+++def _json_object(value: Any) -> dict[str, Any]:+ """Return a mapping from a mapping or JSON object string."""+ if isinstance(value, dict):+ return value+ if isinstance(value, str):+ try:+ decoded = json.loads(value)+ except (json.JSONDecodeError, TypeError):+ return {}+ return decoded if isinstance(decoded, dict) else {}+ return {}+++def _field(mapping: dict[str, Any], *names: str) -> str:+ """Read the first non-empty string representation of named fields."""+ for name in names:+ value = str(mapping.get(name) or "").strip()+ if value:+ return value+ return ""diff --git a/src/agentscope/app/channel/_dingtalk/_channel.py b/src/agentscope/app/channel/_dingtalk/_channel.pynew file mode 100644index 000000000..e5981aad6--- /dev/null+++ b/src/agentscope/app/channel/_dingtalk/_channel.py@@ -0,0 +1,1226 @@+# -*- coding: utf-8 -*-+"""DingTalk channel using the official Stream SDK.++The Stream SDK owns the long-lived inbound connection. Markdown replies use+the short-lived ``sessionWebhook`` included in an inbound callback. Stable+target sends, media transfer, cards, and user search use DingTalk OpenAPI.+"""++import asyncio+import base64+import binascii+from dataclasses import dataclass+import json+import mimetypes+import time+from typing import Any, AsyncIterator, Awaitable, Callable, TYPE_CHECKING+from urllib.parse import quote_plus, urlparse++from pydantic import BaseModel, Field++from ...._logging import logger+from ....event import ReplyEndEvent, RequireUserConfirmEvent+from ....message import (+ Base64Source,+ DataBlock,+ Msg,+ TextBlock,+ ThinkingBlock,+ ToolCallBlock,+ ToolResultBlock,+)+from .._base import (+ ChannelBase,+ ChannelCapability,+ ChannelConfirmationResultEvent,+ ChannelEvent,+ ChannelStatus,+ ChatKind,+ _EVENT_ADAPTER,+)+from ._card import (+ _approval_card_data,+ _parse_card_callback,+ _resolved_card_data,+)+from ._openapi import _DingTalkOpenAPI++if TYPE_CHECKING:+ from ....tool import ToolBase+ from ....workspace import WorkspaceBase++_CHATBOT_TOPIC = "/v1.0/im/bot/messages/get"+_CARD_CALLBACK_TOPIC = "/v1.0/card/instances/callback"+_GROUP_CONVERSATION = "2"+_MAX_LEN = 4000+_MARKDOWN_TITLE = "AgentScope"+_STATUS_POLL_INTERVAL = 0.2+_STREAM_MIN_INTERVAL = 0.3+_STREAM_MAX_CONTENT_BYTES = 1024+_STREAM_FALLBACK_NOTICE = (+ "Streaming stopped. The complete reply follows as a Markdown message."+)+_DEFAULT_MAX_MEDIA_BYTES = 10 * 1024 * 1024+_MEDIA_MESSAGE_TYPES = frozenset(+ {"audio", "file", "picture", "richText", "video"},+)+++@dataclass(frozen=True, slots=True)+class _SessionWebhook:+ """A callback-scoped reply URL and its expiration time."""++ url: str+ expires_at_ms: int | None+++class DingTalkChannel(ChannelBase):+ """DingTalk enterprise application robot channel."""++ channel_type = "dingtalk"+ display_name = "DingTalk"+ description = "Enterprise robot for DingTalk groups and direct messages."+ icon_url = "https://www.google.com/s2/favicons?domain=dingtalk.com&sz=128"+ platform_bot_id_field = "client_id"++ class Credentials(BaseModel):+ """DingTalk application credentials."""++ client_id: str = Field(+ title="Client ID",+ description="DingTalk application Client ID (AppKey)",+ )+ client_secret: str = Field(+ title="Client Secret",+ description="DingTalk application Client Secret (AppSecret)",+ json_schema_extra={"format": "password"},+ )++ class Config(BaseModel):+ """DingTalk platform options."""++ only_at_reply: bool = Field(+ default=True,+ title="Reply only when mentioned",+ description="In group chats, reply only when the bot is "+ "@mentioned",+ )+ show_tool_process: bool = Field(+ default=False,+ title="Show tool process",+ description="Show tool calls and results inline in the reply",+ )+ show_thinking: bool = Field(+ default=False,+ title="Show thinking",+ description="Show the model's reasoning inline in the reply",+ )+ max_media_bytes: int = Field(+ default=_DEFAULT_MAX_MEDIA_BYTES,+ ge=1,+ le=100 * 1024 * 1024,+ title="Maximum media size",+ description="Maximum bytes accepted for one inbound or "+ "outbound attachment",+ )+ approval_card_template_id: str = Field(+ default="",+ title="Approval card template ID",+ description="DingTalk Card Platform template used for tool "+ "approval. Send tools are available only when configured.",+ )+ streaming_card_template_id: str = Field(+ default="",+ title="Streaming card template ID",+ description="Optional DingTalk AI Card template used for "+ "streaming replies. Replies use normal Markdown when empty.",+ )+ streaming_card_key: str = Field(+ default="content",+ min_length=1,+ title="Streaming card content key",+ description="Template variable key of the AI Card streaming "+ "component.",+ )++ capabilities = ChannelCapability(+ text=True,+ markdown=True,+ image=True,+ file=True,+ interactive=True,+ streaming=False,+ max_message_length=_MAX_LEN,+ )++ def __init__(+ self,+ channel_id: str,+ credentials: "DingTalkChannel.Credentials",+ config: "DingTalkChannel.Config",+ ) -> None:+ """Build a DingTalk channel from validated settings.++ Args:+ channel_id (`str`): This channel instance's unique id.+ credentials (`DingTalkChannel.Credentials`): DingTalk Client ID+ and Client Secret.+ config (`DingTalkChannel.Config`): Channel display and routing+ options.+ """+ self._channel_id = channel_id+ self._client_id = credentials.client_id+ self._client_secret = credentials.client_secret+ self._config = config+ self.capabilities = type(self).capabilities.model_copy(+ update={+ "streaming": bool(config.streaming_card_template_id),+ },+ )+ self.status = ChannelStatus()+ self._stream_client: Any = None+ self._http: Any = None+ self._openapi: _DingTalkOpenAPI | None = None+ self._emit: (+ Callable[+ [ChannelEvent | ChannelConfirmationResultEvent],+ Awaitable[None],+ ]+ | None+ ) = None+ self._session_webhooks: dict[str, _SessionWebhook] = {}+ self._chat_names: dict[str, str] = {}++ @property+ def channel_id(self) -> str:+ """The unique channel instance identifier."""+ return self._channel_id++ async def start_listening(+ self,+ emit: Callable[+ [ChannelEvent | ChannelConfirmationResultEvent],+ Awaitable[None],+ ],+ ) -> None:+ """Start the DingTalk Stream connection until cancelled.++ The official SDK performs reconnects. This method owns both the+ SDK client and the asynchronous HTTP client used for replies.++ Args:+ emit (`Callable`): Gateway callback for normalised inbound+ events.+ """+ self._emit = emit+ self.status.state = "connecting"+ self.status.last_error = ""+ stream_task: asyncio.Task[Any] | None = None+ ever_connected = False+ try:+ self._http = self._new_http_client()+ self._openapi = _DingTalkOpenAPI(+ self._client_id,+ self._client_secret,+ self._http,+ )+ self._stream_client = self._new_stream_client()+ stream_task = asyncio.create_task(self._stream_client.start())+ while not stream_task.done():+ if getattr(self._stream_client, "websocket", None) is not None:+ ever_connected = True+ self.status.state = "connected"+ self.status.last_error = ""+ elif ever_connected:+ self.status.state = "retrying"+ await asyncio.sleep(_STATUS_POLL_INTERVAL)+ await stream_task+ if self.status.state != "stopped":+ raise RuntimeError(+ "DingTalk Stream client stopped unexpectedly",+ )+ except Exception as error: # pylint: disable=broad-except+ self.status.state = "failed"+ self.status.last_error = str(error)+ logger.exception(+ "DingTalk '%s' Stream client failed",+ self._channel_id,+ )+ while True:+ await asyncio.sleep(30.0)+ finally:+ if self._stream_client is not None:+ try:+ await self._stream_client.stop()+ except Exception: # pylint: disable=broad-except+ logger.debug(+ "DingTalk '%s' Stream client stop failed",+ self._channel_id,+ )+ if stream_task is not None:+ if not stream_task.done():+ stream_task.cancel()+ await asyncio.gather(stream_task, return_exceptions=True)+ if self._http is not None:+ await self._http.aclose()+ self._stream_client = None+ self._http = None+ self._openapi = None+ self.status.state = "stopped"++ async def send_response(+ self,+ event: ChannelEvent,+ events: AsyncIterator[dict],+ ) -> None:+ """Send an Agent reply using an optional DingTalk AI Card stream.++ Without a streaming-card template the complete reply is sent as one+ or more Markdown messages. A configured card is updated at a bounded+ rate and falls back to Markdown if card creation or updating fails.++ Args:+ event (`ChannelEvent`): The DingTalk reply target.+ events (`AsyncIterator[dict]`): The run's streamed Agent events.+ """+ reply: Msg | None = None+ confirm: RequireUserConfirmEvent | None = None+ stream_ref: str | None = None+ stream_failed = False+ last_stream_update = 0.0+ async for raw in events:+ agent_event = _EVENT_ADAPTER.validate_python(raw)+ if isinstance(agent_event, RequireUserConfirmEvent):+ confirm = agent_event+ break+ reply_id = getattr(agent_event, "reply_id", None)+ if reply_id is not None:+ if reply is None:+ reply = Msg(+ name="assistant",+ role="assistant",+ content=[],+ )+ reply.id = reply_id+ reply.append_event(agent_event)+ if isinstance(agent_event, ReplyEndEvent):+ break++ if (+ not self.capabilities.streaming+ or stream_failed+ or reply is None+ or not self._has_streaming_text(reply)+ ):+ continue+ rendered = self._render(+ reply,+ show_thinking=self._config.show_thinking,+ show_tool_process=self._config.show_tool_process,+ )+ text = "".join(+ block.text+ for block in rendered+ if isinstance(block, TextBlock)+ )+ if not text:+ continue+ if not self._fits_streaming_card(text):+ stream_failed = True+ continue+ if stream_ref is None:+ stream_ref = await self._open_streaming_card(event.chat_id)+ if stream_ref is None:+ stream_failed = True+ continue+ now = time.monotonic()+ if now - last_stream_update >= _STREAM_MIN_INTERVAL:+ last_stream_update = now+ if not await self._update_streaming_card(+ stream_ref,+ text,+ ):+ stream_failed = True++ blocks = self._render(+ reply,+ show_thinking=self._config.show_thinking,+ show_tool_process=self._config.show_tool_process,+ )+ text = "".join(+ block.text for block in blocks if isinstance(block, TextBlock)+ )+ streamed = await self._finish_streaming_card(stream_ref, text)+ for block in blocks:+ if isinstance(block, TextBlock):+ if streamed:+ continue+ for part in self._split_long_message(block.text):+ if part:+ await self._send_text(event.chat_id, part)+ elif isinstance(block, DataBlock):+ await self._send_data(event.chat_id, block)+ if confirm is not None:+ await self._present_confirm(event, confirm)++ @staticmethod+ def _fits_streaming_card(text: str) -> bool:+ """Whether a full Markdown update fits DingTalk's request limit."""+ return len(text.encode("utf-8")) <= _STREAM_MAX_CONTENT_BYTES++ def _has_streaming_text(self, reply: Msg) -> bool:+ """Whether the partial reply contains text enabled for display."""+ for block in reply.content:+ if isinstance(block, TextBlock) and block.text.strip():+ return True+ if (+ isinstance(block, ThinkingBlock)+ and self._config.show_thinking+ and block.thinking.strip()+ ):+ return True+ if (+ isinstance(block, ToolCallBlock)+ and self._config.show_tool_process+ ):+ return True+ if (+ isinstance(block, ToolResultBlock)+ and self._config.show_tool_process+ and isinstance(block.output, str)+ and block.output.strip()+ ):+ return True+ return False++ async def _open_streaming_card(self, chat_id: str) -> str | None:+ """Create and deliver a configured AI streaming card."""+ if self._openapi is None:+ return None+ return await self._openapi.create_streaming_card(+ chat_id,+ self._config.streaming_card_template_id,+ self._config.streaming_card_key,+ )++ async def _update_streaming_card(+ self,+ out_track_id: str,+ text: str,+ *,+ finalize: bool = False,+ is_error: bool = False,+ ) -> bool:+ """Write the complete Markdown value to one AI streaming card."""+ if self._openapi is None or not self._fits_streaming_card(text):+ return False+ return await self._openapi.stream_card(+ out_track_id,+ self._config.streaming_card_key,+ text,+ finalize=finalize,+ is_error=is_error,+ )++ async def _finish_streaming_card(+ self,+ out_track_id: str | None,+ text: str,+ ) -> bool:+ """Finalize a live card, returning false for Markdown fallback."""+ if out_track_id is None or not text:+ return False+ updated = await self._update_streaming_card(+ out_track_id,+ text,+ finalize=True,+ )+ if not updated:+ await self._update_streaming_card(+ out_track_id,+ _STREAM_FALLBACK_NOTICE,+ finalize=True,+ is_error=True,+ )+ return updated++ async def chat_kind(self, chat_id: str) -> ChatKind | None:+ """Return the audience kind encoded in a DingTalk chat id.++ Args:+ chat_id (`str`): ``group:<openConversationId>`` or+ ``user:<staffId>``.++ Returns:+ `ChatKind | None`: Group, private, or ``None`` for an unknown+ address.+ """+ if chat_id.startswith("group:"):+ return ChatKind.GROUP+ if chat_id.startswith("user:"):+ return ChatKind.PRIVATE+ return None++ async def chat_name(self, chat_id: str) -> str:+ """Return a cached inbound conversation title.++ Args:+ chat_id (`str`): The encoded DingTalk chat id.++ Returns:+ `str`: The title supplied by DingTalk, or an empty string.+ """+ return self._chat_names.get(chat_id, "")++ async def list_bot_chats(self) -> list[dict]:+ """List conversations observed by this robot process.++ DingTalk does not expose an application-robot equivalent of+ Feishu's bot-chat enumeration API. The result is therefore limited+ to conversations from which this process has received a callback.++ Returns:+ `list[dict]`: Known encoded targets, names, and chat types.+ """+ return [+ {+ "chat_id": chat_id,+ "name": name,+ "chat_type": (+ "group" if chat_id.startswith("group:") else "private"+ ),+ }+ for chat_id, name in self._chat_names.items()+ ]++ async def list_tools(+ self,+ workspace: "WorkspaceBase",+ ) -> list["ToolBase"]:+ """Expose DingTalk discovery and target-send tools to the agent.++ Args:+ workspace (`WorkspaceBase`): Calling session workspace whose+ backend is used for file reads.++ Returns:+ `list[ToolBase]`: DingTalk agent tools.+ """+ from ._tools import (+ ListConversations,+ ListUsers,+ SendFile,+ SendImage,+ SendMessage,+ )++ backend = workspace.get_backend()+ tools: list["ToolBase"] = [+ ListConversations(self, backend),+ ListUsers(self, backend),+ ]+ if self._config.approval_card_template_id:+ tools.extend(+ [+ SendMessage(self, backend),+ SendFile(self, backend),+ SendImage(self, backend),+ ],+ )+ return tools++ async def search_users(+ self,+ query: str,+ limit: int = 20,+ ) -> list[dict[str, Any]]:+ """Search users visible to the DingTalk application.++ Args:+ query (`str`): User-name search term.+ limit (`int`): Maximum number of results.++ Returns:+ `list[dict[str, Any]]`: Basic visible user profiles.+ """+ if self._openapi is None:+ logger.warning("DingTalk OpenAPI client is not running")+ return []+ return await self._openapi.search_users(query, limit)++ async def send_message_to(self, target: str, text: str) -> bool:+ """Send Markdown text to an encoded DingTalk target.++ Args:+ target (`str`): Target from a discovery tool.+ text (`str`): Markdown-formatted message body.++ Returns:+ `bool`: Whether DingTalk accepted the message.+ """+ if self._openapi is None:+ logger.warning("DingTalk OpenAPI client is not running")+ return False+ return await self._openapi.send_text(target, text)++ async def send_file_to(+ self,+ target: str,+ data: bytes,+ file_name: str,+ ) -> bool:+ """Upload and send a workspace file to a DingTalk target.++ Args:+ target (`str`): Target from a discovery tool.+ data (`bytes`): File bytes.+ file_name (`str`): Display filename.++ Returns:+ `bool`: Whether DingTalk accepted the file.+ """+ if self._openapi is None:+ logger.warning("DingTalk OpenAPI client is not running")+ return False+ if len(data) > self._config.max_media_bytes:+ logger.warning("DingTalk outbound media exceeds the size limit")+ return False+ return await self._openapi.send_media(+ target,+ data,+ self._safe_file_name(file_name),+ "application/octet-stream",+ )++ async def send_image_to(+ self,+ target: str,+ data: bytes,+ file_name: str,+ ) -> bool:+ """Upload and send a workspace image to a DingTalk target.++ Args:+ target (`str`): Target from a discovery tool.+ data (`bytes`): Image bytes.+ file_name (`str`): Image filename used for MIME detection.++ Returns:+ `bool`: Whether DingTalk accepted the image.+ """+ if self._openapi is None:+ logger.warning("DingTalk OpenAPI client is not running")+ return False+ if len(data) > self._config.max_media_bytes:+ logger.warning("DingTalk outbound media exceeds the size limit")+ return False+ safe_name = self._safe_file_name(file_name)+ media_type = mimetypes.guess_type(safe_name)[0] or ""+ if not media_type.startswith("image/"):+ logger.warning("DingTalk SendImage requires an image file")+ return False+ return await self._openapi.send_media(+ target,+ data,+ safe_name,+ media_type,+ )++ def _new_http_client(self) -> Any:+ """Create the asynchronous HTTP client used by this channel."""+ import httpx++ return httpx.AsyncClient(timeout=30.0)++ def _new_stream_client(self) -> Any:+ """Build and configure the official DingTalk Stream client."""+ import dingtalk_stream # type: ignore[import-untyped]+ import websockets # type: ignore[import-untyped]++ channel = self+ on_callback = self._on_callback+ on_card_callback = self._on_card_callback++ class _StoppableStreamClient(+ dingtalk_stream.DingTalkStreamClient,+ ):+ """Add cooperative shutdown to the official Stream client.++ ``dingtalk-stream`` 0.24.3 has no ``stop`` method and its+ ``start`` loop catches cancellation. Keep the SDK's connection+ and routing methods while providing a lifecycle that Agent+ Service can terminate cleanly.+ """++ def __init__(self, credential: Any) -> None:+ super().__init__(credential)+ self.websocket: Any = None+ self._stop_event = asyncio.Event()+ self._worker_tasks: set[asyncio.Task[Any]] = set()+ self._keepalive_task: asyncio.Task[Any] | None = None++ async def start(self) -> None:+ """Connect and reconnect until :meth:`stop` is called."""+ self.pre_start()+ while not self._stop_event.is_set():+ try:+ connection = await asyncio.to_thread(+ self.open_connection,+ )+ if not connection:+ await self._retry_after(10.0)+ continue+ uri = (+ f"{connection['endpoint']}?ticket="+ f"{quote_plus(connection['ticket'])}"+ )+ async with websockets.connect(uri) as websocket:+ self.websocket = websocket+ self._keepalive_task = asyncio.create_task(+ self.keepalive(websocket),+ )+ async for raw_message in websocket:+ if self._stop_event.is_set():+ break+ task = asyncio.create_task(+ self.background_task(+ json.loads(raw_message),+ ),+ )+ self._worker_tasks.add(task)+ task.add_done_callback(+ self._worker_tasks.discard,+ )+ except asyncio.CancelledError:+ raise+ except (+ websockets.exceptions.ConnectionClosedError+ ) as error:+ if not self._stop_event.is_set():+ self.logger.warning(+ "DingTalk Stream connection closed: %s",+ error,+ )+ await self._retry_after(10.0)+ except Exception as error: # pylint: disable=broad-except+ if not self._stop_event.is_set():+ self.logger.warning(+ "DingTalk Stream connection failed: %s",+ error,+ )+ await self._retry_after(3.0)+ finally:+ await self._cancel_keepalive()+ self.websocket = None++ async def stop(self) -> None:+ """Stop reconnecting and close all Stream tasks."""+ self._stop_event.set()+ websocket = self.websocket+ if websocket is not None:+ await websocket.close()+ await self._cancel_keepalive()+ tasks = list(self._worker_tasks)+ for task in tasks:+ task.cancel()+ if tasks:+ await asyncio.gather(*tasks, return_exceptions=True)+ self._worker_tasks.clear()++ async def _retry_after(self, seconds: float) -> None:+ """Wait for a reconnect delay or an earlier stop request."""+ try:+ await asyncio.wait_for(+ self._stop_event.wait(),+ timeout=seconds,+ )+ except TimeoutError:+ pass++ async def _cancel_keepalive(self) -> None:+ """Cancel the SDK keepalive task when one is active."""+ task = self._keepalive_task+ self._keepalive_task = None+ if task is not None and not task.done():+ task.cancel()+ await asyncio.gather(task, return_exceptions=True)++ class _MessageHandler(dingtalk_stream.CallbackHandler):+ """Forward one SDK callback into the owning channel."""++ async def process(self, callback: Any) -> tuple[int, str]:+ """Process one robot message callback.++ Args:+ callback (`Any`): The Stream SDK callback message.++ Returns:+ `tuple[int, str]`: DingTalk acknowledgement status and+ message.+ """+ try:+ await on_callback(callback.data)+ except Exception: # pylint: disable=broad-except+ logger.exception(+ "DingTalk '%s' callback failed",+ channel.channel_id,+ )+ return (+ dingtalk_stream.AckMessage.STATUS_SYSTEM_EXCEPTION,+ "ERROR",+ )+ return dingtalk_stream.AckMessage.STATUS_OK, "OK"++ class _CardHandler(dingtalk_stream.CallbackHandler):+ """Forward an advanced-card callback into the channel."""++ async def process(self, callback: Any) -> tuple[int, str]:+ """Process one approval-card action callback.++ Args:+ callback (`Any`): The Stream SDK callback message.++ Returns:+ `tuple[int, str]`: DingTalk acknowledgement status and+ message.+ """+ try:+ await on_card_callback(callback.data)+ except Exception: # pylint: disable=broad-except+ logger.exception(+ "DingTalk '%s' card callback failed",+ channel.channel_id,+ )+ return (+ dingtalk_stream.AckMessage.STATUS_SYSTEM_EXCEPTION,+ "ERROR",+ )+ return dingtalk_stream.AckMessage.STATUS_OK, "OK"++ credential = dingtalk_stream.Credential(+ self._client_id,+ self._client_secret,+ )+ client = _StoppableStreamClient(credential)+ client.register_callback_handler(_CHATBOT_TOPIC, _MessageHandler())+ client.register_callback_handler(_CARD_CALLBACK_TOPIC, _CardHandler())+ return client++ async def _present_confirm(+ self,+ event: ChannelEvent,+ request: RequireUserConfirmEvent,+ ) -> None:+ """Create one approval card for each pending tool call.++ Args:+ event (`ChannelEvent`): Chat receiving the cards.+ request (`RequireUserConfirmEvent`): Pending tool calls.+ """+ template_id = self._config.approval_card_template_id+ if not template_id or self._openapi is None:+ logger.error(+ "DingTalk '%s' cannot deliver tool approval cards",+ self._channel_id,+ )+ return+ approver_id = (+ event.chat_id.removeprefix("user:")+ if event.chat_id.startswith("user:")+ else ""+ )+ for tool in request.tool_calls:+ card_data = _approval_card_data(+ tool.id,+ event.chat_id,+ tool.name,+ tool.input,+ approver_id,+ str(event.metadata.get("agent_id") or ""),+ str(event.metadata.get("session_id") or ""),+ )+ out_track_id = await self._openapi.create_approval_card(+ event.chat_id,+ approver_id,+ template_id,+ card_data,+ )+ if out_track_id is None:+ await self._send_text(+ event.chat_id,+ "DingTalk could not present the tool approval card. "+ "Please ask the administrator to verify the card "+ "template and application permissions.",+ )++ async def _on_card_callback(self, payload: dict[str, Any]) -> None:+ """Validate a card decision and emit the gateway resume event.++ Args:+ payload (`dict[str, Any]`): Stream advanced-card callback data.+ """+ decision = _parse_card_callback(payload)+ if decision is None:+ logger.warning("DingTalk ignored an invalid card callback")+ return+ if decision.approver_id and decision.user_id != decision.approver_id:+ logger.warning(+ "DingTalk ignored an approval from an unexpected user",+ )+ return+ if self._emit is None:+ return+ await self._emit(+ ChannelConfirmationResultEvent(+ channel_id=self._channel_id,+ chat_id=decision.chat_id,+ channel_user_id=decision.user_id,+ agent_id=decision.agent_id,+ session_id=decision.session_id,+ tool_call_id=decision.tool_call_id,+ approved=decision.approved,+ actor=decision.user_id,+ ),+ )+ if self._openapi is not None:+ await self._openapi.update_approval_card(+ decision.out_track_id,+ _resolved_card_data(decision.approved),+ )++ async def _on_callback(self, payload: dict[str, Any]) -> None:+ """Normalise a DingTalk robot callback and emit it.++ Args:+ payload (`dict[str, Any]`): Parsed callback data from the Stream+ SDK.+ """+ conversation_type = str(payload.get("conversationType", ""))+ is_group = conversation_type == _GROUP_CONVERSATION+ if (+ is_group+ and self._config.only_at_reply+ and payload.get("isInAtList") is False+ ):+ return++ user_id = str(+ payload.get("senderStaffId") or payload.get("senderId") or "",+ )+ conversation_id = str(payload.get("conversationId") or "")+ target_id = conversation_id if is_group else user_id+ if not user_id or not target_id:+ logger.warning(+ "DingTalk '%s' ignored message without stable sender/target",+ self._channel_id,+ )+ return++ chat_id = f"group:{target_id}" if is_group else f"user:{target_id}"+ title = str(payload.get("conversationTitle") or "")+ sender_name = str(payload.get("senderNick") or "")+ self._chat_names[chat_id] = title if is_group else sender_name+ self._cache_session_webhook(chat_id, payload)+ content = await self._parse_content(payload)+ if not content or self._emit is None:+ return++ await self._emit(+ ChannelEvent(+ channel_id=self._channel_id,+ channel_user_id=user_id,+ channel_user_name=sender_name,+ chat_id=chat_id,+ chat_name=title if is_group else "",+ channel_message_id=str(payload.get("msgId") or "") or None,+ content=content,+ metadata={+ "chat_type": "group" if is_group else "private",+ "conversation_type": conversation_type,+ },+ ),+ )++ async def _parse_content(+ self,+ payload: dict[str, Any],+ ) -> list[TextBlock | DataBlock]:+ """Convert a callback's text and media into content blocks.++ Args:+ payload (`dict[str, Any]`): Parsed DingTalk callback data.++ Returns:+ `list[TextBlock | DataBlock]`: Content in callback order.+ """+ message_type = str(payload.get("msgtype") or "")+ if message_type == "text":+ text_value = payload.get("text") or {}+ text = str(text_value.get("content") or "").strip()+ return [TextBlock(text=text)] if text else []+ if message_type not in _MEDIA_MESSAGE_TYPES:+ return []++ raw_content = payload.get("content") or {}+ if not isinstance(raw_content, dict):+ return []+ if message_type == "richText":+ return await self._parse_rich_text(raw_content)++ blocks: list[TextBlock | DataBlock] = []+ recognition = str(raw_content.get("recognition") or "").strip()+ if recognition:+ blocks.append(TextBlock(text=recognition))+ download_code = str(raw_content.get("downloadCode") or "")+ if not download_code:+ return blocks+ file_name, fallback_type = self._media_description(+ message_type,+ raw_content,+ )+ block = await self._download_media(+ download_code,+ file_name,+ fallback_type,+ )+ if block is not None:+ blocks.append(block)+ elif not blocks:+ blocks.append(+ TextBlock(+ text=f"Unable to download DingTalk file: {file_name}",+ ),+ )+ return blocks++ async def _parse_rich_text(+ self,+ content: dict[str, Any],+ ) -> list[TextBlock | DataBlock]:+ """Preserve text/image order from a rich-text callback."""+ blocks: list[TextBlock | DataBlock] = []+ items = content.get("richText") or []+ if not isinstance(items, list):+ return blocks+ for item in items:+ if not isinstance(item, dict):+ continue+ text = str(item.get("text") or "").strip()+ if text:+ blocks.append(TextBlock(text=text))+ download_code = str(item.get("downloadCode") or "")+ if download_code:+ block = await self._download_media(+ download_code,+ "image",+ "image/jpeg",+ )+ if block is not None:+ blocks.append(block)+ return blocks++ async def _download_media(+ self,+ download_code: str,+ file_name: str,+ fallback_type: str,+ ) -> DataBlock | None:+ """Download one media code and build a base64 data block.++ Args:+ download_code (`str`): DingTalk robot-message download code.+ file_name (`str`): Attachment display name.+ fallback_type (`str`): MIME type used when the server omits it.++ Returns:+ `DataBlock | None`: Downloaded media, or ``None`` on failure.+ """+ if self._openapi is None:+ logger.warning("DingTalk OpenAPI client is not running")+ return None+ result = await self._openapi.download_media(+ download_code,+ self._config.max_media_bytes,+ )+ if result is None:+ return None+ data, media_type = result+ if not media_type or media_type == "application/octet-stream":+ media_type = fallback_type+ return DataBlock(+ source=Base64Source(+ data=base64.b64encode(data).decode("ascii"),+ media_type=media_type,+ ),+ name=file_name,+ )++ async def _send_data(self, chat_id: str, block: DataBlock) -> bool:+ """Upload and send one base64 data block through OpenAPI.++ Args:+ chat_id (`str`): Encoded DingTalk destination.+ block (`DataBlock`): Agent-produced attachment.++ Returns:+ `bool`: Whether DingTalk accepted the media message.+ """+ if not isinstance(block.source, Base64Source):+ logger.warning("DingTalk cannot send URL data blocks as files")+ return False+ if self._openapi is None:+ logger.warning("DingTalk OpenAPI client is not running")+ return False+ try:+ data = base64.b64decode(block.source.data, validate=True)+ except (binascii.Error, ValueError):+ logger.warning("DingTalk received invalid base64 output")+ return False+ if len(data) > self._config.max_media_bytes:+ logger.warning("DingTalk outbound media exceeds the size limit")+ return False+ media_type = block.source.media_type or "application/octet-stream"+ if media_type.startswith("image/"):+ fallback_name = "image.png"+ else:+ extension = mimetypes.guess_extension(media_type) or ""+ fallback_name = f"file{extension}"+ file_name = self._safe_file_name(block.name or fallback_name)+ return await self._openapi.send_media(+ chat_id,+ data,+ file_name,+ media_type,+ )++ @staticmethod+ def _media_description(+ message_type: str,+ content: dict[str, Any],+ ) -> tuple[str, str]:+ """Return a safe filename and fallback MIME type for media."""+ if message_type == "picture":+ return "image", "image/jpeg"+ if message_type == "video":+ suffix = str(content.get("videoType") or "mp4").lower()+ return f"video.{suffix}", f"video/{suffix}"+ if message_type == "audio":+ return "audio", "audio/mpeg"+ file_name = DingTalkChannel._safe_file_name(+ str(content.get("fileName") or "file"),+ )+ guessed_type = mimetypes.guess_type(file_name)[0]+ return file_name, guessed_type or "application/octet-stream"++ @staticmethod+ def _safe_file_name(file_name: str) -> str:+ """Strip directory components from a platform filename."""+ return file_name.replace("\\", "/").rsplit("/", 1)[-1] or "file"++ def _cache_session_webhook(+ self,+ chat_id: str,+ payload: dict[str, Any],+ ) -> None:+ """Cache a trusted callback reply URL for the current process.++ Args:+ chat_id (`str`): Encoded DingTalk destination.+ payload (`dict[str, Any]`): Inbound callback data.+ """+ url = str(payload.get("sessionWebhook") or "")+ if not self._is_dingtalk_url(url):+ return+ raw_expiry = payload.get("sessionWebhookExpiredTime")+ expires_at_ms: int | None = None+ if raw_expiry not in (None, ""):+ try:+ expires_at_ms = int(str(raw_expiry))+ if expires_at_ms < 100_000_000_000:+ expires_at_ms *= 1000+ except (TypeError, ValueError):+ logger.warning(+ "DingTalk '%s' received an invalid webhook expiration",+ self._channel_id,+ )+ return+ self._session_webhooks[chat_id] = _SessionWebhook(+ url=url,+ expires_at_ms=expires_at_ms,+ )++ async def _send_text(self, chat_id: str, text: str) -> bool:+ """Send Markdown through a webhook or stable OpenAPI target.++ Args:+ chat_id (`str`): Encoded DingTalk destination.+ text (`str`): Markdown-formatted text to send.++ Returns:+ `bool`: Whether DingTalk accepted the request.+ """+ webhook = self._session_webhooks.get(chat_id)+ now_ms = int(time.time() * 1000)+ if webhook is None or (+ webhook.expires_at_ms is not None+ and webhook.expires_at_ms <= now_ms+ ):+ self._session_webhooks.pop(chat_id, None)+ if self._openapi is not None:+ return await self._openapi.send_text(chat_id, text)+ logger.warning(+ "DingTalk '%s' has no valid reply webhook for '%s'",+ self._channel_id,+ chat_id,+ )+ return False+ if self._http is None:+ logger.warning(+ "DingTalk '%s' HTTP client is not running",+ self._channel_id,+ )+ return False++ try:+ response = await self._http.post(+ webhook.url,+ json={+ "msgtype": "markdown",+ "markdown": {+ "title": _MARKDOWN_TITLE,+ "text": text,+ },+ },+ )+ response.raise_for_status()+ result = response.json()+ if result.get("errcode", 0) != 0:+ logger.warning(+ "DingTalk '%s' rejected a session reply: code=%s",+ self._channel_id,+ result.get("errcode"),+ )+ return False+ return True+ except Exception: # pylint: disable=broad-except+ logger.exception(+ "DingTalk '%s' session reply failed",+ self._channel_id,+ )+ return False++ @staticmethod+ def _is_dingtalk_url(url: str) -> bool:+ """Return whether a callback URL belongs to DingTalk over HTTPS.++ Args:+ url (`str`): URL supplied in an inbound callback.++ Returns:+ `bool`: Whether the URL is safe to use as a session webhook.+ """+ parsed = urlparse(url)+ hostname = (parsed.hostname or "").lower()+ return parsed.scheme == "https" and (+ hostname == "dingtalk.com" or hostname.endswith(".dingtalk.com")+ )diff --git a/src/agentscope/app/channel/_dingtalk/_openapi.py b/src/agentscope/app/channel/_dingtalk/_openapi.pynew file mode 100644index 000000000..f08e5a0e8--- /dev/null+++ b/src/agentscope/app/channel/_dingtalk/_openapi.py@@ -0,0 +1,626 @@+# -*- coding: utf-8 -*-+"""Minimal asynchronous DingTalk OpenAPI client for channel media."""++import asyncio+import ipaddress+import json+import time+from typing import Any+from urllib.parse import urlparse+from uuid import uuid1, uuid4++from ...._logging import logger++_API = "https://api.dingtalk.com/v1.0"+_OAPI = "https://oapi.dingtalk.com"+_TOKEN_REFRESH_BUFFER_SECONDS = 300+_SUPPORTED_FILE_TYPES = frozenset({"doc", "docx", "pdf", "rar", "xlsx", "zip"})+++class _DingTalkOpenAPI:+ """Call only the DingTalk OpenAPI operations needed by the channel."""++ def __init__(+ self,+ client_id: str,+ client_secret: str,+ http: Any,+ ) -> None:+ """Bind application credentials and a shared async HTTP client.++ Args:+ client_id (`str`): DingTalk application Client ID.+ client_secret (`str`): DingTalk application Client Secret.+ http (`Any`): An ``httpx.AsyncClient``-compatible object.+ """+ self._client_id = client_id+ self._client_secret = client_secret+ self._http = http+ self._token: str | None = None+ self._token_expires_at = 0.0+ self._token_lock = asyncio.Lock()++ async def download_media(+ self,+ download_code: str,+ max_bytes: int,+ ) -> tuple[bytes, str] | None:+ """Resolve and download one robot-message attachment.++ Args:+ download_code (`str`): Code from the inbound message content.+ max_bytes (`int`): Maximum accepted response size.++ Returns:+ `tuple[bytes, str] | None`: Bytes and response media type, or+ ``None`` when DingTalk rejects the request or it is too large.+ """+ token = await self._access_token()+ if token is None:+ return None+ try:+ response = await self._http.post(+ f"{_API}/robot/messageFiles/download",+ headers=self._headers(token),+ json={+ "robotCode": self._client_id,+ "downloadCode": download_code,+ },+ )+ response.raise_for_status()+ result = response.json()+ download_url = self._safe_download_url(+ str(result.get("downloadUrl") or ""),+ )+ if download_url is None:+ logger.warning("DingTalk returned an unsafe media URL")+ return None+ return await self._download_bytes(download_url, max_bytes)+ except Exception: # pylint: disable=broad-except+ logger.exception("DingTalk media URL resolution failed")+ return None++ async def send_media(+ self,+ chat_id: str,+ data: bytes,+ file_name: str,+ media_type: str,+ ) -> bool:+ """Upload and send an image or file to an encoded chat target.++ Args:+ chat_id (`str`): ``group:<openConversationId>`` or+ ``user:<staffId>``.+ data (`bytes`): Media bytes.+ file_name (`str`): Display filename.+ media_type (`str`): MIME type.++ Returns:+ `bool`: Whether DingTalk accepted both upload and send calls.+ """+ is_image = media_type.startswith("image/")+ suffix = file_name.rsplit(".", 1)[-1].lower()+ if not is_image and suffix not in _SUPPORTED_FILE_TYPES:+ logger.warning(+ "DingTalk does not support outbound '.%s' files",+ suffix,+ )+ return False+ media_id = await self._upload_media(+ data,+ file_name,+ media_type,+ "image" if is_image else "file",+ )+ if media_id is None:+ return False+ if is_image:+ msg_key = "sampleImageMsg"+ msg_param = {"photoURL": media_id}+ else:+ msg_key = "sampleFile"+ msg_param = {+ "mediaId": media_id,+ "fileName": file_name,+ "fileType": suffix,+ }+ return await self._send_message(chat_id, msg_key, msg_param)++ async def send_text(self, chat_id: str, text: str) -> bool:+ """Send Markdown-formatted text to an encoded target.++ Args:+ chat_id (`str`): ``group:<openConversationId>`` or+ ``user:<staffId>``.+ text (`str`): Markdown-formatted message body.++ Returns:+ `bool`: Whether DingTalk accepted the message.+ """+ return await self._send_message(+ chat_id,+ "sampleMarkdown",+ {"title": "AgentScope", "text": text},+ )++ async def create_approval_card(+ self,+ chat_id: str,+ approver_id: str,+ template_id: str,+ card_data: dict[str, str],+ ) -> str | None:+ """Create and deliver one Stream-callback approval card.++ Args:+ chat_id (`str`): Encoded DingTalk user or group target.+ approver_id (`str`): Optional user permitted to see and decide+ the card. Empty means normal audience visibility.+ template_id (`str`): Card Platform template identifier.+ card_data (`dict[str, str]`): Template parameter map.++ Returns:+ `str | None`: The card's outbound tracking id, or ``None`` when+ creation or delivery fails.+ """+ return await self._create_and_deliver_card(+ chat_id,+ template_id,+ card_data,+ approver_id,+ )++ async def create_streaming_card(+ self,+ chat_id: str,+ template_id: str,+ content_key: str,+ ) -> str | None:+ """Create and deliver an AI streaming card.++ Args:+ chat_id (`str`): Encoded DingTalk user or group target.+ template_id (`str`): AI Card template identifier.+ content_key (`str`): Template streaming-component variable key.++ Returns:+ `str | None`: Outbound tracking id, or ``None`` on failure.+ """+ return await self._create_and_deliver_card(+ chat_id,+ template_id,+ {content_key: ""},+ )++ async def stream_card(+ self,+ out_track_id: str,+ content_key: str,+ content: str,+ *,+ finalize: bool = False,+ is_error: bool = False,+ ) -> bool:+ """Update an AI Card streaming component with full content.++ Args:+ out_track_id (`str`): Tracking id returned by card creation.+ content_key (`str`): Template streaming-component variable key.+ content (`str`): Complete Markdown content for this update.+ finalize (`bool`): Whether this is the final update.+ is_error (`bool`): Whether the card should enter error state.++ Returns:+ `bool`: Whether DingTalk accepted the streaming update.+ """+ token = await self._access_token()+ if token is None:+ return False+ return await self._request(+ "PUT",+ f"{_API}/card/streaming",+ token,+ {+ "outTrackId": out_track_id,+ "guid": str(uuid1()),+ "key": content_key,+ "content": content,+ "isFull": True,+ "isFinalize": finalize,+ "isError": is_error,+ },+ "card streaming update",+ )++ async def update_approval_card(+ self,+ out_track_id: str,+ card_data: dict[str, str],+ ) -> bool:+ """Replace approval-card template parameters after a decision.++ Args:+ out_track_id (`str`): Tracking id returned by card creation.+ card_data (`dict[str, str]`): Resolved template parameter map.++ Returns:+ `bool`: Whether DingTalk accepted the update.+ """+ token = await self._access_token()+ if token is None:+ return False+ return await self._request(+ "PUT",+ f"{_API}/card/instances",+ token,+ {+ "outTrackId": out_track_id,+ "cardData": {"cardParamMap": card_data},+ },+ "card update",+ )++ async def _create_and_deliver_card(+ self,+ chat_id: str,+ template_id: str,+ card_data: dict[str, str],+ recipient_id: str = "",+ ) -> str | None:+ """Create a Card Platform instance and deliver it to a target."""+ if chat_id.startswith("group:"):+ conversation_id = chat_id.removeprefix("group:")+ open_space_id = f"dtv1.card//IM_GROUP.{conversation_id}"+ group_model: dict[str, Any] = {"robotCode": self._client_id}+ if recipient_id:+ group_model["recipients"] = [recipient_id]+ delivery_model: dict[str, Any] = {+ "imGroupOpenDeliverModel": group_model,+ }+ elif chat_id.startswith("user:"):+ user_id = chat_id.removeprefix("user:")+ if recipient_id and user_id != recipient_id:+ logger.warning("DingTalk card target does not match user")+ return None+ open_space_id = f"dtv1.card//IM_ROBOT.{user_id}"+ delivery_model = {+ "imRobotOpenDeliverModel": {"spaceType": "IM_ROBOT"},+ }+ else:+ logger.warning("Invalid DingTalk card target")+ return None+ token = await self._access_token()+ if token is None:+ return None+ out_track_id = uuid4().hex+ created = await self._request(+ "POST",+ f"{_API}/card/instances",+ token,+ {+ "cardTemplateId": template_id,+ "outTrackId": out_track_id,+ "cardData": {"cardParamMap": card_data},+ "callbackType": "STREAM",+ "imGroupOpenSpaceModel": {"supportForward": False},+ "imRobotOpenSpaceModel": {"supportForward": False},+ },+ "card creation",+ )+ if not created:+ return None+ delivered = await self._request(+ "POST",+ f"{_API}/card/instances/deliver",+ token,+ {+ "outTrackId": out_track_id,+ "openSpaceId": open_space_id,+ "userIdType": 1,+ **delivery_model,+ },+ "card delivery",+ )+ return out_track_id if delivered else None++ async def search_users(+ self,+ query: str,+ limit: int,+ ) -> list[dict[str, Any]]:+ """Search enterprise users visible to the application.++ DingTalk's search endpoint returns user ids only. This method+ resolves the matching profiles through the user-detail endpoint so+ callers can disambiguate people with similar names.++ Args:+ query (`str`): User-name search term.+ limit (`int`): Maximum number of users to return.++ Returns:+ `list[dict[str, Any]]`: Visible user ids and basic profiles.+ """+ token = await self._access_token()+ if token is None:+ return []+ try:+ response = await self._http.post(+ f"{_API}/contact/users/search",+ headers=self._headers(token),+ json={+ "queryWord": query,+ "offset": 0,+ "size": limit,+ },+ )+ response.raise_for_status()+ try:+ result = response.json()+ except ValueError:+ result = {}+ if not isinstance(result, dict):+ result = {}+ user_ids = [+ str(user_id) for user_id in result.get("list", []) if user_id+ ][:limit]+ except Exception: # pylint: disable=broad-except+ logger.exception("DingTalk user search failed")+ return []++ users: list[dict[str, Any]] = []+ for user_id in user_ids:+ detail = await self._user_detail(token, user_id)+ users.append(+ detail+ or {+ "user_id": user_id,+ "name": "",+ "title": "",+ "department_ids": [],+ },+ )+ return users++ async def _access_token(self) -> str | None:+ """Return a cached application token, refreshing it when needed."""+ if self._token and time.monotonic() < self._token_expires_at:+ return self._token+ async with self._token_lock:+ if self._token and time.monotonic() < self._token_expires_at:+ return self._token+ try:+ response = await self._http.post(+ f"{_API}/oauth2/accessToken",+ json={+ "appKey": self._client_id,+ "appSecret": self._client_secret,+ },+ )+ response.raise_for_status()+ result = response.json()+ token = str(result.get("accessToken") or "")+ expires_in = int(result.get("expireIn") or 0)+ if not token or expires_in <= 0:+ logger.warning("DingTalk returned an invalid access token")+ return None+ reserve = min(+ _TOKEN_REFRESH_BUFFER_SECONDS,+ max(expires_in // 10, 1),+ )+ self._token = token+ self._token_expires_at = (+ time.monotonic() + expires_in - reserve+ )+ return token+ except Exception: # pylint: disable=broad-except+ logger.exception("DingTalk access token request failed")+ return None++ async def _download_bytes(+ self,+ url: str,+ max_bytes: int,+ ) -> tuple[bytes, str] | None:+ """Download a response incrementally with a hard size limit."""+ try:+ async with self._http.stream(+ "GET",+ url,+ follow_redirects=False,+ ) as response:+ response.raise_for_status()+ raw_length = response.headers.get("content-length")+ if raw_length and int(raw_length) > max_bytes:+ logger.warning("DingTalk media exceeds the size limit")+ return None+ chunks: list[bytes] = []+ size = 0+ async for chunk in response.aiter_bytes():+ size += len(chunk)+ if size > max_bytes:+ logger.warning("DingTalk media exceeds the size limit")+ return None+ chunks.append(chunk)+ media_type = response.headers.get(+ "content-type",+ "application/octet-stream",+ ).split(";", 1)[0]+ return b"".join(chunks), media_type+ except Exception: # pylint: disable=broad-except+ logger.exception("DingTalk media download failed")+ return None++ async def _upload_media(+ self,+ data: bytes,+ file_name: str,+ media_type: str,+ upload_type: str,+ ) -> str | None:+ """Upload media and return the legacy media id."""+ token = await self._access_token()+ if token is None:+ return None+ try:+ response = await self._http.post(+ f"{_OAPI}/media/upload",+ params={"access_token": token},+ data={"type": upload_type},+ files={"media": (file_name, data, media_type)},+ )+ response.raise_for_status()+ result = response.json()+ if result.get("errcode", 0) != 0:+ logger.warning(+ "DingTalk media upload rejected: code=%s",+ result.get("errcode"),+ )+ return None+ media_id = str(result.get("media_id") or "")+ return media_id or None+ except Exception: # pylint: disable=broad-except+ logger.exception("DingTalk media upload failed")+ return None++ async def _user_detail(+ self,+ token: str,+ user_id: str,+ ) -> dict[str, Any] | None:+ """Resolve one user id through the legacy contact endpoint."""+ try:+ response = await self._http.post(+ f"{_OAPI}/topapi/v2/user/get",+ params={"access_token": token},+ json={"userid": user_id, "language": "zh_CN"},+ )+ response.raise_for_status()+ payload = response.json()+ if payload.get("errcode", 0) != 0:+ logger.warning(+ "DingTalk user detail rejected: code=%s",+ payload.get("errcode"),+ )+ return None+ result = payload.get("result") or {}+ return {+ "user_id": str(result.get("userid") or user_id),+ "name": str(result.get("name") or ""),+ "title": str(result.get("title") or ""),+ "department_ids": result.get("dept_id_list") or [],+ }+ except Exception: # pylint: disable=broad-except+ logger.exception("DingTalk user detail request failed")+ return None++ async def _send_message(+ self,+ chat_id: str,+ msg_key: str,+ msg_param: dict[str, str],+ ) -> bool:+ """Send a template message to an encoded user or group target."""+ token = await self._access_token()+ if token is None:+ return False+ target: dict[str, Any]+ if chat_id.startswith("group:"):+ url = f"{_API}/robot/groupMessages/send"+ target = {"openConversationId": chat_id.removeprefix("group:")}+ elif chat_id.startswith("user:"):+ url = f"{_API}/robot/oToMessages/batchSend"+ target = {"userIds": [chat_id.removeprefix("user:")]}+ else:+ logger.warning("Invalid DingTalk message target")+ return False+ body: dict[str, Any] = {+ "robotCode": self._client_id,+ "msgKey": msg_key,+ "msgParam": json.dumps(msg_param, ensure_ascii=False),+ **target,+ }+ try:+ response = await self._http.post(+ url,+ headers=self._headers(token),+ json=body,+ )+ response.raise_for_status()+ result = response.json()+ code = result.get("code")+ if code not in (None, "", 0, "0"):+ logger.warning(+ "DingTalk message send rejected: code=%s",+ code,+ )+ return False+ return True+ except Exception: # pylint: disable=broad-except+ logger.exception("DingTalk message send failed")+ return False++ async def _request(+ self,+ method: str,+ url: str,+ token: str,+ body: dict[str, Any],+ operation: str,+ ) -> bool:+ """Issue one authenticated JSON request and check API errors."""+ try:+ response = await self._http.request(+ method,+ url,+ headers=self._headers(token),+ json=body,+ )+ response.raise_for_status()+ result = response.json()+ code = result.get("code")+ if code not in (None, "", 0, "0"):+ logger.warning(+ "DingTalk %s rejected: code=%s",+ operation,+ code,+ )+ return False+ return True+ except Exception: # pylint: disable=broad-except+ logger.exception("DingTalk %s failed", operation)+ return False++ @staticmethod+ def _headers(token: str) -> dict[str, str]:+ """Build DingTalk OpenAPI authentication headers."""+ return {+ "Content-Type": "application/json",+ "x-acs-dingtalk-access-token": token,+ }++ @staticmethod+ def _safe_download_url(url: str) -> str | None:+ """Return a safe HTTPS media URL from DingTalk OpenAPI.++ DingTalk currently returns signed Alibaba Cloud OSS URLs with an+ ``http`` scheme. Upgrade only those known OSS hosts to HTTPS; never+ follow arbitrary clear-text download URLs.+ """+ parsed = urlparse(url)+ if not parsed.hostname or parsed.username or parsed.password:+ return None+ hostname = parsed.hostname.lower()+ if hostname == "localhost":+ return None+ try:+ if not ipaddress.ip_address(hostname).is_global:+ return None+ except ValueError:+ pass+ if parsed.scheme == "https":+ return url+ if parsed.scheme == "http" and hostname.endswith(".aliyuncs.com"):+ return parsed._replace(scheme="https").geturl()+ return Nonediff --git a/src/agentscope/app/channel/_dingtalk/_tools/__init__.py b/src/agentscope/app/channel/_dingtalk/_tools/__init__.pynew file mode 100644index 000000000..fa1c222c1--- /dev/null+++ b/src/agentscope/app/channel/_dingtalk/_tools/__init__.py@@ -0,0 +1,16 @@+# -*- coding: utf-8 -*-+"""DingTalk agent tools for discovery and target sending."""++from ._list_conversations import ListConversations+from ._list_users import ListUsers+from ._send_file import SendFile+from ._send_image import SendImage+from ._send_message import SendMessage++__all__ = [+ "ListConversations",+ "ListUsers",+ "SendFile",+ "SendImage",+ "SendMessage",+]diff --git a/src/agentscope/app/channel/_dingtalk/_tools/_base.py b/src/agentscope/app/channel/_dingtalk/_tools/_base.pynew file mode 100644index 000000000..576ff114f--- /dev/null+++ b/src/agentscope/app/channel/_dingtalk/_tools/_base.py@@ -0,0 +1,88 @@+# -*- coding: utf-8 -*-+"""Shared base and result helper for DingTalk agent tools."""++from typing import Any, TYPE_CHECKING++from .....message import TextBlock, ToolResultState+from .....permission import (+ PermissionBehavior,+ PermissionContext,+ PermissionDecision,+)+from .....tool import BackendBase, ToolBase, ToolChunk++if TYPE_CHECKING:+ from .._channel import DingTalkChannel+++def _ack(accepted: bool, what: str) -> ToolChunk:+ """Convert a DingTalk send result into a tool chunk.++ Args:+ accepted (`bool`): Whether DingTalk accepted the request.+ what (`str`): Short description of the attempted operation.++ Returns:+ `ToolChunk`: Success or error result for the agent.+ """+ if accepted:+ return ToolChunk(content=[TextBlock(text=f"Sent {what}.")])+ return ToolChunk(+ content=[+ TextBlock(+ text=f"Failed to send {what}: DingTalk rejected the request.",+ ),+ ],+ state=ToolResultState.ERROR,+ )+++class _DingTalkToolBase(ToolBase):+ """Base for DingTalk tools bound to a channel and workspace."""++ is_concurrency_safe: bool = False+ is_state_injected: bool = False+ is_external_tool: bool = False+ is_mcp: bool = False+ mcp_name: str | None = None++ def __init__(+ self,+ channel: "DingTalkChannel",+ backend: BackendBase,+ ) -> None:+ """Bind the live channel and session workspace backend.++ Args:+ channel (`DingTalkChannel`): Live DingTalk channel.+ backend (`BackendBase`): Workspace backend for file reads.+ """+ super().__init__()+ self._channel = channel+ self._backend = backend++ async def check_permissions(+ self,+ tool_input: dict[str, Any],+ context: PermissionContext,+ ) -> PermissionDecision:+ """Allow lookups and ask before cross-target sends.++ Args:+ tool_input (`dict[str, Any]`): Proposed tool arguments.+ context (`PermissionContext`): Session permission context.++ Returns:+ `PermissionDecision`: Read allow or send confirmation request.+ """+ del tool_input, context+ if self.is_read_only:+ return PermissionDecision(+ behavior=PermissionBehavior.ALLOW,+ message=f"{self.name} is a read-only lookup.",+ )+ return PermissionDecision(+ behavior=PermissionBehavior.ASK,+ message="Sending to another DingTalk conversation needs the "+ "user's confirmation.",+ )diff --git a/src/agentscope/app/channel/_dingtalk/_tools/_list_conversations.py b/src/agentscope/app/channel/_dingtalk/_tools/_list_conversations.pynew file mode 100644index 000000000..af6d5bcff--- /dev/null+++ b/src/agentscope/app/channel/_dingtalk/_tools/_list_conversations.py@@ -0,0 +1,60 @@+# -*- coding: utf-8 -*-+"""List conversations observed by the DingTalk robot process."""++import json++from pydantic import Field++from .....message import TextBlock+from .....tool import ParamsBase, ToolChunk+from ._base import _DingTalkToolBase+++class _ListConversationsParams(ParamsBase):+ query: str | None = Field(+ default=None,+ description="Optional case-insensitive name filter.",+ )+++class ListConversations(_DingTalkToolBase):+ """List DingTalk conversations previously observed by this robot."""++ name: str = "ListConversations"+ description: str = """List DingTalk conversations this robot process has \+already received messages from.++## Important Limitation+DingTalk application robots cannot enumerate every group they belong to. \+This result contains only conversations observed since the channel process \+started.++## Output+A JSON array of ``{target, name, chat_type}``. Copy ``target`` verbatim into \+a DingTalk Send* tool."""+ is_read_only: bool = True+ input_schema: dict = _ListConversationsParams.model_json_schema()++ async def __call__(self, query: str | None = None) -> ToolChunk:+ """Return observed conversations filtered by name.++ Args:+ query (`str | None`): Optional case-insensitive name filter.++ Returns:+ `ToolChunk`: JSON-encoded address records.+ """+ chats = await self._channel.list_bot_chats()+ needle = (query or "").lower()+ items = [+ {+ "target": chat.get("chat_id", ""),+ "name": chat.get("name", ""),+ "chat_type": chat.get("chat_type", ""),+ }+ for chat in chats+ if not needle or needle in (chat.get("name", "") or "").lower()+ ]+ return ToolChunk(+ content=[TextBlock(text=json.dumps(items, ensure_ascii=False))],+ )diff --git a/src/agentscope/app/channel/_dingtalk/_tools/_list_users.py b/src/agentscope/app/channel/_dingtalk/_tools/_list_users.pynew file mode 100644index 000000000..5e933ae63--- /dev/null+++ b/src/agentscope/app/channel/_dingtalk/_tools/_list_users.py@@ -0,0 +1,69 @@+# -*- coding: utf-8 -*-+"""Search users visible in the DingTalk enterprise directory."""++import json++from pydantic import Field++from .....message import TextBlock+from .....tool import ParamsBase, ToolChunk+from ._base import _DingTalkToolBase+++class _ListUsersParams(ParamsBase):+ query: str = Field(+ min_length=1,+ description="User name to search for in the DingTalk directory.",+ )+ limit: int = Field(+ default=20,+ ge=1,+ le=50,+ description="Maximum number of matches to return.",+ )+++class ListUsers(_DingTalkToolBase):+ """Search enterprise users and return ready-to-send targets."""++ name: str = "ListUsers"+ description: str = """Search users visible to the DingTalk application.++## When to Use+- You need a stable DingTalk user target before sending a direct message.++## Output+A JSON array of ``{target, name, title, department_ids}``. Copy ``target`` \+verbatim into a DingTalk Send* tool. Results depend on the application's \+directory permissions."""+ is_read_only: bool = True+ input_schema: dict = _ListUsersParams.model_json_schema()++ async def __call__(+ self,+ query: str,+ limit: int = 20,+ ) -> ToolChunk:+ """Search visible users by name.++ Args:+ query (`str`): User-name search term.+ limit (`int`): Maximum result count.++ Returns:+ `ToolChunk`: JSON-encoded user target records.+ """+ users = await self._channel.search_users(query, limit)+ items = [+ {+ "target": f"user:{user.get('user_id', '')}",+ "name": user.get("name", ""),+ "title": user.get("title", ""),+ "department_ids": user.get("department_ids", []),+ }+ for user in users+ if user.get("user_id")+ ]+ return ToolChunk(+ content=[TextBlock(text=json.dumps(items, ensure_ascii=False))],+ )diff --git a/src/agentscope/app/channel/_dingtalk/_tools/_send_file.py b/src/agentscope/app/channel/_dingtalk/_tools/_send_file.pynew file mode 100644index 000000000..46a7c433c--- /dev/null+++ b/src/agentscope/app/channel/_dingtalk/_tools/_send_file.py@@ -0,0 +1,64 @@+# -*- coding: utf-8 -*-+"""Send a workspace file to a specified DingTalk user or group."""++from pathlib import Path++from pydantic import Field++from .....message import TextBlock, ToolResultState+from .....tool import ParamsBase, ToolChunk+from ._base import _ack, _DingTalkToolBase+++class _SendFileParams(ParamsBase):+ path: str = Field(+ description="Absolute path to a file in the calling workspace.",+ )+ target: str = Field(+ pattern=r"^(user|group):.+$",+ description="Encoded target returned by ListConversations or "+ "ListUsers.",+ )+++class SendFile(_DingTalkToolBase):+ """Send a supported workspace file to a DingTalk target."""++ name: str = "SendFile"+ description: str = """Send a workspace file to a specified DingTalk user \+or group.++Supported DingTalk file extensions are doc, docx, pdf, rar, xlsx, and zip. \+Obtain ``target`` from a discovery tool. The operation requires \+confirmation. Use ``SendImage`` for inline images."""+ is_read_only: bool = False+ input_schema: dict = _SendFileParams.model_json_schema()++ async def __call__(self, path: str, target: str) -> ToolChunk:+ """Read a workspace file and send it to a target.++ Args:+ path (`str`): Workspace file path.+ target (`str`): Encoded DingTalk target.++ Returns:+ `ToolChunk`: DingTalk acceptance or workspace error.+ """+ try:+ raw = await self._backend.read_file(path)+ except Exception as error: # pylint: disable=broad-except+ return ToolChunk(+ content=[+ TextBlock(+ text=f"SendFile: cannot read {path!r}: {error}",+ ),+ ],+ state=ToolResultState.ERROR,+ )+ file_name = Path(path).name+ accepted = await self._channel.send_file_to(+ target,+ raw,+ file_name,+ )+ return _ack(accepted, f"file {file_name} to {target}")diff --git a/src/agentscope/app/channel/_dingtalk/_tools/_send_image.py b/src/agentscope/app/channel/_dingtalk/_tools/_send_image.pynew file mode 100644index 000000000..5b98a9a1d--- /dev/null+++ b/src/agentscope/app/channel/_dingtalk/_tools/_send_image.py@@ -0,0 +1,63 @@+# -*- coding: utf-8 -*-+"""Send a workspace image to a specified DingTalk user or group."""++from pathlib import Path++from pydantic import Field++from .....message import TextBlock, ToolResultState+from .....tool import ParamsBase, ToolChunk+from ._base import _ack, _DingTalkToolBase+++class _SendImageParams(ParamsBase):+ path: str = Field(+ description="Absolute path to an image in the calling workspace.",+ )+ target: str = Field(+ pattern=r"^(user|group):.+$",+ description="Encoded target returned by ListConversations or "+ "ListUsers.",+ )+++class SendImage(_DingTalkToolBase):+ """Send a workspace image inline to a DingTalk target."""++ name: str = "SendImage"+ description: str = """Send a workspace image to a specified DingTalk user \+or group so it renders inline.++Obtain ``target`` from ``ListConversations`` or ``ListUsers``. The operation \+requires confirmation."""+ is_read_only: bool = False+ input_schema: dict = _SendImageParams.model_json_schema()++ async def __call__(self, path: str, target: str) -> ToolChunk:+ """Read a workspace image and send it to a target.++ Args:+ path (`str`): Workspace image path.+ target (`str`): Encoded DingTalk target.++ Returns:+ `ToolChunk`: DingTalk acceptance or workspace error.+ """+ try:+ raw = await self._backend.read_file(path)+ except Exception as error: # pylint: disable=broad-except+ return ToolChunk(+ content=[+ TextBlock(+ text=f"SendImage: cannot read {path!r}: {error}",+ ),+ ],+ state=ToolResultState.ERROR,+ )+ file_name = Path(path).name+ accepted = await self._channel.send_image_to(+ target,+ raw,+ file_name,+ )+ return _ack(accepted, f"image to {target}")diff --git a/src/agentscope/app/channel/_dingtalk/_tools/_send_message.py b/src/agentscope/app/channel/_dingtalk/_tools/_send_message.pynew file mode 100644index 000000000..963b82d02--- /dev/null+++ b/src/agentscope/app/channel/_dingtalk/_tools/_send_message.py@@ -0,0 +1,45 @@+# -*- coding: utf-8 -*-+"""Send Markdown text to a specified DingTalk user or group."""++from pydantic import Field++from .....tool import ParamsBase, ToolChunk+from ._base import _ack, _DingTalkToolBase+++class _SendMessageParams(ParamsBase):+ target: str = Field(+ pattern=r"^(user|group):.+$",+ description="Encoded target returned by ListConversations or "+ "ListUsers.",+ )+ text: str = Field(+ min_length=1,+ description="Markdown-formatted message body.",+ )+++class SendMessage(_DingTalkToolBase):+ """Send Markdown text to a conversation other than the current one."""++ name: str = "SendMessage"+ description: str = """Send Markdown text to a DingTalk user or group.++Use this only when the user asks to contact a target other than the current \+conversation. Obtain ``target`` from ``ListConversations`` or ``ListUsers``. \+The operation requires confirmation."""+ is_read_only: bool = False+ input_schema: dict = _SendMessageParams.model_json_schema()++ async def __call__(self, target: str, text: str) -> ToolChunk:+ """Send Markdown text to an encoded target.++ Args:+ target (`str`): Encoded DingTalk target.+ text (`str`): Markdown-formatted message body.++ Returns:+ `ToolChunk`: DingTalk acceptance result.+ """+ accepted = await self._channel.send_message_to(target, text)+ return _ack(accepted, f"message to {target}")diff --git a/tests/channel_dingtalk_e2e.py b/tests/channel_dingtalk_e2e.pynew file mode 100644index 000000000..65eb354aa--- /dev/null+++ b/tests/channel_dingtalk_e2e.py@@ -0,0 +1,554 @@+# -*- coding: utf-8 -*-+"""Manual end-to-end checks for the DingTalk channel.++These checks use a real DingTalk internal application and intentionally do+not run as part of the pytest suite. Credentials are accepted only through+environment variables so they cannot be exposed in shell history::++ export DINGTALK_CLIENT_ID=ding...+ export DINGTALK_CLIENT_SECRET=...+ export DINGTALK_APPROVAL_CARD_TEMPLATE_ID=....schema+ export DINGTALK_STREAMING_CARD_TEMPLATE_ID=....schema+ uv run python tests/channel_dingtalk_e2e.py direct++Available scenarios are ``direct``, ``group``, ``approval``, ``streaming``,+``shutdown``, and ``all``. Follow the interactive instructions printed by+the selected scenario.+"""++import argparse+import asyncio+import base64+from collections.abc import AsyncIterator, Awaitable, Callable+import os+from typing import Any, TypeAlias+from uuid import uuid4++from agentscope.app.channel import DingTalkChannel+from agentscope.app.channel._base import (+ ChannelConfirmationResultEvent,+ ChannelEvent,+)+from agentscope.app.channel._dingtalk._card import _approval_card_data+from agentscope.event import (+ ReplyEndEvent,+ ReplyStartEvent,+ TextBlockDeltaEvent,+ TextBlockEndEvent,+ TextBlockStartEvent,+)+from agentscope.message import DataBlock++_PNG = base64.b64decode(+ "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNk"+ "/x8AAusB9Y9Z3xkAAAAASUVORK5CYII=",+)+_PDF = (+ b"%PDF-1.4\n1 0 obj<</Type/Catalog/Pages 2 0 R>>endobj\n"+ b"2 0 obj<</Type/Pages/Count 0/Kids[]>>endobj\n"+ b"trailer<</Root 1 0 R>>\n%%EOF\n"+)+_Event: TypeAlias = ChannelEvent | ChannelConfirmationResultEvent+_Emitter = Callable[[_Event], Awaitable[None]]+++def _credentials() -> DingTalkChannel.Credentials:+ """Read real-application credentials from the environment."""+ client_id = os.environ.get("DINGTALK_CLIENT_ID", "")+ client_secret = os.environ.get("DINGTALK_CLIENT_SECRET", "")+ if not client_id or not client_secret:+ raise ValueError(+ "Set DINGTALK_CLIENT_ID and DINGTALK_CLIENT_SECRET first.",+ )+ return DingTalkChannel.Credentials(+ client_id=client_id,+ client_secret=client_secret,+ )+++def _template_id(variable: str) -> str:+ """Read a required Card Platform template id."""+ value = os.environ.get(variable, "")+ if not value:+ raise ValueError(f"Set {variable} to a published template id.")+ return value+++def _channel(+ name: str,+ **config: Any,+) -> DingTalkChannel:+ """Construct a real DingTalk channel for one isolated scenario."""+ config.setdefault("only_at_reply", False)+ return DingTalkChannel(+ name,+ _credentials(),+ DingTalkChannel.Config(**config),+ )+++async def _run_until(+ channel: DingTalkChannel,+ emit: _Emitter,+ completed: asyncio.Event,+ instruction: str,+ timeout: float,+) -> bool:+ """Run a listener until a scenario completes or times out."""+ listener = asyncio.create_task(channel.start_listening(emit))+ try:+ for _ in range(150):+ if channel.status.state == "connected":+ print(f"READY: {instruction}", flush=True)+ break+ if channel.status.state == "failed":+ print("FAIL: Stream connection failed", flush=True)+ return False+ await asyncio.sleep(0.2)+ else:+ print("FAIL: Stream connection timed out", flush=True)+ return False++ try:+ await asyncio.wait_for(completed.wait(), timeout=timeout)+ except TimeoutError:+ print("FAIL: interactive scenario timed out", flush=True)+ return False+ return True+ finally:+ listener.cancel()+ await asyncio.gather(listener, return_exceptions=True)+++async def _direct(timeout: float) -> bool:+ """Check direct callbacks, discovery, users, and bidirectional media."""+ channel = _channel("dingtalk-direct-e2e")+ completed = asyncio.Event()+ results: dict[str, bool] = {}++ def maybe_complete() -> None:+ required = (+ "inbound_text",+ "conversation",+ "user_search",+ "target_text",+ "target_image",+ "target_file",+ "inbound_image",+ "inbound_file",+ )+ if all(results.get(key) for key in required):+ completed.set()++ async def emit(event: _Event) -> None:+ if not isinstance(event, ChannelEvent):+ return+ data_blocks = [+ block for block in event.content if isinstance(block, DataBlock)+ ]+ for block in data_blocks:+ media_type = block.source.media_type+ if media_type.startswith("image/"):+ results["inbound_image"] = True+ print("PASS: inbound image converted to DataBlock", flush=True)+ else:+ results["inbound_file"] = True+ print("PASS: inbound file converted to DataBlock", flush=True)+ if data_blocks:+ maybe_complete()+ return+ if results.get("inbound_text"):+ return++ results["inbound_text"] = event.metadata.get("chat_type") == "private"+ print(+ (+ "PASS: direct Stream callback normalized"+ if results["inbound_text"]+ else "FAIL: callback is not a direct message"+ ),+ flush=True,+ )+ api = channel._openapi # pylint: disable=protected-access+ if api is None:+ print("FAIL: OpenAPI client unavailable", flush=True)+ completed.set()+ return++ conversations = await channel.list_bot_chats()+ results["conversation"] = any(+ item.get("chat_id") == event.chat_id for item in conversations+ )+ print(+ (+ "PASS: observed direct conversation listed"+ if results["conversation"]+ else "FAIL: direct conversation is missing"+ ),+ flush=True,+ )++ users = await api.search_users(event.channel_user_name, 20)+ results["user_search"] = any(+ user.get("user_id") == event.channel_user_id for user in users+ )+ print(+ (+ "PASS: user search returned the inbound user"+ if results["user_search"]+ else "FAIL: inbound user is missing from search"+ ),+ flush=True,+ )++ target = f"user:{event.channel_user_id}"+ results["target_text"] = await api.send_text(+ target,+ "**AgentScope DingTalk E2E**\n\nTargeted Markdown passed.",+ )+ results["target_image"] = await api.send_media(+ target,+ _PNG,+ "agentscope-e2e.png",+ "image/png",+ )+ results["target_file"] = await api.send_media(+ target,+ _PDF,+ "agentscope-e2e.pdf",+ "application/pdf",+ )+ for key, label in (+ ("target_text", "targeted Markdown"),+ ("target_image", "targeted image"),+ ("target_file", "targeted file"),+ ):+ print(+ (+ f"PASS: {label} accepted"+ if results[key]+ else f"FAIL: {label} rejected"+ ),+ flush=True,+ )+ maybe_complete()++ finished = await _run_until(+ channel,+ emit,+ completed,+ "send a direct text message, then one image and one PDF",+ timeout,+ )+ return finished and all(results.values())+++async def _group(timeout: float) -> bool:+ """Check group callback normalization, discovery, and targeted send."""+ channel = _channel("dingtalk-group-e2e", only_at_reply=True)+ completed = asyncio.Event()+ succeeded = False++ async def emit(event: _Event) -> None:+ nonlocal succeeded+ if not isinstance(event, ChannelEvent) or completed.is_set():+ return+ is_group = event.metadata.get("chat_type") == "group"+ conversations = await channel.list_bot_chats()+ discovered = any(+ item.get("chat_id") == event.chat_id+ and item.get("chat_type") == "group"+ for item in conversations+ )+ api = channel._openapi # pylint: disable=protected-access+ sent = bool(+ api+ and await api.send_text(+ event.chat_id,+ "**AgentScope group E2E**\n\nTargeted group Markdown passed.",+ ),+ )+ for ok, label in (+ (is_group, "group callback normalized"),+ (discovered, "observed group conversation listed"),+ (sent, "targeted group Markdown accepted"),+ ):+ print(f"{'PASS' if ok else 'FAIL'}: {label}", flush=True)+ succeeded = is_group and discovered and sent+ completed.set()++ finished = await _run_until(+ channel,+ emit,+ completed,+ "mention the robot in a test group",+ timeout,+ )+ return finished and succeeded+++async def _approval(timeout: float) -> bool:+ """Check approval-card delivery and both callback decisions."""+ template_id = _template_id("DINGTALK_APPROVAL_CARD_TEMPLATE_ID")+ channel = _channel(+ "dingtalk-approval-e2e",+ approval_card_template_id=template_id,+ )+ completed = asyncio.Event()+ run_id = uuid4().hex+ inbound: ChannelEvent | None = None+ expected = True+ current_tool_call_id = ""+ results: list[bool] = []++ async def deliver(decision: bool) -> bool:+ nonlocal current_tool_call_id+ if inbound is None:+ return False+ api = channel._openapi # pylint: disable=protected-access+ if api is None:+ return False+ label = "approve" if decision else "deny"+ current_tool_call_id = f"e2e-{run_id}-{label}"+ out_track_id = await api.create_approval_card(+ inbound.chat_id,+ inbound.channel_user_id,+ template_id,+ _approval_card_data(+ current_tool_call_id,+ inbound.chat_id,+ "SendMessage",+ '{"target":"user:e2e","text":"approval E2E"}',+ inbound.channel_user_id,+ f"e2e-agent-{run_id}",+ f"e2e-session-{run_id}",+ ),+ )+ if out_track_id:+ print(+ f"READY: click {'approve' if decision else 'reject'}",+ flush=True,+ )+ else:+ print("FAIL: approval card was not delivered", flush=True)+ return bool(out_track_id)++ async def emit(event: _Event) -> None:+ nonlocal inbound, expected+ if isinstance(event, ChannelEvent):+ if inbound is not None:+ return+ inbound = event+ if not await deliver(True):+ completed.set()+ return+ if event.tool_call_id != current_tool_call_id:+ print("IGNORED: callback from another card", flush=True)+ return+ matched = event.approved is expected+ results.append(matched)+ print(+ f"{'PASS' if matched else 'FAIL'}: "+ f"{'approval' if expected else 'denial'} callback routed",+ flush=True,+ )+ if expected:+ expected = False+ if not await deliver(False):+ completed.set()+ else:+ completed.set()++ finished = await _run_until(+ channel,+ emit,+ completed,+ "send a direct message to receive the first approval card",+ timeout,+ )+ return finished and results == [True, True]+++async def _streaming_events() -> AsyncIterator[dict[str, Any]]:+ """Yield a small Agent event stream with visible update intervals."""+ reply_id = f"dingtalk-streaming-e2e-{uuid4().hex}"+ for start_event in (+ ReplyStartEvent(+ session_id="dingtalk-streaming-e2e",+ reply_id=reply_id,+ name="assistant",+ ),+ TextBlockStartEvent(reply_id=reply_id, block_id="text-1"),+ ):+ yield start_event.model_dump(mode="json")+ for delta in (+ "# AgentScope DingTalk streaming E2E",+ "\n\n- AI card created",+ "\n- Incremental Markdown updated",+ "\n- Stream finalized successfully",+ ):+ yield TextBlockDeltaEvent(+ reply_id=reply_id,+ block_id="text-1",+ delta=delta,+ ).model_dump(mode="json")+ await asyncio.sleep(0.4)+ for end_event in (+ TextBlockEndEvent(reply_id=reply_id, block_id="text-1"),+ ReplyEndEvent(+ session_id="dingtalk-streaming-e2e",+ reply_id=reply_id,+ ),+ ):+ yield end_event.model_dump(mode="json")+++async def _streaming(timeout: float) -> bool:+ """Check AI-card creation, incremental updates, and finalization."""+ template_id = _template_id("DINGTALK_STREAMING_CARD_TEMPLATE_ID")+ channel = _channel(+ "dingtalk-streaming-e2e",+ streaming_card_template_id=template_id,+ streaming_card_key="content",+ )+ completed = asyncio.Event()+ succeeded = False++ async def emit(event: _Event) -> None:+ nonlocal succeeded+ if not isinstance(event, ChannelEvent) or completed.is_set():+ return+ api = channel._openapi # pylint: disable=protected-access+ if api is None:+ print("FAIL: OpenAPI client unavailable", flush=True)+ completed.set()+ return+ create = api.create_streaming_card+ update = api.stream_card+ created = False+ updates: list[tuple[bool, bool]] = []++ async def tracked_create(*args: Any, **kwargs: Any) -> str | None:+ nonlocal created+ result = await create(*args, **kwargs)+ created = bool(result)+ return result++ async def tracked_update(*args: Any, **kwargs: Any) -> bool:+ result = await update(*args, **kwargs)+ updates.append((bool(kwargs.get("finalize")), result))+ return result++ setattr(api, "create_streaming_card", tracked_create)+ setattr(api, "stream_card", tracked_update)+ try:+ await channel.send_response(event, _streaming_events())+ finally:+ setattr(api, "create_streaming_card", create)+ setattr(api, "stream_card", update)+ succeeded = (+ created+ and len(updates) >= 2+ and all(ok for _, ok in updates)+ and any(finalize for finalize, _ in updates)+ )+ print(+ (+ "PASS: AI card created, incrementally updated, and finalized"+ if succeeded+ else "FAIL: AI streaming-card lifecycle was incomplete"+ ),+ flush=True,+ )+ completed.set()++ finished = await _run_until(+ channel,+ emit,+ completed,+ "send a direct message to receive the streaming AI card",+ timeout,+ )+ return finished and succeeded+++async def _shutdown(_timeout: float) -> bool:+ """Check that the official Stream connection stops promptly."""+ channel = _channel("dingtalk-shutdown-e2e")++ async def emit(event: _Event) -> None:+ del event++ listener = asyncio.create_task(channel.start_listening(emit))+ for _ in range(150):+ if channel.status.state == "connected":+ break+ if channel.status.state == "failed":+ print("FAIL: Stream connection failed", flush=True)+ return False+ await asyncio.sleep(0.2)+ else:+ print("FAIL: Stream connection timed out", flush=True)+ return False++ listener.cancel()+ try:+ await asyncio.wait_for(listener, timeout=5.0)+ except asyncio.CancelledError:+ pass+ except TimeoutError:+ print("FAIL: Stream listener did not stop within 5 seconds")+ return False+ succeeded = channel.status.state == "stopped"+ print(+ (+ "PASS: real DingTalk Stream stopped cleanly"+ if succeeded+ else "FAIL: Channel did not enter stopped state"+ ),+ flush=True,+ )+ return succeeded+++_SCENARIOS: dict[str, Callable[[float], Awaitable[bool]]] = {+ "direct": _direct,+ "group": _group,+ "approval": _approval,+ "streaming": _streaming,+ "shutdown": _shutdown,+}+++async def _main(scenario: str, timeout: float) -> int:+ """Run one scenario or the complete interactive sequence."""+ names = list(_SCENARIOS) if scenario == "all" else [scenario]+ for name in names:+ print(f"\n=== DingTalk E2E: {name} ===", flush=True)+ if not await _SCENARIOS[name](timeout):+ print(f"FAIL: {name}", flush=True)+ return 1+ print(f"PASS: {name}", flush=True)+ return 0+++def _parse_args() -> argparse.Namespace:+ """Parse the manual runner command line."""+ parser = argparse.ArgumentParser(description=__doc__)+ parser.add_argument(+ "scenario",+ choices=(*_SCENARIOS, "all"),+ help="real DingTalk scenario to run",+ )+ parser.add_argument(+ "--timeout",+ type=float,+ default=300.0,+ help="seconds allowed for each interactive scenario",+ )+ return parser.parse_args()+++if __name__ == "__main__":+ _ARGS = _parse_args()+ raise SystemExit(asyncio.run(_main(_ARGS.scenario, _ARGS.timeout)))diff --git a/tests/channel_dingtalk_test.py b/tests/channel_dingtalk_test.pynew file mode 100644index 000000000..da14dccf7--- /dev/null+++ b/tests/channel_dingtalk_test.py@@ -0,0 +1,1433 @@+# -*- coding: utf-8 -*-+"""Unit tests for the DingTalk Channel text and media paths."""++# pylint: disable=protected-access,missing-function-docstring+import asyncio+import base64+import json+import time+from typing import Any, AsyncIterator, cast+from unittest import IsolatedAsyncioTestCase+from unittest.mock import patch+from uuid import UUID++from agentscope.app.channel import DingTalkChannel+from agentscope.app.channel._base import (+ ChannelConfirmationResultEvent,+ ChannelEvent,+ ChatKind,+)+from agentscope.app.channel._dingtalk._openapi import _DingTalkOpenAPI+from agentscope.app.channel._registry import ChannelTypeRegistry+from agentscope.event import (+ DataBlockDeltaEvent,+ DataBlockEndEvent,+ DataBlockStartEvent,+ ReplyEndEvent,+ ReplyStartEvent,+ RequireUserConfirmEvent,+ TextBlockDeltaEvent,+ TextBlockEndEvent,+ TextBlockStartEvent,+)+from agentscope.message import (+ Base64Source,+ DataBlock,+ TextBlock,+ ToolCallBlock,+)+from agentscope.permission import PermissionBehavior, PermissionContext+from agentscope.workspace import WorkspaceBase++_REPLY_ID = "reply-1"+_WEBHOOK = "https://oapi.dingtalk.com/robot/sendBySession?session=secret"+++class _FakeResponse:+ """Minimal successful HTTP response."""++ def __init__(self, result: dict[str, Any] | None = None) -> None:+ self._result = result if result is not None else {"errcode": 0}++ def raise_for_status(self) -> None:+ pass++ def json(self) -> dict[str, Any]:+ return self._result+++class _FakeHTTP:+ """Record outbound webhook calls."""++ def __init__(self) -> None:+ self.posts: list[tuple[str, dict[str, Any]]] = []+ self.closed = False++ async def post(self, url: str, **kwargs: Any) -> _FakeResponse:+ self.posts.append((url, kwargs))+ return _FakeResponse()++ async def aclose(self) -> None:+ self.closed = True+++class _FakeStreamClient:+ """A cancellable stand-in for the official Stream client."""++ def __init__(self) -> None:+ self.websocket: object | None = object()+ self.started = asyncio.Event()+ self._stopped = asyncio.Event()+ self.stop_calls = 0++ async def start(self) -> None:+ self.started.set()+ await self._stopped.wait()++ async def stop(self) -> None:+ self.stop_calls += 1+ self._stopped.set()+++class _FakeMediaOpenAPI:+ """Return fixed downloads and record channel media sends."""++ def __init__(+ self,+ download: tuple[bytes, str] | None = (b"media", "image/png"),+ ) -> None:+ self.download = download+ self.download_calls: list[tuple[str, int]] = []+ self.send_calls: list[tuple[str, bytes, str, str]] = []+ self.text_calls: list[tuple[str, str]] = []+ self.search_result: list[dict[str, Any]] = []+ self.approval_calls: list[tuple[str, str, str, dict[str, str]]] = []+ self.card_updates: list[tuple[str, dict[str, str]]] = []+ self.streaming_card_id: str | None = "stream-track-1"+ self.streaming_card_calls: list[tuple[str, str, str]] = []+ self.streaming_updates: list[tuple[str, str, str, bool, bool]] = []+ self.streaming_update_success = True++ async def download_media(+ self,+ download_code: str,+ max_bytes: int,+ ) -> tuple[bytes, str] | None:+ self.download_calls.append((download_code, max_bytes))+ return self.download++ async def send_media(+ self,+ chat_id: str,+ data: bytes,+ file_name: str,+ media_type: str,+ ) -> bool:+ self.send_calls.append((chat_id, data, file_name, media_type))+ return True++ async def send_text(self, chat_id: str, text: str) -> bool:+ self.text_calls.append((chat_id, text))+ return True++ async def search_users(+ self,+ query: str,+ limit: int,+ ) -> list[dict[str, Any]]:+ del query+ return self.search_result[:limit]++ async def create_approval_card(+ self,+ chat_id: str,+ approver_id: str,+ template_id: str,+ card_data: dict[str, str],+ ) -> str:+ self.approval_calls.append(+ (chat_id, approver_id, template_id, card_data),+ )+ return "track-1"++ async def update_approval_card(+ self,+ out_track_id: str,+ card_data: dict[str, str],+ ) -> bool:+ self.card_updates.append((out_track_id, card_data))+ return True++ async def create_streaming_card(+ self,+ chat_id: str,+ template_id: str,+ content_key: str,+ ) -> str | None:+ self.streaming_card_calls.append(+ (chat_id, template_id, content_key),+ )+ return self.streaming_card_id++ async def stream_card(+ self,+ out_track_id: str,+ content_key: str,+ content: str,+ *,+ finalize: bool = False,+ is_error: bool = False,+ ) -> bool:+ self.streaming_updates.append(+ (out_track_id, content_key, content, finalize, is_error),+ )+ return self.streaming_update_success+++class _FakeBackend:+ """Workspace backend that records reads and returns fixed files."""++ def __init__(self, files: dict[str, bytes] | None = None) -> None:+ self.files = files or {}+ self.reads: list[str] = []++ async def read_file(self, path: str) -> bytes:+ self.reads.append(path)+ if path not in self.files:+ raise FileNotFoundError(path)+ return self.files[path]+++class _FakeWorkspace:+ """Workspace wrapper exposing a fake backend."""++ def __init__(self, backend: _FakeBackend) -> None:+ self.backend = backend++ def get_backend(self) -> _FakeBackend:+ return self.backend+++class _StreamResponse(_FakeResponse):+ """Async streaming download response."""++ def __init__(+ self,+ chunks: list[bytes],+ media_type: str,+ content_length: int | None = None,+ ) -> None:+ super().__init__()+ self._chunks = chunks+ self.headers = {"content-type": media_type}+ if content_length is not None:+ self.headers["content-length"] = str(content_length)++ async def __aenter__(self) -> "_StreamResponse":+ return self++ async def __aexit__(self, *args: Any) -> None:+ del args++ async def aiter_bytes(self) -> AsyncIterator[bytes]:+ for chunk in self._chunks:+ yield chunk+++class _OpenAPIHTTP(_FakeHTTP):+ """Queue JSON responses and one streaming media response."""++ def __init__(+ self,+ responses: list[_FakeResponse],+ stream_response: _StreamResponse | None = None,+ ) -> None:+ super().__init__()+ self._responses = responses+ self._stream_response = stream_response+ self.streams: list[tuple[str, str, dict[str, Any]]] = []+ self.requests: list[tuple[str, str, dict[str, Any]]] = []++ async def post(self, url: str, **kwargs: Any) -> _FakeResponse:+ self.posts.append((url, kwargs))+ return self._responses.pop(0)++ async def request(+ self,+ method: str,+ url: str,+ **kwargs: Any,+ ) -> _FakeResponse:+ self.requests.append((method, url, kwargs))+ return self._responses.pop(0)++ def stream(+ self,+ method: str,+ url: str,+ **kwargs: Any,+ ) -> _StreamResponse:+ self.streams.append((method, url, kwargs))+ if self._stream_response is None:+ raise RuntimeError("no stream response")+ return self._stream_response+++def _openapi(+ *responses: dict[str, Any],+ stream_response: _StreamResponse | None = None,+) -> tuple[_DingTalkOpenAPI, _OpenAPIHTTP]:+ http = _OpenAPIHTTP(+ [+ _FakeResponse({"accessToken": "token", "expireIn": 7200}),+ *(_FakeResponse(response) for response in responses),+ ],+ stream_response,+ )+ return _DingTalkOpenAPI("client", "secret", http), http+++def _channel(+ *,+ only_at_reply: bool = True,+ approval_card_template_id: str = "approval.schema",+ streaming_card_template_id: str = "",+ streaming_card_key: str = "content",+) -> DingTalkChannel:+ return DingTalkChannel(+ "ding-1",+ DingTalkChannel.Credentials(+ client_id="client-id",+ client_secret="client-secret",+ ),+ DingTalkChannel.Config(+ only_at_reply=only_at_reply,+ approval_card_template_id=approval_card_template_id,+ streaming_card_template_id=streaming_card_template_id,+ streaming_card_key=streaming_card_key,+ ),+ )+++def _channel_with_openapi(+ openapi: _FakeMediaOpenAPI | None = None,+ **config: Any,+) -> tuple[DingTalkChannel, _FakeMediaOpenAPI]:+ openapi = openapi or _FakeMediaOpenAPI()+ channel = _channel(**config)+ channel._openapi = cast(_DingTalkOpenAPI, openapi)+ return channel, openapi+++def _payload(**overrides: Any) -> dict[str, Any]:+ payload: dict[str, Any] = {+ "conversationType": "2",+ "conversationId": "cid-group-1",+ "conversationTitle": "Engineering",+ "senderStaffId": "user-1",+ "senderNick": "Alice",+ "msgId": "message-1",+ "msgtype": "text",+ "text": {"content": " hello "},+ "isInAtList": True,+ "sessionWebhook": _WEBHOOK,+ "sessionWebhookExpiredTime": int(time.time() * 1000) + 60_000,+ }+ payload.update(overrides)+ return payload+++async def _message_callbacks(+ channel: DingTalkChannel,+ *payloads: dict[str, Any],+) -> list[ChannelEvent]:+ received: list[ChannelEvent] = []++ async def emit(event: ChannelEvent) -> None:+ received.append(event)++ channel._emit = emit+ for payload in payloads:+ await channel._on_callback(payload)+ return received+++def _message_event(+ chat_id: str = "group:cid-group-1",+ *,+ user_id: str = "user-1",+ metadata: dict[str, Any] | None = None,+) -> ChannelEvent:+ return ChannelEvent(+ channel_id="ding-1",+ channel_user_id=user_id,+ chat_id=chat_id,+ metadata=metadata or {},+ )+++async def _event_stream(text: str = "hello from agent") -> AsyncIterator[dict]:+ events = [+ ReplyStartEvent(+ session_id="session-1",+ reply_id=_REPLY_ID,+ name="assistant",+ ),+ TextBlockStartEvent(reply_id=_REPLY_ID, block_id="text-1"),+ TextBlockDeltaEvent(+ reply_id=_REPLY_ID,+ block_id="text-1",+ delta=text,+ ),+ TextBlockEndEvent(reply_id=_REPLY_ID, block_id="text-1"),+ ReplyEndEvent(session_id="session-1", reply_id=_REPLY_ID),+ ]+ for event in events:+ yield event.model_dump(mode="json")+++async def _image_event_stream() -> AsyncIterator[dict]:+ events = [+ ReplyStartEvent(+ session_id="session-1",+ reply_id=_REPLY_ID,+ name="assistant",+ ),+ DataBlockStartEvent(+ reply_id=_REPLY_ID,+ block_id="image-1",+ media_type="image/png",+ ),+ DataBlockDeltaEvent(+ reply_id=_REPLY_ID,+ block_id="image-1",+ data=base64.b64encode(b"image bytes").decode("ascii"),+ media_type="image/png",+ ),+ DataBlockEndEvent(reply_id=_REPLY_ID, block_id="image-1"),+ ReplyEndEvent(session_id="session-1", reply_id=_REPLY_ID),+ ]+ for event in events:+ yield event.model_dump(mode="json")+++async def _confirmation_event_stream() -> AsyncIterator[dict]:+ events = [+ ReplyStartEvent(+ session_id="session-1",+ reply_id=_REPLY_ID,+ name="assistant",+ ),+ RequireUserConfirmEvent(+ reply_id=_REPLY_ID,+ tool_calls=[+ ToolCallBlock(+ id="tool-1",+ name="SendMessage",+ input='{"target":"user:user-2","text":"hello"}',+ ),+ ],+ ),+ ]+ for event in events:+ yield event.model_dump(mode="json")+++def _card_callback(+ *,+ action: str = "approve",+ user_id: str = "user-1",+ approver_id: str = "",+) -> dict[str, Any]:+ return {+ "type": "actionCallback",+ "outTrackId": "track-1",+ "userId": user_id,+ "content": json.dumps(+ {+ "cardPrivateData": {+ "params": {+ "action": action,+ "toolCallId": "tool-1",+ "chatId": "group:cid-group-1",+ "agentId": "agent-1",+ "sessionId": "session-1",+ "approverId": approver_id,+ },+ },+ },+ ),+ }+++async def _confirmation_callbacks(+ channel: DingTalkChannel,+ *payloads: dict[str, Any],+) -> list[ChannelConfirmationResultEvent]:+ received: list[ChannelConfirmationResultEvent] = []++ async def emit(event: ChannelConfirmationResultEvent) -> None:+ received.append(event)++ channel._emit = emit+ for payload in payloads:+ await channel._on_card_callback(payload)+ return received+++class DingTalkChannelTest( # pylint: disable=too-many-public-methods+ IsolatedAsyncioTestCase,+):+ """DingTalk callback, lifecycle, and reply tests."""++ async def test_official_stream_client_registration(self) -> None:+ channel = _channel()++ client = channel._new_stream_client()++ self.assertIn(+ "/v1.0/im/bot/messages/get",+ client.callback_handler_map,+ )+ self.assertIn(+ "/v1.0/card/instances/callback",+ client.callback_handler_map,+ )++ async def test_official_stream_client_stops_during_retry(self) -> None:+ channel = _channel()+ client = channel._new_stream_client()++ with patch.object(client, "open_connection", return_value=None):+ listener = asyncio.create_task(client.start())+ await asyncio.sleep(0.05)+ await client.stop()+ await asyncio.wait_for(listener, timeout=1.0)++ self.assertTrue(listener.done())++ async def test_official_stream_client_propagates_cancellation(+ self,+ ) -> None:+ channel = _channel()+ client = channel._new_stream_client()++ with patch.object(client, "open_connection", return_value=None):+ listener = asyncio.create_task(client.start())+ await asyncio.sleep(0.05)+ listener.cancel()+ with self.assertRaises(asyncio.CancelledError):+ await asyncio.wait_for(listener, timeout=1.0)++ async def test_public_registration_and_secret_schema(self) -> None:+ registry = ChannelTypeRegistry([DingTalkChannel])+ schema = registry.list_types()[0]++ self.assertEqual(schema.channel_type, "dingtalk")+ self.assertEqual(schema.platform_bot_id_field, "client_id")+ secret = schema.credentials_schema["properties"]["client_secret"]+ self.assertEqual(secret["format"], "password")++ async def test_group_text_callback_is_normalised(self) -> None:+ channel = _channel()+ received = await _message_callbacks(channel, _payload())++ self.assertEqual(len(received), 1)+ event = received[0]+ self.assertEqual(event.channel_user_id, "user-1")+ self.assertEqual(event.channel_user_name, "Alice")+ self.assertEqual(event.chat_id, "group:cid-group-1")+ self.assertEqual(event.chat_name, "Engineering")+ self.assertEqual(event.channel_message_id, "message-1")+ self.assertEqual(event.message, "hello")+ self.assertEqual(event.metadata["chat_type"], "group")+ self.assertNotIn("sessionWebhook", event.metadata)+ self.assertEqual(+ await channel.chat_kind(event.chat_id),+ ChatKind.GROUP,+ )+ self.assertEqual(await channel.chat_name(event.chat_id), "Engineering")++ async def test_private_text_callback_uses_staff_id(self) -> None:+ channel = _channel()+ received = await _message_callbacks(+ channel,+ _payload(+ conversationType="1",+ conversationId="cid-private-not-used",+ conversationTitle="not-used",+ ),+ )++ self.assertEqual(received[0].chat_id, "user:user-1")+ self.assertEqual(received[0].chat_name, "")+ self.assertEqual(+ await channel.chat_kind(received[0].chat_id),+ ChatKind.PRIVATE,+ )+ self.assertEqual(await channel.chat_name("user:user-1"), "Alice")++ async def test_list_bot_chats_returns_only_observed_targets(self) -> None:+ channel = _channel()+ await _message_callbacks(+ channel,+ _payload(),+ _payload(conversationType="1", conversationTitle=""),+ )++ self.assertEqual(+ await channel.list_bot_chats(),+ [+ {+ "chat_id": "group:cid-group-1",+ "name": "Engineering",+ "chat_type": "group",+ },+ {+ "chat_id": "user:user-1",+ "name": "Alice",+ "chat_type": "private",+ },+ ],+ )++ async def test_group_message_without_mention_is_ignored(self) -> None:+ channel = _channel(only_at_reply=True)+ received = await _message_callbacks(+ channel,+ _payload(isInAtList=False),+ )++ self.assertEqual(received, [])++ async def test_non_text_and_invalid_target_are_ignored(self) -> None:+ channel = _channel()+ received = await _message_callbacks(+ channel,+ _payload(msgtype="picture"),+ _payload(senderStaffId="", senderId=""),+ )++ self.assertEqual(received, [])++ async def test_picture_callback_downloads_data_block(self) -> None:+ channel, media_api = _channel_with_openapi(+ _FakeMediaOpenAPI((b"png bytes", "image/png")),+ )+ received = await _message_callbacks(+ channel,+ _payload(+ msgtype="picture",+ content={"downloadCode": "picture-code"},+ ),+ )++ self.assertEqual(media_api.download_calls[0][0], "picture-code")+ block = cast(DataBlock, received[0].content[0])+ self.assertIsInstance(block, DataBlock)+ self.assertIsInstance(block.source, Base64Source)+ self.assertEqual(block.source.media_type, "image/png")+ self.assertEqual(base64.b64decode(block.source.data), b"png bytes")++ async def test_file_callback_preserves_safe_filename(self) -> None:+ channel, _ = _channel_with_openapi(+ _FakeMediaOpenAPI(+ (b"pdf bytes", "application/octet-stream"),+ ),+ )+ received = await _message_callbacks(+ channel,+ _payload(+ msgtype="file",+ content={+ "downloadCode": "file-code",+ "fileName": "../reports/result.pdf",+ },+ ),+ )++ block = cast(DataBlock, received[0].content[0])+ self.assertEqual(block.name, "result.pdf")+ self.assertEqual(block.source.media_type, "application/pdf")++ async def test_audio_callback_keeps_recognition_before_media(self) -> None:+ channel, _ = _channel_with_openapi(+ _FakeMediaOpenAPI((b"audio", "audio/mpeg")),+ )+ received = await _message_callbacks(+ channel,+ _payload(+ msgtype="audio",+ content={+ "downloadCode": "audio-code",+ "recognition": "transcribed speech",+ },+ ),+ )++ self.assertIsInstance(received[0].content[0], TextBlock)+ self.assertEqual(received[0].message, "transcribed speech")+ audio = cast(DataBlock, received[0].content[1])+ self.assertEqual(audio.source.media_type, "audio/mpeg")++ async def test_rich_text_preserves_text_image_order(self) -> None:+ channel, _ = _channel_with_openapi()+ received = await _message_callbacks(+ channel,+ _payload(+ msgtype="richText",+ content={+ "richText": [+ {"text": "before"},+ {"downloadCode": "rich-image", "type": "picture"},+ {"text": "after"},+ ],+ },+ ),+ )++ self.assertIsInstance(received[0].content[0], TextBlock)+ self.assertIsInstance(received[0].content[1], DataBlock)+ self.assertIsInstance(received[0].content[2], TextBlock)+ self.assertEqual(received[0].message, "beforeafter")++ async def test_media_download_failure_is_visible(self) -> None:+ channel, _ = _channel_with_openapi(+ _FakeMediaOpenAPI(download=None),+ )+ received = await _message_callbacks(+ channel,+ _payload(+ msgtype="file",+ content={"downloadCode": "bad", "fileName": "bad.zip"},+ ),+ )++ self.assertIn("Unable to download", received[0].message)++ async def test_unsafe_session_webhook_is_not_cached(self) -> None:+ channel = _channel()+ received = await _message_callbacks(+ channel,+ _payload(sessionWebhook="https://example.com/steal"),+ )++ self.assertEqual(len(received), 1)+ self.assertNotIn(received[0].chat_id, channel._session_webhooks)++ async def test_send_response_uses_cached_session_webhook(self) -> None:+ channel = _channel()+ received = await _message_callbacks(channel, _payload())+ http = _FakeHTTP()+ channel._http = http++ await channel.send_response(received[0], _event_stream())++ self.assertEqual(len(http.posts), 1)+ url, request = http.posts[0]+ self.assertEqual(url, _WEBHOOK)+ self.assertEqual(request["json"]["msgtype"], "markdown")+ self.assertEqual(+ request["json"]["markdown"]["text"],+ "hello from agent",+ )+ self.assertEqual(request["json"]["markdown"]["title"], "AgentScope")++ async def test_streaming_is_disabled_without_ai_card_template(+ self,+ ) -> None:+ channel = _channel(streaming_card_template_id="")++ self.assertFalse(channel.capabilities.streaming)++ async def test_send_response_streams_when_ai_card_is_configured(+ self,+ ) -> None:+ channel, media_api = _channel_with_openapi(+ streaming_card_template_id="ai-card.schema",+ streaming_card_key="answer",+ )+ event = _message_event()++ await channel.send_response(event, _event_stream())++ self.assertTrue(channel.capabilities.streaming)+ self.assertEqual(+ media_api.streaming_card_calls,+ [("group:cid-group-1", "ai-card.schema", "answer")],+ )+ self.assertGreaterEqual(len(media_api.streaming_updates), 1)+ self.assertEqual(+ media_api.streaming_updates[-1],+ (+ "stream-track-1",+ "answer",+ "hello from agent",+ True,+ False,+ ),+ )+ self.assertEqual(media_api.text_calls, [])++ async def test_streaming_card_creation_failure_falls_back_to_markdown(+ self,+ ) -> None:+ media_api = _FakeMediaOpenAPI()+ media_api.streaming_card_id = None+ channel, _ = _channel_with_openapi(+ media_api,+ streaming_card_template_id="ai-card.schema",+ )+ event = _message_event("user:user-1")++ await channel.send_response(event, _event_stream())++ self.assertEqual(+ media_api.text_calls,+ [("user:user-1", "hello from agent")],+ )++ async def test_streaming_card_update_failure_falls_back_to_markdown(+ self,+ ) -> None:+ media_api = _FakeMediaOpenAPI()+ media_api.streaming_update_success = False+ channel, _ = _channel_with_openapi(+ media_api,+ streaming_card_template_id="ai-card.schema",+ )+ event = _message_event()++ await channel.send_response(event, _event_stream())++ self.assertEqual(+ media_api.text_calls,+ [("group:cid-group-1", "hello from agent")],+ )+ self.assertTrue(media_api.streaming_updates[-1][3])+ self.assertTrue(media_api.streaming_updates[-1][4])++ async def test_oversized_streaming_reply_uses_markdown_only(self) -> None:+ channel, media_api = _channel_with_openapi(+ streaming_card_template_id="ai-card.schema",+ )+ event = _message_event()+ text = "中" * 342++ await channel.send_response(event, _event_stream(text))++ self.assertEqual(media_api.streaming_card_calls, [])+ self.assertEqual(media_api.text_calls, [(event.chat_id, text)])++ async def test_send_response_uploads_image_data_block(self) -> None:+ channel, media_api = _channel_with_openapi()+ event = _message_event()++ await channel.send_response(event, _image_event_stream())++ self.assertEqual(+ media_api.send_calls,+ [+ (+ "group:cid-group-1",+ b"image bytes",+ "image.png",+ "image/png",+ ),+ ],+ )++ async def test_send_response_presents_tool_approval_card(self) -> None:+ channel, media_api = _channel_with_openapi()+ event = _message_event(+ metadata={"agent_id": "agent-1", "session_id": "session-1"},+ )++ await channel.send_response(event, _confirmation_event_stream())++ self.assertEqual(len(media_api.approval_calls), 1)+ chat_id, approver, template, card_data = media_api.approval_calls[0]+ self.assertEqual(chat_id, "group:cid-group-1")+ self.assertEqual(approver, "")+ self.assertEqual(template, "approval.schema")+ self.assertEqual(card_data["toolCallId"], "tool-1")+ self.assertEqual(card_data["agentId"], "agent-1")++ async def test_approval_callback_emits_resume_event_and_updates_card(+ self,+ ) -> None:+ channel, media_api = _channel_with_openapi()+ received = await _confirmation_callbacks(+ channel,+ _card_callback(action="deny"),+ )++ self.assertEqual(len(received), 1)+ self.assertEqual(received[0].tool_call_id, "tool-1")+ self.assertEqual(received[0].chat_id, "group:cid-group-1")+ self.assertEqual(received[0].agent_id, "agent-1")+ self.assertEqual(received[0].session_id, "session-1")+ self.assertFalse(received[0].approved)+ self.assertEqual(received[0].actor, "user-1")+ self.assertEqual(media_api.card_updates[0][0], "track-1")+ self.assertEqual(media_api.card_updates[0][1]["status"], "denied")++ async def test_approval_callback_accepts_approval_aliases(self) -> None:+ for action in ("approve", "agree"):+ with self.subTest(action=action):+ channel, media_api = _channel_with_openapi()+ received = await _confirmation_callbacks(+ channel,+ _card_callback(action=action),+ )++ self.assertTrue(received[0].approved)+ self.assertEqual(+ media_api.card_updates[0][1]["status"],+ "approved",+ )++ async def test_approval_callback_rejects_another_user(self) -> None:+ channel, media_api = _channel_with_openapi()+ received = await _confirmation_callbacks(+ channel,+ _card_callback(+ user_id="unexpected-user",+ approver_id="user-1",+ ),+ )++ self.assertEqual(received, [])+ self.assertEqual(media_api.card_updates, [])++ async def test_send_file_strips_path_and_keeps_extension(self) -> None:+ channel, media_api = _channel_with_openapi()+ block = DataBlock(+ source=Base64Source(+ data=base64.b64encode(b"pdf").decode("ascii"),+ media_type="application/pdf",+ ),+ name="../../report.pdf",+ )++ sent = await channel._send_data("user:user-1", block)++ self.assertTrue(sent)+ self.assertEqual(media_api.send_calls[0][2], "report.pdf")+++class DingTalkToolTest(IsolatedAsyncioTestCase):+ """DingTalk discovery and target-send tool tests."""++ async def test_channel_target_operations_reuse_openapi(self) -> None:+ media_api = _FakeMediaOpenAPI()+ media_api.search_result = [+ {+ "user_id": "user-2",+ "name": "Bob",+ "title": "Engineer",+ "department_ids": [1],+ },+ ]+ channel, _ = _channel_with_openapi(media_api)++ users = await channel.search_users("Bob", 5)+ message_sent = await channel.send_message_to(+ "user:user-2",+ "hello",+ )+ file_sent = await channel.send_file_to(+ "group:cid-2",+ b"pdf",+ "report.pdf",+ )+ image_sent = await channel.send_image_to(+ "user:user-2",+ b"png",+ "chart.png",+ )++ self.assertEqual(users[0]["name"], "Bob")+ self.assertTrue(message_sent)+ self.assertTrue(file_sent)+ self.assertTrue(image_sent)+ self.assertEqual(+ media_api.text_calls,+ [("user:user-2", "hello")],+ )+ self.assertEqual(+ media_api.send_calls[0][3],+ "application/octet-stream",+ )+ self.assertEqual(media_api.send_calls[1][3], "image/png")++ async def test_list_tools_forms_discovery_send_chain(self) -> None:+ from agentscope.app.channel._dingtalk._tools import (+ ListConversations,+ ListUsers,+ SendFile,+ SendMessage,+ )++ media_api = _FakeMediaOpenAPI()+ media_api.search_result = [+ {+ "user_id": "user-2",+ "name": "Bob",+ "title": "Engineer",+ "department_ids": [1],+ },+ ]+ channel, _ = _channel_with_openapi(media_api)+ channel._chat_names["group:cid-2"] = "Finance"+ backend = _FakeBackend({"/workspace/report.pdf": b"pdf"})+ workspace = cast(WorkspaceBase, _FakeWorkspace(backend))++ tools = await channel.list_tools(workspace)++ self.assertEqual(+ [tool.name for tool in tools],+ [+ "ListConversations",+ "ListUsers",+ "SendMessage",+ "SendFile",+ "SendImage",+ ],+ )+ conversations = await cast(ListConversations, tools[0])()+ conversation_items = json.loads(conversations.content[0].text)+ self.assertEqual(conversation_items[0]["target"], "group:cid-2")+ users = await cast(ListUsers, tools[1])("Bob", 10)+ user_items = json.loads(users.content[0].text)+ self.assertEqual(user_items[0]["target"], "user:user-2")++ message_result = await cast(SendMessage, tools[2])(+ "user:user-2",+ "hello",+ )+ file_result = await cast(SendFile, tools[3])(+ "/workspace/report.pdf",+ "group:cid-2",+ )++ self.assertIn("Sent message", message_result.content[0].text)+ self.assertIn("Sent file", file_result.content[0].text)+ self.assertEqual(backend.reads, ["/workspace/report.pdf"])++ async def test_dingtalk_tool_permissions_match_feishu_policy(self) -> None:+ channel = _channel()+ backend = _FakeBackend()+ tools = await channel.list_tools(+ cast(WorkspaceBase, _FakeWorkspace(backend)),+ )++ read_decision = await tools[0].check_permissions(+ {},+ PermissionContext(),+ )+ send_decision = await tools[2].check_permissions(+ {},+ PermissionContext(),+ )++ self.assertEqual(read_decision.behavior, PermissionBehavior.ALLOW)+ self.assertEqual(send_decision.behavior, PermissionBehavior.ASK)++ async def test_send_tools_require_approval_card_configuration(+ self,+ ) -> None:+ channel = _channel(approval_card_template_id="")+ tools = await channel.list_tools(+ cast(WorkspaceBase, _FakeWorkspace(_FakeBackend())),+ )++ self.assertEqual(+ [tool.name for tool in tools],+ ["ListConversations", "ListUsers"],+ )+++class DingTalkChannelLifecycleTest(IsolatedAsyncioTestCase):+ """DingTalk reply-webhook and connection lifecycle tests."""++ async def test_expired_session_webhook_is_not_used(self) -> None:+ channel = _channel()+ received = await _message_callbacks(+ channel,+ _payload(+ sessionWebhookExpiredTime=int(time.time() * 1000) - 1,+ ),+ )+ http = _FakeHTTP()+ channel._http = http++ sent = await channel._send_text(received[0].chat_id, "late reply")++ self.assertFalse(sent)+ self.assertEqual(http.posts, [])++ async def test_missing_webhook_falls_back_to_openapi(self) -> None:+ channel, media_api = _channel_with_openapi()++ sent = await channel._send_text("group:cid-2", "fallback")++ self.assertTrue(sent)+ self.assertEqual(+ media_api.text_calls,+ [("group:cid-2", "fallback")],+ )++ async def test_lifecycle_stops_stream_and_http_clients(self) -> None:+ channel = _channel()+ http = _FakeHTTP()+ stream = _FakeStreamClient()++ async def emit(event: ChannelEvent) -> None:+ del event++ with (+ patch.object(channel, "_new_http_client", return_value=http),+ patch.object(channel, "_new_stream_client", return_value=stream),+ ):+ listener = asyncio.create_task(channel.start_listening(emit))+ await asyncio.wait_for(stream.started.wait(), timeout=1.0)+ await asyncio.sleep(0.25)+ self.assertEqual(channel.status.state, "connected")+ listener.cancel()+ with self.assertRaises(asyncio.CancelledError):+ await listener++ self.assertEqual(stream.stop_calls, 1)+ self.assertTrue(http.closed)+ self.assertEqual(channel.status.state, "stopped")++ async def test_lifecycle_parks_after_initialisation_failure(self) -> None:+ channel = _channel()+ http = _FakeHTTP()++ async def emit(event: ChannelEvent) -> None:+ del event++ with (+ patch.object(channel, "_new_http_client", return_value=http),+ patch.object(+ channel,+ "_new_stream_client",+ side_effect=RuntimeError("bad credentials"),+ ),+ ):+ listener = asyncio.create_task(channel.start_listening(emit))+ for _ in range(20):+ if channel.status.state == "failed":+ break+ await asyncio.sleep(0.01)+ self.assertEqual(channel.status.state, "failed")+ self.assertEqual(channel.status.last_error, "bad credentials")+ self.assertFalse(listener.done())+ listener.cancel()+ with self.assertRaises(asyncio.CancelledError):+ await listener++ self.assertTrue(http.closed)+ self.assertEqual(channel.status.state, "stopped")+++class DingTalkOpenAPITest(IsolatedAsyncioTestCase):+ """Token, media download, upload, and target-send tests."""++ async def test_download_media_resolves_and_limits_stream(self) -> None:+ api, http = _openapi(+ {"downloadUrl": "https://media.example/file"},+ stream_response=_StreamResponse(+ [b"abc", b"def"],+ "application/pdf",+ content_length=6,+ ),+ )++ result = await api.download_media("download-code", max_bytes=6)++ self.assertEqual(result, (b"abcdef", "application/pdf"))+ self.assertEqual(http.streams[0][0], "GET")+ resolve_request = http.posts[1][1]+ self.assertEqual(resolve_request["json"]["robotCode"], "client")+ self.assertEqual(+ resolve_request["headers"]["x-acs-dingtalk-access-token"],+ "token",+ )++ async def test_download_upgrades_dingtalk_oss_url_to_https(self) -> None:+ download_url = "http://bucket.oss-cn-test.aliyuncs.com/file?sig=x"+ api, http = _openapi(+ {"downloadUrl": download_url},+ stream_response=_StreamResponse([b"image"], "image/png"),+ )++ result = await api.download_media("download-code", max_bytes=10)++ self.assertEqual(result, (b"image", "image/png"))+ self.assertEqual(+ http.streams[0][1],+ "https://bucket.oss-cn-test.aliyuncs.com/file?sig=x",+ )++ async def test_download_rejects_untrusted_http_url(self) -> None:+ api, http = _openapi(+ {"downloadUrl": "http://media.example/file"},+ )++ result = await api.download_media("download-code", max_bytes=10)++ self.assertIsNone(result)+ self.assertEqual(http.streams, [])++ async def test_download_rejects_content_length_over_limit(self) -> None:+ api, _ = _openapi(+ {"downloadUrl": "https://media.example/file"},+ stream_response=_StreamResponse(+ [b"too large"],+ "application/zip",+ content_length=9,+ ),+ )++ result = await api.download_media("download-code", max_bytes=4)++ self.assertIsNone(result)++ async def test_download_rejects_stream_over_limit(self) -> None:+ api, _ = _openapi(+ {"downloadUrl": "https://media.example/file"},+ stream_response=_StreamResponse(+ [b"abc", b"def"],+ "application/octet-stream",+ ),+ )++ result = await api.download_media("download-code", max_bytes=5)++ self.assertIsNone(result)++ async def test_upload_and_send_group_file(self) -> None:+ api, http = _openapi(+ {"errcode": 0, "media_id": "media-id"},+ {"processQueryKey": "query-key"},+ )++ sent = await api.send_media(+ "group:cid-1",+ b"pdf",+ "report.pdf",+ "application/pdf",+ )++ self.assertTrue(sent)+ self.assertEqual(http.posts[1][1]["data"], {"type": "file"})+ send_request = http.posts[2][1]["json"]+ self.assertEqual(send_request["msgKey"], "sampleFile")+ self.assertEqual(send_request["openConversationId"], "cid-1")+ self.assertEqual(+ json.loads(send_request["msgParam"]),+ {+ "mediaId": "media-id",+ "fileName": "report.pdf",+ "fileType": "pdf",+ },+ )++ async def test_upload_and_send_user_image(self) -> None:+ api, http = _openapi(+ {"errcode": 0, "media_id": "image-id"},+ {"processQueryKey": "query-key"},+ )++ sent = await api.send_media(+ "user:user-1",+ b"png",+ "image.png",+ "image/png",+ )++ self.assertTrue(sent)+ self.assertEqual(http.posts[1][1]["data"], {"type": "image"})+ send_request = http.posts[2][1]["json"]+ self.assertEqual(send_request["msgKey"], "sampleImageMsg")+ self.assertEqual(send_request["userIds"], ["user-1"])+ self.assertEqual(+ json.loads(send_request["msgParam"]),+ {"photoURL": "image-id"},+ )++ async def test_send_text_uses_group_markdown_template(self) -> None:+ api, http = _openapi(+ {"processQueryKey": "query-key"},+ )++ sent = await api.send_text("group:cid-1", "hello")++ self.assertTrue(sent)+ request = http.posts[1][1]["json"]+ self.assertEqual(request["msgKey"], "sampleMarkdown")+ self.assertEqual(request["openConversationId"], "cid-1")+ self.assertEqual(+ json.loads(request["msgParam"]),+ {"title": "AgentScope", "text": "hello"},+ )++ async def test_send_text_uses_user_markdown_template(self) -> None:+ api, http = _openapi(+ {"processQueryKey": "query-key"},+ )++ sent = await api.send_text("user:user-1", "**hello**")++ self.assertTrue(sent)+ request = http.posts[1][1]["json"]+ self.assertEqual(request["msgKey"], "sampleMarkdown")+ self.assertEqual(request["userIds"], ["user-1"])+ self.assertEqual(+ json.loads(request["msgParam"]),+ {"title": "AgentScope", "text": "**hello**"},+ )++ async def test_search_users_resolves_profile_details(self) -> None:+ api, http = _openapi(+ {"list": ["user-1", "user-2"]},+ {+ "errcode": 0,+ "result": {+ "userid": "user-1",+ "name": "Alice",+ "title": "Engineer",+ "dept_id_list": [1, 2],+ },+ },+ {"errcode": 500},+ )++ users = await api.search_users("Alice", 10)++ self.assertEqual(+ http.posts[1][1]["json"],+ {"queryWord": "Alice", "offset": 0, "size": 10},+ )+ self.assertEqual(users[0]["name"], "Alice")+ self.assertEqual(users[0]["department_ids"], [1, 2])+ self.assertEqual(users[1]["user_id"], "user-2")+ self.assertEqual(users[1]["name"], "")++ async def test_create_deliver_and_update_group_approval_card(self) -> None:+ api, http = _openapi({}, {}, {})++ out_track_id = await api.create_approval_card(+ "group:cid-1",+ "",+ "approval.schema",+ {"toolCallId": "tool-1"},+ )+ updated = await api.update_approval_card(+ cast(str, out_track_id),+ {"status": "approved"},+ )++ self.assertIsNotNone(out_track_id)+ self.assertTrue(updated)+ create_method, create_url, create_request = http.requests[0]+ self.assertEqual(create_method, "POST")+ self.assertTrue(create_url.endswith("/card/instances"))+ self.assertEqual(+ create_request["json"]["cardTemplateId"],+ "approval.schema",+ )+ self.assertEqual(create_request["json"]["callbackType"], "STREAM")+ deliver_method, deliver_url, deliver_request = http.requests[1]+ self.assertEqual(deliver_method, "POST")+ self.assertTrue(deliver_url.endswith("/card/instances/deliver"))+ self.assertEqual(+ deliver_request["json"]["openSpaceId"],+ "dtv1.card//IM_GROUP.cid-1",+ )+ self.assertEqual(+ deliver_request["json"]["imGroupOpenDeliverModel"],+ {"robotCode": "client"},+ )+ self.assertEqual(http.requests[2][0], "PUT")+ self.assertEqual(+ http.requests[2][2]["json"]["outTrackId"],+ out_track_id,+ )++ async def test_deliver_private_approval_card_to_encoded_user(self) -> None:+ api, http = _openapi({}, {})++ out_track_id = await api.create_approval_card(+ "user:user-1",+ "",+ "approval.schema",+ {"toolCallId": "tool-1"},+ )++ self.assertIsNotNone(out_track_id)+ delivery = http.requests[1][2]["json"]+ self.assertEqual(+ delivery["openSpaceId"],+ "dtv1.card//IM_ROBOT.user-1",+ )+ self.assertEqual(+ delivery["imRobotOpenDeliverModel"],+ {"spaceType": "IM_ROBOT"},+ )++ async def test_create_deliver_and_stream_group_ai_card(self) -> None:+ api, http = _openapi({}, {}, {})++ out_track_id = await api.create_streaming_card(+ "group:cid-1",+ "ai-card.schema",+ "answer",+ )+ updated = await api.stream_card(+ cast(str, out_track_id),+ "answer",+ "**complete**",+ finalize=True,+ )++ self.assertIsNotNone(out_track_id)+ self.assertTrue(updated)+ create = http.requests[0][2]["json"]+ self.assertEqual(create["cardTemplateId"], "ai-card.schema")+ self.assertEqual(create["cardData"]["cardParamMap"], {"answer": ""})+ delivery = http.requests[1][2]["json"]+ self.assertEqual(+ delivery["openSpaceId"],+ "dtv1.card//IM_GROUP.cid-1",+ )+ method, url, request = http.requests[2]+ self.assertEqual(method, "PUT")+ self.assertTrue(url.endswith("/card/streaming"))+ self.assertEqual(request["json"]["outTrackId"], out_track_id)+ self.assertEqual(request["json"]["key"], "answer")+ self.assertEqual(request["json"]["content"], "**complete**")+ self.assertTrue(request["json"]["isFull"])+ self.assertTrue(request["json"]["isFinalize"])+ self.assertEqual(+ str(UUID(request["json"]["guid"])),+ request["json"]["guid"],+ )++ async def test_unsupported_file_type_is_not_sent(self) -> None:+ api, http = _openapi(+ {"errcode": 0, "media_id": "media-id"},+ )++ sent = await api.send_media(+ "user:user-1",+ b"text",+ "notes.txt",+ "text/plain",+ )++ self.assertFalse(sent)+ self.assertEqual(http.posts, [])