Skip to content

Build and run agents you can see, understand and trust.

feat(channel): add DingTalk knowledge base tools (#2464)

DiegoCluv70fe41c07f63b
diff --git a/src/agentscope/app/_service/_chat.py b/src/agentscope/app/_service/_chat.py
index cf060a3ba..895230f23 100644
--- a/src/agentscope/app/_service/_chat.py
+++ b/src/agentscope/app/_service/_chat.py
@@ -896,17 +896,36 @@ class ChatService:
# 1c. Resolve the channel binding ONCE; the toolkit and the
# system-prompt attachment share it.
# -------------------------------------------------------------
+ channel_origin = (
+ session_record.origin
+ if isinstance(session_record.origin, ChannelOrigin)
+ else None
+ )
channel = (
await self._channel_clients.get(
- session_record.origin.channel_id,
+ channel_origin.channel_id,
)
- if isinstance(session_record.origin, ChannelOrigin)
+ if channel_origin is not None
and self._channel_clients is not None
else None
)
+ chat_kind = (
+ await channel.chat_kind(channel_origin.chat_id)
+ if channel is not None and channel_origin is not None
+ else None
+ )
+ # Channel tools that read as the session's user are only
+ # safe in a 1:1 chat. A group session is shared, so one
+ # member's turn would otherwise read with another's
+ # permissions.
channel_tools = (
- await channel.list_tools(workspace)
- if channel is not None
+ await channel.list_tools(
+ workspace,
+ channel_origin.channel_user_id
+ if chat_kind is ChatKind.PRIVATE
+ else None,
+ )
+ if channel is not None and channel_origin is not None
else []
)
@@ -1064,13 +1083,11 @@ class ChatService:
attachment = f"You're within a session (id={session_id})."
# Channel-bound sessions: tell the agent which chat it serves.
- if channel is not None:
+ if channel is not None and channel_origin is not None:
tools = ", ".join(t.name for t in channel_tools)
- chat_id = session_record.origin.chat_id
- kind = await channel.chat_kind(chat_id)
- name = (
- session_record.origin.chat_name
- or await channel.chat_name(chat_id)
+ chat_id = channel_origin.chat_id
+ name = channel_origin.chat_name or await channel.chat_name(
+ chat_id,
)
where = f' named "{name}"' if name else ""
attachment += (
@@ -1080,13 +1097,13 @@ class ChatService:
f"send there are relayed to you here, and your "
f"replies are delivered back to that same chat."
)
- if kind is ChatKind.GROUP:
+ if chat_kind is ChatKind.GROUP:
attachment += (
" It is a group chat, so messages may come "
"from several different people; each incoming "
"user turn is labelled with its sender."
)
- elif kind is ChatKind.PRIVATE:
+ elif chat_kind is ChatKind.PRIVATE:
attachment += (
" It is a one-to-one private chat with a "
"single user."
diff --git a/src/agentscope/app/channel/_base.py b/src/agentscope/app/channel/_base.py
index 15ea1f363..604635872 100644
--- a/src/agentscope/app/channel/_base.py
+++ b/src/agentscope/app/channel/_base.py
@@ -17,7 +17,15 @@ from __future__ import annotations
from abc import ABC, abstractmethod
from datetime import datetime
from enum import Enum
-from typing import Any, AsyncIterator, Awaitable, Callable, TYPE_CHECKING
+from typing import (
+ Any,
+ AsyncIterator,
+ Awaitable,
+ Callable,
+ Generic,
+ TypeVar,
+ TYPE_CHECKING,
+)
from pydantic import BaseModel, Field, TypeAdapter
@@ -41,6 +49,7 @@ _NO_TEXT_REPLY = "(Agent returned no text content)"
_AGENT_ERROR_REPLY = (
"❌ Agent encountered an error. Please check the agent configuration."
)
+_WikiEntry = TypeVar("_WikiEntry", "WikiSpace", "WikiNode")
# Deserialize a bus event dict back into its typed AgentEvent.
_EVENT_ADAPTER: TypeAdapter = TypeAdapter(AgentEvent)
@@ -187,10 +196,84 @@ class ChatKind(str, Enum):
PRIVATE = "private"
+class WikiSpace(BaseModel):
+ """One wiki space — what a platform calls a knowledge base."""
+
+ space_id: str
+ """The space's platform id."""
+
+ name: str
+ """Display name, as the platform shows it."""
+
+ root_node_id: str
+ """Where browsing starts; pass it to
+ :meth:`ChannelBase.list_wiki_nodes`."""
+
+ description: str | None = None
+ """What the space is for, when the platform records one."""
+
+ url: str | None = None
+ """Link to the space in the platform's own UI, for a person to open."""
+
+
+class WikiNode(BaseModel):
+ """One entry in a wiki space's tree — a folder or a document."""
+
+ node_id: str
+ """The entry's platform id, used to browse or read it."""
+
+ name: str
+ """Display name, as the platform shows it."""
+
+ has_children: bool = False
+ """Whether it can be browsed with :meth:`ChannelBase.list_wiki_nodes`."""
+
+ is_document: bool = False
+ """Whether it can be read with :meth:`ChannelBase.read_wiki_document`."""
+
+ url: str | None = None
+ """Link to the entry in the platform's own UI, for a person to open."""
+
+ updated_at: datetime | None = None
+ """When it last changed, so the agent can judge how current it is."""
+
+
+class WikiPage(BaseModel, Generic[_WikiEntry]):
+ """One page of a wiki listing, and where the next one starts."""
+
+ items: list[_WikiEntry]
+ """The entries on this page, in the platform's own order."""
+
+ next_token: str | None = None
+ """Pass back to the same call for the next page; ``None`` at the end."""
+
+
+class WikiDocument(BaseModel):
+ """A bounded read of one wiki document.
+
+ Bounded because a document is read in block ranges: a long one costs
+ several calls rather than one reply too large for the model to use.
+ """
+
+ node_id: str
+ """The document's platform id."""
+
+ name: str
+ """Display name, as the platform shows it."""
+
+ content: list[TextBlock | DataBlock]
+ """The range that was read, in the same block types as
+ :attr:`ChannelEvent.content`, so it reaches the agent unconverted."""
+
+ next_start_index: int | None = None
+ """Where a follow-up read resumes; ``None`` once the document ends."""
+
+
class ChannelCapability(BaseModel):
"""Platform capability declaration for gateway degradation decisions.
- All flags describe the send direction (agent → platform).
+ Flags describe the send direction (agent → platform) unless the flag
+ says otherwise.
"""
text: bool = True
@@ -210,6 +293,12 @@ class ChannelCapability(BaseModel):
max_message_length: int = 4000
"""Max characters per message; longer replies are split before send."""
+ wiki: bool = False
+ """Whether the platform has a wiki the agent can browse and read as
+ the message sender — the read direction, unlike the flags above. A
+ channel that sets it implements the three wiki methods on
+ :class:`ChannelBase`, and inherits the tools that call them."""
+
class ChannelBase(ABC):
"""Abstract base for platform channels.
@@ -463,15 +552,106 @@ class ChannelBase(ABC):
async def list_tools( # pylint: disable=unused-argument
self,
workspace: "WorkspaceBase",
+ channel_user_id: str | None = None,
) -> list["ToolBase"]:
"""Platform tools exposed to the agent — e.g. send a file to a
- different user/group than the conversation. Default: none.
+ different user/group than the conversation.
+
+ Default: the wiki tools, for a platform that has a wiki and a
+ session that acts as a known user. A subclass adds its own
+ platform tools to what this returns.
Args:
workspace (`WorkspaceBase`): The calling session's workspace,
so file-sending tools read from it, not the host.
+ channel_user_id (`str | None`, optional): The platform user the
+ session acts as, for tools that read with that user's own
+ permissions. ``None`` when the session has no single such
+ user — a shared group session, or a chat whose audience the
+ platform cannot classify.
"""
- return []
+ from ._tools import ListWikiNodes, ListWikiSpaces, ReadWikiDocument
+
+ if not (self.capabilities.wiki and channel_user_id):
+ return []
+ return [
+ ListWikiSpaces(self, channel_user_id),
+ ListWikiNodes(self, channel_user_id),
+ ReadWikiDocument(self, channel_user_id),
+ ]
+
+ # -- Optional wiki access, read as one platform user --
+
+ async def list_wiki_spaces( # pylint: disable=unused-argument
+ self,
+ channel_user_id: str,
+ limit: int,
+ next_token: str | None = None,
+ ) -> WikiPage[WikiSpace]:
+ """Wiki spaces readable by one platform user.
+
+ Every wiki call names the user it acts as, so the platform applies
+ that user's own permissions rather than the bot's. Default: empty,
+ for a platform with no wiki.
+
+ Args:
+ channel_user_id (`str`): The platform user to read as.
+ limit (`int`): Maximum spaces to return.
+ next_token (`str | None`, optional): Token from a previous page.
+
+ Returns:
+ `WikiPage[WikiSpace]`: One page of spaces.
+ """
+ return WikiPage(items=[])
+
+ async def list_wiki_nodes( # pylint: disable=unused-argument
+ self,
+ channel_user_id: str,
+ parent_node_id: str,
+ limit: int,
+ next_token: str | None = None,
+ ) -> WikiPage[WikiNode]:
+ """Direct children of one wiki space root or folder.
+
+ Default: empty, for a platform with no wiki.
+
+ Args:
+ channel_user_id (`str`): The platform user to read as.
+ parent_node_id (`str`): The space root or folder to browse.
+ limit (`int`): Maximum children to return.
+ next_token (`str | None`, optional): Token from a previous page.
+
+ Returns:
+ `WikiPage[WikiNode]`: One page of child entries.
+ """
+ return WikiPage(items=[])
+
+ async def read_wiki_document( # pylint: disable=unused-argument
+ self,
+ channel_user_id: str,
+ node_id: str,
+ start_index: int,
+ max_blocks: int,
+ ) -> WikiDocument | None:
+ """Read a bounded range of one wiki document.
+
+ Default: ``None``, for a platform with no wiki.
+
+ Args:
+ channel_user_id (`str`): The platform user to read as.
+ node_id (`str`): The document to read.
+ start_index (`int`): First block index to read.
+ max_blocks (`int`): Maximum blocks to read.
+
+ Returns:
+ `WikiDocument | None`: The range that was read, or ``None``
+ when the node is not a document this platform can read.
+
+ Raises:
+ `RuntimeError`: If the platform refuses the read, with a
+ message naming what the operator has to fix.
+ """
+ return None
def _split_long_message(self, text: str) -> list[str]:
"""Split text into chunks within the platform length limit.
diff --git a/src/agentscope/app/channel/_dingtalk/_channel.py b/src/agentscope/app/channel/_dingtalk/_channel.py
index 0d5685058..646900473 100644
--- a/src/agentscope/app/channel/_dingtalk/_channel.py
+++ b/src/agentscope/app/channel/_dingtalk/_channel.py
@@ -11,6 +11,7 @@ import base64
import binascii
import json
import mimetypes
+import re
import time
from typing import Any, AsyncIterator, Awaitable, Callable, TYPE_CHECKING
from urllib.parse import quote_plus
@@ -35,6 +36,10 @@ from .._base import (
ChannelEvent,
ChannelStatus,
ChatKind,
+ WikiDocument,
+ WikiNode,
+ WikiPage,
+ WikiSpace,
_EVENT_ADAPTER,
)
from ._card import (
@@ -49,6 +54,10 @@ if TYPE_CHECKING:
from ....tool import ToolBase
from ....workspace import WorkspaceBase
+# One tool result should stay readable to the model; a longer document is
+# read across several calls instead.
+_MAX_DOCUMENT_CHARS = 20_000
+_LAST_BLOCK_INDEX = 2**31 - 1
_CHATBOT_TOPIC = "/v1.0/im/bot/messages/get"
_CARD_CALLBACK_TOPIC = "/v1.0/card/instances/callback"
_GROUP_CONVERSATION = "2"
@@ -151,6 +160,7 @@ class DingTalkChannel(ChannelBase):
interactive=True,
streaming=False,
max_message_length=_MAX_LEN,
+ wiki=True,
)
def __init__(
@@ -510,12 +520,15 @@ class DingTalkChannel(ChannelBase):
async def list_tools(
self,
workspace: "WorkspaceBase",
+ channel_user_id: str | None = None,
) -> list["ToolBase"]:
- """Expose DingTalk discovery and target-send tools to the agent.
+ """Expose DingTalk tools to the agent.
Args:
workspace (`WorkspaceBase`): Calling session workspace whose
backend is used for file reads.
+ channel_user_id (`str | None`, optional): The DingTalk user the
+ session acts as, passed through to the inherited wiki tools.
Returns:
`list[ToolBase]`: DingTalk agent tools.
@@ -535,7 +548,7 @@ class DingTalkChannel(ChannelBase):
SendMessage(self, backend),
SendFile(self, backend),
SendImage(self, backend),
- ]
+ ] + await super().list_tools(workspace, channel_user_id)
async def search_users(
self,
@@ -553,6 +566,124 @@ class DingTalkChannel(ChannelBase):
"""
return await self._api().search_users(query, limit)
+ async def list_wiki_spaces(
+ self,
+ channel_user_id: str,
+ limit: int,
+ next_token: str | None = None,
+ ) -> WikiPage[WikiSpace]:
+ """List the DingTalk knowledge bases one user can read.
+
+ Args:
+ channel_user_id (`str`): Staff id from the inbound event.
+ limit (`int`): Maximum spaces to return.
+ next_token (`str | None`, optional): Token from a previous page.
+
+ Returns:
+ `WikiPage[WikiSpace]`: One page of knowledge bases.
+
+ Raises:
+ `RuntimeError`: If DingTalk rejects the lookup.
+ """
+ payload = await self._api().list_wiki_workspaces(
+ channel_user_id,
+ limit,
+ next_token,
+ )
+ return WikiPage(
+ items=[
+ WikiSpace(
+ space_id=item["workspaceId"],
+ name=item.get("name") or "",
+ root_node_id=item.get("rootNodeId") or "",
+ description=item.get("description") or None,
+ url=item.get("url") or None,
+ )
+ for item in payload.get("workspaces") or []
+ if isinstance(item, dict) and item.get("workspaceId")
+ ],
+ next_token=payload.get("nextToken") or None,
+ )
+
+ async def list_wiki_nodes(
+ self,
+ channel_user_id: str,
+ parent_node_id: str,
+ limit: int,
+ next_token: str | None = None,
+ ) -> WikiPage[WikiNode]:
+ """List the children of one DingTalk knowledge node.
+
+ Args:
+ channel_user_id (`str`): Staff id from the inbound event.
+ parent_node_id (`str`): Knowledge-base root or folder node id.
+ limit (`int`): Maximum children to return.
+ next_token (`str | None`, optional): Token from a previous page.
+
+ Returns:
+ `WikiPage[WikiNode]`: One page of child entries.
+
+ Raises:
+ `RuntimeError`: If DingTalk rejects the lookup.
+ """
+ payload = await self._api().list_wiki_nodes(
+ channel_user_id,
+ parent_node_id,
+ limit,
+ next_token,
+ )
+ return WikiPage(
+ items=[
+ _wiki_node(item)
+ for item in payload.get("nodes") or []
+ if isinstance(item, dict) and item.get("nodeId")
+ ],
+ next_token=payload.get("nextToken") or None,
+ )
+
+ async def read_wiki_document(
+ self,
+ channel_user_id: str,
+ node_id: str,
+ start_index: int,
+ max_blocks: int,
+ ) -> WikiDocument | None:
+ """Read a bounded block range of one DingTalk document.
+
+ Args:
+ channel_user_id (`str`): Staff id from the inbound event.
+ node_id (`str`): Wiki node id, which is also the document key.
+ start_index (`int`): First block index to read.
+ max_blocks (`int`): Maximum blocks to read.
+
+ Returns:
+ `WikiDocument | None`: The range read, or ``None`` when the
+ node is not an ``ALIDOC`` document.
+
+ Raises:
+ `RuntimeError`: If DingTalk rejects the lookup.
+ """
+ node = await self._api().get_wiki_node(channel_user_id, node_id)
+ if not _wiki_node(node).is_document:
+ return None
+ blocks = await self._api().read_document_blocks(
+ channel_user_id,
+ node_id,
+ start_index,
+ start_index + max_blocks - 1,
+ )
+ markdown, next_start_index = _render_blocks(
+ blocks,
+ start_index,
+ max_blocks,
+ )
+ return WikiDocument(
+ node_id=node.get("nodeId") or node_id,
+ name=node.get("name") or "",
+ content=[TextBlock(type="text", text=markdown)],
+ next_start_index=next_start_index,
+ )
+
async def send_message_to(self, target: str, text: str) -> bool:
"""Send Markdown text to an encoded DingTalk target.
@@ -1104,3 +1235,121 @@ class DingTalkChannel(ChannelBase):
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 _wiki_node(node: dict[str, Any]) -> WikiNode:
+ """Map one DingTalk wiki node onto the platform-neutral model.
+
+ Args:
+ node (`dict[str, Any]`): Raw node from the DingTalk wiki API.
+
+ Returns:
+ `WikiNode`: The neutral entry. ``ALIDOC`` is the only document
+ type the block reader below understands.
+ """
+ return WikiNode(
+ node_id=node.get("nodeId") or "",
+ name=node.get("name") or "",
+ has_children=bool(node.get("hasChildren")),
+ is_document=(
+ str(node.get("type") or "").upper() == "FILE"
+ and str(node.get("category") or "ALIDOC").upper() == "ALIDOC"
+ ),
+ url=node.get("url") or None,
+ updated_at=node.get("modifiedTime") or None,
+ )
+
+
+def _render_blocks(
+ blocks: list[dict[str, Any]],
+ start_index: int,
+ max_blocks: int,
+) -> tuple[str, int | None]:
+ """Render DingTalk document blocks as Markdown within a budget.
+
+ Args:
+ blocks (`list[dict[str, Any]]`): Raw blocks in document order.
+ start_index (`int`): The index the read started at.
+ max_blocks (`int`): The number of blocks that were requested.
+
+ Returns:
+ `tuple[str, int | None]`: The Markdown, and where a follow-up read
+ resumes — ``None`` once the document is exhausted.
+ """
+ parts: list[str] = []
+ total = 0
+ last_index = start_index - 1
+ for block in sorted(blocks, key=_block_index):
+ rendered = _render_block(block)
+ added = len(rendered) + (2 if parts else 0)
+ # Stop before the block that would overflow, never inside one: the
+ # resume index counts whole blocks, so a split tail is unreachable.
+ if parts and total + added > _MAX_DOCUMENT_CHARS:
+ return "\n\n".join(parts), last_index + 1
+ parts.append(rendered)
+ last_index = _block_index(block)
+ total += added
+ exhausted = len(blocks) < max_blocks
+ return "\n\n".join(parts), None if exhausted else last_index + 1
+
+
+def _render_block(block: dict[str, Any]) -> str:
+ """Render one DingTalk block, naming the ones Markdown cannot carry."""
+ block_type = str(block.get("blockType") or "unknown")
+ detail = block.get(block_type)
+ detail = detail if isinstance(detail, dict) else {}
+ text = str(detail.get("text") or block.get("text") or "")
+ if block_type == "heading":
+ match = re.search(r"([1-6])$", str(detail.get("level") or "1"))
+ return f"{'#' * int(match.group(1) if match else 1)} {text}".rstrip()
+ if block_type in ("paragraph", "callout"):
+ return text
+ if block_type == "unorderedList":
+ return f"- {text}".rstrip()
+ if block_type == "orderedList":
+ return f"1. {text}".rstrip()
+ if block_type == "blockquote":
+ return f"> {text}".rstrip()
+ if block_type == "table":
+ return _render_table(detail)
+ return f"[Unsupported block: {block_type}]"
+
+
+def _render_table(detail: dict[str, Any]) -> str:
+ """Render a DingTalk table block as a Markdown table.
+
+ DingTalk carries the cell text inside the block as a 2-D array, so a
+ table reaches the agent whole rather than as a placeholder, and counts
+ as the single block its index refers to.
+ """
+ rows = [
+ [
+ str(cell)
+ .replace("\\", "\\\\")
+ .replace("|", "\\|")
+ .replace("\r", " ")
+ .replace("\n", " ")
+ for cell in row
+ ]
+ for row in detail.get("cells") or []
+ if isinstance(row, list)
+ ]
+ if not rows:
+ size = f"{detail.get('rowSize', '?')}x{detail.get('colSize', '?')}"
+ return f"[Table: {size}, no cell content]"
+ width = max(len(row) for row in rows)
+ header, *body = [row + [""] * (width - len(row)) for row in rows]
+ lines = [
+ "| " + " | ".join(header) + " |",
+ "| " + " | ".join(["---"] * width) + " |",
+ *("| " + " | ".join(row) + " |" for row in body),
+ ]
+ return "\n".join(lines)
+
+
+def _block_index(block: dict[str, Any]) -> int:
+ """Return a sortable block index, putting malformed values last."""
+ try:
+ return int(block.get("index", _LAST_BLOCK_INDEX))
+ except (TypeError, ValueError):
+ return _LAST_BLOCK_INDEX
diff --git a/src/agentscope/app/channel/_dingtalk/_openapi.py b/src/agentscope/app/channel/_dingtalk/_openapi.py
index f6b2ce291..99124f709 100644
--- a/src/agentscope/app/channel/_dingtalk/_openapi.py
+++ b/src/agentscope/app/channel/_dingtalk/_openapi.py
@@ -6,14 +6,16 @@ import ipaddress
import json
import time
from typing import Any
-from urllib.parse import urlparse
+from urllib.parse import quote, urlparse
from uuid import uuid1, uuid4
from ...._logging import logger
-_API = "https://api.dingtalk.com/v1.0"
+_API_ROOT = "https://api.dingtalk.com"
+_API = f"{_API_ROOT}/v1.0"
_OAPI = "https://oapi.dingtalk.com"
_TOKEN_REFRESH_BUFFER_SECONDS = 300
+_UNION_ID_CACHE_SIZE = 2048
# Enough of a refusal to name the offending field, not so much that a
# rejected payload is echoed back into the log.
_ERROR_BODY_CHARS = 500
@@ -48,6 +50,161 @@ class _DingTalkOpenAPI:
self._token: str | None = None
self._token_expires_at = 0.0
self._token_lock = asyncio.Lock()
+ self._union_ids: dict[str, str] = {}
+
+ async def _operator_id(self, user_id: str) -> str:
+ """Resolve a staff id to the union id the wiki APIs act as.
+
+ Args:
+ user_id (`str`): Enterprise staff id from the robot callback.
+
+ Returns:
+ `str`: The user's union id.
+
+ Raises:
+ `RuntimeError`: If the application cannot read the profile.
+ """
+ cached = self._union_ids.get(user_id)
+ if cached:
+ return cached
+ token = await self._access_token()
+ detail = await self._user_detail(token, user_id) if token else None
+ union_id = str((detail or {}).get("union_id") or "")
+ if not union_id:
+ raise RuntimeError(
+ "DingTalk could not resolve the current user's unionId. "
+ "Check the application's contact permission.",
+ )
+ if len(self._union_ids) >= _UNION_ID_CACHE_SIZE:
+ self._union_ids.pop(next(iter(self._union_ids)))
+ self._union_ids[user_id] = union_id
+ return union_id
+
+ async def list_wiki_workspaces(
+ self,
+ user_id: str,
+ limit: int,
+ next_token: str | None = None,
+ ) -> dict[str, Any]:
+ """List the wiki workspaces visible to one DingTalk user.
+
+ Args:
+ user_id (`str`): The staff id to act as.
+ limit (`int`): Maximum results requested from DingTalk.
+ next_token (`str | None`): Optional pagination token.
+
+ Returns:
+ `dict[str, Any]`: DingTalk's ``workspaces`` and ``nextToken``.
+
+ Raises:
+ `RuntimeError`: If DingTalk rejects the lookup.
+ """
+ return await self._wiki_get(
+ "/v2.0/wiki/workspaces",
+ user_id,
+ {
+ "maxResults": limit,
+ "nextToken": next_token,
+ "withPermissionRole": True,
+ },
+ "wiki-workspace listing",
+ )
+
+ async def list_wiki_nodes(
+ self,
+ user_id: str,
+ parent_node_id: str,
+ limit: int,
+ next_token: str | None = None,
+ ) -> dict[str, Any]:
+ """List the direct children of one DingTalk wiki node.
+
+ Args:
+ user_id (`str`): The staff id to act as.
+ parent_node_id (`str`): Workspace root or folder node id.
+ limit (`int`): Maximum results requested from DingTalk.
+ next_token (`str | None`): Optional pagination token.
+
+ Returns:
+ `dict[str, Any]`: DingTalk's ``nodes`` and ``nextToken``.
+
+ Raises:
+ `RuntimeError`: If DingTalk rejects the lookup.
+ """
+ return await self._wiki_get(
+ "/v2.0/wiki/nodes",
+ user_id,
+ {
+ "parentNodeId": parent_node_id,
+ "maxResults": limit,
+ "nextToken": next_token,
+ "withPermissionRole": True,
+ },
+ "wiki-node listing",
+ )
+
+ async def get_wiki_node(
+ self,
+ user_id: str,
+ node_id: str,
+ ) -> dict[str, Any]:
+ """Get the metadata of one DingTalk wiki node.
+
+ Args:
+ user_id (`str`): The staff id to act as.
+ node_id (`str`): Wiki node identifier.
+
+ Returns:
+ `dict[str, Any]`: Node metadata, or an empty mapping if DingTalk
+ returns no node.
+
+ Raises:
+ `RuntimeError`: If DingTalk rejects the lookup.
+ """
+ payload = await self._wiki_get(
+ f"/v2.0/wiki/nodes/{quote(node_id, safe='')}",
+ user_id,
+ {
+ "withPermissionRole": True,
+ "withStatisticalInfo": True,
+ },
+ "wiki-node lookup",
+ )
+ node = payload.get("node")
+ return node if isinstance(node, dict) else {}
+
+ async def read_document_blocks(
+ self,
+ user_id: str,
+ doc_key: str,
+ start_index: int,
+ end_index: int,
+ ) -> list[dict[str, Any]]:
+ """Read a bounded range of DingTalk document blocks.
+
+ Args:
+ user_id (`str`): The staff id to act as.
+ doc_key (`str`): Document key (Wiki node ids normally work).
+ start_index (`int`): First block index, inclusive.
+ end_index (`int`): Last block index, inclusive.
+
+ Returns:
+ `list[dict[str, Any]]`: Raw block objects in document order.
+
+ Raises:
+ `RuntimeError`: If DingTalk rejects the lookup.
+ """
+ payload = await self._wiki_get(
+ f"/v1.0/doc/suites/documents/{quote(doc_key, safe='')}/blocks",
+ user_id,
+ {"startIndex": start_index, "endIndex": end_index},
+ "document-block reading",
+ )
+ result = payload.get("result")
+ data = result.get("data") if isinstance(result, dict) else None
+ if not isinstance(data, list):
+ return []
+ return [item for item in data if isinstance(item, dict)]
async def download_media(
self,
@@ -532,6 +689,7 @@ class _DingTalkOpenAPI:
result = payload.get("result") or {}
return {
"user_id": str(result.get("userid") or user_id),
+ "union_id": str(result.get("unionid") or ""),
"name": str(result.get("name") or ""),
"title": str(result.get("title") or ""),
"department_ids": result.get("dept_id_list") or [],
@@ -595,6 +753,79 @@ class _DingTalkOpenAPI:
logger.exception("DingTalk message send failed")
return False
+ async def _wiki_get(
+ self,
+ path: str,
+ user_id: str,
+ params: dict[str, Any],
+ operation: str,
+ ) -> dict[str, Any]:
+ """Issue an authenticated GET that acts as one DingTalk user.
+
+ Args:
+ path (`str`): Absolute path below ``api.dingtalk.com``.
+ user_id (`str`): The staff id to act as.
+ params (`dict[str, Any]`): Additional query parameters.
+ operation (`str`): Human-readable operation for errors.
+
+ Returns:
+ `dict[str, Any]`: JSON response object.
+
+ Raises:
+ `RuntimeError`: If authentication, permissions, transport,
+ or response validation fails.
+ """
+ token = await self._access_token()
+ if token is None:
+ raise RuntimeError(
+ f"DingTalk {operation} failed: no application access token.",
+ )
+ query = {
+ "operatorId": await self._operator_id(user_id),
+ **{k: v for k, v in params.items() if v is not None and v != ""},
+ }
+ try:
+ response = await self._http.get(
+ f"{_API_ROOT}{path}",
+ headers=self._headers(token),
+ params=query,
+ )
+ try:
+ payload = response.json()
+ except ValueError as exc:
+ raise RuntimeError(
+ f"DingTalk {operation} returned invalid JSON.",
+ ) from exc
+ if not isinstance(payload, dict):
+ raise RuntimeError(
+ f"DingTalk {operation} returned an invalid response.",
+ )
+ code = payload.get("code") or payload.get("errcode")
+ message = str(
+ payload.get("message")
+ or payload.get("errmsg")
+ or payload.get("errorMessage")
+ or "request rejected",
+ )
+ if (
+ response.status_code >= 400
+ or code not in (None, "", 0, "0")
+ or payload.get("success") is False
+ ):
+ raise RuntimeError(
+ f"DingTalk {operation} failed (HTTP "
+ f"{response.status_code}, code={code or 'unknown'}): "
+ f"{message[:_ERROR_BODY_CHARS]}",
+ )
+ return payload
+ except RuntimeError:
+ raise
+ except Exception as exc:
+ logger.exception("DingTalk %s failed", operation)
+ raise RuntimeError(
+ f"DingTalk {operation} failed: {type(exc).__name__}.",
+ ) from exc
+
async def _request(
self,
method: str,
diff --git a/src/agentscope/app/channel/_feishu/_channel.py b/src/agentscope/app/channel/_feishu/_channel.py
index 539c2f889..ba010e408 100644
--- a/src/agentscope/app/channel/_feishu/_channel.py
+++ b/src/agentscope/app/channel/_feishu/_channel.py
@@ -941,6 +941,7 @@ class FeishuChannel(ChannelBase):
async def list_tools(
self,
workspace: "WorkspaceBase",
+ channel_user_id: str | None = None,
) -> list["ToolBase"]:
"""Expose the Feishu send/discovery tools to the agent.
@@ -948,6 +949,8 @@ class FeishuChannel(ChannelBase):
workspace (`WorkspaceBase`):
The calling session's workspace; the send-file tools read
their payload from its backend by absolute path.
+ channel_user_id (`str | None`, optional): The platform user
+ the session acts as, passed through to the inherited tools.
Returns:
`list[ToolBase]`: The Feishu agent tools.
@@ -967,7 +970,7 @@ class FeishuChannel(ChannelBase):
SendMessage(self, backend),
SendFile(self, backend),
SendImage(self, backend),
- ]
+ ] + await super().list_tools(workspace, channel_user_id)
# -- Agent-tool operations (act on chats/users other than the current) --
diff --git a/src/agentscope/app/channel/_gateway.py b/src/agentscope/app/channel/_gateway.py
index fa651ddb9..0029d0e19 100644
--- a/src/agentscope/app/channel/_gateway.py
+++ b/src/agentscope/app/channel/_gateway.py
@@ -324,6 +324,7 @@ class ChannelGateway:
channel_id=record.id,
chat_id=event.chat_id,
chat_name=event.chat_name or None,
+ channel_user_id=event.channel_user_id or None,
),
)
diff --git a/src/agentscope/app/channel/_tools/__init__.py b/src/agentscope/app/channel/_tools/__init__.py
new file mode 100644
index 000000000..83cc803aa
--- /dev/null
+++ b/src/agentscope/app/channel/_tools/__init__.py
@@ -0,0 +1,12 @@
+# -*- coding: utf-8 -*-
+"""Agent tools shared by every channel whose platform has a wiki."""
+
+from ._list_wiki_nodes import ListWikiNodes
+from ._list_wiki_spaces import ListWikiSpaces
+from ._read_wiki_document import ReadWikiDocument
+
+__all__ = [
+ "ListWikiNodes",
+ "ListWikiSpaces",
+ "ReadWikiDocument",
+]
diff --git a/src/agentscope/app/channel/_tools/_base.py b/src/agentscope/app/channel/_tools/_base.py
new file mode 100644
index 000000000..1abca4762
--- /dev/null
+++ b/src/agentscope/app/channel/_tools/_base.py
@@ -0,0 +1,61 @@
+# -*- coding: utf-8 -*-
+"""Shared base for the read-only wiki tools."""
+
+from typing import Any, TYPE_CHECKING
+
+from ....permission import (
+ PermissionBehavior,
+ PermissionContext,
+ PermissionDecision,
+)
+from ....tool import ToolBase
+
+if TYPE_CHECKING:
+ from .._base import ChannelBase
+
+
+class _WikiToolBase(ToolBase):
+ """A wiki lookup bound to the one platform user it reads as."""
+
+ is_read_only: bool = True
+ 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: "ChannelBase",
+ channel_user_id: str,
+ ) -> None:
+ """Bind the live channel and the user whose access is used.
+
+ Args:
+ channel (`ChannelBase`): The channel serving this session.
+ channel_user_id (`str`): The platform user to read as. Supplied
+ by the server from the inbound message, never by the model.
+ """
+ super().__init__()
+ self._channel = channel
+ self._channel_user_id = channel_user_id
+
+ async def check_permissions(
+ self,
+ tool_input: dict[str, Any],
+ context: PermissionContext,
+ ) -> PermissionDecision:
+ """Allow the lookup: the platform already scopes it to the user.
+
+ Args:
+ tool_input (`dict[str, Any]`): Proposed tool arguments.
+ context (`PermissionContext`): Session permission context.
+
+ Returns:
+ `PermissionDecision`: Always allow.
+ """
+ del tool_input, context
+ return PermissionDecision(
+ behavior=PermissionBehavior.ALLOW,
+ message=f"{self.name} is a read-only lookup.",
+ )
diff --git a/src/agentscope/app/channel/_tools/_list_wiki_nodes.py b/src/agentscope/app/channel/_tools/_list_wiki_nodes.py
new file mode 100644
index 000000000..ebe32705a
--- /dev/null
+++ b/src/agentscope/app/channel/_tools/_list_wiki_nodes.py
@@ -0,0 +1,87 @@
+# -*- coding: utf-8 -*-
+"""Browse one level of a wiki space's tree."""
+
+import json
+
+from pydantic import Field
+
+from ._base import _WikiToolBase
+from ....message import TextBlock, ToolResultState
+from ....tool import ParamsBase, ToolChunk
+
+
+class _ListWikiNodesParams(ParamsBase):
+ parent_node_id: str = Field(
+ min_length=1,
+ max_length=512,
+ description="A space's root node id, or a folder's node id.",
+ )
+ limit: int = Field(
+ default=50,
+ ge=1,
+ le=100,
+ description="Maximum number of direct children to return.",
+ )
+ next_token: str = Field(
+ default="",
+ max_length=2048,
+ description="Pagination token returned by a previous call.",
+ )
+
+
+class ListWikiNodes(_WikiToolBase):
+ """List the direct children of one wiki space root or folder."""
+
+ name: str = "ListWikiNodes"
+ description: str = """Browse a wiki space one level at a time.
+
+Pass a ``root_node_id`` from ``ListWikiSpaces``, or a folder's ``node_id``.
+An entry with ``has_children=true`` is a folder you can browse again; one
+with ``is_document=true`` can be read with ``ReadWikiDocument``. Use a
+returned ``next_token`` to continue the same listing."""
+ input_schema: dict = _ListWikiNodesParams.model_json_schema()
+
+ async def __call__(
+ self,
+ parent_node_id: str,
+ limit: int = 50,
+ next_token: str = "",
+ ) -> ToolChunk:
+ """List the children visible below ``parent_node_id``.
+
+ Args:
+ parent_node_id (`str`): Space root or folder node id.
+ limit (`int`): Maximum result count.
+ next_token (`str`): Optional pagination token.
+
+ Returns:
+ `ToolChunk`: JSON-encoded child entries and the next page token.
+ """
+ try:
+ page = await self._channel.list_wiki_nodes(
+ self._channel_user_id,
+ parent_node_id,
+ limit,
+ next_token or None,
+ )
+ except RuntimeError as exc:
+ return ToolChunk(
+ content=[TextBlock(text=str(exc))],
+ state=ToolResultState.ERROR,
+ )
+ return ToolChunk(
+ content=[
+ TextBlock(
+ text=json.dumps(
+ {
+ "nodes": [
+ node.model_dump(mode="json")
+ for node in page.items
+ ],
+ "next_token": page.next_token or "",
+ },
+ ensure_ascii=False,
+ ),
+ ),
+ ],
+ )
diff --git a/src/agentscope/app/channel/_tools/_list_wiki_spaces.py b/src/agentscope/app/channel/_tools/_list_wiki_spaces.py
new file mode 100644
index 000000000..5b9c9684f
--- /dev/null
+++ b/src/agentscope/app/channel/_tools/_list_wiki_spaces.py
@@ -0,0 +1,80 @@
+# -*- coding: utf-8 -*-
+"""List the wiki spaces the current platform user can read."""
+
+import json
+
+from pydantic import Field
+
+from ._base import _WikiToolBase
+from ....message import TextBlock, ToolResultState
+from ....tool import ParamsBase, ToolChunk
+
+
+class _ListWikiSpacesParams(ParamsBase):
+ limit: int = Field(
+ default=20,
+ ge=1,
+ le=50,
+ description="Maximum number of spaces to return.",
+ )
+ next_token: str = Field(
+ default="",
+ max_length=2048,
+ description="Pagination token returned by a previous call.",
+ )
+
+
+class ListWikiSpaces(_WikiToolBase):
+ """List wiki spaces readable by the current sender."""
+
+ name: str = "ListWikiSpaces"
+ description: str = """List the wiki spaces (knowledge bases) the current
+user can read on the chat platform.
+
+Use a returned ``root_node_id`` with ``ListWikiNodes`` to browse a space. If
+``next_token`` comes back non-empty, call again with it to get the next page.
+Access is evaluated as the person who sent the current message; the model
+cannot supply or change that identity."""
+ input_schema: dict = _ListWikiSpacesParams.model_json_schema()
+
+ async def __call__(
+ self,
+ limit: int = 20,
+ next_token: str = "",
+ ) -> ToolChunk:
+ """List the spaces visible to the bound user.
+
+ Args:
+ limit (`int`): Maximum result count.
+ next_token (`str`): Optional pagination token.
+
+ Returns:
+ `ToolChunk`: JSON-encoded spaces and the next page token.
+ """
+ try:
+ page = await self._channel.list_wiki_spaces(
+ self._channel_user_id,
+ limit,
+ next_token or None,
+ )
+ except RuntimeError as exc:
+ return ToolChunk(
+ content=[TextBlock(text=str(exc))],
+ state=ToolResultState.ERROR,
+ )
+ return ToolChunk(
+ content=[
+ TextBlock(
+ text=json.dumps(
+ {
+ "spaces": [
+ space.model_dump(mode="json")
+ for space in page.items
+ ],
+ "next_token": page.next_token or "",
+ },
+ ensure_ascii=False,
+ ),
+ ),
+ ],
+ )
diff --git a/src/agentscope/app/channel/_tools/_read_wiki_document.py b/src/agentscope/app/channel/_tools/_read_wiki_document.py
new file mode 100644
index 000000000..7aac56136
--- /dev/null
+++ b/src/agentscope/app/channel/_tools/_read_wiki_document.py
@@ -0,0 +1,95 @@
+# -*- coding: utf-8 -*-
+"""Read a bounded range of one wiki document."""
+
+import json
+
+from pydantic import Field
+
+from ._base import _WikiToolBase
+from ....message import TextBlock, ToolResultState
+from ....tool import ParamsBase, ToolChunk
+
+
+class _ReadWikiDocumentParams(ParamsBase):
+ node_id: str = Field(
+ min_length=1,
+ max_length=512,
+ description="Node id of a document returned by ListWikiNodes.",
+ )
+ start_index: int = Field(
+ default=0,
+ ge=0,
+ description="First content block to read.",
+ )
+ max_blocks: int = Field(
+ default=50,
+ ge=1,
+ le=100,
+ description="Maximum number of content blocks to read.",
+ )
+
+
+class ReadWikiDocument(_WikiToolBase):
+ """Read one wiki document as the current sender."""
+
+ name: str = "ReadWikiDocument"
+ description: str = """Read the text of a wiki document.
+
+Use a ``node_id`` that ``ListWikiNodes`` reported with ``is_document=true``.
+A long document is read in ranges: when the result carries
+``next_start_index``, call again with it to continue."""
+ input_schema: dict = _ReadWikiDocumentParams.model_json_schema()
+
+ async def __call__(
+ self,
+ node_id: str,
+ start_index: int = 0,
+ max_blocks: int = 50,
+ ) -> ToolChunk:
+ """Read a bounded range of the document's content blocks.
+
+ Args:
+ node_id (`str`): The document to read.
+ start_index (`int`): First block index to read.
+ max_blocks (`int`): Maximum number of blocks to read.
+
+ Returns:
+ `ToolChunk`: The document's content, plus where to resume.
+ """
+ try:
+ document = await self._channel.read_wiki_document(
+ self._channel_user_id,
+ node_id,
+ start_index,
+ max_blocks,
+ )
+ except RuntimeError as exc:
+ return ToolChunk(
+ content=[TextBlock(text=str(exc))],
+ state=ToolResultState.ERROR,
+ )
+ if document is None:
+ return ToolChunk(
+ content=[
+ TextBlock(
+ text="That node is not a readable wiki document.",
+ ),
+ ],
+ state=ToolResultState.ERROR,
+ )
+ return ToolChunk(
+ content=[
+ TextBlock(
+ text=json.dumps(
+ {
+ "node_id": document.node_id,
+ "name": document.name,
+ "start_index": start_index,
+ "next_start_index": document.next_start_index,
+ },
+ ensure_ascii=False,
+ ),
+ ),
+ *document.content,
+ ],
+ )
diff --git a/src/agentscope/app/storage/_model/_session.py b/src/agentscope/app/storage/_model/_session.py
index 76192e219..5364d37b8 100644
--- a/src/agentscope/app/storage/_model/_session.py
+++ b/src/agentscope/app/storage/_model/_session.py
@@ -60,6 +60,12 @@ class ChannelOrigin(BaseModel):
because the name arrives with the inbound message: a node that never
holds the connection cannot look it up."""
+ channel_user_id: str | None = None
+ """The platform user who opened the session, when the platform named
+ one. Channels whose tools act with the sender's own permissions read
+ it to bind those tools; ``None`` on sessions created before it was
+ recorded."""
+
class TeamOrigin(BaseModel):
"""A session a team minted for one of its members.
diff --git a/tests/channel_dingtalk_test.py b/tests/channel_dingtalk_test.py
index 7d2d118fd..3605f0e8d 100644
--- a/tests/channel_dingtalk_test.py
+++ b/tests/channel_dingtalk_test.py
@@ -39,6 +39,7 @@ from agentscope.message import (
DataBlock,
TextBlock,
ToolCallBlock,
+ ToolResultState,
)
from agentscope.permission import PermissionBehavior, PermissionContext
from agentscope.workspace import WorkspaceBase
@@ -121,6 +122,12 @@ class _FakeMediaOpenAPI:
self.streaming_card_calls: list[tuple[str, str, str]] = []
self.streaming_updates: list[tuple[str, str, str, bool, bool]] = []
self.streaming_update_success = True
+ self.wiki_workspaces: dict[str, Any] = {"workspaces": []}
+ self.wiki_nodes: dict[str, Any] = {"nodes": []}
+ self.wiki_node: dict[str, Any] = {}
+ self.document_blocks: list[dict[str, Any]] = []
+ self.wiki_calls: list[tuple[Any, ...]] = []
+ self.wiki_error: Exception | None = None
async def download_media(
self,
@@ -152,6 +159,60 @@ class _FakeMediaOpenAPI:
del query
return self.search_result[:limit]
+ def _wiki_call(self, *call: Any) -> None:
+ self.wiki_calls.append(call)
+ if self.wiki_error is not None:
+ raise self.wiki_error
+
+ async def list_wiki_workspaces(
+ self,
+ user_id: str,
+ limit: int,
+ next_token: str | None = None,
+ ) -> dict[str, Any]:
+ self._wiki_call("list_wiki_workspaces", user_id, limit, next_token)
+ return self.wiki_workspaces
+
+ async def list_wiki_nodes(
+ self,
+ user_id: str,
+ parent_node_id: str,
+ limit: int,
+ next_token: str | None = None,
+ ) -> dict[str, Any]:
+ self._wiki_call(
+ "list_wiki_nodes",
+ user_id,
+ parent_node_id,
+ limit,
+ next_token,
+ )
+ return self.wiki_nodes
+
+ async def get_wiki_node(
+ self,
+ user_id: str,
+ node_id: str,
+ ) -> dict[str, Any]:
+ self._wiki_call("get_wiki_node", user_id, node_id)
+ return self.wiki_node
+
+ async def read_document_blocks(
+ self,
+ user_id: str,
+ doc_key: str,
+ start_index: int,
+ end_index: int,
+ ) -> list[dict[str, Any]]:
+ self._wiki_call(
+ "read_document_blocks",
+ user_id,
+ doc_key,
+ start_index,
+ end_index,
+ )
+ return self.document_blocks
+
async def create_approval_card(
self,
chat_id: str,
@@ -262,6 +323,7 @@ class _OpenAPIHTTP(_FakeHTTP):
self._stream_response = stream_response
self.streams: list[tuple[str, str, dict[str, Any]]] = []
self.requests: list[tuple[str, str, dict[str, Any]]] = []
+ self.gets: list[tuple[str, dict[str, Any]]] = []
async def post(self, url: str, **kwargs: Any) -> _FakeResponse:
self.posts.append((url, kwargs))
@@ -276,6 +338,10 @@ class _OpenAPIHTTP(_FakeHTTP):
self.requests.append((method, url, kwargs))
return self._responses.pop(0)
+ async def get(self, url: str, **kwargs: Any) -> _FakeResponse:
+ self.gets.append((url, kwargs))
+ return self._responses.pop(0)
+
def stream(
self,
method: str,
@@ -1044,7 +1110,7 @@ class DingTalkChannelTest( # pylint: disable=too-many-public-methods
class DingTalkToolTest(IsolatedAsyncioTestCase):
- """DingTalk discovery and target-send tool tests."""
+ """DingTalk discovery, knowledge, and target-send tool tests."""
async def test_channel_target_operations_reuse_openapi(self) -> None:
media_api = _FakeMediaOpenAPI()
@@ -1161,6 +1227,241 @@ class DingTalkToolTest(IsolatedAsyncioTestCase):
self.assertEqual(read_decision.behavior, PermissionBehavior.ALLOW)
self.assertEqual(send_decision.behavior, PermissionBehavior.ASK)
+ async def test_wiki_tools_are_bound_to_current_sender(self) -> None:
+ from agentscope.app.channel._tools import (
+ ListWikiNodes,
+ ListWikiSpaces,
+ ReadWikiDocument,
+ )
+
+ media_api = _FakeMediaOpenAPI()
+ media_api.wiki_workspaces = {
+ "workspaces": [
+ {
+ "workspaceId": "space-1",
+ "name": "Engineering",
+ "rootNodeId": "root-1",
+ "url": "https://example.invalid/space-1",
+ },
+ ],
+ "nextToken": "spaces-next",
+ }
+ media_api.wiki_nodes = {
+ "nodes": [
+ {
+ "nodeId": "doc-1",
+ "name": "Runbook",
+ "type": "FILE",
+ "category": "ALIDOC",
+ "hasChildren": False,
+ },
+ ],
+ }
+ media_api.wiki_node = {
+ "nodeId": "doc-1",
+ "name": "Runbook",
+ "type": "FILE",
+ "category": "ALIDOC",
+ }
+ media_api.document_blocks = [
+ {
+ "blockType": "heading",
+ "heading": {"level": "heading-2", "text": "Deploy"},
+ "index": 0,
+ },
+ {
+ "blockType": "paragraph",
+ "paragraph": {"text": "Run the release command."},
+ "index": 1,
+ },
+ {
+ "blockType": "table",
+ "table": {
+ "rowSize": 2,
+ "colSize": 2,
+ "cells": [["Step", "Owner"], ["Deploy", "Alice"]],
+ },
+ "index": 2,
+ },
+ ]
+ channel, _ = _channel_with_openapi(media_api)
+ workspace = cast(WorkspaceBase, _FakeWorkspace(_FakeBackend()))
+
+ tools = await channel.list_tools(workspace, "staff-1")
+
+ self.assertListEqual(
+ [tool.name for tool in tools],
+ [
+ "ListConversations",
+ "ListUsers",
+ "SendMessage",
+ "SendFile",
+ "SendImage",
+ "ListWikiSpaces",
+ "ListWikiNodes",
+ "ReadWikiDocument",
+ ],
+ )
+ for tool in tools[5:]:
+ self.assertNotIn(
+ "channel_user_id",
+ tool.input_schema["properties"],
+ )
+ decision = await tool.check_permissions({}, PermissionContext())
+ self.assertEqual(decision.behavior, PermissionBehavior.ALLOW)
+
+ spaces = await cast(ListWikiSpaces, tools[5])(10, "")
+ nodes = await cast(ListWikiNodes, tools[6])("root-1", 25, "")
+ document = await cast(ReadWikiDocument, tools[7])("doc-1", 0, 3)
+
+ self.assertDictEqual(
+ json.loads(spaces.content[0].text),
+ {
+ "spaces": [
+ {
+ "space_id": "space-1",
+ "name": "Engineering",
+ "root_node_id": "root-1",
+ "description": None,
+ "url": "https://example.invalid/space-1",
+ },
+ ],
+ "next_token": "spaces-next",
+ },
+ )
+ self.assertDictEqual(
+ json.loads(nodes.content[0].text),
+ {
+ "nodes": [
+ {
+ "node_id": "doc-1",
+ "name": "Runbook",
+ "has_children": False,
+ "is_document": True,
+ "url": None,
+ "updated_at": None,
+ },
+ ],
+ "next_token": "",
+ },
+ )
+ # A full page may have more behind it, so a resume point is given.
+ self.assertDictEqual(
+ json.loads(document.content[0].text),
+ {
+ "node_id": "doc-1",
+ "name": "Runbook",
+ "start_index": 0,
+ "next_start_index": 3,
+ },
+ )
+ self.assertEqual(
+ document.content[1].text,
+ "## Deploy\n\nRun the release command.\n\n"
+ "| Step | Owner |\n| --- | --- |\n| Deploy | Alice |",
+ )
+ self.assertListEqual(
+ media_api.wiki_calls,
+ [
+ ("list_wiki_workspaces", "staff-1", 10, None),
+ ("list_wiki_nodes", "staff-1", "root-1", 25, None),
+ ("get_wiki_node", "staff-1", "doc-1"),
+ ("read_document_blocks", "staff-1", "doc-1", 0, 2),
+ ],
+ )
+
+ async def test_an_oversized_block_is_returned_whole(self) -> None:
+ """A block is never split: its tail could never be requested."""
+ from agentscope.app.channel._tools import ReadWikiDocument
+
+ media_api = _FakeMediaOpenAPI()
+ media_api.wiki_node = {
+ "nodeId": "doc-1",
+ "name": "Runbook",
+ "type": "FILE",
+ "category": "ALIDOC",
+ }
+ media_api.document_blocks = [
+ {
+ "blockType": "paragraph",
+ "paragraph": {"text": "x" * 30_000},
+ "index": 0,
+ },
+ ]
+ channel, _ = _channel_with_openapi(media_api)
+ tools = await channel.list_tools(
+ cast(WorkspaceBase, _FakeWorkspace(_FakeBackend())),
+ "staff-1",
+ )
+
+ document = await cast(ReadWikiDocument, tools[7])("doc-1", 0, 1)
+
+ self.assertDictEqual(
+ json.loads(document.content[0].text),
+ {
+ "node_id": "doc-1",
+ "name": "Runbook",
+ "start_index": 0,
+ "next_start_index": 1,
+ },
+ )
+ self.assertEqual(document.content[1].text, "x" * 30_000)
+
+ async def test_a_folder_node_is_not_a_readable_document(self) -> None:
+ from agentscope.app.channel._tools import ReadWikiDocument
+
+ media_api = _FakeMediaOpenAPI()
+ media_api.wiki_node = {
+ "nodeId": "folder-1",
+ "name": "Runbooks",
+ "type": "FOLDER",
+ "hasChildren": True,
+ }
+ channel, _ = _channel_with_openapi(media_api)
+ tools = await channel.list_tools(
+ cast(WorkspaceBase, _FakeWorkspace(_FakeBackend())),
+ "staff-1",
+ )
+
+ document = await cast(ReadWikiDocument, tools[7])("folder-1", 0, 10)
+
+ self.assertEqual(document.state, ToolResultState.ERROR)
+ self.assertIn("not a readable", document.content[0].text)
+
+ async def test_wiki_tools_hidden_without_channel_sender(self) -> None:
+ channel = _channel()
+ workspace = cast(WorkspaceBase, _FakeWorkspace(_FakeBackend()))
+
+ tools = await channel.list_tools(workspace)
+
+ self.assertListEqual(
+ [tool.name for tool in tools],
+ [
+ "ListConversations",
+ "ListUsers",
+ "SendMessage",
+ "SendFile",
+ "SendImage",
+ ],
+ )
+
+ async def test_wiki_identity_failure_is_visible(self) -> None:
+ media_api = _FakeMediaOpenAPI()
+ media_api.wiki_error = RuntimeError(
+ "DingTalk could not resolve the current user's unionId. "
+ "Check the application's contact permission.",
+ )
+ channel, _ = _channel_with_openapi(media_api)
+ tools = await channel.list_tools(
+ cast(WorkspaceBase, _FakeWorkspace(_FakeBackend())),
+ "staff-without-contact-access",
+ )
+
+ result = await tools[5](limit=20, next_token="")
+
+ self.assertEqual(result.state, ToolResultState.ERROR)
+ self.assertIn("contact permission", result.content[0].text)
+
async def test_send_tools_do_not_depend_on_card_configuration(
self,
) -> None:
@@ -1464,6 +1765,137 @@ class DingTalkOpenAPITest(IsolatedAsyncioTestCase):
self.assertEqual(users[1]["user_id"], "user-2")
self.assertEqual(users[1]["name"], "")
+ async def test_wiki_gets_resolve_and_cache_the_operator(self) -> None:
+ """Every wiki call acts as the sender's resolved unionId."""
+ api, http = _openapi(
+ {
+ "errcode": 0,
+ "result": {"userid": "staff-1", "unionid": "union-1"},
+ },
+ {
+ "workspaces": [{"workspaceId": "space/1"}],
+ "nextToken": "space-next",
+ },
+ {"nodes": [{"nodeId": "doc/1"}]},
+ {"node": {"nodeId": "doc/1"}},
+ {
+ "success": True,
+ "result": {
+ "data": [
+ {
+ "blockType": "paragraph",
+ "paragraph": {"text": "hello"},
+ "index": 0,
+ },
+ ],
+ },
+ },
+ )
+
+ spaces = await api.list_wiki_workspaces("staff-1", 20)
+ nodes = await api.list_wiki_nodes("staff-1", "root-1", 50, "node-next")
+ node = await api.get_wiki_node("staff-1", "doc/1")
+ blocks = await api.read_document_blocks("staff-1", "doc/1", 0, 49)
+
+ self.assertDictEqual(
+ spaces,
+ {
+ "workspaces": [{"workspaceId": "space/1"}],
+ "nextToken": "space-next",
+ },
+ )
+ self.assertDictEqual(nodes, {"nodes": [{"nodeId": "doc/1"}]})
+ self.assertDictEqual(node, {"nodeId": "doc/1"})
+ self.assertListEqual(
+ blocks,
+ [
+ {
+ "blockType": "paragraph",
+ "paragraph": {"text": "hello"},
+ "index": 0,
+ },
+ ],
+ )
+ # One profile lookup for four calls: the unionId is cached.
+ self.assertEqual(len(http.posts), 2)
+ headers = {
+ "x-acs-dingtalk-access-token": "token",
+ "Content-Type": "application/json",
+ }
+ self.assertListEqual(
+ http.gets,
+ [
+ (
+ "https://api.dingtalk.com/v2.0/wiki/workspaces",
+ {
+ "headers": headers,
+ "params": {
+ "operatorId": "union-1",
+ "maxResults": 20,
+ "withPermissionRole": True,
+ },
+ },
+ ),
+ (
+ "https://api.dingtalk.com/v2.0/wiki/nodes",
+ {
+ "headers": headers,
+ "params": {
+ "operatorId": "union-1",
+ "parentNodeId": "root-1",
+ "maxResults": 50,
+ "nextToken": "node-next",
+ "withPermissionRole": True,
+ },
+ },
+ ),
+ (
+ "https://api.dingtalk.com/v2.0/wiki/nodes/doc%2F1",
+ {
+ "headers": headers,
+ "params": {
+ "operatorId": "union-1",
+ "withPermissionRole": True,
+ "withStatisticalInfo": True,
+ },
+ },
+ ),
+ (
+ "https://api.dingtalk.com/v1.0/doc/suites/documents/"
+ "doc%2F1/blocks",
+ {
+ "headers": headers,
+ "params": {
+ "operatorId": "union-1",
+ "startIndex": 0,
+ "endIndex": 49,
+ },
+ },
+ ),
+ ],
+ )
+
+ async def test_wiki_get_surfaces_a_permission_error(self) -> None:
+ api, _ = _openapi(
+ {
+ "errcode": 0,
+ "result": {"userid": "staff-1", "unionid": "union-1"},
+ },
+ {
+ "code": "Forbidden.AccessDenied",
+ "message": "missing Wiki permission",
+ },
+ )
+
+ with self.assertRaisesRegex(RuntimeError, "missing Wiki permission"):
+ await api.list_wiki_workspaces("staff-1", 20)
+
+ async def test_an_unresolvable_sender_is_reported(self) -> None:
+ api, _ = _openapi({"errcode": 0, "result": {"userid": "staff-1"}})
+
+ with self.assertRaisesRegex(RuntimeError, "contact permission"):
+ await api.list_wiki_workspaces("staff-1", 20)
+
async def test_create_deliver_and_update_group_approval_card(self) -> None:
api, http = _openapi({}, {}, {}, {})
diff --git a/tests/channel_gateway_test.py b/tests/channel_gateway_test.py
index 2dc6b620a..fbb446c44 100644
--- a/tests/channel_gateway_test.py
+++ b/tests/channel_gateway_test.py
@@ -320,6 +320,18 @@ class _RecordingStorage:
self.upserts.append(kwargs)
+class _InboundStorage(_RecordingStorage):
+ """Storage stub for one normal inbound channel message."""
+
+ def __init__(self, record: ChannelRecord) -> None:
+ super().__init__()
+ self.record = record
+
+ async def get_channel(self, channel_id: str) -> ChannelRecord | None:
+ """Return the configured channel by id."""
+ return self.record if channel_id == self.record.id else None
+
+
def _channel_record(user_id: str) -> ChannelRecord:
return ChannelRecord(
id="chan-1",
@@ -379,6 +391,43 @@ class WorkspaceIsolationTest(IsolatedAsyncioTestCase):
)
+class TrustedChannelIdentityTest(IsolatedAsyncioTestCase):
+ """The gateway records the trusted sender on the session's origin."""
+
+ async def test_session_origin_carries_the_trusted_sender(self) -> None:
+ record = _channel_record("owner-1")
+ storage = _InboundStorage(record)
+ bus = InMemoryMessageBus()
+ gateway = ChannelGateway(
+ storage=storage,
+ message_bus=bus,
+ workspace_manager=_WM(isolation=IsolationPolicy.PER_AGENT),
+ )
+
+ await gateway.process(
+ ChannelEvent(
+ channel_id=record.id,
+ channel_user_id="staff-1",
+ chat_id="group:cid-1",
+ chat_name="Product",
+ content=[TextBlock(text="hello")],
+ ),
+ )
+
+ self.assertEqual(
+ storage.upserts[0]["origin"],
+ ChannelOrigin(
+ channel_id=record.id,
+ chat_id="group:cid-1",
+ chat_name="Product",
+ channel_user_id="staff-1",
+ ),
+ )
+ queued = await bus.queue_drain(MessageBusKeys.wakeup_queue())
+ self.assertEqual(len(queued), 1)
+ self.assertNotIn("channel_user_id", queued[0][1])
+
+
class FeishuPostParseTest(IsolatedAsyncioTestCase):
"""Feishu rich-text ``post`` flattens to ordered text + data blocks."""
@@ -522,6 +571,7 @@ class ChatNameRecordingTest(IsolatedAsyncioTestCase):
channel_id="chan-1",
chat_id="group:cid-1",
chat_name="产品群",
+ channel_user_id="u",
),
)
@@ -535,6 +585,7 @@ class ChatNameRecordingTest(IsolatedAsyncioTestCase):
channel_id="chan-1",
chat_id="group:cid-1",
chat_name=None,
+ channel_user_id="u",
),
)
diff --git a/tests/service_chat_channel_delivery_test.py b/tests/service_chat_channel_delivery_test.py
index 3f8137c70..835501ea7 100644
--- a/tests/service_chat_channel_delivery_test.py
+++ b/tests/service_chat_channel_delivery_test.py
@@ -24,6 +24,7 @@ from agentscope.app.channel import (
ChannelEvent,
ChannelStatus,
ChannelTypeRegistry,
+ ChatKind,
)
from agentscope.app.message_bus import InMemoryMessageBus
from agentscope.event import ReplyEndEvent, ReplyStartEvent
@@ -52,6 +53,7 @@ class _RecordingChannel(ChannelBase):
display_name = "Fake"
platform_bot_id_field = "bot_id"
instances: list["_RecordingChannel"] = []
+ tool_user_ids: list[str | None] = []
class Credentials(BaseModel):
"""Credentials for the fake platform."""
@@ -98,6 +100,24 @@ class _RecordingChannel(ChannelBase):
self.seen.append(evt.get("type", ""))
self.done.set()
+ async def list_tools(
+ self,
+ workspace: object,
+ channel_user_id: str | None = None,
+ ) -> list:
+ """Record the trusted user the service equips tools with."""
+ del workspace
+ self.tool_user_ids.append(channel_user_id)
+ return []
+
+ async def chat_kind(self, chat_id: str) -> ChatKind | None:
+ """Classify a chat by an id prefix the tests control."""
+ if chat_id.startswith("private:"):
+ return ChatKind.PRIVATE
+ if chat_id.startswith("group:"):
+ return ChatKind.GROUP
+ return None
+
class _Storage:
"""Serve one channel-bound session, its agent, and its channel."""
@@ -145,6 +165,7 @@ class ChannelDeliveryFromTheRunTest(IsolatedAsyncioTestCase):
def setUp(self) -> None:
"""Isolate the instances each test observes."""
_RecordingChannel.instances.clear()
+ _RecordingChannel.tool_user_ids.clear()
def _fixture(self, source: SessionOrigin) -> tuple:
"""Build a session of ``source`` plus its agent and channel."""
@@ -299,3 +320,45 @@ class ChannelDeliveryFromTheRunTest(IsolatedAsyncioTestCase):
self.assertListEqual(_RecordingChannel.instances, [])
finally:
await clients.__aexit__(None, None, None)
+
+ async def test_a_private_chat_equips_tools_with_its_user(self) -> None:
+ """A 1:1 session has one sender, so tools may act as them."""
+ clients = await self._run(
+ ChannelOrigin(
+ channel_id="chan-1",
+ chat_id="private:chat-1",
+ channel_user_id="staff-1",
+ ),
+ )
+ try:
+ self.assertListEqual(_RecordingChannel.tool_user_ids, ["staff-1"])
+ finally:
+ await clients.__aexit__(None, None, None)
+
+ async def test_a_group_chat_equips_tools_with_no_user(self) -> None:
+ """A shared session must not let tools act as one member."""
+ clients = await self._run(
+ ChannelOrigin(
+ channel_id="chan-1",
+ chat_id="group:chat-1",
+ channel_user_id="staff-1",
+ ),
+ )
+ try:
+ self.assertListEqual(_RecordingChannel.tool_user_ids, [None])
+ finally:
+ await clients.__aexit__(None, None, None)
+
+ async def test_an_unclassifiable_chat_equips_no_user(self) -> None:
+ """An audience the platform cannot classify is treated as shared."""
+ clients = await self._run(
+ ChannelOrigin(
+ channel_id="chan-1",
+ chat_id="chat-1",
+ channel_user_id="staff-1",
+ ),
+ )
+ try:
+ self.assertListEqual(_RecordingChannel.tool_user_ids, [None])
+ finally:
+ await clients.__aexit__(None, None, None)