Skip to content

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

feat(channel): implement channel (#1997)

qbcefba74eda38b
diff --git a/.gitignore b/.gitignore
index 730e6c8f8..df5029fbb 100644
--- a/.gitignore
+++ b/.gitignore
@@ -163,4 +163,6 @@ npm-debug.log*
pnpm-debug.log*
yarn-debug.log*
yarn-error.log*
-lerna-debug.log*
\ No newline at end of file
+lerna-debug.log*
+
+**/workspaces/
\ No newline at end of file
diff --git a/README.md b/README.md
index f152653b3..4ac319cba 100644
--- a/README.md
+++ b/README.md
@@ -73,6 +73,8 @@ rather than constraining them with strict prompts and opinionated orchestrations
## News
<!-- BEGIN NEWS -->
+- **[2026-08] `INTE`:** Feishu (Lark) and Discord channels supported. [Feishu](https://docs.agentscope.io/latest/en/deploy/channel/feishu) | [Discord](https://docs.agentscope.io/latest/en/deploy/channel/discord)
+- **[2026-08] `FEAT`:** Channels supported — connect agents to IM platforms in agent service. [Example](https://github.com/agentscope-ai/agentscope/tree/main/examples/agent_service) | [Docs](https://docs.agentscope.io/latest/en/deploy/channel/overview)
- **[2026-08] `INTE`:** GitHub MCP Registry and ClawHub supported as built-in hubs. [Example](https://github.com/agentscope-ai/agentscope/tree/main/examples/agent_service) | [Docs](https://docs.agentscope.io/latest/en/deploy/hub)
- **[2026-08] `FEAT`:** MCP & Skill Hub supported — browse a hub, install into your library, add to a workspace. [Example](https://github.com/agentscope-ai/agentscope/tree/main/examples/agent_service) | [Docs](https://docs.agentscope.io/latest/en/deploy/hub)
- **[2026-07] `INTE`:** Daytona-based workspace/sandbox supported. [Docs](https://docs.agentscope.io/latest/en/building-blocks/workspace)
@@ -81,8 +83,6 @@ rather than constraining them with strict prompts and opinionated orchestrations
- **[2026-06] `FEAT`:** Agentic Memory supported. [Example](https://github.com/agentscope-ai/agentscope/tree/main/examples/long_term_memory/agentic_memory) | [Docs](https://docs.agentscope.io/latest/en/building-blocks/long-term-memory)
- **[2026-06] `FEAT`:** Distributed & Multi-Tenancy & Multi-Session RAG service supported. [Docs](https://docs.agentscope.io/latest/en/deploy/agent-team)
- **[2026-06] `FEAT`:** RAG supported. [Example](https://github.com/agentscope-ai/agentscope/tree/main/examples/rag) | [Docs](https://docs.agentscope.io/latest/en/building-blocks/rag)
-- **[2026-06] `INTE`:** Mem0 supported. [Example](https://github.com/agentscope-ai/agentscope/tree/main/examples/long_term_memory) | [Docs](https://docs.agentscope.io/latest/en)
-- **[2026-06] `FEAT`:** Agent Team supported. [Example](https://github.com/agentscope-ai/agentscope/tree/main/examples/agent_service) | [Docs](https://docs.agentscope.io/latest/en/deploy/agent-team)
<!-- END NEWS -->
[More news →](./docs/NEWS.md)
diff --git a/README_zh.md b/README_zh.md
index 9e7e25f67..aefe3efe6 100644
--- a/README_zh.md
+++ b/README_zh.md
@@ -73,6 +73,8 @@ AgentScope 2.0 是一款面向生产、易于使用的智能体框架,提供
## 新闻
<!-- BEGIN NEWS -->
+- **[2026-08] `集成`:** 支持飞书(Lark)与 Discord 频道。[飞书](https://docs.agentscope.io/latest/zh/deploy/channel/feishu) | [Discord](https://docs.agentscope.io/latest/zh/deploy/channel/discord)
+- **[2026-08] `功能`:** 支持消息频道 —— 将智能体接入即时通讯平台。[样例](https://github.com/agentscope-ai/agentscope/tree/main/examples/agent_service) | [文档](https://docs.agentscope.io/latest/zh/deploy/channel/overview)
- **[2026-08] `集成`:** 内置集成 GitHub MCP Registry 与 ClawHub。[样例](https://github.com/agentscope-ai/agentscope/tree/main/examples/agent_service) | [文档](https://docs.agentscope.io/latest/zh/deploy/hub)
- **[2026-08] `功能`:** 支持 MCP & Skill Hub —— 浏览 hub、安装到个人库、再添加到工作区。[样例](https://github.com/agentscope-ai/agentscope/tree/main/examples/agent_service) | [文档](https://docs.agentscope.io/latest/zh/deploy/hub)
- **[2026-07] `集成`:** 集成 Daytona 工作区/沙箱实现。 [文档](https://docs.agentscope.io/latest/en/building-blocks/workspace)
@@ -81,8 +83,6 @@ AgentScope 2.0 是一款面向生产、易于使用的智能体框架,提供
- **[2026-06] `功能`:** 支持 Agentic Memory。 [样例](https://github.com/agentscope-ai/agentscope/tree/main/examples/long_term_memory/agentic_memory) | [文档](https://docs.agentscope.io/latest/zh/building-blocks/long-term-memory)
- **[2026-06] `功能`:** 支持分布式 & 多租户 & 多会话 RAG 服务。 [文档](https://docs.agentscope.io/latest/en/deploy/agent-team)
- **[2026-06] `功能`:** 支持多模态 RAG。 [样例](https://github.com/agentscope-ai/agentscope/tree/main/examples/rag) | [文档](https://docs.agentscope.io/latest/en/building-blocks/rag)
-- **[2026-06] `集成`:** 集成 Mem0 长期记忆。 [Example](https://github.com/agentscope-ai/agentscope/tree/main/examples/long_term_memory) | [Docs](https://docs.agentscope.io/latest/zh)
-- **[2026-06] `功能`:** 支持 Agent Team。[样例](https://github.com/agentscope-ai/agentscope/tree/main/examples/agent_service) | [文档](https://docs.agentscope.io/latest/zh/deploy/agent-team)
<!-- END NEWS -->
[更多新闻 →](./docs/NEWS_zh.md)
diff --git a/docs/NEWS.md b/docs/NEWS.md
index a6475fb3a..765456fbd 100644
--- a/docs/NEWS.md
+++ b/docs/NEWS.md
@@ -2,6 +2,8 @@
<!-- The first 10 items are automatically synced to README.md and README_zh.md via GitHub Actions. -->
<!-- To update news in READMEs, modify this file and push to trigger the workflow. -->
+- **[2026-08] `INTE`:** Feishu (Lark) and Discord channels supported. [Feishu](https://docs.agentscope.io/latest/en/deploy/channel/feishu) | [Discord](https://docs.agentscope.io/latest/en/deploy/channel/discord)
+- **[2026-08] `FEAT`:** Channels supported — connect agents to IM platforms in agent service. [Example](https://github.com/agentscope-ai/agentscope/tree/main/examples/agent_service) | [Docs](https://docs.agentscope.io/latest/en/deploy/channel/overview)
- **[2026-08] `INTE`:** GitHub MCP Registry and ClawHub supported as built-in hubs. [Example](https://github.com/agentscope-ai/agentscope/tree/main/examples/agent_service) | [Docs](https://docs.agentscope.io/latest/en/deploy/hub)
- **[2026-08] `FEAT`:** MCP & Skill Hub supported — browse a hub, install into your library, add to a workspace. [Example](https://github.com/agentscope-ai/agentscope/tree/main/examples/agent_service) | [Docs](https://docs.agentscope.io/latest/en/deploy/hub)
- **[2026-07] `INTE`:** Daytona-based workspace/sandbox supported. [Docs](https://docs.agentscope.io/latest/en/building-blocks/workspace)
diff --git a/docs/NEWS_zh.md b/docs/NEWS_zh.md
index 80f420330..b654872a3 100644
--- a/docs/NEWS_zh.md
+++ b/docs/NEWS_zh.md
@@ -2,6 +2,8 @@
<!-- The first 10 items are automatically synced to README.md and README_zh.md via GitHub Actions. -->
<!-- To update news in READMEs, modify this file and push to trigger the workflow. -->
+- **[2026-08] `集成`:** 支持飞书(Lark)与 Discord 频道。[飞书](https://docs.agentscope.io/latest/zh/deploy/channel/feishu) | [Discord](https://docs.agentscope.io/latest/zh/deploy/channel/discord)
+- **[2026-08] `功能`:** 支持消息频道 —— 将智能体接入即时通讯平台。[样例](https://github.com/agentscope-ai/agentscope/tree/main/examples/agent_service) | [文档](https://docs.agentscope.io/latest/zh/deploy/channel/overview)
- **[2026-08] `集成`:** 内置集成 GitHub MCP Registry 与 ClawHub。[样例](https://github.com/agentscope-ai/agentscope/tree/main/examples/agent_service) | [文档](https://docs.agentscope.io/latest/zh/deploy/hub)
- **[2026-08] `功能`:** 支持 MCP & Skill Hub —— 浏览 hub、安装到个人库、再添加到工作区。[样例](https://github.com/agentscope-ai/agentscope/tree/main/examples/agent_service) | [文档](https://docs.agentscope.io/latest/zh/deploy/hub)
- **[2026-07] `集成`:** 集成 Daytona 工作区/沙箱实现。 [文档](https://docs.agentscope.io/latest/en/building-blocks/workspace)
diff --git a/examples/agent_service/main.py b/examples/agent_service/main.py
index 9e83b9ab7..84f8122d6 100644
--- a/examples/agent_service/main.py
+++ b/examples/agent_service/main.py
@@ -7,6 +7,7 @@ from fastapi.middleware import Middleware
from fastapi.middleware.cors import CORSMiddleware
from agentscope.app import create_app, SubAgentTemplate
+from agentscope.app.channel import DiscordChannel, FeishuChannel
from agentscope.app.hub import ClawSkillHub, GitHubMCPHub
from agentscope.app.message_bus import InMemoryMessageBus
from agentscope.app.rag.knowledge_base_manager import CollectionPerKbManager
@@ -125,6 +126,10 @@ so anything you want them to see MUST be sent through `TeamSay`.""",
allow_headers=["*"],
),
],
+ channels=[
+ DiscordChannel,
+ FeishuChannel,
+ ],
)
diff --git a/examples/web_ui/frontend/src/App.tsx b/examples/web_ui/frontend/src/App.tsx
index b7d583d4d..497bc4db4 100644
--- a/examples/web_ui/frontend/src/App.tsx
+++ b/examples/web_ui/frontend/src/App.tsx
@@ -11,6 +11,7 @@ import { buildChatTour } from '@/components/tour/chatTourSteps';
import { TourCard } from '@/components/tour/TourCard';
import { UploadProvider } from '@/context/UploadContext';
import { useTranslation } from '@/i18n/useI18n';
+import { ChannelPage } from '@/pages/channel';
import { ChatPage } from '@/pages/chat';
import { CredentialPage } from '@/pages/credential';
import { KnowledgePage } from '@/pages/knowledge';
@@ -47,6 +48,7 @@ const router = createBrowserRouter([
element: <ChatPage />,
},
{ path: '/schedule', element: <SchedulePage /> },
+ { path: '/channel', element: <ChannelPage /> },
{ path: '/credential', element: <CredentialPage /> },
{ path: '/mcp', element: <MCPHubPage /> },
{ path: '/mcp/:hubId', element: <MCPHubPage /> },
diff --git a/examples/web_ui/frontend/src/api/channel.ts b/examples/web_ui/frontend/src/api/channel.ts
new file mode 100644
index 000000000..cd5859bef
--- /dev/null
+++ b/examples/web_ui/frontend/src/api/channel.ts
@@ -0,0 +1,38 @@
+import { client } from './client';
+import type {
+ ChannelChatIdsResponse,
+ ChannelRecord,
+ ChannelSessionsResponse,
+ ChannelStatus,
+ ChannelTypeSchema,
+ CreateChannelRequest,
+ UpdateChannelRequest,
+} from './types';
+
+export const channelApi = {
+ listTypes: () => client.get<ChannelTypeSchema[]>('/channels/types'),
+
+ list: () => client.get<ChannelRecord[]>('/channels/'),
+
+ get: (channelId: string) => client.get<ChannelRecord>(`/channels/${channelId}`),
+
+ create: (body: CreateChannelRequest) => client.post<ChannelRecord>('/channels/', body),
+
+ update: (channelId: string, body: UpdateChannelRequest) =>
+ client.patch<ChannelRecord>(`/channels/${channelId}`, body),
+
+ delete: (channelId: string) => client.delete(`/channels/${channelId}`),
+
+ enable: (channelId: string) => client.post<{ status: string }>(`/channels/${channelId}/enable`),
+
+ disable: (channelId: string) =>
+ client.post<{ status: string }>(`/channels/${channelId}/disable`),
+
+ status: (channelId: string) => client.get<ChannelStatus>(`/channels/${channelId}/status`),
+
+ listSessions: (channelId: string) =>
+ client.get<ChannelSessionsResponse>(`/channels/${channelId}/sessions`),
+
+ listChatIds: (channelId: string) =>
+ client.get<ChannelChatIdsResponse>(`/channels/${channelId}/chat_ids`),
+};
diff --git a/examples/web_ui/frontend/src/api/index.ts b/examples/web_ui/frontend/src/api/index.ts
index 5f1c5afec..0dca2e988 100644
--- a/examples/web_ui/frontend/src/api/index.ts
+++ b/examples/web_ui/frontend/src/api/index.ts
@@ -10,4 +10,5 @@ export { skillApi } from './skill';
export { scheduleApi } from './schedule';
export { embeddingModelApi, modelApi, ttsModelApi } from './model';
export { knowledgeBaseApi } from './knowledgeBase';
+export { channelApi } from './channel';
export { healthApi } from './health';
diff --git a/examples/web_ui/frontend/src/api/types.ts b/examples/web_ui/frontend/src/api/types.ts
index 46cb458d6..76ac5c874 100644
--- a/examples/web_ui/frontend/src/api/types.ts
+++ b/examples/web_ui/frontend/src/api/types.ts
@@ -111,7 +111,7 @@ export interface AgentSchemaV2Response {
// ─── Session ──────────────────────────────────────────────────────────────────
-export type SessionSource = 'user' | 'schedule';
+export type SessionSource = 'user' | 'schedule' | 'channel';
export interface SessionConfig {
name: string;
@@ -133,6 +133,7 @@ export interface SessionRecord extends RecordBase {
agent_id: string;
source: SessionSource;
source_schedule_id: string | null;
+ source_channel_id: string | null;
/**
* The team this session participates in, if any. Set when the
* session is the leader of a team (the session that called
@@ -931,6 +932,89 @@ export interface ListSupportedContentTypesResponse {
extensions: string[];
}
+// ─── Channel ──────────────────────────────────────────────────────────────────
+
+// How inbound messages are grouped into agent sessions.
+export type SessionScope = 'per_chat' | 'per_chat_user';
+
+// One routing rule: match an inbound event, then pick the agent and how
+// its session is grouped. Rules are ordered; the first match wins and the
+// last must be a catch-all (match_value === '*').
+export interface ChannelBinding {
+ match_key: string;
+ match_value: string;
+ agent_id: string;
+ session_scope: SessionScope;
+}
+
+export interface RoutingConfig {
+ bindings: ChannelBinding[];
+}
+
+export interface SessionSettings {
+ chat_model_config: ChatModelConfig;
+ fallback_chat_model_config?: ChatModelConfig | null;
+ permission_mode: PermissionMode;
+}
+
+export interface ChannelRecord {
+ id: string;
+ channel_type: string;
+ name: string | null;
+ user_id: string;
+ platform_bot_id: string;
+ enabled: boolean;
+ platform_config: Record<string, unknown>;
+ routing: RoutingConfig;
+ session: SessionSettings;
+ created_at: string;
+ updated_at: string;
+}
+
+export interface CreateChannelRequest {
+ channel_type: string;
+ name?: string | null;
+ credentials: Record<string, unknown>;
+ platform_config?: Record<string, unknown>;
+ routing: RoutingConfig;
+ session: SessionSettings;
+ enabled?: boolean;
+}
+
+export interface UpdateChannelRequest {
+ name?: string | null;
+ platform_config?: Record<string, unknown>;
+ routing?: RoutingConfig;
+ session?: SessionSettings;
+ enabled?: boolean;
+}
+
+export interface ChannelTypeSchema {
+ channel_type: string;
+ display_name: string;
+ description?: string;
+ icon_url?: string;
+ credentials_schema: Record<string, unknown>;
+ config_schema: Record<string, unknown>;
+ platform_bot_id_field?: string;
+}
+
+export type ChannelState = 'stopped' | 'connecting' | 'retrying' | 'connected' | 'failed';
+
+export interface ChannelStatus {
+ state: ChannelState;
+ last_error: string;
+}
+
+export interface ChannelSessionsResponse {
+ sessions: SessionRecord[];
+ total: number;
+}
+
+export interface ChannelChatIdsResponse {
+ chats: { chat_id: string; name: string; source: string }[];
+}
+
// ─── TTS ──────────────────────────────────────────────────────────────────────
export interface TTSModelCard {
diff --git a/examples/web_ui/frontend/src/components/layout/AppSidebar.tsx b/examples/web_ui/frontend/src/components/layout/AppSidebar.tsx
index 464d404b7..820307593 100644
--- a/examples/web_ui/frontend/src/components/layout/AppSidebar.tsx
+++ b/examples/web_ui/frontend/src/components/layout/AppSidebar.tsx
@@ -1,6 +1,7 @@
import {
BookText,
BotMessageSquare,
+ Cable,
Calendars,
Compass,
KeyRound,
@@ -9,10 +10,8 @@ import {
UserRound,
} from 'lucide-react';
import { useOnborda } from 'onborda';
-import { useState } from 'react';
import { useNavigate, useLocation } from 'react-router-dom';
-import { getUserId } from '@/api/client';
import AgentScope from '@/assets/images/agentscope_white.svg?react';
import MCPSvg from '@/assets/images/mcp.svg?react';
import { CHAT_TOUR_NAME } from '@/components/tour/chatTourSteps';
@@ -35,8 +34,6 @@ export function AppSidebar() {
const location = useLocation();
const { t } = useTranslation();
const { startOnborda } = useOnborda();
- // Read once: the username only changes via /setup, which remounts this.
- const [initial] = useState(() => getUserId().trim().slice(0, 1).toUpperCase());
const handleStartTour = () => {
if (!location.pathname.startsWith('/chat')) {
@@ -91,6 +88,16 @@ export function AppSidebar() {
<Calendars />
</SidebarMenuButton>
</SidebarMenuItem>
+ <SidebarMenuItem>
+ <SidebarMenuButton
+ tooltip={{ children: t('common.channel'), hidden: false }}
+ isActive={location.pathname === '/channel'}
+ onClick={() => navigate('/channel')}
+ className="px-2"
+ >
+ <Cable />
+ </SidebarMenuButton>
+ </SidebarMenuItem>
</SidebarMenu>
</SidebarGroupContent>
</SidebarGroup>
@@ -174,7 +181,7 @@ export function AppSidebar() {
onClick={() => navigate('/setup')}
className="justify-center"
>
- {initial || <UserRound />}
+ <UserRound />
</SidebarMenuButton>
</SidebarMenuItem>
</SidebarMenu>
diff --git a/examples/web_ui/frontend/src/components/popover/ModelParametersPopover.tsx b/examples/web_ui/frontend/src/components/popover/ModelParametersPopover.tsx
index 847317f58..19065da2a 100644
--- a/examples/web_ui/frontend/src/components/popover/ModelParametersPopover.tsx
+++ b/examples/web_ui/frontend/src/components/popover/ModelParametersPopover.tsx
@@ -202,14 +202,14 @@ interface Props {
modelCard: ModelCard | null;
/** Called when the user edits the primary model's parameters. */
onChange: (parameters: Record<string, unknown>) => void;
- /** Currently selected fallback model. `null` means no fallback configured. */
- selectedFallbackModel: ChatModelConfig | null;
+ /** Currently selected fallback model. `null` means no fallback configured. `undefined` hides the section. */
+ selectedFallbackModel?: ChatModelConfig | null;
/** Called when the user picks a fallback model or clears the selection. */
- onFallbackChange: (config: ChatModelConfig | null) => void;
- /** Currently selected TTS model. `null` means TTS is disabled. */
- selectedTTSModel: TTSModelConfig | null;
+ onFallbackChange?: (config: ChatModelConfig | null) => void;
+ /** Currently selected TTS model. `null` means TTS is disabled. `undefined` hides the TTS section entirely. */
+ selectedTTSModel?: TTSModelConfig | null;
/** Called when the user picks a TTS model+voice or disables TTS. */
- onTTSChange: (config: TTSModelConfig | null) => void;
+ onTTSChange?: (config: TTSModelConfig | null) => void;
}
/**
@@ -257,7 +257,7 @@ export function ModelParametersPopover({
);
const handleSelectFallback = (type: string, credentialId: string, model: string) => {
- onFallbackChange({
+ onFallbackChange?.({
type,
credential_id: credentialId,
model,
@@ -277,69 +277,71 @@ export function ModelParametersPopover({
</DropdownMenuTrigger>
<DropdownMenuContent align="start" className="min-w-40">
{/* ----- Fallback model selection ----- */}
- <DropdownMenuSub>
- <DropdownMenuSubTrigger>
- <span className="truncate">
- {selectedFallbackModel
- ? t('model-parameters.fallbackLabelWithModel', {
- model: selectedFallbackModel.model,
- })
- : t('model-parameters.fallbackLabel')}
- </span>
- </DropdownMenuSubTrigger>
- <DropdownMenuSubContent className="max-h-72 overflow-y-auto">
- {!hasFallbackOptions ? (
- <div className="px-2 py-3 text-center text-sm text-muted-foreground">
- <p>{t('llm-select.empty.title')}</p>
- </div>
- ) : (
- Object.entries(groups).map(([type, items], idx) => (
- <div key={type}>
- {idx > 0 && <DropdownMenuSeparator />}
- <DropdownMenuLabel>
- {type.replace(/_credential$/, '')}
- </DropdownMenuLabel>
- {items.flatMap(({ credential, models }) =>
- models.map((m) => {
- const isSelected =
- selectedFallbackModel?.credential_id ===
- credential.id &&
- selectedFallbackModel?.model === m.name;
- return (
- <DropdownMenuCheckboxItem
- key={`${credential.id}-${m.name}`}
- checked={isSelected}
- onCheckedChange={(checked) => {
- if (checked) {
- handleSelectFallback(
- type,
- credential.id,
- m.name,
- );
- } else {
- onFallbackChange(null);
- }
- }}
- >
- {m.label}
- </DropdownMenuCheckboxItem>
- );
- }),
- )}
+ {onFallbackChange !== undefined && (
+ <DropdownMenuSub>
+ <DropdownMenuSubTrigger>
+ <span className="truncate">
+ {selectedFallbackModel
+ ? t('model-parameters.fallbackLabelWithModel', {
+ model: selectedFallbackModel.model,
+ })
+ : t('model-parameters.fallbackLabel')}
+ </span>
+ </DropdownMenuSubTrigger>
+ <DropdownMenuSubContent className="max-h-72 overflow-y-auto">
+ {!hasFallbackOptions ? (
+ <div className="px-2 py-3 text-center text-sm text-muted-foreground">
+ <p>{t('llm-select.empty.title')}</p>
</div>
- ))
- )}
- <DropdownMenuSeparator />
- <DropdownMenuCheckboxItem
- checked={!selectedFallbackModel}
- onCheckedChange={(checked) => {
- if (checked) onFallbackChange(null);
- }}
- >
- {t('llm-select.noFallback')}
- </DropdownMenuCheckboxItem>
- </DropdownMenuSubContent>
- </DropdownMenuSub>
+ ) : (
+ Object.entries(groups).map(([type, items], idx) => (
+ <div key={type}>
+ {idx > 0 && <DropdownMenuSeparator />}
+ <DropdownMenuLabel>
+ {type.replace(/_credential$/, '')}
+ </DropdownMenuLabel>
+ {items.flatMap(({ credential, models }) =>
+ models.map((m) => {
+ const isSelected =
+ selectedFallbackModel?.credential_id ===
+ credential.id &&
+ selectedFallbackModel?.model === m.name;
+ return (
+ <DropdownMenuCheckboxItem
+ key={`${credential.id}-${m.name}`}
+ checked={isSelected}
+ onCheckedChange={(checked) => {
+ if (checked) {
+ handleSelectFallback(
+ type,
+ credential.id,
+ m.name,
+ );
+ } else {
+ onFallbackChange(null);
+ }
+ }}
+ >
+ {m.label}
+ </DropdownMenuCheckboxItem>
+ );
+ }),
+ )}
+ </div>
+ ))
+ )}
+ <DropdownMenuSeparator />
+ <DropdownMenuCheckboxItem
+ checked={!selectedFallbackModel}
+ onCheckedChange={(checked) => {
+ if (checked) onFallbackChange(null);
+ }}
+ >
+ {t('llm-select.noFallback')}
+ </DropdownMenuCheckboxItem>
+ </DropdownMenuSubContent>
+ </DropdownMenuSub>
+ )}
{/* ----- Primary model parameters ----- */}
<DropdownMenuSub>
@@ -411,205 +413,222 @@ export function ModelParametersPopover({
</DropdownMenuSub>
{/* ----- TTS ----- */}
- <DropdownMenuSub>
- <DropdownMenuSubTrigger>
- <span className="truncate">{t('model-parameters.ttsLabel')}</span>
- </DropdownMenuSubTrigger>
- <DropdownMenuSubContent className="max-h-96 overflow-y-auto">
- {Object.keys(ttsGroups).length === 0 ? (
- <div className="px-2 py-3 text-center text-sm text-muted-foreground">
- <p>{t('model-parameters.ttsEmpty')}</p>
- </div>
- ) : (
- Object.entries(ttsGroups).map(([type, items], idx) => (
- <div key={type}>
- {idx > 0 && <DropdownMenuSeparator />}
- <DropdownMenuLabel>
- {type.replace(/_credential$/, '')}
- </DropdownMenuLabel>
- {items.flatMap(({ credential, models }) =>
- models.map((m) => {
- const isSelected =
- selectedTTSModel?.credential_id === credential.id &&
- selectedTTSModel?.model === m.name;
- return (
- <DropdownMenuCheckboxItem
- key={`${credential.id}-${m.name}`}
- checked={isSelected}
- onSelect={(e) => e.preventDefault()}
- onCheckedChange={(checked) => {
- if (!checked) return;
- const schema = m.parameter_schema as
- | ParameterSchema
- | undefined;
- const defaults: Record<string, unknown> =
- {};
- if (schema?.properties) {
- for (const [k, p] of Object.entries(
- schema.properties,
- )) {
- if (p.default !== undefined) {
- defaults[k] = p.default;
+ {onTTSChange !== undefined && (
+ <DropdownMenuSub>
+ <DropdownMenuSubTrigger>
+ <span className="truncate">{t('model-parameters.ttsLabel')}</span>
+ </DropdownMenuSubTrigger>
+ <DropdownMenuSubContent className="max-h-96 overflow-y-auto">
+ {Object.keys(ttsGroups).length === 0 ? (
+ <div className="px-2 py-3 text-center text-sm text-muted-foreground">
+ <p>{t('model-parameters.ttsEmpty')}</p>
+ </div>
+ ) : (
+ Object.entries(ttsGroups).map(([type, items], idx) => (
+ <div key={type}>
+ {idx > 0 && <DropdownMenuSeparator />}
+ <DropdownMenuLabel>
+ {type.replace(/_credential$/, '')}
+ </DropdownMenuLabel>
+ {items.flatMap(({ credential, models }) =>
+ models.map((m) => {
+ const isSelected =
+ selectedTTSModel?.credential_id ===
+ credential.id &&
+ selectedTTSModel?.model === m.name;
+ return (
+ <DropdownMenuCheckboxItem
+ key={`${credential.id}-${m.name}`}
+ checked={isSelected}
+ onSelect={(e) => e.preventDefault()}
+ onCheckedChange={(checked) => {
+ if (!checked) return;
+ const schema = m.parameter_schema as
+ | ParameterSchema
+ | undefined;
+ const defaults: Record<
+ string,
+ unknown
+ > = {};
+ if (schema?.properties) {
+ for (const [k, p] of Object.entries(
+ schema.properties,
+ )) {
+ if (p.default !== undefined) {
+ defaults[k] = p.default;
+ }
}
}
- }
- onTTSChange({
- type,
- credential_id: credential.id,
- model: m.name,
- parameters: defaults,
- });
- }}
- >
- {m.label}
- {m.realtime && (
- <Badge
- variant="outline"
- className="ml-1.5 text-[10px] px-1 py-0"
- >
- Realtime
- </Badge>
- )}
- </DropdownMenuCheckboxItem>
- );
- }),
- )}
- </div>
- ))
- )}
-
- {/* TTS parameters sub-panel (hover to expand right) */}
- {selectedTTSModel && (
- <>
- <DropdownMenuSeparator />
- <DropdownMenuSub>
- <DropdownMenuSubTrigger>
- {t('model-parameters.ttsParameters')}
- </DropdownMenuSubTrigger>
- <DropdownMenuSubContent className="w-72 max-h-96 overflow-y-auto p-3">
- <div className="mb-3">
- <p className="text-sm font-medium">
- {t('model-parameters.title')}
- </p>
- <p className="text-muted-foreground text-xs">
- {t('model-parameters.ttsParametersDescription')}
- </p>
- </div>
- {(() => {
- if (!selectedTTSModel) return null;
- const selType = selectedTTSModel.type;
- const selItems = ttsGroups[selType];
- if (!selItems) return null;
- let selModel: TTSModelCard | undefined;
- for (const { credential, models } of selItems) {
- if (
- credential.id !== selectedTTSModel.credential_id
- )
- continue;
- selModel = models.find(
- (m) => m.name === selectedTTSModel.model,
+ onTTSChange({
+ type,
+ credential_id: credential.id,
+ model: m.name,
+ parameters: defaults,
+ });
+ }}
+ >
+ {m.label}
+ {m.realtime && (
+ <Badge
+ variant="outline"
+ className="ml-1.5 text-[10px] px-1 py-0"
+ >
+ Realtime
+ </Badge>
+ )}
+ </DropdownMenuCheckboxItem>
);
- if (selModel) break;
- }
- if (!selModel) return null;
- const mSchema = selModel.parameter_schema as
- | ParameterSchema
- | undefined;
- const mProps = mSchema?.properties ?? {};
- const mRequired = mSchema?.required ?? [];
- const mEntries = Object.entries(mProps);
- if (mEntries.length === 0) {
+ }),
+ )}
+ </div>
+ ))
+ )}
+
+ {/* TTS parameters sub-panel (hover to expand right) */}
+ {selectedTTSModel && (
+ <>
+ <DropdownMenuSeparator />
+ <DropdownMenuSub>
+ <DropdownMenuSubTrigger>
+ {t('model-parameters.ttsParameters')}
+ </DropdownMenuSubTrigger>
+ <DropdownMenuSubContent className="w-72 max-h-96 overflow-y-auto p-3">
+ <div className="mb-3">
+ <p className="text-sm font-medium">
+ {t('model-parameters.title')}
+ </p>
+ <p className="text-muted-foreground text-xs">
+ {t('model-parameters.ttsParametersDescription')}
+ </p>
+ </div>
+ {(() => {
+ if (!selectedTTSModel) return null;
+ const selType = selectedTTSModel.type;
+ const selItems = ttsGroups[selType];
+ if (!selItems) return null;
+ let selModel: TTSModelCard | undefined;
+ for (const { credential, models } of selItems) {
+ if (
+ credential.id !==
+ selectedTTSModel.credential_id
+ )
+ continue;
+ selModel = models.find(
+ (m) => m.name === selectedTTSModel.model,
+ );
+ if (selModel) break;
+ }
+ if (!selModel) return null;
+ const mSchema = selModel.parameter_schema as
+ | ParameterSchema
+ | undefined;
+ const mProps = mSchema?.properties ?? {};
+ const mRequired = mSchema?.required ?? [];
+ const mEntries = Object.entries(mProps);
+ if (mEntries.length === 0) {
+ return (
+ <p className="text-muted-foreground text-xs">
+ {t('model-parameters.empty')}
+ </p>
+ );
+ }
+ const curParams = selectedTTSModel.parameters ?? {};
+
return (
- <p className="text-muted-foreground text-xs">
- {t('model-parameters.empty')}
- </p>
- );
- }
- const curParams = selectedTTSModel.parameters ?? {};
+ <div
+ className="grid grid-cols-[auto_1fr] items-center gap-x-3 gap-y-3"
+ onPointerDown={(e) => e.stopPropagation()}
+ onKeyDown={(e) => e.stopPropagation()}
+ >
+ {mEntries.map(([key, prop]) => {
+ const {
+ type: effectiveType,
+ enumValues,
+ } = resolveType(prop);
+ const label = prop.title ?? key;
+ const isReq = mRequired.includes(key);
+ const fieldProps: FieldProps = {
+ id: `tts-${selModel!.name}-${key}`,
+ label,
+ required: isReq,
+ prop,
+ value: curParams[key],
+ onChange: (v) => {
+ const next = {
+ ...curParams,
+ [key]: v,
+ };
+ if (
+ v === '' ||
+ v === undefined
+ ) {
+ delete next[key];
+ }
+ onTTSChange({
+ ...selectedTTSModel,
+ parameters: next,
+ });
+ },
+ };
- return (
- <div
- className="grid grid-cols-[auto_1fr] items-center gap-x-3 gap-y-3"
- onPointerDown={(e) => e.stopPropagation()}
- onKeyDown={(e) => e.stopPropagation()}
- >
- {mEntries.map(([key, prop]) => {
- const { type: effectiveType, enumValues } =
- resolveType(prop);
- const label = prop.title ?? key;
- const isReq = mRequired.includes(key);
- const fieldProps: FieldProps = {
- id: `tts-${selModel!.name}-${key}`,
- label,
- required: isReq,
- prop,
- value: curParams[key],
- onChange: (v) => {
- const next = {
- ...curParams,
- [key]: v,
- };
- if (v === '' || v === undefined) {
- delete next[key];
- }
- onTTSChange({
- ...selectedTTSModel,
- parameters: next,
- });
- },
- };
+ let field: React.ReactNode;
+ if (effectiveType === 'boolean') {
+ field = (
+ <BooleanField {...fieldProps} />
+ );
+ } else if (enumValues) {
+ field = (
+ <EnumField {...fieldProps} />
+ );
+ } else if (
+ effectiveType === 'number' ||
+ effectiveType === 'integer'
+ ) {
+ field = (
+ <NumberField {...fieldProps} />
+ );
+ } else {
+ field = (
+ <StringField {...fieldProps} />
+ );
+ }
- let field: React.ReactNode;
- if (effectiveType === 'boolean') {
- field = (
- <BooleanField {...fieldProps} />
+ return (
+ <Tooltip key={key}>
+ <TooltipTrigger asChild>
+ <div className="col-span-2 grid grid-cols-subgrid items-center">
+ {field}
+ </div>
+ </TooltipTrigger>
+ {prop.description && (
+ <TooltipContent side="left">
+ {prop.description}
+ </TooltipContent>
+ )}
+ </Tooltip>
);
- } else if (enumValues) {
- field = <EnumField {...fieldProps} />;
- } else if (
- effectiveType === 'number' ||
- effectiveType === 'integer'
- ) {
- field = <NumberField {...fieldProps} />;
- } else {
- field = <StringField {...fieldProps} />;
- }
-
- return (
- <Tooltip key={key}>
- <TooltipTrigger asChild>
- <div className="col-span-2 grid grid-cols-subgrid items-center">
- {field}
- </div>
- </TooltipTrigger>
- {prop.description && (
- <TooltipContent side="left">
- {prop.description}
- </TooltipContent>
- )}
- </Tooltip>
- );
- })}
- </div>
- );
- })()}
- </DropdownMenuSubContent>
- </DropdownMenuSub>
- </>
- )}
+ })}
+ </div>
+ );
+ })()}
+ </DropdownMenuSubContent>
+ </DropdownMenuSub>
+ </>
+ )}
- <DropdownMenuSeparator />
- <DropdownMenuCheckboxItem
- checked={!selectedTTSModel}
- onSelect={(e) => e.preventDefault()}
- onCheckedChange={(checked) => {
- if (checked) onTTSChange(null);
- }}
- >
- {t('model-parameters.noTts')}
- </DropdownMenuCheckboxItem>
- </DropdownMenuSubContent>
- </DropdownMenuSub>
+ <DropdownMenuSeparator />
+ <DropdownMenuCheckboxItem
+ checked={!selectedTTSModel}
+ onSelect={(e) => e.preventDefault()}
+ onCheckedChange={(checked) => {
+ if (checked) onTTSChange(null);
+ }}
+ >
+ {t('model-parameters.noTts')}
+ </DropdownMenuCheckboxItem>
+ </DropdownMenuSubContent>
+ </DropdownMenuSub>
+ )}
</DropdownMenuContent>
</DropdownMenu>
);
diff --git a/examples/web_ui/frontend/src/hooks/useChannels.ts b/examples/web_ui/frontend/src/hooks/useChannels.ts
new file mode 100644
index 000000000..9a84ca505
--- /dev/null
+++ b/examples/web_ui/frontend/src/hooks/useChannels.ts
@@ -0,0 +1,71 @@
+import { useState, useEffect, useCallback } from 'react';
+
+import { channelApi } from '../api';
+import type { ChannelRecord, CreateChannelRequest, UpdateChannelRequest } from '../api';
+
+export function useChannels() {
+ const [channels, setChannels] = useState<ChannelRecord[]>([]);
+ const [loading, setLoading] = useState(false);
+ const [error, setError] = useState<Error | null>(null);
+
+ const refetch = useCallback(async () => {
+ setLoading(true);
+ setError(null);
+ try {
+ const res = await channelApi.list();
+ setChannels(res);
+ } catch (e) {
+ setError(e as Error);
+ } finally {
+ setLoading(false);
+ }
+ }, []);
+
+ useEffect(() => {
+ refetch();
+ }, [refetch]);
+
+ const create = useCallback(
+ async (body: CreateChannelRequest) => {
+ const res = await channelApi.create(body);
+ await refetch();
+ return res;
+ },
+ [refetch],
+ );
+
+ const update = useCallback(
+ async (channelId: string, body: UpdateChannelRequest) => {
+ const res = await channelApi.update(channelId, body);
+ await refetch();
+ return res;
+ },
+ [refetch],
+ );
+
+ const remove = useCallback(
+ async (channelId: string) => {
+ await channelApi.delete(channelId);
+ await refetch();
+ },
+ [refetch],
+ );
+
+ const enable = useCallback(
+ async (channelId: string) => {
+ await channelApi.enable(channelId);
+ await refetch();
+ },
+ [refetch],
+ );
+
+ const disable = useCallback(
+ async (channelId: string) => {
+ await channelApi.disable(channelId);
+ await refetch();
+ },
+ [refetch],
+ );
+
+ return { channels, loading, error, refetch, create, update, remove, enable, disable };
+}
diff --git a/examples/web_ui/frontend/src/i18n/locales/en.json b/examples/web_ui/frontend/src/i18n/locales/en.json
index a1b9b65ee..b92be8623 100644
--- a/examples/web_ui/frontend/src/i18n/locales/en.json
+++ b/examples/web_ui/frontend/src/i18n/locales/en.json
@@ -3,6 +3,7 @@
"add": "Add",
"agent": "Agent",
"cancel": "Cancel",
+ "channel": "Channels",
"chat": "Chat",
"close": "Close",
"confirm": "Confirm",
@@ -117,7 +118,8 @@
"team": "Team",
"team_message": "Team",
"schedule": "Schedule",
- "system": "System"
+ "system": "System",
+ "channel": "Channel"
},
"error": {
"title": "Reply failed",
@@ -421,6 +423,7 @@
"skillDescription": "Are you sure you want to remove this skill from the workspace?"
},
"schedule": {
+ "subtitle": "Schedule recurring or one-off tasks for your agents",
"calendar": "Calendar",
"createSchedule": {
"description": "Set up a recurring or one-time scheduled task for an agent.",
@@ -596,7 +599,88 @@
},
"team-sidebar": {
"membersHeading": "Members",
- "noMembers": "No members yet — ask the leader to spawn one with AgentCreate."
+ "noMembers": "No members yet — ask the leader to spawn one with AgentCreate.",
+ "running": "Running",
+ "idle": "Idle",
+ "missingSession": "(no session)"
+ },
+ "channel": {
+ "title": "Channels",
+ "subtitle": "Connect external platforms like Feishu and Discord so agents work in group chats",
+ "status": "Status",
+ "connected": "Connected",
+ "enable": "Enable",
+ "disable": "Disable",
+ "deleteEntity": "channel",
+ "routing": "Routing",
+ "routingDesc": "Match inbound messages to an agent and a session scope. The last rule matches everything else.",
+ "sectionActive": "Connected",
+ "sectionAdd": "Add Channel",
+ "rules": "{{count}} rules",
+ "empty": {
+ "title": "No channels",
+ "description": "Create a channel to connect your agent to external platforms like Feishu, DingTalk, etc."
+ },
+ "create": {
+ "title": "Create Channel",
+ "titleFor": "Connect {{name}}",
+ "description": "Connect an agent to an external messaging platform.",
+ "channelType": "Platform",
+ "nameLabel": "Name",
+ "namePlaceholder": "e.g. Support desk",
+ "nameDesc": "Tells apart channels on the same platform",
+ "modelDesc": "Initial model for a new session",
+ "permissionMode": "Permission Mode",
+ "permissionModeDesc": "Initial permission mode for a new session",
+ "showToolMessages": "Show Tool Messages",
+ "showToolMessagesDesc": "Display tool call/result messages in the channel.",
+ "showThinking": "Show Thinking",
+ "showThinkingDesc": "Display model reasoning process in the channel."
+ },
+ "edit": {
+ "title": "Edit Channel",
+ "description": "Update routing, model, and reply settings. Platform and credentials are immutable."
+ },
+ "sessionScope": {
+ "per_chat": "Per Chat",
+ "per_chat_user": "Per Chat User"
+ },
+ "sessions": {
+ "title": "Sessions",
+ "empty": "No sessions yet",
+ "openInChat": "Open in chat"
+ },
+ "detail": {
+ "config": "Configuration",
+ "configDesc": "Initial configuration applied to new sessions",
+ "configItem": "Item",
+ "configValue": "Value",
+ "condition": "Condition",
+ "created": "Created",
+ "deleteChannel": "Delete channel",
+ "routingDesc": "How inbound messages map to an agent and session scope",
+ "sessionsDesc": "Sessions this channel has spawned",
+ "selectHint": "Select a channel to see details"
+ },
+ "state": {
+ "stopped": "Stopped",
+ "connecting": "Connecting",
+ "retrying": "Reconnecting",
+ "connected": "Connected",
+ "failed": "Failed"
+ },
+ "binding": {
+ "rule": "Match Rule",
+ "matchKey": "Match field",
+ "matchValue": "Match value",
+ "matchValuePlaceholder": "e.g. a chat_id",
+ "routeTo": "Route to",
+ "scope": "Session scope",
+ "fallback": "Fallback Rule",
+ "fallbackDesc": "Messages not matched by any rule above are routed here",
+ "catchAll": "All other messages",
+ "addRule": "Add rule"
+ }
},
"mcp": {
"subtitle": "Browse and install MCP servers",
diff --git a/examples/web_ui/frontend/src/i18n/locales/zh.json b/examples/web_ui/frontend/src/i18n/locales/zh.json
index 0c7c14886..f6a0a9125 100644
--- a/examples/web_ui/frontend/src/i18n/locales/zh.json
+++ b/examples/web_ui/frontend/src/i18n/locales/zh.json
@@ -1,8 +1,9 @@
{
"common": {
"add": "添加",
- "agent": "Agent",
+ "agent": "智能体",
"cancel": "取消",
+ "channel": "频道",
"chat": "聊天",
"close": "关闭",
"confirm": "确认",
@@ -117,7 +118,8 @@
"team": "团队",
"team_message": "团队消息",
"schedule": "定时任务",
- "system": "系统消息"
+ "system": "系统消息",
+ "channel": "频道"
},
"error": {
"title": "回复失败",
@@ -128,7 +130,7 @@
"upstream": "上游模型服务返回了错误。",
"connection": "无法连接模型服务 —— 网络错误或超时。",
"internal": "发生了未预期的内部错误。",
- "setup": "会话准备失败 —— 请检查该 agent 的模型、工具和知识库配置。",
+ "setup": "会话准备失败 —— 请检查该智能体的模型、工具和知识库配置。",
"unknown": "回复因未知错误失败。"
}
},
@@ -139,32 +141,32 @@
"newSession": "新会话",
"greeting": "我们从哪儿开始?",
"agent": {
- "selectPlaceholder": "选择 Agent",
- "emptyTitle": "暂无 Agent",
- "emptyDescription": "创建一个 Agent 开始使用。",
+ "selectPlaceholder": "选择智能体",
+ "emptyTitle": "暂无智能体",
+ "emptyDescription": "创建一个智能体开始使用。",
"groupYours": "我的",
"groupShared": "共享给我"
},
"session": {
"label": "会话",
"emptyTitle": "暂无会话",
- "emptyNoAgent": "请先选择一个 Agent。",
+ "emptyNoAgent": "请先选择一个智能体。",
"emptyHasAgent": "创建会话开始对话。",
"today": "今天",
"earlier": "更早"
}
},
"dialog-agent-create": {
- "title": "创建 Agent",
- "description": "定义新 Agent 的身份与行为。"
+ "title": "创建智能体",
+ "description": "定义新智能体的身份与行为。"
},
"agent-form": {
"identity": {
- "legend": "Agent 身份",
- "description": "定义此 Agent 行为的名称和指令。",
+ "legend": "智能体身份",
+ "description": "定义此智能体行为的名称和指令。",
"name": {
"label": "名称",
- "placeholder": "我的 Agent"
+ "placeholder": "我的智能体"
},
"system-prompt": {
"label": "系统提示词"
@@ -201,22 +203,22 @@
},
"invite-config": {
"legend": "邀请配置",
- "description": "控制此 Agent 是否可被其他 Agent 通过 AgentInvite 邀请。",
+ "description": "控制此智能体是否可被其他智能体通过 AgentInvite 邀请。",
"invitable": {
"label": "允许被邀请"
},
"invite-description": {
"label": "邀请说明",
- "placeholder": "简要描述此 Agent 的专长;允许被邀请时必填。"
+ "placeholder": "简要描述此智能体的专长;允许被邀请时必填。"
}
}
},
"dialog-agent-edit": {
- "title": "编辑 Agent",
- "description": "更新此 Agent 的配置。"
+ "title": "编辑智能体",
+ "description": "更新此智能体的配置。"
},
"dialog-agent-delete": {
- "entity": "Agent",
+ "entity": "智能体",
"confirm": "删除"
},
"dialog-session-delete": {
@@ -319,7 +321,7 @@
}
},
"knowledge": {
- "subtitle": "管理 Agent 使用的知识库",
+ "subtitle": "管理智能体使用的知识库",
"selectHint": "未选择知识库",
"selectHintDescription": "从左侧选择一个知识库以查看详情。",
"list": {
@@ -421,9 +423,10 @@
"skillDescription": "确定要将该技能从工作区中移除吗?"
},
"schedule": {
+ "subtitle": "为智能体设置定时或一次性的计划任务",
"calendar": "日历",
"createSchedule": {
- "description": "为 Agent 设置定时或一次性的计划任务。",
+ "description": "为智能体设置定时或一次性的计划任务。",
"descriptionLabel": "描述",
"descriptionPlaceholder": "描述这个计划任务的用途...",
"namePlaceholder": "例如:每日报告",
@@ -447,7 +450,7 @@
"nextMonth": "下个月",
"nextYear": "下一年",
"noSchedules": "暂无日程",
- "noSchedulesDescription": "创建日程以自动化 Agent 任务。",
+ "noSchedulesDescription": "创建日程以自动化智能体任务。",
"pickDate": "选择日期",
"permissionMode": "权限模式",
"timezone": "时区",
@@ -502,8 +505,8 @@
"skip": "跳过",
"step": "第 {{current}} / {{total}} 步",
"createAgent": {
- "title": "创建 Agent",
- "content": "先创建一个 Agent —— 与你对话的智能体。"
+ "title": "创建智能体",
+ "content": "先创建一个智能体 —— 与你对话的智能体。"
},
"createSession": {
"title": "创建会话",
@@ -596,7 +599,88 @@
},
"team-sidebar": {
"membersHeading": "成员",
- "noMembers": "还没有成员——让队长用 AgentCreate 添加一个。"
+ "noMembers": "还没有成员——让队长用 AgentCreate 添加一个。",
+ "running": "运行中",
+ "idle": "空闲",
+ "missingSession": "(无会话)"
+ },
+ "channel": {
+ "title": "频道",
+ "subtitle": "接入飞书、Discord 等外部平台,让智能体在群聊里工作",
+ "status": "状态",
+ "connected": "已连接",
+ "enable": "启用",
+ "disable": "停用",
+ "deleteEntity": "频道",
+ "routing": "路由",
+ "routingDesc": "将入站消息匹配到某个智能体和会话粒度。最后一条规则匹配其余所有消息。",
+ "sectionActive": "已接入",
+ "sectionAdd": "添加频道",
+ "rules": "{{count}} 条规则",
+ "empty": {
+ "title": "暂无频道",
+ "description": "创建一个频道,将智能体连接到飞书、钉钉等外部平台。"
+ },
+ "create": {
+ "title": "创建频道",
+ "titleFor": "接入 {{name}}",
+ "description": "将智能体连接到外部消息平台。",
+ "channelType": "平台",
+ "nameLabel": "名称",
+ "namePlaceholder": "如:客服值班",
+ "nameDesc": "便于区分同平台的多个频道",
+ "modelDesc": "新会话创建时的初始模型",
+ "permissionMode": "权限模式",
+ "permissionModeDesc": "新会话创建时的初始权限模式",
+ "showToolMessages": "显示工具消息",
+ "showToolMessagesDesc": "在频道中展示工具调用和返回消息。",
+ "showThinking": "显示思维过程",
+ "showThinkingDesc": "在频道中展示模型推理过程。"
+ },
+ "edit": {
+ "title": "编辑频道",
+ "description": "修改路由、模型与回复设置。平台与凭据不可修改。"
+ },
+ "sessionScope": {
+ "per_chat": "按聊天",
+ "per_chat_user": "按聊天+用户"
+ },
+ "sessions": {
+ "title": "派生会话",
+ "empty": "还没有会话",
+ "openInChat": "在对话中打开"
+ },
+ "detail": {
+ "config": "配置",
+ "configDesc": "新会话创建时应用的初始配置",
+ "configItem": "配置项",
+ "configValue": "值",
+ "condition": "条件",
+ "created": "创建时间",
+ "deleteChannel": "删除频道",
+ "routingDesc": "入站消息如何匹配到智能体与会话粒度",
+ "sessionsDesc": "该频道派生出的会话",
+ "selectHint": "选择一个频道查看详情"
+ },
+ "state": {
+ "stopped": "已停止",
+ "connecting": "连接中",
+ "retrying": "重连中",
+ "connected": "已连接",
+ "failed": "连接失败"
+ },
+ "binding": {
+ "rule": "匹配规则",
+ "matchKey": "匹配字段",
+ "matchValue": "匹配值",
+ "matchValuePlaceholder": "如某个 chat_id",
+ "routeTo": "路由到",
+ "scope": "会话粒度",
+ "fallback": "兜底规则",
+ "fallbackDesc": "未命中上面任何规则的消息,都路由到这里",
+ "catchAll": "其余所有消息",
+ "addRule": "添加规则"
+ }
},
"mcp": {
"subtitle": "浏览并安装 MCP 服务",
@@ -654,6 +738,6 @@
},
"agent-menu": {
"settings": "设置",
- "delete": "删除 Agent"
+ "delete": "删除智能体"
}
}
diff --git a/examples/web_ui/frontend/src/pages/channel/bindings-editor.tsx b/examples/web_ui/frontend/src/pages/channel/bindings-editor.tsx
new file mode 100644
index 000000000..44427f990
--- /dev/null
+++ b/examples/web_ui/frontend/src/pages/channel/bindings-editor.tsx
@@ -0,0 +1,183 @@
+import { Check, ChevronDown, Plus, Trash2 } from 'lucide-react';
+
+import type { AgentView, ChannelBinding, SessionScope } from '@/api';
+import { AgentSelect } from '@/components/select/AgentSelect';
+import { Button } from '@/components/ui/button';
+import {
+ DropdownMenu,
+ DropdownMenuContent,
+ DropdownMenuItem,
+ DropdownMenuTrigger,
+} from '@/components/ui/dropdown-menu';
+import { Input } from '@/components/ui/input';
+import { useTranslation } from '@/i18n/useI18n';
+
+const SESSION_SCOPES: SessionScope[] = ['per_chat', 'per_chat_user'];
+
+/** Session-scope picker on the shadcn dropdown-menu, matching AgentSelect. */
+function ScopeSelect({
+ value,
+ onChange,
+}: {
+ value: SessionScope;
+ onChange: (scope: SessionScope) => void;
+}) {
+ const { t } = useTranslation();
+ return (
+ <DropdownMenu>
+ <DropdownMenuTrigger asChild>
+ <Button
+ variant="outline"
+ size="default"
+ className="w-full justify-between gap-1 font-normal"
+ >
+ <span className="truncate">{t(`channel.sessionScope.${value}`)}</span>
+ <ChevronDown className="size-3.5 text-muted-foreground" />
+ </Button>
+ </DropdownMenuTrigger>
+ <DropdownMenuContent align="start" className="min-w-40">
+ {SESSION_SCOPES.map((s) => (
+ <DropdownMenuItem key={s} onSelect={() => onChange(s)}>
+ <Check
+ className={`size-3.5 shrink-0 ${s === value ? 'opacity-100' : 'opacity-0'}`}
+ />
+ <span className="flex-1">{t(`channel.sessionScope.${s}`)}</span>
+ </DropdownMenuItem>
+ ))}
+ </DropdownMenuContent>
+ </DropdownMenu>
+ );
+}
+
+interface Props {
+ value: ChannelBinding[];
+ onChange: (bindings: ChannelBinding[]) => void;
+ agents: AgentView[];
+}
+
+/**
+ * Editor for a channel's routing rules. The last row is always the
+ * catch-all (match_value === '*'); extra rules are matched, in order,
+ * before it. First match wins.
+ */
+export function BindingsEditor({ value, onChange, agents }: Props) {
+ const { t } = useTranslation();
+
+ const update = (i: number, patch: Partial<ChannelBinding>) => {
+ onChange(value.map((b, idx) => (idx === i ? { ...b, ...patch } : b)));
+ };
+
+ const removeRule = (i: number) => {
+ onChange(value.filter((_, idx) => idx !== i));
+ };
+
+ const addRule = () => {
+ const catchAll = value[value.length - 1];
+ const rule: ChannelBinding = {
+ match_key: 'chat_id',
+ match_value: '',
+ agent_id: catchAll?.agent_id ?? agents[0]?.id ?? '',
+ session_scope: 'per_chat',
+ };
+ // Insert before the catch-all so it stays last.
+ onChange([...value.slice(0, -1), rule, ...value.slice(-1)]);
+ };
+
+ // Agent + session-scope selects, shared by every rule and the fallback.
+ const targets = (binding: ChannelBinding, i: number) => (
+ <div className="grid grid-cols-2 gap-2.5">
+ <div className="flex flex-col gap-1">
+ <span className="text-xs text-muted-foreground">
+ {t('channel.binding.routeTo')}
+ </span>
+ <AgentSelect
+ size="default"
+ className="w-full"
+ agents={agents}
+ value={binding.agent_id || null}
+ onChange={(id) => update(i, { agent_id: id })}
+ />
+ </div>
+ <div className="flex flex-col gap-1">
+ <span className="text-xs text-muted-foreground">{t('channel.binding.scope')}</span>
+ <ScopeSelect
+ value={binding.session_scope}
+ onChange={(s) => update(i, { session_scope: s })}
+ />
+ </div>
+ </div>
+ );
+
+ return (
+ <div className="flex flex-col gap-2.5">
+ {value.map((binding, i) => {
+ const isCatchAll = i === value.length - 1;
+ if (isCatchAll) {
+ return (
+ <div
+ key={i}
+ className="flex flex-col gap-2.5 rounded-lg border border-dashed bg-muted/30 p-3"
+ >
+ <div>
+ <span className="text-xs font-medium">
+ {t('channel.binding.fallback')}
+ </span>
+ <p className="mt-0.5 text-xs text-muted-foreground">
+ {t('channel.binding.fallbackDesc')}
+ </p>
+ </div>
+ {targets(binding, i)}
+ </div>
+ );
+ }
+ return (
+ <div key={i} className="flex flex-col gap-2.5 rounded-lg border p-3">
+ <div className="flex items-center justify-between">
+ <span className="text-xs font-medium text-muted-foreground">
+ {t('channel.binding.rule')} {i + 1}
+ </span>
+ <Button
+ size="icon-sm"
+ variant="ghost"
+ className="-mr-1 size-6 text-destructive"
+ onClick={() => removeRule(i)}
+ >
+ <Trash2 className="size-3.5" />
+ </Button>
+ </div>
+ <div className="grid grid-cols-2 gap-2.5">
+ <div className="flex flex-col gap-1">
+ <span className="text-xs text-muted-foreground">
+ {t('channel.binding.matchKey')}
+ </span>
+ <Input
+ className="font-mono text-xs"
+ value={binding.match_key}
+ onChange={(e) => update(i, { match_key: e.target.value })}
+ placeholder="chat_id"
+ />
+ </div>
+ <div className="flex flex-col gap-1">
+ <span className="text-xs text-muted-foreground">
+ {t('channel.binding.matchValue')}
+ </span>
+ <Input
+ className="font-mono text-xs"
+ value={binding.match_value}
+ onChange={(e) => update(i, { match_value: e.target.value })}
+ placeholder={t('channel.binding.matchValuePlaceholder')}
+ />
+ </div>
+ </div>
+ {targets(binding, i)}
+ </div>
+ );
+ })}
+
+ <Button variant="ghost" size="sm" className="self-start" onClick={addRule}>
+ <Plus className="size-3.5" />
+ {t('channel.binding.addRule')}
+ </Button>
+ </div>
+ );
+}
diff --git a/examples/web_ui/frontend/src/pages/channel/channel-detail-panel.tsx b/examples/web_ui/frontend/src/pages/channel/channel-detail-panel.tsx
new file mode 100644
index 000000000..b510c6485
--- /dev/null
+++ b/examples/web_ui/frontend/src/pages/channel/channel-detail-panel.tsx
@@ -0,0 +1,289 @@
+import {
+ ArrowRight,
+ Check,
+ ChevronRight,
+ CircleAlert,
+ Minus,
+ Pencil,
+ Trash2,
+ X,
+} from 'lucide-react';
+import * as React from 'react';
+import { useNavigate } from 'react-router-dom';
+
+import type { ChannelRecord, ChannelStatus, ChannelTypeSchema, SessionRecord } from '@/api';
+import { channelApi } from '@/api';
+import { Alert, AlertDescription } from '@/components/ui/alert';
+import { Button } from '@/components/ui/button';
+import {
+ Table,
+ TableBody,
+ TableCell,
+ TableHead,
+ TableHeader,
+ TableRow,
+} from '@/components/ui/table';
+import { useTranslation } from '@/i18n/useI18n';
+import { ChannelStatusBadge } from '@/pages/channel/channel-status';
+import { TypeAvatar } from '@/pages/channel/type-avatar';
+
+/** Uppercase muted header cell, matching the credential-page tables. */
+function HeadCell({ children, className }: { children?: React.ReactNode; className?: string }) {
+ return (
+ <TableHead
+ className={`h-auto bg-muted px-3 py-2 font-mono text-[9.5px] font-normal uppercase tracking-widest text-text-tertiary ${className ?? ''}`}
+ >
+ {children}
+ </TableHead>
+ );
+}
+
+interface Props {
+ channel: ChannelRecord;
+ type?: ChannelTypeSchema;
+ status?: ChannelStatus | null;
+ agentName: (agentId: string) => string;
+ onEdit: () => void;
+ onDelete: () => void;
+ onClose: () => void;
+}
+
+/** Read-only detail view for a channel; edits happen via the dialog. */
+export function ChannelDetailPanel({
+ channel,
+ type,
+ status,
+ agentName,
+ onEdit,
+ onDelete,
+ onClose,
+}: Props) {
+ const { t } = useTranslation();
+ const navigate = useNavigate();
+ const [sessions, setSessions] = React.useState<SessionRecord[]>([]);
+
+ const typeName = type?.display_name ?? channel.channel_type;
+ const name = channel.name?.trim() || typeName;
+ const model = channel.session.chat_model_config?.model;
+
+ React.useEffect(() => {
+ setSessions([]);
+ channelApi
+ .listSessions(channel.id)
+ .then((r) => setSessions(r.sessions))
+ .catch(() => setSessions([]));
+ }, [channel.id]);
+
+ const bool = (v: boolean) =>
+ v ? (
+ <Check className="size-4 text-emerald-600" />
+ ) : (
+ <Minus className="size-4 text-muted-foreground/40" />
+ );
+ const text = (v: React.ReactNode) => <span className="font-mono">{v}</span>;
+
+ // Config rows: label + a value node, all one size.
+ const configRows: { label: string; value: React.ReactNode }[] = [
+ { label: t('channel.create.channelType'), value: text(typeName) },
+ ...(model ? [{ label: t('common.model'), value: text(model) }] : []),
+ { label: t('channel.create.permissionMode'), value: text(channel.session.permission_mode) },
+ ];
+ // Platform options (show tool/thinking, only_at_reply, …) from the schema.
+ const cfgProps =
+ (
+ type?.config_schema as
+ | { properties?: Record<string, Record<string, unknown>> }
+ | undefined
+ )?.properties ?? {};
+ for (const [key, def] of Object.entries(cfgProps)) {
+ const raw = channel.platform_config[key] ?? def.default;
+ configRows.push({
+ label: (def.title as string) || key,
+ value: typeof raw === 'boolean' ? bool(raw) : text(String(raw ?? '')),
+ });
+ }
+
+ return (
+ <div className="flex h-full flex-col overflow-hidden rounded-[22px] bg-card shadow-panel">
+ <div className="flex items-start justify-between gap-3 px-5 pt-5 pb-4">
+ <div className="flex min-w-0 items-center gap-3">
+ <TypeAvatar type={type} className="size-10 rounded-lg" />
+ <div className="min-w-0">
+ <div className="truncate text-base font-semibold">{name}</div>
+ <div className="mt-0.5 flex items-center gap-2">
+ <ChannelStatusBadge enabled={channel.enabled} status={status} />
+ <span className="font-mono text-[11px] text-muted-foreground">
+ {channel.id.slice(0, 8)}
+ </span>
+ </div>
+ </div>
+ </div>
+ <div className="flex items-center gap-1">
+ <Button
+ size="icon-sm"
+ variant="ghost"
+ onClick={onEdit}
+ tooltip={t('common.edit')}
+ >
+ <Pencil className="size-3.5" />
+ </Button>
+ <Button
+ size="icon-sm"
+ variant="ghost"
+ onClick={onClose}
+ tooltip={t('common.close')}
+ >
+ <X className="size-3.5" />
+ </Button>
+ </div>
+ </div>
+
+ <div className="flex flex-1 flex-col gap-6 overflow-y-auto px-5 pb-5">
+ {status?.last_error && (
+ <Alert variant="destructive">
+ <CircleAlert />
+ <AlertDescription>{status.last_error}</AlertDescription>
+ </Alert>
+ )}
+
+ <section>
+ <div className="text-xs font-semibold uppercase tracking-wide text-muted-foreground">
+ {t('channel.detail.config')}
+ </div>
+ <p className="mt-1 mb-3 text-[11px] text-muted-foreground">
+ {t('channel.detail.configDesc')}
+ </p>
+ <div className="overflow-hidden rounded-lg border">
+ <Table>
+ <TableHeader>
+ <TableRow>
+ <HeadCell>{t('channel.detail.configItem')}</HeadCell>
+ <HeadCell>{t('channel.detail.configValue')}</HeadCell>
+ </TableRow>
+ </TableHeader>
+ <TableBody>
+ {configRows.map((row, i) => (
+ <TableRow key={i}>
+ <TableCell className="px-3 py-2 text-xs">
+ {row.label}
+ </TableCell>
+ <TableCell className="px-3 py-2 text-xs">
+ {row.value}
+ </TableCell>
+ </TableRow>
+ ))}
+ </TableBody>
+ </Table>
+ </div>
+ </section>
+
+ <section>
+ <div className="flex items-center gap-2 text-xs font-semibold uppercase tracking-wide text-muted-foreground">
+ {t('channel.routing')}
+ <span className="rounded bg-muted px-2 py-0.5 font-mono text-[10px]">
+ {channel.routing.bindings.length}
+ </span>
+ </div>
+ <p className="mt-1 mb-3 text-[11px] text-muted-foreground">
+ {t('channel.detail.routingDesc')}
+ </p>
+ <div className="overflow-hidden rounded-lg border">
+ <Table>
+ <TableHeader>
+ <TableRow>
+ <HeadCell>{t('channel.detail.condition')}</HeadCell>
+ <HeadCell className="w-6" />
+ <HeadCell>{t('common.agent')}</HeadCell>
+ <HeadCell>{t('channel.binding.scope')}</HeadCell>
+ </TableRow>
+ </TableHeader>
+ <TableBody>
+ {channel.routing.bindings.map((b, i) => {
+ const isCatchAll = i === channel.routing.bindings.length - 1;
+ return (
+ <TableRow key={i}>
+ <TableCell className="px-3 py-2 font-mono text-xs">
+ {isCatchAll
+ ? t('channel.binding.fallback')
+ : `${b.match_key} = ${b.match_value}`}
+ </TableCell>
+ <TableCell className="w-6 px-0 text-center">
+ <ArrowRight className="inline size-3.5 text-muted-foreground" />
+ </TableCell>
+ <TableCell className="px-3 py-2 text-xs">
+ {agentName(b.agent_id)}
+ </TableCell>
+ <TableCell className="px-3 py-2 text-xs text-muted-foreground">
+ {t(`channel.sessionScope.${b.session_scope}`)}
+ </TableCell>
+ </TableRow>
+ );
+ })}
+ </TableBody>
+ </Table>
+ </div>
+ </section>
+
+ <section>
+ <div className="flex items-center gap-2 text-xs font-semibold uppercase tracking-wide text-muted-foreground">
+ {t('channel.sessions.title')}
+ <span className="rounded bg-muted px-2 py-0.5 font-mono text-[10px]">
+ {sessions.length}
+ </span>
+ </div>
+ <p className="mt-1 mb-3 text-[11px] text-muted-foreground">
+ {t('channel.detail.sessionsDesc')}
+ </p>
+ {sessions.length === 0 ? (
+ <p className="text-sm text-muted-foreground">
+ {t('channel.sessions.empty')}
+ </p>
+ ) : (
+ <div className="overflow-hidden rounded-lg border">
+ <Table>
+ <TableHeader>
+ <TableRow>
+ <HeadCell>{t('channel.sessions.title')}</HeadCell>
+ <HeadCell>{t('channel.detail.created')}</HeadCell>
+ <HeadCell className="w-6" />
+ </TableRow>
+ </TableHeader>
+ <TableBody>
+ {sessions.map((s) => (
+ <TableRow
+ key={s.id}
+ className="group cursor-pointer"
+ onClick={() => navigate(`/chat/${s.agent_id}/${s.id}`)}
+ title={t('channel.sessions.openInChat')}
+ >
+ <TableCell className="max-w-0 truncate px-3 py-2 text-xs">
+ {s.config.name || s.id}
+ </TableCell>
+ <TableCell className="px-3 py-2 font-mono text-[11px] text-muted-foreground">
+ {new Date(s.created_at).toLocaleDateString()}
+ </TableCell>
+ <TableCell className="w-6 px-0 text-center">
+ <ChevronRight className="inline size-3.5 text-muted-foreground opacity-0 transition group-hover:opacity-100" />
+ </TableCell>
+ </TableRow>
+ ))}
+ </TableBody>
+ </Table>
+ </div>
+ )}
+ </section>
+ </div>
+
+ <div className="px-5 pt-2 pb-5">
+ <Button
+ variant="ghost"
+ className="w-full text-destructive hover:bg-destructive/10 hover:text-destructive"
+ onClick={onDelete}
+ >
+ <Trash2 className="size-3.5" />
+ {t('channel.detail.deleteChannel')}
+ </Button>
+ </div>
+ </div>
+ );
+}
diff --git a/examples/web_ui/frontend/src/pages/channel/channel-form.tsx b/examples/web_ui/frontend/src/pages/channel/channel-form.tsx
new file mode 100644
index 000000000..ced4a6702
--- /dev/null
+++ b/examples/web_ui/frontend/src/pages/channel/channel-form.tsx
@@ -0,0 +1,325 @@
+import * as React from 'react';
+
+import type {
+ AgentView,
+ ChannelBinding,
+ ChannelRecord,
+ ChannelTypeSchema,
+ ChatModelConfig,
+ CreateChannelRequest,
+ PermissionMode,
+ UpdateChannelRequest,
+} from '@/api';
+import { ModelParametersPopover } from '@/components/popover/ModelParametersPopover';
+import { LlmSelect } from '@/components/select/LlmSelect';
+import { PermissionModeSelect } from '@/components/select/PermissionModeSelect';
+import {
+ Field,
+ FieldContent,
+ FieldDescription,
+ FieldGroup,
+ FieldLabel,
+} from '@/components/ui/field';
+import { Input } from '@/components/ui/input';
+import { Separator } from '@/components/ui/separator';
+import { Switch } from '@/components/ui/switch';
+import { useAvailableModels } from '@/hooks/useAvailableModels';
+import { useTranslation } from '@/i18n/useI18n';
+import { BindingsEditor } from '@/pages/channel/bindings-editor';
+
+export interface ChannelFormValue {
+ channelType: string;
+ name: string;
+ credentials: Record<string, string>;
+ platformConfig: Record<string, unknown>;
+ bindings: ChannelBinding[];
+ chatModelConfig: ChatModelConfig | null;
+ fallbackChatModelConfig: ChatModelConfig | null;
+ permissionMode: PermissionMode;
+}
+
+export function defaultChannelForm(agentId = ''): ChannelFormValue {
+ return {
+ channelType: 'feishu',
+ name: '',
+ credentials: {},
+ platformConfig: {},
+ bindings: [
+ {
+ match_key: 'chat_id',
+ match_value: '*',
+ agent_id: agentId,
+ session_scope: 'per_chat',
+ },
+ ],
+ chatModelConfig: null,
+ fallbackChatModelConfig: null,
+ permissionMode: 'default' as PermissionMode,
+ };
+}
+
+export function channelFormFromRecord(record: ChannelRecord): ChannelFormValue {
+ return {
+ channelType: record.channel_type,
+ name: record.name ?? '',
+ credentials: {},
+ platformConfig: record.platform_config ?? {},
+ bindings: record.routing.bindings,
+ chatModelConfig: record.session.chat_model_config,
+ fallbackChatModelConfig: record.session.fallback_chat_model_config ?? null,
+ permissionMode: record.session.permission_mode,
+ };
+}
+
+function sessionSettings(v: ChannelFormValue) {
+ return {
+ session: {
+ chat_model_config: v.chatModelConfig as ChatModelConfig,
+ fallback_chat_model_config: v.fallbackChatModelConfig,
+ permission_mode: v.permissionMode,
+ },
+ };
+}
+
+export function toCreateRequest(v: ChannelFormValue): CreateChannelRequest {
+ return {
+ channel_type: v.channelType,
+ name: v.name.trim() || null,
+ credentials: v.credentials,
+ platform_config: v.platformConfig,
+ routing: { bindings: v.bindings },
+ enabled: true,
+ ...sessionSettings(v),
+ };
+}
+
+export function toUpdateRequest(v: ChannelFormValue): UpdateChannelRequest {
+ return {
+ name: v.name.trim() || null,
+ platform_config: v.platformConfig,
+ routing: { bindings: v.bindings },
+ ...sessionSettings(v),
+ };
+}
+
+interface Props {
+ value: ChannelFormValue;
+ onChange: (value: ChannelFormValue) => void;
+ agents: AgentView[];
+ channelTypes: ChannelTypeSchema[];
+ /** Create mode exposes type + credential fields; edit mode locks them. */
+ mode: 'create' | 'edit';
+}
+
+export function ChannelForm({ value, onChange, agents, channelTypes, mode }: Props) {
+ const { t } = useTranslation();
+ const { groups } = useAvailableModels();
+
+ const set = <K extends keyof ChannelFormValue>(key: K, v: ChannelFormValue[K]) =>
+ onChange({ ...value, [key]: v });
+
+ const typeSchema = React.useMemo(
+ () => channelTypes.find((ct) => ct.channel_type === value.channelType),
+ [channelTypes, value.channelType],
+ );
+
+ const credentialFields = React.useMemo(() => {
+ const schema = typeSchema?.credentials_schema as
+ | { properties?: Record<string, Record<string, unknown>>; required?: string[] }
+ | undefined;
+ if (!schema?.properties) return [];
+ const required = schema.required ?? [];
+ return Object.entries(schema.properties).map(([key, def]) => ({
+ key,
+ title: (def.title as string) || key,
+ description: def.description as string | undefined,
+ format: def.format as string | undefined,
+ required: required.includes(key),
+ }));
+ }, [typeSchema]);
+
+ const configFields = React.useMemo(() => {
+ const schema = typeSchema?.config_schema as
+ | { properties?: Record<string, Record<string, unknown>> }
+ | undefined;
+ if (!schema?.properties) return [];
+ return Object.entries(schema.properties).map(([key, def]) => ({
+ key,
+ title: (def.title as string) || key,
+ description: def.description as string | undefined,
+ type: def.type as string | undefined,
+ default: def.default,
+ }));
+ }, [typeSchema]);
+
+ const selectedModelCard = React.useMemo(() => {
+ if (!value.chatModelConfig) return null;
+ const items = groups[value.chatModelConfig.type];
+ if (!items) return null;
+ for (const { models } of items) {
+ const card = models.find((m) => m.name === value.chatModelConfig!.model);
+ if (card) return card;
+ }
+ return null;
+ }, [groups, value.chatModelConfig?.type, value.chatModelConfig?.model]);
+
+ return (
+ <FieldGroup className="[&>[data-orientation=horizontal]>:last-child]:w-48">
+ {mode === 'edit' && (
+ <Field orientation="horizontal">
+ <FieldLabel>{t('channel.create.channelType')}</FieldLabel>
+ <span className="text-sm">{typeSchema?.display_name ?? value.channelType}</span>
+ </Field>
+ )}
+
+ <Field orientation="horizontal">
+ <FieldContent>
+ <FieldLabel>{t('channel.create.nameLabel')}</FieldLabel>
+ <FieldDescription className="text-xs">
+ {t('channel.create.nameDesc')}
+ </FieldDescription>
+ </FieldContent>
+ <Input
+ className="text-sm"
+ value={value.name}
+ onChange={(e) => set('name', e.target.value)}
+ placeholder={t('channel.create.namePlaceholder')}
+ />
+ </Field>
+
+ {mode === 'create' &&
+ credentialFields.map((field) => (
+ <Field key={field.key}>
+ <FieldLabel>
+ {field.title}
+ {field.required && ' *'}
+ </FieldLabel>
+ <Input
+ className="text-sm"
+ type={field.format === 'password' ? 'password' : 'text'}
+ value={value.credentials[field.key] || ''}
+ onChange={(e) =>
+ set('credentials', {
+ ...value.credentials,
+ [field.key]: e.target.value,
+ })
+ }
+ placeholder={field.description || field.title}
+ />
+ </Field>
+ ))}
+
+ <Separator />
+
+ <Field orientation="horizontal">
+ <FieldContent>
+ <FieldLabel>{t('common.model')}</FieldLabel>
+ <FieldDescription className="text-xs">
+ {t('channel.create.modelDesc')}
+ </FieldDescription>
+ </FieldContent>
+ <div className="flex w-full items-center gap-1">
+ <LlmSelect
+ size="default"
+ className="min-w-0 flex-1"
+ value={value.chatModelConfig}
+ onChange={(v) => set('chatModelConfig', v)}
+ />
+ <ModelParametersPopover
+ selectedModel={value.chatModelConfig}
+ modelCard={selectedModelCard}
+ onChange={(parameters) =>
+ value.chatModelConfig &&
+ set('chatModelConfig', { ...value.chatModelConfig, parameters })
+ }
+ selectedFallbackModel={value.fallbackChatModelConfig}
+ onFallbackChange={(cfg) => set('fallbackChatModelConfig', cfg)}
+ />
+ </div>
+ </Field>
+
+ <Field orientation="horizontal">
+ <FieldContent>
+ <FieldLabel>{t('channel.create.permissionMode')}</FieldLabel>
+ <FieldDescription className="text-xs">
+ {t('channel.create.permissionModeDesc')}
+ </FieldDescription>
+ </FieldContent>
+ <PermissionModeSelect
+ size="default"
+ className="w-full"
+ value={value.permissionMode}
+ onChange={(v) => set('permissionMode', v)}
+ />
+ </Field>
+
+ <Separator />
+
+ <Field>
+ <FieldLabel>{t('channel.routing')}</FieldLabel>
+ <span className="mb-1 text-xs text-muted-foreground">
+ {t('channel.routingDesc')}
+ </span>
+ <BindingsEditor
+ value={value.bindings}
+ onChange={(b) => set('bindings', b)}
+ agents={agents}
+ />
+ </Field>
+
+ <Separator />
+
+ {configFields.map((field) => (
+ <Field key={field.key}>
+ <div className="flex flex-row items-center justify-between gap-4">
+ <div className="flex flex-col gap-y-0.5">
+ <FieldLabel>{field.title}</FieldLabel>
+ {field.description && (
+ <span className="text-xs text-muted-foreground">
+ {field.description}
+ </span>
+ )}
+ </div>
+ {field.type === 'boolean' ? (
+ <Switch
+ checked={
+ (value.platformConfig[field.key] as boolean) ??
+ (field.default as boolean) ??
+ false
+ }
+ onCheckedChange={(v) =>
+ set('platformConfig', {
+ ...value.platformConfig,
+ [field.key]: v,
+ })
+ }
+ />
+ ) : (
+ <Input
+ className="h-8 w-48 text-sm"
+ value={String(
+ value.platformConfig[field.key] ?? field.default ?? '',
+ )}
+ onChange={(e) =>
+ set('platformConfig', {
+ ...value.platformConfig,
+ [field.key]: e.target.value,
+ })
+ }
+ />
+ )}
+ </div>
+ </Field>
+ ))}
+ </FieldGroup>
+ );
+}
+
+export function isChannelFormValid(v: ChannelFormValue, mode: 'create' | 'edit'): boolean {
+ if (!v.name.trim()) return false;
+ if (!v.chatModelConfig) return false;
+ if (v.bindings.length === 0) return false;
+ if (v.bindings.some((b) => !b.agent_id)) return false;
+ if (mode === 'create' && !v.channelType) return false;
+ return true;
+}
diff --git a/examples/web_ui/frontend/src/pages/channel/channel-status.tsx b/examples/web_ui/frontend/src/pages/channel/channel-status.tsx
new file mode 100644
index 000000000..0487ea020
--- /dev/null
+++ b/examples/web_ui/frontend/src/pages/channel/channel-status.tsx
@@ -0,0 +1,44 @@
+import type { ChannelStatus } from '@/api';
+import { useTranslation } from '@/i18n/useI18n';
+
+const TONE: Record<string, string> = {
+ disabled: 'text-muted-foreground',
+ stopped: 'text-muted-foreground',
+ connecting: 'text-amber-600',
+ retrying: 'text-amber-600',
+ connected: 'text-emerald-600',
+ failed: 'text-destructive',
+};
+const DOT: Record<string, string> = {
+ disabled: 'bg-muted-foreground/40',
+ stopped: 'bg-muted-foreground/40',
+ connecting: 'bg-amber-500',
+ retrying: 'bg-amber-500',
+ connected: 'bg-emerald-500',
+ failed: 'bg-destructive',
+};
+
+/**
+ * Connection state for a channel. One source: the enabled flag + the polled
+ * runtime status, so the card and the detail panel always agree. A disabled
+ * channel reads "disabled" regardless of any stale runtime status.
+ */
+export function ChannelStatusBadge({
+ enabled,
+ status,
+}: {
+ enabled: boolean;
+ status?: ChannelStatus | null;
+}) {
+ const { t } = useTranslation();
+ const state = !enabled ? 'disabled' : (status?.state ?? 'connecting');
+ const label = state === 'disabled' ? t('common.disabled') : t(`channel.state.${state}`);
+ return (
+ <span
+ className={`inline-flex items-center gap-1.5 text-xs font-medium ${TONE[state] ?? TONE.disabled}`}
+ >
+ <span className={`size-1.5 rounded-full ${DOT[state] ?? DOT.disabled}`} />
+ {label}
+ </span>
+ );
+}
diff --git a/examples/web_ui/frontend/src/pages/channel/create-channel-dialog.tsx b/examples/web_ui/frontend/src/pages/channel/create-channel-dialog.tsx
new file mode 100644
index 000000000..a8aebbcc9
--- /dev/null
+++ b/examples/web_ui/frontend/src/pages/channel/create-channel-dialog.tsx
@@ -0,0 +1,128 @@
+import { CircleAlert, Loader2, PlusCircle, X } from 'lucide-react';
+import * as React from 'react';
+
+import type { ChannelTypeSchema } from '@/api';
+import { channelApi } from '@/api';
+import { Alert, AlertDescription } from '@/components/ui/alert';
+import { Button } from '@/components/ui/button';
+import {
+ Dialog,
+ DialogContent,
+ DialogDescription,
+ DialogFooter,
+ DialogHeader,
+ DialogTitle,
+} from '@/components/ui/dialog';
+import { useAgents } from '@/hooks/useAgents';
+import { useTranslation } from '@/i18n/useI18n';
+import {
+ ChannelForm,
+ defaultChannelForm,
+ isChannelFormValid,
+ toCreateRequest,
+} from '@/pages/channel/channel-form';
+
+interface Props {
+ open: boolean;
+ onOpenChange: (open: boolean) => void;
+ onCreated?: () => void;
+ /** Platform pre-selected from the gallery; falls back to the first type. */
+ initialType?: string;
+}
+
+export function CreateChannelDialog({ open, onOpenChange, onCreated, initialType }: Props) {
+ const { t } = useTranslation();
+ const { agents } = useAgents();
+ const [form, setForm] = React.useState(defaultChannelForm);
+ const [channelTypes, setChannelTypes] = React.useState<ChannelTypeSchema[]>([]);
+ const [loading, setLoading] = React.useState(false);
+ const [error, setError] = React.useState('');
+
+ React.useEffect(() => {
+ if (open) {
+ setForm({
+ ...defaultChannelForm(agents[0]?.id ?? ''),
+ channelType: initialType ?? 'feishu',
+ });
+ setError('');
+ channelApi
+ .listTypes()
+ .then((types) => {
+ setChannelTypes(types);
+ // Default to the first enabled type when the initial
+ // channelType is not among the service's enabled types.
+ setForm((f) =>
+ types.some((ct) => ct.channel_type === f.channelType)
+ ? f
+ : { ...f, channelType: types[0]?.channel_type ?? f.channelType },
+ );
+ })
+ .catch(() => {});
+ }
+ }, [open, agents, initialType]);
+
+ const valid = isChannelFormValid(form, 'create');
+ // The platform is chosen in the gallery, so name the dialog after it.
+ const picked = channelTypes.find((ct) => ct.channel_type === form.channelType);
+
+ const handleSubmit = async () => {
+ setError('');
+ if (!valid) return;
+ setLoading(true);
+ try {
+ await channelApi.create(toCreateRequest(form));
+ onCreated?.();
+ onOpenChange(false);
+ } catch (e) {
+ setError(e instanceof Error ? e.message : String(e));
+ } finally {
+ setLoading(false);
+ }
+ };
+
+ return (
+ <Dialog open={open} onOpenChange={onOpenChange}>
+ <DialogContent className="!w-[560px] !max-w-[560px]">
+ <DialogHeader>
+ <DialogTitle>
+ {picked
+ ? t('channel.create.titleFor', { name: picked.display_name })
+ : t('channel.create.title')}
+ </DialogTitle>
+ <DialogDescription>{t('channel.create.description')}</DialogDescription>
+ </DialogHeader>
+
+ <div className="no-scrollbar -mx-4 max-h-[75vh] overflow-y-auto px-4 pt-1">
+ <ChannelForm
+ mode="create"
+ value={form}
+ onChange={setForm}
+ agents={agents}
+ channelTypes={channelTypes}
+ />
+ {error && (
+ <Alert variant="destructive" className="mt-2">
+ <CircleAlert />
+ <AlertDescription>{error}</AlertDescription>
+ </Alert>
+ )}
+ </div>
+
+ <DialogFooter>
+ <Button variant="ghost" onClick={() => onOpenChange(false)} disabled={loading}>
+ <X className="size-3.5" />
+ {t('common.cancel')}
+ </Button>
+ <Button onClick={handleSubmit} disabled={loading || !valid}>
+ {loading ? (
+ <Loader2 className="size-3.5 animate-spin" />
+ ) : (
+ <PlusCircle className="size-3.5" />
+ )}
+ {loading ? t('common.creating') : t('common.create')}
+ </Button>
+ </DialogFooter>
+ </DialogContent>
+ </Dialog>
+ );
+}
diff --git a/examples/web_ui/frontend/src/pages/channel/edit-channel-dialog.tsx b/examples/web_ui/frontend/src/pages/channel/edit-channel-dialog.tsx
new file mode 100644
index 000000000..75a279820
--- /dev/null
+++ b/examples/web_ui/frontend/src/pages/channel/edit-channel-dialog.tsx
@@ -0,0 +1,110 @@
+import { CircleAlert, Loader2, Save, X } from 'lucide-react';
+import * as React from 'react';
+
+import type { ChannelRecord, ChannelTypeSchema } from '@/api';
+import { channelApi } from '@/api';
+import { Alert, AlertDescription } from '@/components/ui/alert';
+import { Button } from '@/components/ui/button';
+import {
+ Dialog,
+ DialogContent,
+ DialogDescription,
+ DialogFooter,
+ DialogHeader,
+ DialogTitle,
+} from '@/components/ui/dialog';
+import { useAgents } from '@/hooks/useAgents';
+import { useTranslation } from '@/i18n/useI18n';
+import {
+ ChannelForm,
+ channelFormFromRecord,
+ defaultChannelForm,
+ isChannelFormValid,
+ toUpdateRequest,
+} from '@/pages/channel/channel-form';
+
+interface Props {
+ channel: ChannelRecord | null;
+ open: boolean;
+ onOpenChange: (open: boolean) => void;
+ onUpdated?: () => void;
+}
+
+export function EditChannelDialog({ channel, open, onOpenChange, onUpdated }: Props) {
+ const { t } = useTranslation();
+ const { agents } = useAgents();
+ const [form, setForm] = React.useState(defaultChannelForm);
+ const [channelTypes, setChannelTypes] = React.useState<ChannelTypeSchema[]>([]);
+ const [loading, setLoading] = React.useState(false);
+ const [error, setError] = React.useState('');
+
+ React.useEffect(() => {
+ if (open && channel) {
+ setForm(channelFormFromRecord(channel));
+ setError('');
+ channelApi
+ .listTypes()
+ .then(setChannelTypes)
+ .catch(() => {});
+ }
+ }, [open, channel]);
+
+ const valid = isChannelFormValid(form, 'edit');
+
+ const handleSubmit = async () => {
+ if (!channel || !valid) return;
+ setError('');
+ setLoading(true);
+ try {
+ await channelApi.update(channel.id, toUpdateRequest(form));
+ onUpdated?.();
+ onOpenChange(false);
+ } catch (e) {
+ setError(e instanceof Error ? e.message : String(e));
+ } finally {
+ setLoading(false);
+ }
+ };
+
+ return (
+ <Dialog open={open} onOpenChange={onOpenChange}>
+ <DialogContent className="!w-[560px] !max-w-[560px]">
+ <DialogHeader>
+ <DialogTitle>{t('channel.edit.title')}</DialogTitle>
+ <DialogDescription>{t('channel.edit.description')}</DialogDescription>
+ </DialogHeader>
+
+ <div className="no-scrollbar -mx-4 max-h-[75vh] overflow-y-auto px-4 pt-1">
+ <ChannelForm
+ mode="edit"
+ value={form}
+ onChange={setForm}
+ agents={agents}
+ channelTypes={channelTypes}
+ />
+ {error && (
+ <Alert variant="destructive" className="mt-2">
+ <CircleAlert />
+ <AlertDescription>{error}</AlertDescription>
+ </Alert>
+ )}
+ </div>
+
+ <DialogFooter>
+ <Button variant="ghost" onClick={() => onOpenChange(false)} disabled={loading}>
+ <X className="size-3.5" />
+ {t('common.cancel')}
+ </Button>
+ <Button onClick={handleSubmit} disabled={loading || !valid}>
+ {loading ? (
+ <Loader2 className="size-3.5 animate-spin" />
+ ) : (
+ <Save className="size-3.5" />
+ )}
+ {t('common.save')}
+ </Button>
+ </DialogFooter>
+ </DialogContent>
+ </Dialog>
+ );
+}
diff --git a/examples/web_ui/frontend/src/pages/channel/index.tsx b/examples/web_ui/frontend/src/pages/channel/index.tsx
new file mode 100644
index 000000000..77f49d286
--- /dev/null
+++ b/examples/web_ui/frontend/src/pages/channel/index.tsx
@@ -0,0 +1,333 @@
+import { Cable, Plus } from 'lucide-react';
+import * as React from 'react';
+
+import type { ChannelRecord, ChannelStatus, ChannelTypeSchema } from '@/api';
+import { channelApi } from '@/api';
+import { DeleteDialog } from '@/components/dialog/DeleteDialog';
+import {
+ Empty,
+ EmptyDescription,
+ EmptyHeader,
+ EmptyMedia,
+ EmptyTitle,
+} from '@/components/ui/empty';
+import {
+ Item,
+ ItemActions,
+ ItemContent,
+ ItemHeader,
+ ItemMedia,
+ ItemTitle,
+} from '@/components/ui/item';
+import { ResizableHandle, ResizablePanel, ResizablePanelGroup } from '@/components/ui/resizable';
+import { Separator } from '@/components/ui/separator';
+import { Skeleton } from '@/components/ui/skeleton';
+import { Switch } from '@/components/ui/switch';
+import { useAgents } from '@/hooks/useAgents';
+import { useChannels } from '@/hooks/useChannels';
+import { useTranslation } from '@/i18n/useI18n';
+import { ChannelDetailPanel } from '@/pages/channel/channel-detail-panel';
+import { ChannelStatusBadge } from '@/pages/channel/channel-status';
+import { CreateChannelDialog } from '@/pages/channel/create-channel-dialog';
+import { EditChannelDialog } from '@/pages/channel/edit-channel-dialog';
+import { TypeAvatar } from '@/pages/channel/type-avatar';
+
+function ChannelCard({
+ channel,
+ type,
+ agentName,
+ status,
+ onEnable,
+ onDisable,
+ onOpen,
+}: {
+ channel: ChannelRecord;
+ type?: ChannelTypeSchema;
+ agentName: string;
+ status?: ChannelStatus | null;
+ onEnable: () => void;
+ onDisable: () => void;
+ onOpen: () => void;
+}) {
+ const { t } = useTranslation();
+ const typeName = type?.display_name ?? channel.channel_type;
+ const name = channel.name?.trim() || typeName;
+ const model = channel.session.chat_model_config?.model;
+
+ return (
+ <Item
+ variant="outline"
+ onClick={onOpen}
+ className="cursor-pointer items-start shadow-panel transition hover:border-ring/40"
+ >
+ <ItemHeader>
+ <div className="flex min-w-0 items-center gap-3">
+ <ItemMedia>
+ <TypeAvatar type={type} className="size-9 rounded-lg" />
+ </ItemMedia>
+ <div className="min-w-0">
+ <ItemTitle className="truncate">{name}</ItemTitle>
+ <span className="font-mono text-[11px] text-muted-foreground">
+ {typeName}
+ </span>
+ </div>
+ </div>
+ <ItemActions>
+ <Switch
+ checked={channel.enabled}
+ onClick={(e) => e.stopPropagation()}
+ onCheckedChange={(v) => (v ? onEnable() : onDisable())}
+ />
+ </ItemActions>
+ </ItemHeader>
+ <ItemContent className="basis-full gap-1.5 text-xs">
+ <div className="flex items-center justify-between gap-2">
+ <span className="text-muted-foreground">{t('common.agent')}</span>
+ <span className="truncate">{agentName}</span>
+ </div>
+ <div className="flex items-center justify-between gap-2">
+ <span className="text-muted-foreground">{t('channel.routing')}</span>
+ <span className="font-mono">
+ {t('channel.rules', { count: channel.routing.bindings.length })}
+ </span>
+ </div>
+ {model && (
+ <div className="flex items-center justify-between gap-2">
+ <span className="text-muted-foreground">{t('common.model')}</span>
+ <span className="truncate font-mono">{model}</span>
+ </div>
+ )}
+ <div className="flex items-center justify-between gap-2">
+ <span className="text-muted-foreground">{t('channel.status')}</span>
+ <ChannelStatusBadge enabled={channel.enabled} status={status} />
+ </div>
+ </ItemContent>
+ </Item>
+ );
+}
+
+function ChannelTypeCard({ type, onPick }: { type: ChannelTypeSchema; onPick: () => void }) {
+ return (
+ <button
+ onClick={onPick}
+ className="group flex items-start gap-3 rounded-xl border bg-card p-4 text-left shadow-panel transition hover:border-ring/40"
+ >
+ <TypeAvatar type={type} className="size-10 rounded-lg" />
+ <div className="min-w-0 flex-1">
+ <div className="truncate text-sm font-semibold">{type.display_name}</div>
+ {type.description ? (
+ <div className="mt-0.5 line-clamp-2 text-xs text-muted-foreground">
+ {type.description}
+ </div>
+ ) : (
+ <div className="font-mono text-[11px] text-muted-foreground">
+ {type.channel_type}
+ </div>
+ )}
+ </div>
+ <Plus className="size-4 shrink-0 text-muted-foreground opacity-0 transition group-hover:opacity-100" />
+ </button>
+ );
+}
+
+export function ChannelPage() {
+ const { t } = useTranslation();
+ const { channels, loading, refetch, enable, disable, remove } = useChannels();
+ const { agents } = useAgents();
+ const [types, setTypes] = React.useState<ChannelTypeSchema[]>([]);
+ const [createType, setCreateType] = React.useState<string | null>(null);
+ const [editTarget, setEditTarget] = React.useState<ChannelRecord | null>(null);
+ const [deleteTarget, setDeleteTarget] = React.useState<ChannelRecord | null>(null);
+ const [selectedId, setSelectedId] = React.useState<string | null>(null);
+ const [statuses, setStatuses] = React.useState<Record<string, ChannelStatus>>({});
+
+ React.useEffect(() => {
+ channelApi
+ .listTypes()
+ .then(setTypes)
+ .catch(() => {});
+ }, []);
+
+ // One status source, polled and shared by the cards and the detail panel
+ // so they never disagree. Only enabled channels run, so only they have a
+ // status; disabled ones show "已禁用" from the enabled flag.
+ const channelIds = channels
+ .filter((c) => c.enabled)
+ .map((c) => c.id)
+ .join(',');
+ React.useEffect(() => {
+ const ids = channelIds ? channelIds.split(',') : [];
+ if (ids.length === 0) {
+ setStatuses({});
+ return;
+ }
+ let alive = true;
+ const load = () => {
+ Promise.all(
+ ids.map((id) =>
+ channelApi
+ .status(id)
+ .then((s) => [id, s] as const)
+ .catch(() => null),
+ ),
+ ).then((rs) => {
+ if (!alive) return;
+ const next: Record<string, ChannelStatus> = {};
+ for (const r of rs) if (r) next[r[0]] = r[1];
+ setStatuses(next);
+ });
+ };
+ load();
+ const iv = setInterval(load, 10000);
+ return () => {
+ alive = false;
+ clearInterval(iv);
+ };
+ }, [channelIds]);
+
+ const typeOf = (channelType: string) => types.find((ct) => ct.channel_type === channelType);
+ const agentName = (agentId: string) =>
+ agents.find((a) => a.id === agentId)?.data.name ?? agentId.slice(0, 8);
+ const deleteName = (ch: ChannelRecord) =>
+ ch.name?.trim() ||
+ `${typeOf(ch.channel_type)?.display_name ?? ch.channel_type} · ${ch.id.slice(0, 8)}`;
+ // Derived from the live list so an edited/deleted selection stays in sync.
+ const selected = channels.find((c) => c.id === selectedId) ?? null;
+
+ return (
+ <div className="flex size-full p-2">
+ <ResizablePanelGroup orientation="horizontal">
+ <ResizablePanel minSize="24rem">
+ <main className="flex h-full min-h-0 min-w-0 flex-col overflow-hidden rounded-[22px] bg-card shadow-panel">
+ <div className="px-6 pt-5 pb-4">
+ <div className="text-2xl font-semibold">{t('channel.title')}</div>
+ <div className="mt-1 text-sm text-muted-foreground">
+ {t('channel.subtitle')}
+ </div>
+ </div>
+ <Separator />
+
+ <div className="flex-1 overflow-y-auto px-6 py-6">
+ {loading ? (
+ <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-4">
+ {Array.from({ length: 4 }).map((_, i) => (
+ <Skeleton key={i} className="h-40 rounded-lg" />
+ ))}
+ </div>
+ ) : (
+ <>
+ {channels.length === 0 ? (
+ <Empty className="border-none py-10">
+ <EmptyHeader>
+ <EmptyMedia variant="icon">
+ <Cable />
+ </EmptyMedia>
+ <EmptyTitle>{t('channel.empty.title')}</EmptyTitle>
+ <EmptyDescription>
+ {t('channel.empty.description')}
+ </EmptyDescription>
+ </EmptyHeader>
+ </Empty>
+ ) : (
+ <section className="mb-2">
+ <div className="mb-4 flex items-center gap-2">
+ <span className="text-xs font-semibold uppercase tracking-wide text-muted-foreground">
+ {t('channel.sectionActive')}
+ </span>
+ <span className="rounded bg-muted px-2 py-0.5 font-mono text-[10px] text-muted-foreground">
+ {channels.length}
+ </span>
+ </div>
+ <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-4">
+ {channels.map((ch) => (
+ <ChannelCard
+ key={ch.id}
+ channel={ch}
+ type={typeOf(ch.channel_type)}
+ agentName={agentName(
+ ch.routing.bindings[
+ ch.routing.bindings.length - 1
+ ]?.agent_id ?? '',
+ )}
+ status={statuses[ch.id]}
+ onEnable={() => enable(ch.id)}
+ onDisable={() => disable(ch.id)}
+ onOpen={() => setSelectedId(ch.id)}
+ />
+ ))}
+ </div>
+ </section>
+ )}
+
+ <div className="my-8 flex items-center gap-4">
+ <span className="flex items-center gap-2 text-xs font-semibold uppercase tracking-wide text-muted-foreground">
+ <Plus className="size-3.5 text-primary" />
+ {t('channel.sectionAdd')}
+ </span>
+ <div className="flex-1 border-t border-dashed" />
+ </div>
+
+ <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 2xl:grid-cols-4 gap-3">
+ {types.map((ct) => (
+ <ChannelTypeCard
+ key={ct.channel_type}
+ type={ct}
+ onPick={() => setCreateType(ct.channel_type)}
+ />
+ ))}
+ </div>
+ </>
+ )}
+ </div>
+ </main>
+ </ResizablePanel>
+ {selected && (
+ <>
+ <ResizableHandle withHandle className="w-2 bg-transparent" />
+ <ResizablePanel defaultSize="26rem" minSize="22rem">
+ <ChannelDetailPanel
+ channel={selected}
+ type={typeOf(selected.channel_type)}
+ status={statuses[selected.id]}
+ agentName={agentName}
+ onEdit={() => setEditTarget(selected)}
+ onDelete={() => setDeleteTarget(selected)}
+ onClose={() => setSelectedId(null)}
+ />
+ </ResizablePanel>
+ </>
+ )}
+ </ResizablePanelGroup>
+
+ <CreateChannelDialog
+ open={createType !== null}
+ initialType={createType ?? undefined}
+ onOpenChange={(open) => !open && setCreateType(null)}
+ onCreated={refetch}
+ />
+
+ <EditChannelDialog
+ channel={editTarget}
+ open={!!editTarget}
+ onOpenChange={(open) => !open && setEditTarget(null)}
+ onUpdated={refetch}
+ />
+
+ {deleteTarget && (
+ <DeleteDialog
+ open={!!deleteTarget}
+ onOpenChange={(open) => !open && setDeleteTarget(null)}
+ title={t('common.deleteTitle', {
+ entity: t('channel.deleteEntity'),
+ name: deleteName(deleteTarget),
+ })}
+ description={t('common.deleteDescription')}
+ onConfirm={async () => {
+ await remove(deleteTarget.id);
+ setDeleteTarget(null);
+ }}
+ />
+ )}
+ </div>
+ );
+}
diff --git a/examples/web_ui/frontend/src/pages/channel/type-avatar.tsx b/examples/web_ui/frontend/src/pages/channel/type-avatar.tsx
new file mode 100644
index 000000000..d569ef1ce
--- /dev/null
+++ b/examples/web_ui/frontend/src/pages/channel/type-avatar.tsx
@@ -0,0 +1,17 @@
+import type { ChannelTypeSchema } from '@/api';
+import { Avatar, AvatarFallback, AvatarImage } from '@/components/ui/avatar';
+import { avatarTint } from '@/utils/common';
+
+/** Brand avatar for a channel type; falls back to a tinted initial. */
+export function TypeAvatar({ type, className }: { type?: ChannelTypeSchema; className?: string }) {
+ const seed = type?.channel_type ?? '';
+ const label = type?.display_name ?? seed;
+ return (
+ <Avatar className={className}>
+ <AvatarImage src={type?.icon_url || undefined} alt={label} />
+ <AvatarFallback className="rounded-[inherit]" style={avatarTint(seed)}>
+ {label.slice(0, 1).toUpperCase()}
+ </AvatarFallback>
+ </Avatar>
+ );
+}
diff --git a/examples/web_ui/frontend/src/pages/chat/index.tsx b/examples/web_ui/frontend/src/pages/chat/index.tsx
index d269d6149..1451976c8 100644
--- a/examples/web_ui/frontend/src/pages/chat/index.tsx
+++ b/examples/web_ui/frontend/src/pages/chat/index.tsx
@@ -1,8 +1,10 @@
import { format, isToday } from 'date-fns';
import {
BotMessageSquare,
+ Cable,
CalendarClock,
Ellipsis,
+ type LucideIcon,
MessageSquareDashed,
Pencil,
Plus,
@@ -13,7 +15,7 @@ import { useEffect, useState } from 'react';
import { useNavigate, useParams } from 'react-router-dom';
import { ChatViewport } from './ChatViewport';
-import type { SessionRecord } from '@/api';
+import type { SessionRecord, SessionSource } from '@/api';
import { AgentDialog } from '@/components/dialog/AgentDialog';
import { DeleteDialog } from '@/components/dialog/DeleteDialog';
import { EditAgentDialog } from '@/components/dialog/EditAgentDialog';
@@ -75,6 +77,13 @@ import { useTranslation } from '@/i18n/useI18n.ts';
*
* @returns The chat page JSX.
*/
+// Icon per session origin, shown only when a sidebar mixes sources.
+const SOURCE_ICON: Record<SessionSource, LucideIcon> = {
+ user: BotMessageSquare,
+ schedule: CalendarClock,
+ channel: Cable,
+};
+
const ChatPageInner = () => {
const navigate = useNavigate();
const {
@@ -106,7 +115,9 @@ const ChatPageInner = () => {
const selectedAgent = agents.find((a) => a.id === urlAgentId) ?? null;
const currentView = sessions.find((v) => v.session.id === urlSessionId) ?? null;
- const hasScheduleSessions = sessions.some((v) => v.session.source === 'schedule');
+ // Show a per-origin icon only when sessions actually mix sources —
+ // a uniform list needs no disambiguation.
+ const showSourceIcons = new Set(sessions.map((v) => v.session.source)).size > 1;
// "Inner focus" — when the URL carries a third `:memberId` segment
// the user is drilling into a team member's chat. The main sidebar
@@ -297,6 +308,9 @@ const ChatPageInner = () => {
<SidebarMenu>
{todaySessions.map((view) => {
const session = view.session;
+ const SourceIcon =
+ SOURCE_ICON[session.source] ??
+ BotMessageSquare;
return (
<SidebarMenuItem key={session.id}>
{/* Wider right gutter than the stock
@@ -313,13 +327,7 @@ const ChatPageInner = () => {
setOpenMobile(false);
}}
>
- {hasScheduleSessions &&
- (session.source ===
- 'schedule' ? (
- <CalendarClock />
- ) : (
- <BotMessageSquare />
- ))}
+ {showSourceIcons && <SourceIcon />}
<span className="truncate">
{session.config.name ||
session.id}
@@ -386,10 +394,13 @@ const ChatPageInner = () => {
<SidebarMenu>
{earlierSessions.map((view) => {
const session = view.session;
+ const SourceIcon =
+ SOURCE_ICON[session.source] ??
+ BotMessageSquare;
return (
<SidebarMenuItem key={session.id}>
<SidebarMenuButton
- className="group-has-data-[sidebar=menu-action]/menu-item:pr-16"
+ className="text-muted-foreground hover:text-foreground group-has-data-[sidebar=menu-action]/menu-item:pr-16"
isActive={
urlSessionId === session.id
}
@@ -400,13 +411,7 @@ const ChatPageInner = () => {
setOpenMobile(false);
}}
>
- {hasScheduleSessions &&
- (session.source ===
- 'schedule' ? (
- <CalendarClock />
- ) : (
- <BotMessageSquare />
- ))}
+ {showSourceIcons && <SourceIcon />}
<span className="truncate">
{session.config.name ||
session.id}
@@ -520,7 +525,10 @@ const ChatPageInner = () => {
onOpenChange={setDeleteSessionOpen}
title={t('common.deleteTitle', {
entity: t('dialog-session-delete.entity'),
- name: sessionToDelete?.config.name || sessionToDelete?.id || '',
+ name: (() => {
+ const raw = sessionToDelete?.config.name || sessionToDelete?.id || '';
+ return raw.length > 30 ? `${raw.slice(0, 30)}…` : raw;
+ })(),
})}
description={t('common.deleteDescription')}
confirmLabel={t('dialog-session-delete.confirm')}
diff --git a/examples/web_ui/frontend/src/pages/schedule/index.tsx b/examples/web_ui/frontend/src/pages/schedule/index.tsx
index 78d8faf11..addfade5c 100644
--- a/examples/web_ui/frontend/src/pages/schedule/index.tsx
+++ b/examples/web_ui/frontend/src/pages/schedule/index.tsx
@@ -5,6 +5,7 @@ import * as React from 'react';
import type { ScheduleEvent } from './event';
import type { ScheduleRecord } from '@/api';
import { Button } from '@/components/ui/button';
+import { Separator } from '@/components/ui/separator';
import { Tabs, TabsList, TabsTrigger } from '@/components/ui/tabs';
import { useSchedules } from '@/hooks/useSchedules';
import { useTranslation } from '@/i18n/useI18n';
@@ -78,42 +79,50 @@ export function SchedulePage() {
};
return (
- <div className="w-full h-full flex flex-col bg-sidebar overflow-hidden">
- <div className="flex items-center justify-between p-4 flex-shrink-0">
- <span className="text-2xl font-semibold">{t('common.schedule')}</span>
- <div className="flex items-center gap-2">
- <Button size="icon-sm" onClick={() => setIsCreateOpen(true)}>
- <Plus />
- </Button>
- <Tabs
- value={viewMode}
- onValueChange={(value) => setViewMode(value as 'calendar' | 'list')}
- >
- <TabsList>
- <TabsTrigger value="calendar" className="border-none w-[100px]">
- <Calendar className="h-4 w-4" />
- <span>{t('schedule.calendar')}</span>
- </TabsTrigger>
- <TabsTrigger value="list" className="border-none w-[100px]">
- <List className="h-4 w-4" />
- <span>{t('schedule.list')}</span>
- </TabsTrigger>
- </TabsList>
- </Tabs>
+ <div className="flex size-full p-2">
+ <main className="flex h-full min-h-0 min-w-0 flex-1 flex-col overflow-hidden rounded-[22px] bg-card shadow-panel">
+ <div className="flex items-start justify-between gap-3 px-6 pt-5 pb-4">
+ <div>
+ <div className="text-2xl font-semibold">{t('common.schedule')}</div>
+ <div className="mt-1 text-sm text-muted-foreground">
+ {t('schedule.subtitle')}
+ </div>
+ </div>
+ <div className="flex items-center gap-2">
+ <Button size="icon-sm" onClick={() => setIsCreateOpen(true)}>
+ <Plus />
+ </Button>
+ <Tabs
+ value={viewMode}
+ onValueChange={(value) => setViewMode(value as 'calendar' | 'list')}
+ >
+ <TabsList>
+ <TabsTrigger value="calendar" className="border-none w-[100px]">
+ <Calendar className="h-4 w-4" />
+ <span>{t('schedule.calendar')}</span>
+ </TabsTrigger>
+ <TabsTrigger value="list" className="border-none w-[100px]">
+ <List className="h-4 w-4" />
+ <span>{t('schedule.list')}</span>
+ </TabsTrigger>
+ </TabsList>
+ </Tabs>
+ </div>
</div>
- </div>
+ <Separator />
- <div className="flex-1 overflow-hidden rounded-t-3xl bg-white">
- {viewMode === 'calendar' && (
- <CalendarTabPage
- events={events}
- onEventClick={handleEventClick}
- currentDate={currentDate}
- onMonthChange={setCurrentDate}
- />
- )}
- {viewMode === 'list' && <ListTabPage />}
- </div>
+ <div className="flex-1 overflow-hidden">
+ {viewMode === 'calendar' && (
+ <CalendarTabPage
+ events={events}
+ onEventClick={handleEventClick}
+ currentDate={currentDate}
+ onMonthChange={setCurrentDate}
+ />
+ )}
+ {viewMode === 'list' && <ListTabPage />}
+ </div>
+ </main>
<ScheduleDetailDrawer
schedule={selectedSchedule}
diff --git a/pyproject.toml b/pyproject.toml
index d7b29ca7d..d5cdd4279 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -75,6 +75,11 @@ storage-sql = [
]
# S3-compatible blob store
storage-s3 = ["aioboto3"]
+# ------------ Channel ------------
+channel = [
+ "lark-oapi>=1.4.0",
+ "discord.py>=2.3",
+]
# ------------ Workspace (sandbox backends) ------------
workspace-docker = ["aiodocker"]
workspace-e2b = ["e2b"]
@@ -149,6 +154,7 @@ full = [
"agentscope[storage-redis]",
"agentscope[storage-sql]",
"agentscope[storage-s3]",
+ "agentscope[channel]",
"agentscope[workspace]",
"agentscope[tools]",
"agentscope[rag]",
diff --git a/src/agentscope/agent/_agent.py b/src/agentscope/agent/_agent.py
index 295faf615..75b172bdf 100644
--- a/src/agentscope/agent/_agent.py
+++ b/src/agentscope/agent/_agent.py
@@ -7,6 +7,7 @@ import re
from asyncio import Queue
from copy import deepcopy
+from fnmatch import fnmatch
from datetime import datetime
from typing import (
Any,
@@ -1677,6 +1678,39 @@ class Agent:
f"tool results or thinking blocks.",
)
+ # Handle the unsupported input data
+ supported = self.model.formatter.supported_input_media_types
+ for i, block in enumerate(msg.content):
+ if not isinstance(block, DataBlock) or any(
+ fnmatch(block.source.media_type, pattern)
+ for pattern in supported
+ ):
+ continue
+
+ # Convert unsupported input data block into a text block,
+ # and offload it into the workspace
+ url = ""
+ if isinstance(block.source, URLSource):
+ url = str(block.source.url)
+ elif self.offloader is not None:
+ saved = await self.offloader.offload_data_block(block)
+ if isinstance(saved.source, URLSource):
+ url = str(saved.source.url)
+
+ name = f"named '{block.name}' " if block.name else ""
+ if url:
+ text = (
+ f"<system-reminder>An attached file {name}is "
+ f"saved into {url}.</system-reminder>"
+ )
+ else:
+ text = (
+ f"<system-reminder>An unsupported input file "
+ f"{name}is attached with media type "
+ f"'{block.source.media_type}'.</system-reminder>"
+ )
+ msg.content[i] = TextBlock(type="text", text=text)
+
self.state.context.append(msg)
async def _batch_tool_calls(
diff --git a/src/agentscope/app/_app.py b/src/agentscope/app/_app.py
index 5f7822c54..d96a76ad2 100644
--- a/src/agentscope/app/_app.py
+++ b/src/agentscope/app/_app.py
@@ -11,6 +11,7 @@ from .rag.knowledge_base_manager import KnowledgeBaseManagerBase
from .workspace_manager import WorkspaceManagerBase
from ._router import (
agent_router,
+ channel_router,
chat_router,
credential_router,
health_router,
@@ -26,6 +27,7 @@ from ._router import (
workspace_router,
)
from ._types import AgentMiddlewareFactory, AgentToolFactory, SubAgentTemplate
+from .channel import ChannelBase, ChannelTypeRegistry
from .message_bus import MessageBus
from .storage import StorageBase
from ..agent import Agent
@@ -95,6 +97,7 @@ def create_app(
custom_subagent_templates: list[SubAgentTemplate] | None = None,
custom_agent_cls: Type[Agent] | None = None,
resource_access_policy: ResourceAccessPolicyBase | None = None,
+ channels: list[Type[ChannelBase]] | None = None,
download_secret: str | None = None,
title: str = "AgentScope",
version: str = __version__,
@@ -229,6 +232,15 @@ def create_app(
user. When ``None`` (default), a
:class:`DenyAllResourceAccessPolicy` is installed which
preserves the historical owner-isolated behavior.
+ channels (`list[Type[ChannelBase]] | None`, optional):
+ Channel adapter classes this service allows (e.g.
+ ``[FeishuChannel, DiscordChannel]``). Each class
+ self-describes its ``channel_type``, credentials and config,
+ so the service registers it without a separate table; pass a
+ custom :class:`~agentscope.app.channel.ChannelBase` subclass
+ to add a platform. When ``None`` (default), no channel types
+ are registered and the channel feature stays off until the
+ caller opts in by passing at least one adapter class.
download_secret (`str | None`, optional):
Signs the short-lived tokens that let a browser download a
workspace file by navigation. Defaults to a value generated
@@ -264,6 +276,12 @@ def create_app(
app.state.resource_access_policy = (
resource_access_policy or DenyAllResourceAccessPolicy()
)
+ # Channel types this service allows. A channel class self-describes
+ # its credentials / config, so the registry is built straight from
+ # the list — it has no lifecycle, so it lives on app.state directly
+ # rather than being created in the lifespan. Empty by default: the
+ # channel feature is off until the caller passes at least one class.
+ app.state.channel_type_registry = ChannelTypeRegistry(channels or [])
app.state.mcp_hubs = _index_hubs(mcp_hubs, "MCP")
app.state.skill_hubs = _index_hubs(skill_hubs, "skill")
app.state.download_secret = download_secret or secrets.token_urlsafe(32)
@@ -323,6 +341,7 @@ def create_app(
model_router,
tts_model_router,
embedding_model_router,
+ channel_router,
):
app.include_router(router)
diff --git a/src/agentscope/app/_bus_ops.py b/src/agentscope/app/_bus_ops.py
index b2ff904b8..a17d43ec4 100644
--- a/src/agentscope/app/_bus_ops.py
+++ b/src/agentscope/app/_bus_ops.py
@@ -31,6 +31,7 @@ if TYPE_CHECKING:
UserConfirmResultEvent,
UserInterruptEvent,
)
+ from agentscope.message import Msg
# ── publish_session_event ──────────────────────────────────────────────
@@ -74,10 +75,15 @@ async def enqueue_run_trigger(
session_id: str,
agent_id: str,
*,
- kind: Literal["wake", "resume"] = MessageBusKeys.WAKEUP_KIND_WAKE,
+ kind: Literal[
+ "wake",
+ "resume",
+ "message",
+ ] = MessageBusKeys.WAKEUP_KIND_WAKE,
inputs: UserConfirmResultEvent
| ExternalExecutionResultEvent
| UserInterruptEvent
+ | Msg
| None = None,
) -> None:
"""Enqueue a typed run trigger and signal dispatchers.
@@ -91,6 +97,10 @@ async def enqueue_run_trigger(
an external execution result, or a user interrupt. The dispatcher
waits (with backoff) until the parked run releases its lock, then
spawns with ``input_msg`` set to the deserialised event.
+ - ``message`` — start a new turn from a genuine user ``Msg`` (e.g. an
+ inbound channel message). Like ``resume`` it carries input and is
+ re-queued rather than dropped while the session is running; the run
+ persists it and reasons over it as a real user turn.
The payload is serialised to a plain dict before being pushed to the
wakeup queue; the ``MessageBus`` transport layer never sees event
@@ -167,3 +177,49 @@ async def enqueue_index_task(
},
)
await bus.publish(MessageBusKeys.index_tasks_signal(), {})
+
+
+# ── enqueue_channel_output ─────────────────────────────────────────────
+
+
+async def enqueue_channel_output(
+ bus: "MessageBus",
+ *,
+ session_id: str,
+ channel_id: str,
+ chat_id: str,
+ user_id: str,
+ agent_id: str,
+) -> None:
+ """Signal that a channel-bound session is producing output.
+
+ Pushes one signal onto the durable channel-outbound queue and nudges
+ the consumers. Whichever node hosts the channel drains it and
+ forwards the reply back to the platform chat. Called once at the
+ start of a channel-bound run, before the reply is produced.
+
+ Args:
+ bus (`MessageBus`):
+ The application message bus.
+ session_id (`str`):
+ The session about to produce output.
+ channel_id (`str`):
+ The owning channel (locates the adapter + presentation).
+ chat_id (`str`):
+ The platform chat to deliver the reply to.
+ user_id (`str`):
+ The owning user id.
+ agent_id (`str`):
+ The agent id that owns the session.
+ """
+ await bus.queue_push(
+ MessageBusKeys.channel_outbound_queue(),
+ {
+ "session_id": session_id,
+ "channel_id": channel_id,
+ "chat_id": chat_id,
+ "user_id": user_id,
+ "agent_id": agent_id,
+ },
+ )
+ await bus.publish(MessageBusKeys.channel_outbound_signal(), {})
diff --git a/src/agentscope/app/_lifespan.py b/src/agentscope/app/_lifespan.py
index e7bc595a3..107ea8665 100644
--- a/src/agentscope/app/_lifespan.py
+++ b/src/agentscope/app/_lifespan.py
@@ -13,6 +13,7 @@ from ._manager import (
WakeupDispatcher,
)
from ._service import (
+ ChannelService,
ChatService,
IndexSweeper,
IndexTaskConsumer,
@@ -101,6 +102,40 @@ async def lifespan(app: FastAPI) -> AsyncIterator[None]:
)
app.state.resource_access_service = resource_access_service
+ # Channel wiring is built here (before ChatService) so the chat
+ # service can hand the dispatcher to get_toolkit: a session that
+ # came from a channel gets that channel's platform tools. The
+ # type registry has no lifecycle and was built in create_app; the
+ # reconcile/heartbeat loops start later via the dispatcher's
+ # lifespan context.
+ from .channel import (
+ ChannelGateway,
+ ChannelLifecycleDispatcher,
+ )
+
+ # Only wire the channel subsystem when channel types are
+ # registered — otherwise the dispatcher's reconcile would hit
+ # storage backends that don't implement channel methods.
+ channel_type_registry = app.state.channel_type_registry
+ channel_dispatcher = None
+ if channel_type_registry:
+ channel_dispatcher = ChannelLifecycleDispatcher(
+ storage=storage,
+ message_bus=message_bus,
+ type_registry=channel_type_registry,
+ gateway=ChannelGateway(
+ storage=storage,
+ message_bus=message_bus,
+ workspace_manager=workspace_manager,
+ ),
+ )
+ app.state.channel_service = ChannelService(
+ storage=storage,
+ message_bus=message_bus,
+ type_registry=channel_type_registry,
+ )
+ app.state.channel_dispatcher = channel_dispatcher
+
chat_service = ChatService(
storage=storage,
workspace_manager=workspace_manager,
@@ -113,6 +148,7 @@ async def lifespan(app: FastAPI) -> AsyncIterator[None]:
extra_agent_tools=app.state.extra_agent_tools,
custom_subagent_templates=app.state.custom_subagent_templates,
custom_agent_cls=app.state.custom_agent_cls,
+ channel_dispatcher=channel_dispatcher,
)
app.state.chat_service = chat_service
@@ -199,4 +235,10 @@ async def lifespan(app: FastAPI) -> AsyncIterator[None]:
),
)
+ # Start the channel reconcile/heartbeat/outbound loops (the
+ # dispatcher itself was built above, before ChatService) — only
+ # when the channel subsystem is enabled.
+ if channel_dispatcher is not None:
+ await stack.enter_async_context(channel_dispatcher.lifespan())
+
yield
diff --git a/src/agentscope/app/_manager/_wakeup_dispatcher.py b/src/agentscope/app/_manager/_wakeup_dispatcher.py
index 593234052..1144a6f03 100644
--- a/src/agentscope/app/_manager/_wakeup_dispatcher.py
+++ b/src/agentscope/app/_manager/_wakeup_dispatcher.py
@@ -33,11 +33,14 @@ from pydantic import TypeAdapter
from ..._logging import logger
from ...event import (
ExternalExecutionResultEvent,
+ ReplyEndEvent,
UserConfirmResultEvent,
UserInterruptEvent,
)
+from ...message import Msg
+from ...types import ErrorInfo, ErrorType, ReplyFinishedReason
from ..message_bus import MessageBusKeys
-from .._bus_ops import enqueue_run_trigger
+from .._bus_ops import enqueue_run_trigger, publish_session_event
if TYPE_CHECKING:
from ..message_bus import MessageBus
@@ -178,7 +181,7 @@ class WakeupDispatcher:
MessageBusKeys.wakeup_queue(),
max_count=64,
)
- entries = [payload for _entry_id, payload in raw_entries]
+ entries = [payload for _, payload in raw_entries]
except Exception: # pylint: disable=broad-except
logger.exception("WakeupDispatcher: dequeue_wakeups failed.")
return
@@ -228,26 +231,41 @@ class WakeupDispatcher:
``None``.
"""
is_resume = kind == MessageBusKeys.WAKEUP_KIND_RESUME
-
- # Parse the resume input early so every downstream path
- # (lock-retry, spawn-retry) receives a typed event object
- # rather than a raw dict.
- input_msg: UserConfirmResultEvent | ExternalExecutionResultEvent | None
- input_msg = None
- if is_resume:
+ is_message = kind == MessageBusKeys.WAKEUP_KIND_MESSAGE
+ # ``resume`` and ``message`` both carry input that must be
+ # delivered — never dropped while the session is busy.
+ carries_input = is_resume or is_message
+
+ # Parse the carried input early so every downstream path
+ # (lock-retry, spawn-retry) receives a typed object rather than a
+ # raw dict.
+ input_msg: (
+ UserConfirmResultEvent
+ | ExternalExecutionResultEvent
+ | UserInterruptEvent
+ | Msg
+ | None
+ ) = None
+ if carries_input:
if raw_input is None:
logger.warning(
- "WakeupDispatcher: dropping resume trigger for session "
- "%s — no input event carried.",
+ "WakeupDispatcher: dropping %s trigger for session "
+ "%s — no input carried.",
+ kind,
session_id,
)
return
try:
- input_msg = _RESUME_INPUT_ADAPTER.validate_python(raw_input)
+ input_msg = (
+ Msg.model_validate(raw_input)
+ if is_message
+ else _RESUME_INPUT_ADAPTER.validate_python(raw_input)
+ )
except Exception: # pylint: disable=broad-except
logger.exception(
- "WakeupDispatcher: dropping resume trigger for session "
- "%s — input event failed to parse: %r",
+ "WakeupDispatcher: dropping %s trigger for session "
+ "%s — input failed to parse: %r",
+ kind,
session_id,
raw_input,
)
@@ -256,14 +274,15 @@ class WakeupDispatcher:
if await self._bus.is_locked(
MessageBusKeys.session_lock(session_id),
):
- if is_resume:
- # The session is busy finishing its parked tail. Do NOT
- # drop the resume — re-queue it after a short backoff so
- # it lands once the parked run releases its lock.
- self._schedule_resume_retry(
+ if carries_input:
+ # The session is busy. Do NOT drop input-carrying triggers
+ # — re-queue after a short backoff so they land once the
+ # running turn releases its lock.
+ self._schedule_input_retry(
user_id,
session_id,
agent_id,
+ kind,
input_msg,
)
# ``wake`` triggers are safe to drop while running — the
@@ -289,6 +308,21 @@ class WakeupDispatcher:
agent_id,
user_id,
)
+ # Surface an error on the event stream so collectors (e.g. the
+ # channel gateway) fail fast instead of waiting for a timeout.
+ await publish_session_event(
+ self._bus,
+ session_id,
+ ReplyEndEvent(
+ session_id=session_id,
+ reply_id="",
+ finished_reason=ReplyFinishedReason.ERROR,
+ error=ErrorInfo(
+ type=ErrorType.INTERNAL,
+ message="Session no longer exists.",
+ ),
+ ).model_dump(mode="json"),
+ )
return
try:
@@ -305,12 +339,13 @@ class WakeupDispatcher:
except RuntimeError:
# A local run was registered between the running-check and
# the spawn. For ``wake`` that run will drain the inbox; for
- # ``resume`` re-queue so the result is not lost.
- if is_resume:
- self._schedule_resume_retry(
+ # input-carrying kinds re-queue so the input is not lost.
+ if carries_input:
+ self._schedule_input_retry(
user_id,
session_id,
agent_id,
+ kind,
input_msg,
)
else:
@@ -320,31 +355,37 @@ class WakeupDispatcher:
session_id,
)
- def _schedule_resume_retry(
+ def _schedule_input_retry(
self,
user_id: str,
session_id: str,
agent_id: str,
+ kind: str,
input_msg: UserConfirmResultEvent
| ExternalExecutionResultEvent
+ | UserInterruptEvent
+ | Msg
| None,
) -> None:
- """Re-enqueue a ``resume`` trigger after a short backoff.
+ """Re-enqueue an input-carrying (``resume``/``message``) trigger
+ after a short backoff.
- Spawns a detached timer that sleeps, then re-enqueues the resume
+ Spawns a detached timer that sleeps, then re-enqueues the trigger
(which re-fires the signal, re-driving the drain). This keeps the
- resume alive across the window where the parked run still holds
+ input alive across the window where the running turn still holds
the session lock, without a hot re-enqueue loop.
Args:
user_id (`str`):
The owning user id.
session_id (`str`):
- The session to resume.
+ The session to trigger.
agent_id (`str`):
The agent that owns the session.
+ kind (`str`):
+ The trigger kind to re-enqueue (``resume`` / ``message``).
input_msg:
- The parsed input event to redeliver.
+ The parsed input to redeliver.
"""
async def _retry() -> None:
@@ -355,21 +396,22 @@ class WakeupDispatcher:
user_id=user_id,
session_id=session_id,
agent_id=agent_id,
- kind=MessageBusKeys.WAKEUP_KIND_RESUME,
+ kind=kind, # type: ignore[arg-type] # resume | message
inputs=input_msg,
)
except asyncio.CancelledError:
pass
except Exception: # pylint: disable=broad-except
logger.exception(
- "WakeupDispatcher: failed to re-enqueue resume trigger "
+ "WakeupDispatcher: failed to re-enqueue %s trigger "
"for session %s.",
+ kind,
session_id,
)
task = asyncio.create_task(
_retry(),
- name=f"resume-retry:{session_id}",
+ name=f"{kind}-retry:{session_id}",
)
self._retry_tasks.add(task)
task.add_done_callback(self._retry_tasks.discard)
diff --git a/src/agentscope/app/_router/__init__.py b/src/agentscope/app/_router/__init__.py
index a646b527b..5444501d9 100644
--- a/src/agentscope/app/_router/__init__.py
+++ b/src/agentscope/app/_router/__init__.py
@@ -1,6 +1,7 @@
# -*- coding: utf-8 -*-
"""App routers."""
from ._agent import agent_router
+from ._channel import channel_router
from ._chat import chat_router
from ._credential import credential_router
from ._embedding_model import embedding_model_router
@@ -17,6 +18,7 @@ from ._workspace import workspace_router
__all__ = [
"agent_router",
+ "channel_router",
"model_router",
"embedding_model_router",
"tts_model_router",
diff --git a/src/agentscope/app/_router/_channel.py b/src/agentscope/app/_router/_channel.py
new file mode 100644
index 000000000..1e71008d3
--- /dev/null
+++ b/src/agentscope/app/_router/_channel.py
@@ -0,0 +1,280 @@
+# -*- coding: utf-8 -*-
+"""Channel HTTP API.
+
+ GET /channels/types List channel types + schemas
+ GET /channels/ List the user's channels
+ POST /channels/ Create a channel
+ GET /channels/{id} Channel details
+ PATCH /channels/{id} Update routing/session/config
+ DELETE /channels/{id} Delete a channel
+ POST /channels/{id}/enable Enable
+ POST /channels/{id}/disable Disable
+ GET /channels/{id}/status Aggregated runtime status
+ GET /channels/{id}/chat_ids Known chats (for routing config)
+"""
+from fastapi import APIRouter, Depends, HTTPException, status
+
+from ..channel import (
+ ChannelError,
+ ChannelLifecycleDispatcher,
+ ChannelStatus,
+ ChannelTypeRegistry,
+ ChannelTypeSchema,
+)
+from .._service import ChannelService
+from ..deps import (
+ get_channel_dispatcher,
+ get_channel_service,
+ get_channel_type_registry,
+ get_current_user_id,
+ get_storage,
+)
+from ..storage import ChannelRecord, StorageBase
+from ._schema import (
+ ChannelActionResponse,
+ ChannelChatId,
+ ChannelChatIdsResponse,
+ ChannelResponse,
+ ChannelSessionsResponse,
+ CreateChannelRequest,
+ UpdateChannelRequest,
+)
+
+channel_router = APIRouter(prefix="/channels", tags=["channels"])
+
+
+def _to_response(
+ record: ChannelRecord,
+ registry: ChannelTypeRegistry,
+) -> ChannelResponse:
+ """Project a stored record into a client response (credentials hidden).
+
+ Args:
+ record (`ChannelRecord`): The stored channel record.
+ registry (`ChannelTypeRegistry`): Used to derive the display-only
+ ``platform_bot_id`` from the credentials.
+
+ Returns:
+ `ChannelResponse`: The safe, client-facing view.
+ """
+ try:
+ bot_id = registry.extract_platform_bot_id(
+ record.channel_type,
+ record.credentials,
+ )
+ except ValueError:
+ bot_id = ""
+ return ChannelResponse(
+ id=record.id,
+ channel_type=record.channel_type,
+ name=record.name,
+ user_id=record.user_id,
+ platform_bot_id=bot_id,
+ enabled=record.enabled,
+ platform_config=record.platform_config,
+ routing=record.routing,
+ session=record.session,
+ created_at=record.created_at,
+ updated_at=record.updated_at,
+ )
+
+
+async def _owned(
+ channel_id: str,
+ user_id: str,
+ storage: StorageBase,
+) -> ChannelRecord:
+ """Load a channel and assert the caller owns it.
+
+ Args:
+ channel_id (`str`): The channel to load.
+ user_id (`str`): The caller.
+ storage (`StorageBase`): Application storage.
+
+ Returns:
+ `ChannelRecord`: The owned record.
+
+ Raises:
+ `HTTPException`: 404 if it does not exist, 403 if owned by
+ someone else.
+ """
+ record = await storage.get_channel(channel_id)
+ if record is None:
+ raise HTTPException(status.HTTP_404_NOT_FOUND, "Channel not found.")
+ if record.user_id != user_id:
+ raise HTTPException(status.HTTP_403_FORBIDDEN, "Access denied.")
+ return record
+
+
+@channel_router.get("/types")
+async def list_channel_types(
+ registry: ChannelTypeRegistry = Depends(get_channel_type_registry),
+) -> list[ChannelTypeSchema]:
+ """List supported channel types with their JSON schemas."""
+ return registry.list_types()
+
+
+@channel_router.get("/")
+async def list_channels(
+ storage: StorageBase = Depends(get_storage),
+ registry: ChannelTypeRegistry = Depends(get_channel_type_registry),
+ user_id: str = Depends(get_current_user_id),
+) -> list[ChannelResponse]:
+ """List channels owned by the current user."""
+ records = await storage.list_channels(user_id)
+ return [_to_response(r, registry) for r in records]
+
+
+@channel_router.post("/", status_code=status.HTTP_201_CREATED)
+async def create_channel(
+ body: CreateChannelRequest,
+ service: ChannelService = Depends(get_channel_service),
+ registry: ChannelTypeRegistry = Depends(get_channel_type_registry),
+ user_id: str = Depends(get_current_user_id),
+) -> ChannelResponse:
+ """Create a channel."""
+ try:
+ record = await service.create(
+ user_id=user_id,
+ channel_type=body.channel_type,
+ name=body.name,
+ credentials=body.credentials,
+ platform_config=body.platform_config,
+ routing=body.routing,
+ session=body.session,
+ enabled=body.enabled,
+ )
+ except ChannelError as e:
+ raise HTTPException(e.status_code, str(e)) from e
+ except ValueError as e:
+ raise HTTPException(status.HTTP_400_BAD_REQUEST, str(e)) from e
+ return _to_response(record, registry)
+
+
+@channel_router.get("/{channel_id}")
+async def get_channel(
+ channel_id: str,
+ storage: StorageBase = Depends(get_storage),
+ registry: ChannelTypeRegistry = Depends(get_channel_type_registry),
+ user_id: str = Depends(get_current_user_id),
+) -> ChannelResponse:
+ """Get channel details."""
+ record = await _owned(channel_id, user_id, storage)
+ return _to_response(record, registry)
+
+
+@channel_router.patch("/{channel_id}")
+async def update_channel(
+ channel_id: str,
+ body: UpdateChannelRequest,
+ storage: StorageBase = Depends(get_storage),
+ service: ChannelService = Depends(get_channel_service),
+ registry: ChannelTypeRegistry = Depends(get_channel_type_registry),
+ user_id: str = Depends(get_current_user_id),
+) -> ChannelResponse:
+ """Update routing / session / config / enabled."""
+ await _owned(channel_id, user_id, storage)
+ updates = body.model_dump(exclude_unset=True)
+ if not updates:
+ raise HTTPException(
+ status.HTTP_400_BAD_REQUEST,
+ "No fields to update.",
+ )
+ try:
+ record = await service.update(channel_id, updates)
+ except ChannelError as e:
+ raise HTTPException(e.status_code, str(e)) from e
+ return _to_response(record, registry)
+
+
+@channel_router.delete(
+ "/{channel_id}",
+ status_code=status.HTTP_204_NO_CONTENT,
+)
+async def delete_channel(
+ channel_id: str,
+ storage: StorageBase = Depends(get_storage),
+ service: ChannelService = Depends(get_channel_service),
+ user_id: str = Depends(get_current_user_id),
+) -> None:
+ """Delete a channel."""
+ await _owned(channel_id, user_id, storage)
+ await service.delete(channel_id)
+
+
+@channel_router.post("/{channel_id}/enable")
+async def enable_channel(
+ channel_id: str,
+ storage: StorageBase = Depends(get_storage),
+ service: ChannelService = Depends(get_channel_service),
+ user_id: str = Depends(get_current_user_id),
+) -> ChannelActionResponse:
+ """Enable a channel."""
+ await _owned(channel_id, user_id, storage)
+ await service.set_enabled(channel_id, True)
+ return ChannelActionResponse(status="enabled")
+
+
+@channel_router.post("/{channel_id}/disable")
+async def disable_channel(
+ channel_id: str,
+ storage: StorageBase = Depends(get_storage),
+ service: ChannelService = Depends(get_channel_service),
+ user_id: str = Depends(get_current_user_id),
+) -> ChannelActionResponse:
+ """Disable a channel."""
+ await _owned(channel_id, user_id, storage)
+ await service.set_enabled(channel_id, False)
+ return ChannelActionResponse(status="disabled")
+
+
+@channel_router.get("/{channel_id}/status")
+async def channel_status(
+ channel_id: str,
+ storage: StorageBase = Depends(get_storage),
+ dispatcher: ChannelLifecycleDispatcher = Depends(get_channel_dispatcher),
+ user_id: str = Depends(get_current_user_id),
+) -> ChannelStatus:
+ """The channel's live connection status."""
+ await _owned(channel_id, user_id, storage)
+ return await dispatcher.get_status(channel_id)
+
+
+@channel_router.get("/{channel_id}/sessions")
+async def list_channel_sessions(
+ channel_id: str,
+ storage: StorageBase = Depends(get_storage),
+ user_id: str = Depends(get_current_user_id),
+) -> ChannelSessionsResponse:
+ """Sessions this channel spawned, newest first."""
+ await _owned(channel_id, user_id, storage)
+ sessions = await storage.list_sessions_by_channel(user_id, channel_id)
+ return ChannelSessionsResponse(sessions=sessions, total=len(sessions))
+
+
+@channel_router.get("/{channel_id}/chat_ids")
+async def list_chat_ids(
+ channel_id: str,
+ storage: StorageBase = Depends(get_storage),
+ dispatcher: ChannelLifecycleDispatcher = Depends(get_channel_dispatcher),
+ user_id: str = Depends(get_current_user_id),
+) -> ChannelChatIdsResponse:
+ """Known chats for routing config: platform list ∪ passively seen."""
+ await _owned(channel_id, user_id, storage)
+ chats: list[ChannelChatId] = []
+ platform_ids: set[str] = set()
+ for chat in await dispatcher.list_bot_chats(channel_id):
+ cid = chat.get("chat_id", "")
+ if cid:
+ platform_ids.add(cid)
+ chats.append(
+ ChannelChatId(
+ chat_id=cid,
+ name=chat.get("name", ""),
+ source="platform",
+ ),
+ )
+ for cid in await dispatcher.list_seen_chat_ids(channel_id):
+ if cid not in platform_ids:
+ chats.append(ChannelChatId(chat_id=cid, source="recorded"))
+ return ChannelChatIdsResponse(chats=chats)
diff --git a/src/agentscope/app/_router/_schema/__init__.py b/src/agentscope/app/_router/_schema/__init__.py
index 5b649ff40..e21b0bc71 100644
--- a/src/agentscope/app/_router/_schema/__init__.py
+++ b/src/agentscope/app/_router/_schema/__init__.py
@@ -1,6 +1,15 @@
# -*- coding: utf-8 -*-
"""Schema models for the agent service."""
+from ._channel import (
+ ChannelActionResponse,
+ ChannelChatId,
+ ChannelChatIdsResponse,
+ ChannelResponse,
+ ChannelSessionsResponse,
+ CreateChannelRequest,
+ UpdateChannelRequest,
+)
from ._chat import ChatRequest, ChatTriggerResponse
from ._health import ComponentStatus, HealthResponse
from ._hub import HubInfo
@@ -101,6 +110,14 @@ __all__ = [
"CreateAgentResponse",
"UpdateAgentRequest",
"ListSchedulesResponse",
+ # Channel
+ "ChannelActionResponse",
+ "ChannelChatId",
+ "ChannelChatIdsResponse",
+ "ChannelResponse",
+ "ChannelSessionsResponse",
+ "CreateChannelRequest",
+ "UpdateChannelRequest",
# Chat
"ChatRequest",
"ChatTriggerResponse",
diff --git a/src/agentscope/app/_router/_schema/_channel.py b/src/agentscope/app/_router/_schema/_channel.py
new file mode 100644
index 000000000..c2720fe41
--- /dev/null
+++ b/src/agentscope/app/_router/_schema/_channel.py
@@ -0,0 +1,80 @@
+# -*- coding: utf-8 -*-
+"""Request / response schemas for the channel router."""
+from pydantic import BaseModel, Field
+
+from ...storage import (
+ RoutingConfig,
+ SessionRecord,
+ SessionSettings,
+)
+
+
+class CreateChannelRequest(BaseModel):
+ """Request body for creating a channel."""
+
+ channel_type: str = Field(description="Channel type id, e.g. 'feishu'.")
+ name: str | None = Field(
+ default=None,
+ description="Optional display name.",
+ )
+ credentials: dict = Field(description="Platform credentials.")
+ platform_config: dict = Field(
+ default_factory=dict,
+ description="Non-secret platform options.",
+ )
+ routing: RoutingConfig = Field(description="Inbound routing rules.")
+ session: SessionSettings = Field(description="Session/model settings.")
+ enabled: bool = Field(default=True, description="Start it enabled.")
+
+
+class UpdateChannelRequest(BaseModel):
+ """Request body for updating a channel (type/credentials immutable)."""
+
+ name: str | None = None
+ platform_config: dict | None = None
+ routing: RoutingConfig | None = None
+ session: SessionSettings | None = None
+ enabled: bool | None = None
+
+
+class ChannelResponse(BaseModel):
+ """Channel details returned to the client (credentials omitted)."""
+
+ id: str
+ channel_type: str
+ name: str | None
+ user_id: str
+ platform_bot_id: str
+ enabled: bool
+ platform_config: dict
+ routing: RoutingConfig
+ session: SessionSettings
+ created_at: str
+ updated_at: str
+
+
+class ChannelActionResponse(BaseModel):
+ """Result of an enable/disable action."""
+
+ status: str = Field(description="New lifecycle status, e.g. 'enabled'.")
+
+
+class ChannelSessionsResponse(BaseModel):
+ """Sessions a channel has spawned."""
+
+ sessions: list[SessionRecord]
+ total: int
+
+
+class ChannelChatId(BaseModel):
+ """A chat the bot can route to (from the platform or seen inbound)."""
+
+ chat_id: str
+ name: str = ""
+ source: str = Field(description="'platform' or 'recorded'.")
+
+
+class ChannelChatIdsResponse(BaseModel):
+ """Chats available for routing configuration."""
+
+ chats: list[ChannelChatId] = Field(default_factory=list)
diff --git a/src/agentscope/app/_service/__init__.py b/src/agentscope/app/_service/__init__.py
index 5ab3bd9c6..99a3176a3 100644
--- a/src/agentscope/app/_service/__init__.py
+++ b/src/agentscope/app/_service/__init__.py
@@ -6,6 +6,7 @@ from ._access import (
KnowledgeBaseView,
ResourceAccessService,
)
+from ._channel import ChannelService
from ._chat import ChatService
from ._embedding import get_embedding_model
from ._index_sweeper import IndexSweeper
@@ -22,6 +23,7 @@ from ._toolkit import get_toolkit
__all__ = [
"AgentView",
+ "ChannelService",
"ChatService",
"CredentialView",
"IndexSweeper",
diff --git a/src/agentscope/app/_service/_channel.py b/src/agentscope/app/_service/_channel.py
new file mode 100644
index 000000000..849d34de3
--- /dev/null
+++ b/src/agentscope/app/_service/_channel.py
@@ -0,0 +1,179 @@
+# -*- coding: utf-8 -*-
+"""ChannelService — stateless CRUD for channel records.
+
+Validates, writes the record, and publishes a lifecycle notification so
+every node's :class:`ChannelLifecycleDispatcher` reconciles its running
+instances against storage. Holds no channel instances.
+"""
+from datetime import datetime
+
+from ..._utils._common import _generate_id
+from ..message_bus import MessageBus, MessageBusKeys
+from ..storage import (
+ ChannelRecord,
+ RoutingConfig,
+ SessionSettings,
+ StorageBase,
+)
+from ..channel._errors import ChannelError
+from ..channel._registry import ChannelTypeRegistry
+
+
+class ChannelService:
+ """CRUD operations on channel records."""
+
+ def __init__(
+ self,
+ storage: StorageBase,
+ message_bus: MessageBus,
+ type_registry: ChannelTypeRegistry,
+ ) -> None:
+ """Bind storage, the message bus, and the channel type registry.
+
+ Args:
+ storage (`StorageBase`): Application storage.
+ message_bus (`MessageBus`): For lifecycle notifications.
+ type_registry (`ChannelTypeRegistry`): Validates types and
+ builds instances for the pre-create connection check.
+ """
+ self._storage = storage
+ self._bus = message_bus
+ self._types = type_registry
+
+ async def create(
+ self,
+ *,
+ user_id: str,
+ channel_type: str,
+ credentials: dict,
+ platform_config: dict,
+ routing: RoutingConfig,
+ session: SessionSettings,
+ enabled: bool = True,
+ name: str | None = None,
+ ) -> ChannelRecord:
+ """Create a channel, rejecting a bot already bound elsewhere.
+
+ Args:
+ user_id (`str`): Owner of the channel.
+ channel_type (`str`): Registered platform type id.
+ name (`str | None`): Optional display name.
+ credentials (`dict`): Platform credentials.
+ platform_config (`dict`): Platform behaviour options.
+ routing (`RoutingConfig`): Inbound routing rules.
+ session (`SessionSettings`): Derived-session settings.
+ enabled (`bool`): Whether to start the channel immediately.
+ """
+ bot_id = self._types.extract_platform_bot_id(
+ channel_type,
+ credentials,
+ )
+ existing = await self._storage.get_channel_id_by_platform_bot_id(
+ bot_id,
+ )
+ if existing:
+ raise ChannelError(
+ f"Bot '{bot_id}' already registered as channel "
+ f"'{existing}'.",
+ 409,
+ )
+
+ channel_id = _generate_id()
+ now = datetime.now().isoformat()
+ record = ChannelRecord(
+ id=channel_id,
+ channel_type=channel_type,
+ name=name,
+ user_id=user_id,
+ enabled=enabled,
+ credentials=credentials,
+ platform_config=platform_config,
+ routing=routing,
+ session=session,
+ created_at=now,
+ updated_at=now,
+ )
+ await self._storage.upsert_channel(record, bot_id)
+ await self._notify(record.id)
+ return record
+
+ async def update(self, channel_id: str, updates: dict) -> ChannelRecord:
+ """Apply routing/session/platform_config/enabled changes;
+ credentials and channel_type are immutable (recreate to change).
+
+ Args:
+ channel_id (`str`): The channel to update.
+ updates (`dict`): Field changes to apply.
+ """
+ record = await self._require(channel_id)
+ updates.pop("credentials", None)
+ updates.pop("channel_type", None)
+ updated = record.model_copy(
+ update={**updates, "updated_at": datetime.now().isoformat()},
+ )
+ bot_id = self._types.extract_platform_bot_id(
+ updated.channel_type,
+ updated.credentials,
+ )
+ await self._storage.upsert_channel(updated, bot_id)
+ await self._notify(channel_id)
+ return updated
+
+ async def set_enabled(
+ self,
+ channel_id: str,
+ enabled: bool,
+ ) -> ChannelRecord:
+ """Enable or disable a channel.
+
+ Args:
+ channel_id (`str`): The channel to toggle.
+ enabled (`bool`): The new enabled state.
+ """
+ return await self.update(channel_id, {"enabled": enabled})
+
+ async def delete(self, channel_id: str) -> None:
+ """Delete a channel and clear its bot-id index.
+
+ Args:
+ channel_id (`str`): The channel to delete.
+ """
+ record = await self._require(channel_id)
+ bot_id = self._types.extract_platform_bot_id(
+ record.channel_type,
+ record.credentials,
+ )
+ await self._storage.delete_channel(channel_id, bot_id)
+ await self._notify(channel_id)
+
+ # -- internals --
+
+ async def _require(self, channel_id: str) -> ChannelRecord:
+ """Load a channel record or raise a 404 ``ChannelError``.
+
+ Args:
+ channel_id (`str`): The channel to load.
+
+ Returns:
+ `ChannelRecord`: The record.
+ """
+ record = await self._storage.get_channel(channel_id)
+ if record is None:
+ raise ChannelError(f"Channel '{channel_id}' not found.", 404)
+ return record
+
+ async def _notify(self, channel_id: str) -> None:
+ """Publish a lifecycle notification (best-effort).
+
+ Args:
+ channel_id (`str`): The changed channel; reconcile re-reads
+ storage, so the payload is only a nudge.
+ """
+ try:
+ await self._bus.publish(
+ MessageBusKeys.channel_lifecycle(),
+ {"channel_id": channel_id},
+ )
+ except Exception: # pylint: disable=broad-except
+ # Lost notifications are recovered by the periodic reconcile.
+ pass
diff --git a/src/agentscope/app/_service/_chat.py b/src/agentscope/app/_service/_chat.py
index e96809b06..9c4db81a3 100644
--- a/src/agentscope/app/_service/_chat.py
+++ b/src/agentscope/app/_service/_chat.py
@@ -12,13 +12,19 @@ that wants them subscribes through the
``GET /sessions/{sid}/stream`` SSE endpoint.
"""
import asyncio
+from typing import TYPE_CHECKING
from fastapi import HTTPException
-from .._bus_ops import enqueue_run_trigger, publish_session_event
+from .._bus_ops import (
+ enqueue_channel_output,
+ enqueue_run_trigger,
+ publish_session_event,
+)
from ..message_bus import MessageBus, MessageBusKeys
from ..rag.knowledge_base_manager import KnowledgeBaseManagerBase
-from ..storage import StorageBase, AgentRecord, SessionRecord
+from ..channel import ChatKind
+from ..storage import StorageBase, AgentRecord, SessionRecord, SessionSource
from .._manager import BackgroundTaskManager, SchedulerManager
from ..workspace_manager import WorkspaceManagerBase
from ..middleware import (
@@ -57,6 +63,9 @@ from ..._utils._common import _generate_id
from ...message import AssistantMsg, Msg, ToolCallState
from ...permission import AdditionalWorkingDirectory
+if TYPE_CHECKING:
+ from ..channel import ChannelLifecycleDispatcher
+
class ChatService:
"""Run an agent against a session, persisting input/reply messages
@@ -87,6 +96,7 @@ class ChatService:
custom_subagent_templates: dict[str, SubAgentTemplate] | None = None,
custom_agent_cls: type[Agent] | None = None,
extra_projectors: list[EventProjector] | None = None,
+ channel_dispatcher: "ChannelLifecycleDispatcher | None" = None,
) -> None:
"""Initialize chat service.
@@ -145,6 +155,11 @@ class ChatService:
injection style). Each is invoked once per produced
event to mirror a UI feed onto another session; see
:class:`~agentscope.app._types.EventProjector`.
+ channel_dispatcher (`ChannelLifecycleDispatcher | None`, \
+optional):
+ The node's channel dispatcher, forwarded to
+ :func:`get_toolkit` so a channel-originated session's
+ agent gets that channel's platform tools.
"""
self._storage = storage
self._workspace_manager = workspace_manager
@@ -155,6 +170,7 @@ class ChatService:
self._knowledge_base_manager = knowledge_base_manager
self._extra_agent_middlewares = extra_agent_middlewares
self._extra_agent_tools = extra_agent_tools
+ self._channel_dispatcher = channel_dispatcher
self._sub_agent_templates = custom_subagent_templates
self._agent_cls = custom_agent_cls or Agent
self._projection = SessionProjection(message_bus)
@@ -467,6 +483,7 @@ class ChatService:
return True
async def _run_impl(
+ # pylint: disable=too-many-statements,too-many-branches
self,
user_id: str,
session_id: str,
@@ -651,6 +668,7 @@ class ChatService:
resource_access_service=self._access,
extra_factory=self._extra_agent_tools,
sub_agent_templates=self._sub_agent_templates,
+ channel_dispatcher=self._channel_dispatcher,
)
# ----------------------------------------------------------------
@@ -677,11 +695,60 @@ class ChatService:
# ----------------------------------------------------------------
# 5. Assemble the Agent.
# -----------------------------------------------------------------
+ attachment = f"You're within a session (id={session_id})."
+
+ # Channel-bound sessions: tell the agent which chat it serves.
+ if (
+ session_record.source_channel_id
+ and self._channel_dispatcher is not None
+ ):
+ channel = self._channel_dispatcher.get_local_channel(
+ session_record.source_channel_id,
+ )
+ if channel is not None:
+ tools = ", ".join(
+ t.name for t in await channel.list_tools(workspace)
+ )
+ chat_id = session_record.source_chat_id or ""
+ kind = await channel.chat_kind(chat_id)
+ name = await channel.chat_name(chat_id)
+ where = f' named "{name}"' if name else ""
+ attachment += (
+ f" This session is bound to a chat{where} on the "
+ f"{channel.display_name} platform: the messages, "
+ f"images and files people send there are relayed to "
+ f"you here, and your replies are delivered back to "
+ f"that same chat."
+ )
+ if 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:
+ attachment += (
+ " It is a one-to-one private chat with a single "
+ "user."
+ )
+ if tools:
+ attachment += (
+ f" You also have these {channel.display_name} "
+ f"tools available: {tools}."
+ )
+
+ attachment = (
+ f"<system-notification>{attachment}</system-notification>"
+ )
+ system_prompt = (
+ agent_record.data.system_prompt + "\n\n" + attachment
+ )
+
agent_state = session_record.state
agent_state.session_id = session_id
agent = self._agent_cls(
name=agent_record.data.name,
- system_prompt=agent_record.data.system_prompt,
+ system_prompt=system_prompt,
model=model,
toolkit=toolkit,
model_config=ModelConfig(fallback_model=fallback_model),
@@ -715,6 +782,22 @@ class ChatService:
lock_key,
ttl_secs=MessageBusKeys.SESSION_RUN_TTL_SECS,
):
+ # Channel-bound run: signal the output forwarder so the reply
+ # is streamed back to the platform chat. Covers scheduled /
+ # background wakes, not just inbound channel messages.
+ if (
+ session_record.source == SessionSource.CHANNEL
+ and session_record.source_channel_id
+ and session_record.source_chat_id
+ ):
+ await enqueue_channel_output(
+ self._message_bus,
+ session_id=session_id,
+ channel_id=session_record.source_channel_id,
+ chat_id=session_record.source_chat_id,
+ user_id=user_id,
+ agent_id=agent_id,
+ )
reply_msg: Msg | None = None
try:
if input_msg is None or isinstance(input_msg, (Msg, list)):
@@ -787,6 +870,38 @@ class ChatService:
elif input_msg:
reply_msg.append_event(input_msg)
+ # Broadcast the applied decision so observers that
+ # didn't make it (other tabs, the channel card) close it.
+ if isinstance(
+ input_msg,
+ (UserConfirmResultEvent, ExternalExecutionResultEvent),
+ ):
+ await publish_session_event(
+ self._message_bus,
+ session_id,
+ input_msg.model_dump(mode="json"),
+ )
+
+ # Emit a synthetic REPLY_START so SSE subscribers
+ # (frontend, channel gateway) can detect the
+ # continuation without requiring special handling.
+ #
+ # IMPORTANT: The frontend SSE handler must NOT clear
+ # its accumulated message buffer upon receiving a
+ # REPLY_START with the same reply_id as the current
+ # message. This event signals a continuation (e.g.
+ # after an approval flow), not a fresh reply.
+ continuation_start = ReplyStartEvent(
+ session_id=session_id,
+ reply_id=agent.state.reply_id,
+ name=agent_record.data.name,
+ )
+ await publish_session_event(
+ self._message_bus,
+ session_id,
+ continuation_start.model_dump(mode="json"),
+ )
+
async for event in agent.reply_stream(inputs=input_msg):
# Apply to the persisted reply FIRST (synchronous),
# then publish/project — see Case A above.
diff --git a/src/agentscope/app/_service/_model.py b/src/agentscope/app/_service/_model.py
index 6d1134490..1057643c3 100644
--- a/src/agentscope/app/_service/_model.py
+++ b/src/agentscope/app/_service/_model.py
@@ -4,6 +4,7 @@ from ._access import ResourceAccessService
from ..storage import ChatModelConfig
from ...credential import CredentialFactory
from ...model import ChatModelBase
+from ..._logging import logger
async def get_model(
@@ -50,8 +51,23 @@ async def get_model(
if config.parameters
else None
)
- return model_cls(
+ model = model_cls(
credential=credential,
model=config.model,
parameters=parameters,
)
+
+ # Override the formatter's input types with the built-in model card's
+ # when one matches; custom models have no card, so keep the default.
+ try:
+ for card in model_cls.list_models():
+ if card.name == config.model:
+ model.formatter.input_types = card.input_types
+ break
+ except Exception: # pylint: disable=broad-except
+ logger.debug(
+ "Failed to look up model card for %s, using formatter defaults.",
+ config.model,
+ )
+
+ return model
diff --git a/src/agentscope/app/_service/_toolkit.py b/src/agentscope/app/_service/_toolkit.py
index d0c6ef93d..ac381cdbe 100644
--- a/src/agentscope/app/_service/_toolkit.py
+++ b/src/agentscope/app/_service/_toolkit.py
@@ -6,7 +6,7 @@ workspace builtins, MCPs, skills, planning tools (Task*), background-task
control (ToolStop), schedule control (Schedule*), team participation
tools, and caller-supplied extras — into one :class:`Toolkit`.
"""
-from typing import Any, Literal
+from typing import Any, Literal, TYPE_CHECKING
from .._manager import BackgroundTaskManager, SchedulerManager
from ..message_bus import MessageBus
@@ -33,6 +33,9 @@ from ...workspace import WorkspaceBase
from ..access import ResourceKind
from ._access import ResourceAccessService
+if TYPE_CHECKING:
+ from ..channel import ChannelLifecycleDispatcher
+
async def get_toolkit(
*,
@@ -49,6 +52,7 @@ async def get_toolkit(
resource_access_service: ResourceAccessService,
extra_factory: AgentToolFactory | None = None,
sub_agent_templates: dict[str, SubAgentTemplate] | None = None,
+ channel_dispatcher: "ChannelLifecycleDispatcher | None" = None,
) -> Toolkit:
"""Assemble the complete :class:`Toolkit` for one chat turn.
@@ -74,6 +78,9 @@ async def get_toolkit(
(``TeamCreate / AgentCreate / TeamSay / TeamDelete``, plus
``AgentInvite`` when the user has at least one invitable agent).
6. Caller-supplied extras (``extra_factory``)
+ 7. Channel platform tools — only for a session that originated from
+ a channel; the channel exposes them via
+ :meth:`ChannelBase.list_tools` (e.g. send a file to another user).
Plus the workspace's skills and MCPs, which become the toolkit's
``skills_or_loaders`` and ``mcps`` parameters.
@@ -122,6 +129,10 @@ optional):
Passed to the ``AgentCreate`` tool so it can route to
the appropriate template when a ``subagent_type`` is
specified by the leader agent.
+ channel_dispatcher (`ChannelLifecycleDispatcher | None`, optional):
+ The node's channel dispatcher. When the session came from a
+ channel, its local channel is resolved through this to attach
+ that channel's platform tools. ``None`` disables them.
Returns:
`Toolkit`: Fully populated toolkit (tools + skills + MCPs).
@@ -243,6 +254,17 @@ time or interval"
for mw in middlewares:
tools.extend(await mw.list_tools())
+ # Channel platform tools — when this session originated from a
+ # channel, ask that channel (resolved locally; every node runs every
+ # channel) for the tools it lets the agent call, e.g. send a file to
+ # another user. Mirrors ``workspace.list_tools`` / ``mw.list_tools``.
+ if session_record.source_channel_id and channel_dispatcher is not None:
+ channel = channel_dispatcher.get_local_channel(
+ session_record.source_channel_id,
+ )
+ if channel is not None:
+ tools += await channel.list_tools(workspace)
+
return Toolkit(
tools=tools,
skills_or_loaders=await workspace.list_skills(),
diff --git a/src/agentscope/app/channel/__init__.py b/src/agentscope/app/channel/__init__.py
new file mode 100644
index 000000000..fd77b25a6
--- /dev/null
+++ b/src/agentscope/app/channel/__init__.py
@@ -0,0 +1,39 @@
+# -*- coding: utf-8 -*-
+"""Channel module — connect AgentScope agents to IM platforms.
+
+Channels translate a platform (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
+reconciled with storage.
+"""
+from ._base import (
+ ChannelBase,
+ ChannelCapability,
+ ChannelConfirmationResultEvent,
+ ChannelEvent,
+ ChannelStatus,
+ ChatKind,
+)
+from ._dispatcher import ChannelLifecycleDispatcher
+from ._errors import ChannelError
+from ._gateway import ChannelGateway
+from ._registry import ChannelTypeRegistry, ChannelTypeSchema
+from ._discord import DiscordChannel
+from ._feishu import FeishuChannel
+
+__all__ = [
+ "ChannelBase",
+ "ChannelCapability",
+ "ChannelConfirmationResultEvent",
+ "ChannelError",
+ "ChannelEvent",
+ "ChannelStatus",
+ "ChatKind",
+ "ChannelGateway",
+ "ChannelLifecycleDispatcher",
+ "ChannelTypeRegistry",
+ "ChannelTypeSchema",
+ "DiscordChannel",
+ "FeishuChannel",
+]
diff --git a/src/agentscope/app/channel/_base.py b/src/agentscope/app/channel/_base.py
new file mode 100644
index 000000000..60ca91334
--- /dev/null
+++ b/src/agentscope/app/channel/_base.py
@@ -0,0 +1,438 @@
+# -*- coding: utf-8 -*-
+"""Channel base abstractions: events, capability, and the channel base.
+
+A channel has exactly three concerns: keep a long-lived connection,
+normalise platform payloads into :class:`ChannelEvent` /
+:class:`ChannelConfirmationResultEvent` and emit them, and send the
+gateway's outbound instructions back to the platform.
+
+The channel never imports or holds the gateway; it receives an ``emit``
+callback via :meth:`start_listening` and calls it. The dispatcher, in
+turn, only feeds the channel a run's event stream via ``send_response``
+(the channel folds and renders it) plus ``send_reaction`` — never its
+connection loop.
+"""
+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 pydantic import BaseModel, Field, TypeAdapter
+
+from ...event import AgentEvent
+from ...message import (
+ DataBlock,
+ Msg,
+ TextBlock,
+ ThinkingBlock,
+ ToolCallBlock,
+ ToolResultBlock,
+)
+from ...types import ReplyFinishedReason
+
+if TYPE_CHECKING:
+ from ...tool import ToolBase
+ from ...workspace import WorkspaceBase
+
+_NO_TEXT_REPLY = "(Agent returned no text content)"
+_AGENT_ERROR_REPLY = (
+ "❌ Agent encountered an error. Please check the agent configuration."
+)
+# Deserialize a bus event dict back into its typed AgentEvent.
+_EVENT_ADAPTER: TypeAdapter = TypeAdapter(AgentEvent)
+
+
+class ChannelEvent(BaseModel):
+ """A normalised inbound message from an external platform.
+
+ ``content`` reuses the same ``TextBlock`` / ``DataBlock`` types as
+ ``Msg.content`` so the pipeline can hand it to the agent without a
+ conversion step.
+ """
+
+ channel_id: str
+ """Source channel instance identifier."""
+
+ channel_user_id: str
+ """Platform-side unique user identifier."""
+
+ channel_user_name: str = ""
+ """Platform-side user display name, when the channel can provide it
+ cheaply; the gateway falls back to ``channel_user_id`` otherwise."""
+
+ chat_id: str
+ """Platform-side chat/group identifier. Drives session grouping and
+ routing-rule matching."""
+
+ chat_name: str = ""
+ """Human-readable chat/group title, when the channel can provide it
+ cheaply; used to name the derived session."""
+
+ channel_message_id: str | None = None
+ """Platform-side message id, for reply referencing."""
+
+ content: list[TextBlock | DataBlock] = Field(default_factory=list)
+ """Unified content blocks — the single source of truth for content."""
+
+ metadata: dict[str, Any] = Field(default_factory=dict)
+ """Platform-specific metadata: chat_type, tenant_key, etc. Available
+ to routing rules via ``match_key``."""
+
+ received_at: str = Field(
+ default_factory=lambda: datetime.now().isoformat(),
+ )
+
+ @property
+ def message(self) -> str:
+ """Concatenate all ``TextBlock`` texts (convenience accessor)."""
+ return "".join(
+ block.text
+ for block in self.content
+ if isinstance(block, TextBlock)
+ )
+
+
+class ChannelConfirmationResultEvent(BaseModel):
+ """A user's decision on a pending tool-approval, delivered inbound.
+
+ Enters through the *same* gateway entry point as messages. Carries
+ only lookup keys — the authoritative pending tool call is read from
+ the session state, never trusted from this round-tripped payload.
+ """
+
+ channel_id: str
+ """Source channel instance identifier."""
+
+ chat_id: str
+ """Platform chat the decision came from; routes to the session."""
+
+ channel_user_id: str
+ """Platform user who decided; routes to the session."""
+
+ agent_id: str = ""
+ """Target agent resolved when the card was sent; used directly on
+ click so a re-route or metadata-based rule can't misroute the
+ decision. Empty on older cards → fall back to routing."""
+
+ session_id: str = ""
+ """Target session resolved when the card was sent; paired with
+ ``agent_id`` to resume the exact run that is asking."""
+
+ tool_call_id: str
+ """Id of the tool call being answered — the correlation key, matched
+ against the session's awaiting confirmations."""
+
+ approved: bool
+ """The user's decision."""
+
+ actor: str = ""
+ """Platform-side id of whoever made the decision (for audit)."""
+
+
+class ChannelStatus(BaseModel):
+ """Live connection status of a running channel adapter — owned and
+ updated by the adapter itself; read by the dispatcher's status API.
+
+ ``state`` transitions (all set by the adapter):
+ ``stopped`` (default / on teardown) → ``connecting`` → ``connected``;
+ ``retrying`` while reconnecting after a drop; ``failed`` when the
+ adapter gave up (parked, no more retries until the channel is edited).
+ """
+
+ state: str = "stopped"
+ last_error: str = ""
+
+
+class ChatKind(str, Enum):
+ """A chat's audience shape, used to tailor the agent's context.
+
+ ``GROUP`` — many participants; ``PRIVATE`` — a 1:1 conversation.
+ Unknown / not-applicable is represented by ``None`` at call sites,
+ not an enum member.
+ """
+
+ GROUP = "group"
+ PRIVATE = "private"
+
+
+class ChannelCapability(BaseModel):
+ """Platform capability declaration for gateway degradation decisions.
+
+ All flags describe the send direction (agent → platform).
+ """
+
+ text: bool = True
+ markdown: bool = False
+ image: bool = False
+ file: bool = False
+ interactive: bool = False
+ """Whether the platform can present an interactive confirmation UI.
+ Declarative metadata; each channel renders approvals in its own
+ ``send_response`` (a card, a text prompt, ...)."""
+
+ streaming: bool = False
+ """Whether the platform can update one reply message in place. A
+ channel decides how to render inside ``send_response``; this is
+ declarative metadata for the management UI."""
+
+ max_message_length: int = 4000
+ """Max characters per message; longer replies are split before send."""
+
+
+class ChannelBase(ABC):
+ """Abstract base for platform channels.
+
+ A subclass fully describes its platform type on the class itself, so
+ the service can register it from :func:`~agentscope.app.create_app`
+ (``channels=[FeishuChannel, ...]``) without a separate registry
+ table:
+
+ - :attr:`channel_type` / :attr:`display_name` /
+ :attr:`platform_bot_id_field` — type metadata;
+ - nested :class:`Credentials` / :class:`Config` — the credential and
+ option models, overridden by each subclass; the service renders
+ their JSON Schema as frontend forms and validates against them;
+ - ``__init__(channel_id, credentials, config)`` — the uniform
+ construction contract; instances are built per stored channel with
+ that channel's validated ``Credentials`` / ``Config``.
+ """
+
+ channel_type: str
+ """Unique platform type id (e.g. ``"feishu"``). Subclasses set this."""
+
+ display_name: str
+ """Human-readable platform name for the management UI."""
+
+ platform_bot_id_field: str
+ """Credential field that uniquely identifies the bot, used to reject
+ binding the same bot to two channels."""
+
+ description: str = ""
+ """One-line platform description for the management UI."""
+
+ icon_url: str = ""
+ """Brand icon URL for the management UI; empty falls back to a
+ generated avatar."""
+
+ class Credentials(BaseModel):
+ """Secret connection fields (app id, tokens, ...). Subclasses
+ override with their own fields; mark a field secret with
+ ``json_schema_extra={"format": "password"}``."""
+
+ class Config(BaseModel):
+ """Non-secret per-channel behaviour switches. Subclasses override;
+ left empty when the platform exposes no options."""
+
+ def __init__(
+ self,
+ channel_id: str,
+ credentials: "ChannelBase.Credentials",
+ config: "ChannelBase.Config",
+ ) -> None:
+ """Build a channel from its validated credentials and config.
+
+ Args:
+ channel_id (`str`): This channel instance's unique id.
+ credentials (`ChannelBase.Credentials`): Validated secrets.
+ config (`ChannelBase.Config`): Validated platform options.
+ """
+
+ capabilities: ChannelCapability = ChannelCapability()
+
+ status: ChannelStatus
+ """Live connection status; each channel creates its own in ``__init__``
+ (``self.status = ChannelStatus()``) and updates it. Read via the
+ dispatcher's status API."""
+
+ _emit: (
+ Callable[
+ ["ChannelEvent | ChannelConfirmationResultEvent"],
+ Awaitable[None],
+ ]
+ | None
+ ) = None
+ """Gateway entry point, stored by :meth:`start_listening`. Channels
+ dispatch normalised events via ``await self._emit(event)`` and must
+ not access any other gateway state."""
+
+ # -- Identity & connection --
+
+ @property
+ @abstractmethod
+ def channel_id(self) -> str:
+ """The unique channel instance identifier."""
+
+ @abstractmethod
+ async def start_listening(
+ self,
+ emit: Callable[
+ ["ChannelEvent | ChannelConfirmationResultEvent"],
+ Awaitable[None],
+ ],
+ ) -> None:
+ """Store ``emit``, set up resources, then connect and loop
+ receiving events — normalising each into a ``ChannelEvent`` and
+ ``await self._emit(event)`` (auto-reconnect) — releasing
+ resources in a ``finally``. The sole connection-lifecycle method.
+
+ Args:
+ emit (`Callable`): Gateway callback for inbound events; store
+ as ``self._emit`` and call ``await self._emit(event)``.
+ """
+
+ # -- Outbound (agent service → platform). Dispatcher-invoked. --
+
+ @abstractmethod
+ async def send_response(
+ self,
+ event: ChannelEvent,
+ events: AsyncIterator[dict],
+ ) -> None:
+ """Consume the run's agent-event stream and deliver the reply.
+
+ Accumulate the events into a ``Msg`` (:meth:`Msg.append_event`,
+ via :data:`_EVENT_ADAPTER`), render with :meth:`_render`, and send
+ to the platform — streaming or one-shot as the channel chooses;
+ present a confirmation when the run parks.
+
+ Args:
+ event (`ChannelEvent`): The send target (chat id).
+ events (`AsyncIterator[dict]`): The run's session events.
+ """
+
+ def _render(
+ self,
+ reply: Msg | None,
+ *,
+ show_thinking: bool = False,
+ show_tool_process: bool = False,
+ ) -> list[TextBlock | DataBlock]:
+ """Render an accumulated reply into deliverable blocks. The caller
+ (each channel) passes its own ``Config`` flags — the base makes no
+ assumptions about how a subclass stores them.
+
+ Args:
+ reply (`Msg | None`): The accumulated reply.
+ show_thinking (`bool`): Include thinking blocks inline.
+ show_tool_process (`bool`): Include tool call/result inline.
+
+ Returns:
+ `list[TextBlock | DataBlock]`: Text (+ data) blocks to send.
+ """
+ if reply is None:
+ return []
+ parts: list[str] = []
+ data: list[DataBlock] = []
+ for block in reply.content:
+ if isinstance(block, TextBlock):
+ parts.append(block.text)
+ elif isinstance(block, DataBlock):
+ data.append(block)
+ elif isinstance(block, ThinkingBlock):
+ if show_thinking:
+ parts.append(f"\n💭 {block.thinking}\n")
+ elif isinstance(block, ToolCallBlock):
+ if show_tool_process:
+ parts.append(f"\n🔧 Calling tool: {block.name}\n")
+ elif isinstance(block, ToolResultBlock):
+ if show_tool_process and isinstance(block.output, str):
+ parts.append(block.output)
+ text = "".join(parts).strip()
+ if reply.finished_reason == ReplyFinishedReason.ERROR:
+ text = text or _AGENT_ERROR_REPLY
+ elif not text and not data:
+ text = _NO_TEXT_REPLY
+ blocks: list[TextBlock | DataBlock] = (
+ [TextBlock(text=text)] if text else []
+ )
+ blocks.extend(data)
+ return blocks
+
+ async def send_reaction( # pylint: disable=unused-argument
+ self,
+ event: ChannelEvent,
+ emoji_type: str,
+ ) -> str | None:
+ """Add an emoji reaction to the inbound message (e.g. "OnIt").
+
+ Args:
+ event (`ChannelEvent`): The inbound event to react to.
+ emoji_type (`str`): Platform emoji/reaction key.
+
+ Returns:
+ `str | None`: Reaction id for :meth:`remove_reaction`, or
+ ``None`` if unsupported.
+ """
+ return None
+
+ async def remove_reaction(
+ self,
+ event: ChannelEvent,
+ reaction_id: str,
+ ) -> None:
+ """Remove a reaction added by :meth:`send_reaction`. Default: no-op.
+
+ Args:
+ event (`ChannelEvent`): The inbound event that was reacted to.
+ reaction_id (`str`): The id returned by :meth:`send_reaction`.
+ """
+
+ # -- Optional management-UI helpers --
+
+ async def list_bot_chats(self) -> list[dict]:
+ """Fetch the bot's chats/groups as dicts with at least ``chat_id``
+ and ``name``. Default: empty (unsupported).
+ """
+ return []
+
+ async def chat_kind( # pylint: disable=unused-argument
+ self,
+ chat_id: str,
+ ) -> "ChatKind | None":
+ """Best-effort audience shape of ``chat_id`` (group vs 1:1), used
+ to tailor the agent's session context. Default: ``None`` unknown.
+
+ Args:
+ chat_id (`str`): The platform chat to classify.
+ """
+ return None
+
+ async def chat_name( # pylint: disable=unused-argument
+ self,
+ chat_id: str,
+ ) -> str:
+ """Best-effort human display name of ``chat_id`` (e.g. a group
+ title), used to tailor the agent's context. Default: ``""``.
+
+ Args:
+ chat_id (`str`): The platform chat to name.
+ """
+ return ""
+
+ # -- Agent-callable tools --
+
+ async def list_tools( # pylint: disable=unused-argument
+ self,
+ workspace: "WorkspaceBase",
+ ) -> list["ToolBase"]:
+ """Platform tools exposed to the agent — e.g. send a file to a
+ different user/group than the conversation. Default: none.
+
+ Args:
+ workspace (`WorkspaceBase`): The calling session's workspace,
+ so file-sending tools read from it, not the host.
+ """
+ return []
+
+ def _split_long_message(self, text: str) -> list[str]:
+ """Split text into chunks within the platform length limit.
+
+ Args:
+ text (`str`): The text to split.
+ """
+ limit = self.capabilities.max_message_length
+ if len(text) <= limit:
+ return [text]
+ return [text[i : i + limit] for i in range(0, len(text), limit)]
diff --git a/src/agentscope/app/channel/_decision.py b/src/agentscope/app/channel/_decision.py
new file mode 100644
index 000000000..94e075f01
--- /dev/null
+++ b/src/agentscope/app/channel/_decision.py
@@ -0,0 +1,102 @@
+# -*- coding: utf-8 -*-
+"""Stateless tool-approval resume.
+
+The awaiting confirmation is read straight from the session state (the
+single source of truth) and the run is resumed with the decision — no
+server-side pending record. A decision that no longer matches an
+ASKING tool call (stale click, double click) is ignored, giving
+idempotency for free.
+"""
+from ...event import ConfirmResult, UserConfirmResultEvent
+from ...message import ToolCallBlock, ToolCallState
+from .._bus_ops import enqueue_run_trigger
+from ..message_bus import MessageBus, MessageBusKeys
+from ..storage import StorageBase
+
+
+async def _load_awaiting(
+ storage: StorageBase,
+ *,
+ user_id: str,
+ agent_id: str,
+ session_id: str,
+) -> tuple[list[ToolCallBlock], str]:
+ """Load a session's ASKING tool calls and its current reply id.
+
+ Args:
+ storage (`StorageBase`): Application storage.
+ user_id (`str`): Owner of the session.
+ agent_id (`str`): The routed agent.
+ session_id (`str`): The derived session.
+
+ Returns:
+ `tuple[list[ToolCallBlock], str]`: The tool calls awaiting user
+ confirmation, and ``state.reply_id`` (empty when absent).
+ """
+ session = await storage.get_session(
+ user_id=user_id,
+ agent_id=agent_id,
+ session_id=session_id,
+ )
+ agent = await storage.get_agent(user_id=user_id, agent_id=agent_id)
+ if session is None or agent is None:
+ return [], ""
+ asking = [
+ tc
+ for tc in session.state.get_awaiting_tool_calls(agent.data.name)
+ if tc.state == ToolCallState.ASKING
+ ]
+ return asking, session.state.reply_id
+
+
+async def resume_after_decision(
+ bus: MessageBus,
+ storage: StorageBase,
+ *,
+ user_id: str,
+ agent_id: str,
+ session_id: str,
+ tool_call_id: str,
+ approved: bool,
+) -> bool:
+ """Resume the run with a decision on ``tool_call_id``.
+
+ Reads the authoritative tool call from session state (ignoring the
+ caller's round-tripped copy); returns ``False`` — a no-op — when it
+ is not currently ASKING (stale/already resolved).
+
+ Args:
+ bus (`MessageBus`): The application message bus.
+ storage (`StorageBase`): Application storage.
+ user_id (`str`): Owner of the session.
+ agent_id (`str`): The routed agent.
+ session_id (`str`): The derived session.
+ tool_call_id (`str`): The awaiting tool call to answer.
+ approved (`bool`): The user's decision.
+
+ Returns:
+ `bool`: Whether a resume was enqueued.
+ """
+ asking, reply_id = await _load_awaiting(
+ storage,
+ user_id=user_id,
+ agent_id=agent_id,
+ session_id=session_id,
+ )
+ tool_call = next((t for t in asking if t.id == tool_call_id), None)
+ if tool_call is None:
+ return False
+ await enqueue_run_trigger(
+ bus,
+ user_id=user_id,
+ session_id=session_id,
+ agent_id=agent_id,
+ kind=MessageBusKeys.WAKEUP_KIND_RESUME,
+ inputs=UserConfirmResultEvent(
+ reply_id=reply_id,
+ confirm_results=[
+ ConfirmResult(confirmed=approved, tool_call=tool_call),
+ ],
+ ),
+ )
+ return True
diff --git a/src/agentscope/app/channel/_discord/__init__.py b/src/agentscope/app/channel/_discord/__init__.py
new file mode 100644
index 000000000..212fba3c1
--- /dev/null
+++ b/src/agentscope/app/channel/_discord/__init__.py
@@ -0,0 +1,5 @@
+# -*- coding: utf-8 -*-
+"""Discord channel."""
+from ._channel import DiscordChannel
+
+__all__ = ["DiscordChannel"]
diff --git a/src/agentscope/app/channel/_discord/_channel.py b/src/agentscope/app/channel/_discord/_channel.py
new file mode 100644
index 000000000..4228cfca4
--- /dev/null
+++ b/src/agentscope/app/channel/_discord/_channel.py
@@ -0,0 +1,526 @@
+# -*- coding: utf-8 -*-
+"""Discord channel (discord.py, gateway WebSocket).
+
+discord.py is async-native and runs on the app event loop, so — unlike
+Feishu — there is no thread bridging: ``on_message`` and button callbacks
+``await self._emit(...)`` directly. On a button click the channel freezes
+its own card and emits a ``ChannelConfirmationResultEvent`` carrying the
+tool call's id.
+
+Note: this channel opens one gateway connection per node. Discord's own
+model expects one connection per shard; running many nodes for one bot
+needs shard coordination, which is out of scope here.
+"""
+import asyncio
+import base64
+import io
+from typing import AsyncIterator, Awaitable, Callable, TYPE_CHECKING
+
+from pydantic import BaseModel, Field
+
+from ...._logging import logger
+from ....event import ReplyEndEvent, RequireUserConfirmEvent
+from ....message import Base64Source, DataBlock, Msg, TextBlock
+from .._base import (
+ ChannelBase,
+ ChannelCapability,
+ ChannelEvent,
+ ChannelConfirmationResultEvent,
+ ChannelStatus,
+ ChatKind,
+ _EVENT_ADAPTER,
+)
+
+if TYPE_CHECKING:
+ import discord
+
+# Discord's hard limit is 2000 characters per message.
+_MAX_LEN = 2000
+# Give up (and park in 'failed') after this many connects that never came up.
+_MAX_CONNECT_ATTEMPTS = 2
+
+
+class DiscordChannel(ChannelBase):
+ """Discord platform channel."""
+
+ channel_type = "discord"
+ display_name = "Discord"
+ description = "Bot for Discord servers, channels and DMs."
+ icon_url = "https://www.google.com/s2/favicons?domain=discord.com&sz=128"
+ platform_bot_id_field = "application_id"
+
+ class Credentials(BaseModel):
+ """Discord bot credentials."""
+
+ bot_token: str = Field(
+ title="Bot Token",
+ json_schema_extra={"format": "password"},
+ )
+ application_id: str = Field(title="Application ID")
+
+ class Config(BaseModel):
+ """Discord platform options."""
+
+ only_at_reply: bool = Field(
+ default=True,
+ title="Reply only when mentioned",
+ description="In server channels, 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",
+ )
+
+ capabilities = ChannelCapability(
+ text=True,
+ markdown=True,
+ image=True,
+ file=True,
+ interactive=True,
+ max_message_length=_MAX_LEN,
+ )
+
+ def __init__(
+ self,
+ channel_id: str,
+ credentials: "DiscordChannel.Credentials",
+ config: "DiscordChannel.Config",
+ ) -> None:
+ """Read the bot token and options from the validated models.
+
+ Args:
+ channel_id (`str`):
+ This channel instance's unique id.
+ credentials (`DiscordChannel.Credentials`):
+ Validated bot credentials (token + application id).
+ config (`DiscordChannel.Config`):
+ Validated platform options.
+ """
+ self._channel_id = channel_id
+ self._bot_token = credentials.bot_token
+ self._config = config
+ self.status = ChannelStatus()
+ self._client: "discord.Client | None" = None
+ self._stopped = False
+
+ @property
+ def channel_id(self) -> str:
+ """The unique channel instance identifier."""
+ return self._channel_id
+
+ # -- Lifecycle --
+
+ async def start_listening(
+ self,
+ emit: Callable[
+ [ChannelEvent | ChannelConfirmationResultEvent],
+ Awaitable[None],
+ ],
+ ) -> None:
+ """Build the client, register the message handler, run the gateway
+ (discord.py self-reconnects), and close it on exit.
+
+ Args:
+ emit (`Callable`): Gateway callback for inbound events.
+ """
+ import discord
+
+ self._emit = emit
+ self.status.state = "connecting"
+ intents = discord.Intents.default()
+ intents.message_content = True
+ self._client = discord.Client(intents=intents)
+ ever_connected = False
+
+ @self._client.event
+ async def on_message(message: "discord.Message") -> None:
+ """discord.py inbound-message hook.
+
+ Args:
+ message (`discord.Message`): The inbound message.
+ """
+ await self._on_message(message)
+
+ @self._client.event
+ async def on_ready() -> None:
+ """Gateway is up — mark the channel connected."""
+ nonlocal ever_connected
+ ever_connected = True
+ self.status.state = "connected"
+ self.status.last_error = ""
+
+ try:
+ backoff = 1.0
+ attempts = 0
+ while not self._stopped:
+ try:
+ await self._client.start(self._bot_token)
+ except Exception as e: # pylint: disable=broad-except
+ if self._stopped:
+ break
+ self.status.state = "retrying"
+ self.status.last_error = str(e)
+ logger.exception(
+ "Discord '%s' client error",
+ self._channel_id,
+ )
+ if self._stopped:
+ break
+ # Give up only when we never connected (bad token). Park in
+ # 'failed'; editing the channel re-tries. Transient drops
+ # after a good connect keep retrying.
+ if not ever_connected:
+ attempts += 1
+ if attempts >= _MAX_CONNECT_ATTEMPTS:
+ self.status.state = "failed"
+ if not self.status.last_error:
+ self.status.last_error = "connect failed"
+ logger.error(
+ "Discord '%s' giving up after %d attempts: %s",
+ self._channel_id,
+ attempts,
+ self.status.last_error,
+ )
+ while not self._stopped:
+ await asyncio.sleep(30.0)
+ break
+ await asyncio.sleep(backoff)
+ backoff = min(backoff * 2, 30.0)
+ finally:
+ self._stopped = True
+ self.status.state = "stopped"
+ await self._client.close()
+
+ # -- Inbound --
+
+ async def _on_message(self, message: "discord.Message") -> None:
+ """Normalise an inbound message and emit it — ignoring own
+ messages, honouring ``only_at_reply``, downloading attachments.
+
+ Args:
+ message (`discord.Message`): The inbound discord.py message.
+ """
+ if message.author.id == self._client.user.id:
+ return # ignore our own messages
+ try:
+ is_dm = message.guild is None
+ me = self._client.user
+ if (
+ not is_dm
+ and self._config.only_at_reply
+ and me not in message.mentions
+ ):
+ return
+
+ text = message.content or ""
+ for token in (f"<@{me.id}>", f"<@!{me.id}>"):
+ text = text.replace(token, "")
+ text = text.strip()
+
+ content: list[TextBlock | DataBlock] = []
+ for attachment in message.attachments:
+ try:
+ data = await attachment.read()
+ except Exception: # pylint: disable=broad-except
+ logger.debug("Discord attachment download failed")
+ continue
+ content.append(
+ DataBlock(
+ source=Base64Source(
+ data=base64.b64encode(data).decode("ascii"),
+ media_type=attachment.content_type
+ or "application/octet-stream",
+ ),
+ name=attachment.filename,
+ ),
+ )
+ if text:
+ content.append(TextBlock(text=text))
+ if not content or not self._emit:
+ return
+
+ await self._emit(
+ ChannelEvent(
+ channel_id=self._channel_id,
+ channel_user_id=str(message.author.id),
+ chat_id=str(message.channel.id),
+ channel_message_id=str(message.id),
+ content=content,
+ metadata={"chat_type": "dm" if is_dm else "guild"},
+ ),
+ )
+ except Exception: # pylint: disable=broad-except
+ logger.exception(
+ "Discord '%s' message handling failed",
+ self._channel_id,
+ )
+
+ # -- Outbound --
+
+ async def send_response(
+ self,
+ event: ChannelEvent,
+ events: AsyncIterator[dict],
+ ) -> None:
+ """Accumulate the reply (non-streaming) and post it as text +
+ file attachments; present an approval card if the run parks.
+
+ Args:
+ event (`ChannelEvent`): The send target (chat id).
+ events (`AsyncIterator[dict]`): The run's session events.
+ """
+ import discord
+
+ channel = await self._channel(event.chat_id)
+ if channel is None:
+ return
+ reply: Msg | None = None
+ confirm: RequireUserConfirmEvent | None = None
+ async for raw in events:
+ evt = _EVENT_ADAPTER.validate_python(raw)
+ if isinstance(evt, RequireUserConfirmEvent):
+ confirm = evt
+ break
+ reply_id = getattr(evt, "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(evt)
+ if isinstance(evt, ReplyEndEvent):
+ break
+ for block in self._render(
+ reply,
+ show_thinking=self._config.show_thinking,
+ show_tool_process=self._config.show_tool_process,
+ ):
+ if isinstance(block, TextBlock):
+ for part in self._split_long_message(block.text):
+ if part:
+ await channel.send(part)
+ elif isinstance(block.source, Base64Source):
+ await channel.send(
+ file=discord.File(
+ io.BytesIO(base64.b64decode(block.source.data)),
+ filename=block.name or "attachment",
+ ),
+ )
+ if confirm is not None:
+ await self._present_confirm(event, confirm)
+
+ async def _present_confirm(
+ self,
+ event: ChannelEvent,
+ req: RequireUserConfirmEvent,
+ ) -> None:
+ """Post one allow/deny card per tool call; each button carries its
+ ``tool_call_id`` so the click self-correlates.
+
+ Args:
+ event (`ChannelEvent`): The send target, for its ``chat_id``.
+ req (`RequireUserConfirmEvent`): The approval request to show.
+ """
+ channel = await self._channel(event.chat_id)
+ if channel is None:
+ return
+ for tool in req.tool_calls:
+ await channel.send(
+ content="🛡️ Tool execution needs approval\n"
+ f"**Tool:** `{tool.name}`\n"
+ f"**Arguments:** {str(tool.input)[:800]}",
+ view=self._build_view(
+ tool.id,
+ event.metadata.get("agent_id", ""),
+ event.metadata.get("session_id", ""),
+ ),
+ )
+
+ async def list_bot_chats(self) -> list[dict]:
+ """List every text channel the bot can see as ``{chat_id, name}``."""
+ results: list[dict] = []
+ for guild in self._client.guilds:
+ for channel in guild.text_channels:
+ results.append(
+ {
+ "chat_id": str(channel.id),
+ "name": f"{guild.name}#{channel.name}",
+ },
+ )
+ return results
+
+ async def chat_kind(self, chat_id: str) -> ChatKind | None:
+ """Private for a DM channel, group otherwise; ``None`` if the
+ channel id can't be resolved.
+
+ Args:
+ chat_id (`str`): The Discord channel id as a string.
+ """
+ import discord
+
+ channel = await self._channel(chat_id)
+ if channel is None:
+ return None
+ return (
+ ChatKind.PRIVATE
+ if isinstance(channel, discord.DMChannel)
+ else ChatKind.GROUP
+ )
+
+ async def chat_name(self, chat_id: str) -> str:
+ """The channel's name; ``""`` for DMs or an unresolvable id.
+
+ Args:
+ chat_id (`str`): The Discord channel id as a string.
+ """
+ channel = await self._channel(chat_id)
+ return getattr(channel, "name", "") or "" if channel else ""
+
+ # -- Helpers --
+
+ async def _channel(
+ self,
+ chat_id: str,
+ ) -> "discord.abc.Messageable | None":
+ """Resolve a channel id (from cache, then fetch) to a channel.
+
+ Args:
+ chat_id (`str`):
+ The Discord channel id as a string.
+
+ Returns:
+ `discord.abc.Messageable | None`:
+ The channel, or ``None`` if the id is malformed.
+ """
+ try:
+ cid = int(chat_id)
+ except (TypeError, ValueError):
+ return None
+ return self._client.get_channel(
+ cid,
+ ) or await self._client.fetch_channel(
+ cid,
+ )
+
+ def _build_view(
+ self,
+ tool_call_id: str,
+ agent_id: str = "",
+ session_id: str = "",
+ ) -> "discord.ui.View":
+ """Build a two-button approval view whose callbacks freeze the card
+ and emit the decision for ``tool_call_id``.
+
+ Args:
+ tool_call_id (`str`): The tool call the buttons answer.
+ agent_id (`str`): Target agent, echoed on click to resume the
+ exact run without re-resolving routing.
+ session_id (`str`): Target session, echoed alongside
+ ``agent_id``.
+
+ Returns:
+ `discord.ui.View`: The allow/deny view for the card message.
+ """
+ # pylint: disable=protected-access
+ import discord
+
+ channel = self
+
+ class _ApprovalView(discord.ui.View):
+ """A persistent (never-timing-out) allow/deny button view."""
+
+ def __init__(self) -> None:
+ """Build the view with no timeout."""
+ super().__init__(timeout=None)
+
+ @discord.ui.button(
+ label="✅ Approve",
+ style=discord.ButtonStyle.green,
+ )
+ async def approve(
+ self,
+ interaction: "discord.Interaction",
+ _button: "discord.ui.Button",
+ ) -> None:
+ """Emit an approve decision.
+
+ Args:
+ interaction (`discord.Interaction`): The click.
+ _button (`discord.ui.Button`): The clicked button.
+ """
+ await channel._decide(
+ interaction,
+ tool_call_id,
+ True,
+ agent_id,
+ session_id,
+ )
+
+ @discord.ui.button(label="❌ Deny", style=discord.ButtonStyle.red)
+ async def deny(
+ self,
+ interaction: "discord.Interaction",
+ _button: "discord.ui.Button",
+ ) -> None:
+ """Emit a deny decision.
+
+ Args:
+ interaction (`discord.Interaction`): The click.
+ _button (`discord.ui.Button`): The clicked button.
+ """
+ await channel._decide(
+ interaction,
+ tool_call_id,
+ False,
+ agent_id,
+ session_id,
+ )
+
+ return _ApprovalView()
+
+ async def _decide(
+ self,
+ interaction: "discord.Interaction",
+ tool_call_id: str,
+ approved: bool,
+ agent_id: str = "",
+ session_id: str = "",
+ ) -> None:
+ """Freeze the card and emit the decision for ``tool_call_id``.
+
+ Args:
+ interaction (`discord.Interaction`): The click, for the card
+ message, chat id and clicking user.
+ tool_call_id (`str`): The tool call being answered.
+ approved (`bool`): The user's decision.
+ agent_id (`str`): Target agent pinned on the card at send
+ time; resumes the exact run without re-routing.
+ session_id (`str`): Target session pinned alongside
+ ``agent_id``.
+ """
+ await interaction.response.defer()
+ try:
+ await interaction.message.edit(
+ content="✅ Approved" if approved else "🚫 Denied",
+ view=None,
+ )
+ except Exception: # pylint: disable=broad-except
+ logger.debug("Discord card freeze failed")
+ if self._emit:
+ await self._emit(
+ ChannelConfirmationResultEvent(
+ channel_id=self._channel_id,
+ chat_id=str(interaction.channel_id),
+ channel_user_id=str(interaction.user.id),
+ agent_id=agent_id,
+ session_id=session_id,
+ tool_call_id=tool_call_id,
+ approved=approved,
+ ),
+ )
diff --git a/src/agentscope/app/channel/_dispatcher.py b/src/agentscope/app/channel/_dispatcher.py
new file mode 100644
index 000000000..8bf5812f5
--- /dev/null
+++ b/src/agentscope/app/channel/_dispatcher.py
@@ -0,0 +1,424 @@
+# -*- coding: utf-8 -*-
+"""ChannelLifecycleDispatcher — reconcile running instances with storage.
+
+One per node. Storage is the source of truth; this dispatcher makes the
+node's live channel set match the enabled records, driven by lifecycle
+notifications and a periodic sweep (which also self-heals lost
+notifications and refreshes the status heartbeat).
+
+It also forwards each channel-bound run's output back to the platform:
+on an outbound signal it subscribes to the run's event stream (gap-free
+— subscribe **first**, then replay the log, deduplicating by Redis-Stream
+``entry_id``) and hands that stream to the local channel's
+``send_response``, which folds and delivers it. The channel owns
+rendering (streaming, confirmation cards); the dispatcher only feeds it
+the events.
+"""
+import asyncio
+from contextlib import aclosing, asynccontextmanager
+from dataclasses import dataclass
+from typing import AsyncGenerator, AsyncIterator
+
+from ..._logging import logger
+from ..._utils._common import _generate_id
+from ...event import EventType
+from ..message_bus import MessageBus, MessageBusKeys
+from ..storage import ChannelRecord, StorageBase
+from ._base import (
+ ChannelBase,
+ ChannelConfirmationResultEvent,
+ ChannelEvent,
+ ChannelStatus,
+)
+from ._gateway import ChannelGateway
+from ._registry import ChannelTypeRegistry
+
+# Max seconds to wait for a channel-bound run's reply before giving up.
+RESPONSE_TIMEOUT_SECS = 60.0
+# TTL (seconds) of a node's per-channel status heartbeat.
+LIVENESS_TTL_SECS = 30
+
+# Events that end a reply's event stream.
+_TERMINAL_EVENTS = frozenset(
+ {EventType.REPLY_END, EventType.REQUIRE_USER_CONFIRM},
+)
+
+
+@dataclass
+class ChannelInstance:
+ """A running channel, its listener task, and the config version it
+ was started from (for reconcile)."""
+
+ channel: ChannelBase
+ task: asyncio.Task
+ version: str
+
+
+class ChannelLifecycleDispatcher:
+ """Reconciles this node's channel instances against storage."""
+
+ def __init__(
+ self,
+ storage: StorageBase,
+ message_bus: MessageBus,
+ type_registry: ChannelTypeRegistry,
+ gateway: ChannelGateway,
+ ) -> None:
+ """Bind dependencies and start with an empty instance table.
+
+ Args:
+ storage (`StorageBase`): Source of truth for channel records.
+ message_bus (`MessageBus`): Lifecycle / outbound signalling.
+ type_registry (`ChannelTypeRegistry`): Builds instances.
+ gateway (`ChannelGateway`): Inbound event orchestrator bound
+ into each started channel.
+ """
+ self._storage = storage
+ self._bus = message_bus
+ self._types = type_registry
+ self._gateway = gateway
+ self._instances: dict[str, ChannelInstance] = {}
+ self._node_id = _generate_id()
+ self._tasks: list[asyncio.Task] = []
+ self._forward_tasks: set[asyncio.Task] = set()
+
+ def get_local_channel(self, channel_id: str) -> ChannelBase | None:
+ """Return this node's live channel for ``channel_id``, if running —
+ how a channel-originated run's agent tools reach it.
+
+ Args:
+ channel_id (`str`): The channel to look up.
+ """
+ inst = self._instances.get(channel_id)
+ return inst.channel if inst else None
+
+ @asynccontextmanager
+ async def lifespan(self) -> AsyncIterator[None]:
+ """Start reconcile/heartbeat loops; stop all instances on exit."""
+ await self.reconcile()
+ self._tasks = [
+ asyncio.create_task(self._listen(), name="channel-lifecycle"),
+ asyncio.create_task(self._periodic(), name="channel-heartbeat"),
+ asyncio.create_task(self._outbound(), name="channel-outbound"),
+ ]
+ try:
+ yield
+ finally:
+ for task in (*self._tasks, *self._forward_tasks):
+ task.cancel()
+ await asyncio.gather(
+ *self._tasks,
+ *self._forward_tasks,
+ return_exceptions=True,
+ )
+ for cid in set(self._instances):
+ await self._stop(cid)
+
+ # -- Reconcile --
+
+ async def reconcile(self) -> None:
+ """Drive the local instance set to match enabled records."""
+ try:
+ records = await self._storage.list_all_channels()
+ except Exception: # pylint: disable=broad-except
+ logger.exception("channel reconcile: failed to list channels")
+ return
+ desired = {r.id: r for r in records if r.enabled}
+
+ for cid in set(self._instances) - set(desired):
+ await self._stop(cid)
+
+ for cid, record in desired.items():
+ inst = self._instances.get(cid)
+ # A channel that gave up (state 'failed') parks its task alive, so
+ # ``task.done()`` stays False and it is not restarted here; editing
+ # the channel bumps ``updated_at`` and re-triggers a fresh start.
+ if (
+ inst is None
+ or inst.version != record.updated_at
+ or inst.task.done()
+ ):
+ if inst is not None:
+ await self._stop(cid)
+ await self._start(record)
+
+ async def _start(self, record: ChannelRecord) -> None:
+ """Build, start, and register one channel from its record.
+
+ Args:
+ record (`ChannelRecord`): The enabled channel to start.
+ """
+ try:
+ channel = self._types.create_channel(
+ channel_type=record.channel_type,
+ channel_id=record.id,
+ credentials=record.credentials,
+ config=record.platform_config,
+ )
+ task = asyncio.create_task(
+ channel.start_listening(self._gateway.process),
+ name=f"channel-listener:{record.id}",
+ )
+ self._instances[record.id] = ChannelInstance(
+ channel,
+ task,
+ record.updated_at,
+ )
+ logger.info(
+ "channel '%s' (%s) started",
+ record.id,
+ record.channel_type,
+ )
+ except Exception: # pylint: disable=broad-except
+ logger.exception("channel '%s' failed to start", record.id)
+
+ async def _stop(self, channel_id: str) -> None:
+ """Cancel a channel's listener; its ``start_listening`` ``finally``
+ releases resources.
+
+ Args:
+ channel_id (`str`): The channel to stop; a no-op if not here.
+ """
+ inst = self._instances.pop(channel_id, None)
+ if inst is None:
+ return
+ inst.task.cancel()
+ try:
+ await inst.task
+ except (
+ asyncio.CancelledError,
+ Exception,
+ ): # pylint: disable=broad-except
+ pass
+ logger.info("channel '%s' stopped", channel_id)
+
+ # -- Loops --
+
+ async def _listen(self) -> None:
+ """Reconcile on each lifecycle notification (reconnect on drop)."""
+ backoff = 1.0
+ while True:
+ try:
+ async for _ in self._bus.subscribe(
+ MessageBusKeys.channel_lifecycle(),
+ ):
+ backoff = 1.0
+ await self.reconcile()
+ except asyncio.CancelledError: # pylint: disable=try-except-raise
+ raise
+ except Exception: # pylint: disable=broad-except
+ logger.warning("channel lifecycle subscription lost")
+ await asyncio.sleep(backoff)
+ backoff = min(backoff * 2, 30.0)
+
+ async def _outbound(self) -> None:
+ """Drain channel-output signals and forward each run's reply; the
+ per-run lease makes the at-least-once drain effectively once."""
+ await self._drain_outbound()
+ backoff = 1.0
+ while True:
+ try:
+ async for _ in self._bus.subscribe(
+ MessageBusKeys.channel_outbound_signal(),
+ ):
+ backoff = 1.0
+ await self._drain_outbound()
+ except asyncio.CancelledError: # pylint: disable=try-except-raise
+ raise
+ except Exception: # pylint: disable=broad-except
+ logger.warning("channel outbound subscription lost")
+ await asyncio.sleep(backoff)
+ backoff = min(backoff * 2, 30.0)
+
+ async def _drain_outbound(self) -> None:
+ """Forward every queued output signal this node can serve."""
+ try:
+ jobs = await self._bus.queue_drain(
+ MessageBusKeys.channel_outbound_queue(),
+ )
+ except Exception: # pylint: disable=broad-except
+ logger.exception("channel outbound drain failed")
+ return
+ for _entry_id, job in jobs:
+ inst = self._instances.get(job.get("channel_id", ""))
+ if inst is None:
+ # Not hosted here (reconcile lag). Under no-sharding every
+ # node hosts every enabled channel, so drop this stale one.
+ continue
+ task = asyncio.create_task(
+ self._forward(job, inst.channel),
+ name=f"channel-forward:{job.get('session_id', '')}",
+ )
+ self._forward_tasks.add(task)
+ task.add_done_callback(self._forward_tasks.discard)
+
+ # -- Output forwarding (a run's reply → the platform) --
+
+ async def _forward(self, job: dict, channel: ChannelBase) -> None:
+ """Feed one channel-bound run's event stream to ``send_response``.
+
+ The channel folds and delivers it (streaming, confirmation cards);
+ this only subscribes and hands over the stream.
+
+ Args:
+ job (`dict`):
+ ``{session_id, channel_id, chat_id, user_id, agent_id}``
+ from the outbound signal.
+ channel (`ChannelBase`): The local channel for ``channel_id``.
+ """
+ record = await self._storage.get_channel(job["channel_id"])
+ if record is None:
+ return
+ # Dedup across nodes: the drain is at-least-once, so claim a
+ # per-run lease first — only the winner forwards, the rest skip.
+ lock_key = MessageBusKeys.channel_forward_lease(job["session_id"])
+ if not await self._bus.try_lock(
+ lock_key,
+ ttl_secs=int(RESPONSE_TIMEOUT_SECS) + 10,
+ ):
+ return
+ # Synthetic send target — background runs have no inbound message.
+ # Carry the run's identity so a confirmation card can pin its exact
+ # target and skip routing re-resolution on click.
+ target = ChannelEvent(
+ channel_id=job["channel_id"],
+ channel_user_id="",
+ chat_id=job["chat_id"],
+ metadata={
+ "session_id": job["session_id"],
+ "agent_id": job["agent_id"],
+ },
+ )
+ try:
+ async with aclosing(
+ self._event_stream(job["session_id"]),
+ ) as events:
+ await asyncio.wait_for(
+ channel.send_response(target, events),
+ timeout=RESPONSE_TIMEOUT_SECS,
+ )
+ except (asyncio.TimeoutError, TimeoutError):
+ pass # leave whatever was delivered
+ except Exception: # pylint: disable=broad-except
+ logger.exception("channel send_response failed")
+ finally:
+ await self._bus.unlock(lock_key)
+
+ async def _event_stream(
+ self,
+ session_id: str,
+ ) -> AsyncGenerator[dict, None]:
+ """Yield a run's events gap-free, stopping after the terminal one.
+
+ Subscribe **first** (buffering live events), replay the log, then
+ go live — deduplicating by ``entry_id`` so the seam is neither
+ missed nor double-counted.
+
+ Args:
+ session_id (`str`): The run's session, whose events are read.
+
+ Yields:
+ `dict`: Each session event, up to and including the terminal
+ ``REPLY_END`` / ``REQUIRE_USER_CONFIRM``.
+ """
+ event_key = MessageBusKeys.session_events(session_id)
+ ready = asyncio.Event()
+ queue: asyncio.Queue[dict] = asyncio.Queue()
+ seen: set[str] = set()
+
+ async def feeder() -> None:
+ """Buffer live subscription events into the local queue."""
+ try:
+ async for evt in self._bus.subscribe(
+ event_key,
+ on_ready=ready.set,
+ ):
+ await queue.put(evt)
+ except asyncio.CancelledError:
+ pass
+
+ feeder_task = asyncio.create_task(feeder())
+ try:
+ await asyncio.wait_for(ready.wait(), timeout=5.0)
+ for entry_id, evt in await self._bus.log_read(
+ event_key,
+ max_count=MessageBusKeys.SESSION_REPLAY_MAX_LEN,
+ ):
+ seen.add(str(entry_id))
+ yield evt
+ if evt.get("type", "") in _TERMINAL_EVENTS:
+ return
+ while True:
+ evt = await queue.get()
+ eid = evt.get("_entry_id")
+ if eid is not None:
+ if str(eid) in seen:
+ continue
+ seen.add(str(eid))
+ yield evt
+ if evt.get("type", "") in _TERMINAL_EVENTS:
+ return
+ finally:
+ feeder_task.cancel()
+ try:
+ await feeder_task
+ except (
+ asyncio.CancelledError,
+ Exception,
+ ): # pylint: disable=broad-except
+ pass
+
+ async def _periodic(self) -> None:
+ """Periodic reconcile (self-heals lost lifecycle events)."""
+ interval = max(5.0, LIVENESS_TTL_SECS / 2)
+ while True:
+ await asyncio.sleep(interval)
+ await self.reconcile()
+
+ # -- Read APIs (for the router) --
+
+ async def get_status(self, channel_id: str) -> ChannelStatus:
+ """The channel's live connection status, or ``stopped`` if it is not
+ running here (disabled / not yet started).
+
+ Args:
+ channel_id (`str`): The channel to report on.
+ """
+ inst = self._instances.get(channel_id)
+ return inst.channel.status if inst else ChannelStatus(state="stopped")
+
+ async def list_bot_chats(self, channel_id: str) -> list[dict]:
+ """Chats the bot is in, via the local channel if running.
+
+ Args:
+ channel_id (`str`): The channel to query.
+ """
+ inst = self._instances.get(channel_id)
+ return await inst.channel.list_bot_chats() if inst else []
+
+ async def list_seen_chat_ids(self, channel_id: str) -> list[str]:
+ """Chat_ids passively recorded from inbound messages.
+
+ Args:
+ channel_id (`str`): The channel to list seen chats for.
+ """
+ fields = await self._bus.registry_getall(
+ MessageBusKeys.channel_seen_chats(channel_id),
+ )
+ return sorted(fields.keys())
+
+ async def dispatch(
+ self,
+ event: ChannelEvent | ChannelConfirmationResultEvent,
+ channel_id: str,
+ ) -> None:
+ """Route an event through the gateway (used by tests).
+
+ Args:
+ event (`ChannelEvent | ChannelConfirmationResultEvent`): The
+ event to route.
+ channel_id (`str`): The channel whose gateway handles it.
+ """
+ inst = self._instances.get(channel_id)
+ if inst:
+ await self._gateway.process(event)
diff --git a/src/agentscope/app/channel/_errors.py b/src/agentscope/app/channel/_errors.py
new file mode 100644
index 000000000..bc1051114
--- /dev/null
+++ b/src/agentscope/app/channel/_errors.py
@@ -0,0 +1,23 @@
+# -*- coding: utf-8 -*-
+"""Channel module exception."""
+
+
+class ChannelError(Exception):
+ """A channel operation failed.
+
+ Carries the HTTP status the router should surface, so one exception
+ covers every case (not-found → 404, duplicate bot → 409, bad request
+ → 400) without a subclass per case — the router reads
+ :attr:`status_code` and the message.
+ """
+
+ def __init__(self, message: str, status_code: int = 400) -> None:
+ """Bind the error message and the HTTP status to surface.
+
+ Args:
+ message (`str`): The human-readable error.
+ status_code (`int`, defaults to 400): The HTTP status the
+ router should return.
+ """
+ super().__init__(message)
+ self.status_code = status_code
diff --git a/src/agentscope/app/channel/_feishu/__init__.py b/src/agentscope/app/channel/_feishu/__init__.py
new file mode 100644
index 000000000..9931c2921
--- /dev/null
+++ b/src/agentscope/app/channel/_feishu/__init__.py
@@ -0,0 +1,5 @@
+# -*- coding: utf-8 -*-
+"""Feishu (Lark) channel."""
+from ._channel import FeishuChannel
+
+__all__ = ["FeishuChannel"]
diff --git a/src/agentscope/app/channel/_feishu/_card_templates.py b/src/agentscope/app/channel/_feishu/_card_templates.py
new file mode 100644
index 000000000..bdde0c695
--- /dev/null
+++ b/src/agentscope/app/channel/_feishu/_card_templates.py
@@ -0,0 +1,213 @@
+# -*- coding: utf-8 -*-
+"""Feishu interactive-card helpers for the tool-approval flow.
+
+The card round-trips lookup keys (``tool_call_id``, ``chat_id`` and the
+resolved ``agent_id`` / ``session_id``) plus the click's approve/deny —
+the authoritative tool call is read from session state on resume, never
+trusted from the card.
+"""
+import json
+from typing import Any
+
+_ACTION_TYPE = "tool_guard_approval"
+_APPROVE = "approve"
+_DENY = "deny"
+
+
+def _build_approval_card(
+ tool_call_id: str,
+ chat_id: str,
+ tool_name: str,
+ summary: str,
+ agent_id: str = "",
+ session_id: str = "",
+) -> str:
+ """Build the approval card (JSON string) for a pending tool call.
+
+ Args:
+ tool_call_id (`str`): The awaiting tool call the buttons answer.
+ chat_id (`str`): Chat the card is sent to, echoed on click for
+ session routing.
+ tool_name (`str`): Name of the tool, shown in the card body.
+ summary (`str`): A rendering of the tool arguments (truncated).
+ agent_id (`str`): Target agent, echoed on click to resume the
+ exact run without re-resolving routing.
+ session_id (`str`): Target session, echoed on click alongside
+ ``agent_id``.
+
+ Returns:
+ `str`: The card as a JSON string.
+ """
+ base = {
+ "type": _ACTION_TYPE,
+ "tool_call_id": tool_call_id,
+ "chat_id": chat_id,
+ "agent_id": agent_id,
+ "session_id": session_id,
+ }
+ body = f"**Tool:** `{tool_name}`"
+ if summary:
+ shown = summary if len(summary) <= 800 else summary[:799] + "…"
+ body += f"\n**Arguments:** {shown}"
+ card = {
+ "config": {"wide_screen_mode": True},
+ "header": {
+ "template": "orange",
+ "title": {
+ "tag": "plain_text",
+ "content": "🛡️ Tool execution needs approval",
+ },
+ },
+ "elements": [
+ {"tag": "markdown", "content": body},
+ {"tag": "hr"},
+ {
+ "tag": "action",
+ "actions": [
+ {
+ "tag": "button",
+ "text": {"tag": "plain_text", "content": "✅ Allow"},
+ "type": "primary",
+ "value": {**base, "action": _APPROVE},
+ },
+ {
+ "tag": "button",
+ "text": {"tag": "plain_text", "content": "❌ Deny"},
+ "type": "danger",
+ "value": {**base, "action": _DENY},
+ },
+ ],
+ },
+ ],
+ }
+ return json.dumps(card, ensure_ascii=False)
+
+
+def _resolved_card(approved: bool) -> dict:
+ """Build the post-decision card object that replaces the approval card.
+
+ Args:
+ approved (`bool`): The decision, selecting the colour and text.
+
+ Returns:
+ `dict`: The card object (schema 1.0).
+ """
+ return {
+ "config": {"wide_screen_mode": True},
+ "header": {
+ "template": "green" if approved else "red",
+ "title": {
+ "tag": "plain_text",
+ "content": "✅ Allowed" if approved else "🚫 Denied",
+ },
+ },
+ "elements": [
+ {
+ "tag": "markdown",
+ "content": (
+ "The tool was allowed to run."
+ if approved
+ else "The tool was denied."
+ ),
+ },
+ ],
+ }
+
+
+def _parse_action(
+ value: Any,
+) -> tuple[str, str, bool, str, str] | None:
+ """Parse a card button's value into ``(tool_call_id, chat_id,
+ approved, agent_id, session_id)``.
+
+ Args:
+ value (`Any`): The clicked button's ``value`` — a dict (or JSON
+ string) carrying ``type`` / ``tool_call_id`` / ``chat_id`` /
+ ``action`` / ``agent_id`` / ``session_id``.
+
+ Returns:
+ `tuple[str, str, bool, str, str] | None`: ``(tool_call_id,
+ chat_id, approved, agent_id, session_id)`` for a valid button,
+ or ``None`` if not one of ours.
+ """
+ if isinstance(value, str):
+ try:
+ value = json.loads(value)
+ except (json.JSONDecodeError, TypeError):
+ return None
+ if not isinstance(value, dict) or value.get("type") != _ACTION_TYPE:
+ return None
+ tool_call_id = str(value.get("tool_call_id") or "").strip()
+ chat_id = str(value.get("chat_id") or "").strip()
+ action = str(value.get("action") or "").strip().lower()
+ if not tool_call_id or action not in (_APPROVE, _DENY):
+ return None
+ agent_id = str(value.get("agent_id") or "").strip()
+ session_id = str(value.get("session_id") or "").strip()
+ return tool_call_id, chat_id, action == _APPROVE, agent_id, session_id
+
+
+def _build_toast(approved: bool) -> Any:
+ """Build a toast-only card-callback response (no card update).
+
+ Used for clicks we cannot act on (e.g. an unparseable button), where
+ the card should stay as-is.
+
+ Args:
+ approved (`bool`):
+ The decision, selecting the toast style and text.
+
+ Returns:
+ `Any`:
+ A ``P2CardActionTriggerResponse`` when lark_oapi is
+ importable, else a plain dict with the same shape.
+ """
+ return _wrap_response({"toast": _toast(approved)})
+
+
+def _build_action_response(approved: bool) -> Any:
+ """Build the card-callback response for a decision: a toast plus the
+ resolved card, so Feishu updates the clicked card in place — no
+ separate, rate-limit-racing PATCH.
+
+ Args:
+ approved (`bool`): The decision, selecting toast and card.
+
+ Returns:
+ `Any`: A ``P2CardActionTriggerResponse`` (or dict fallback).
+ """
+ return _wrap_response(
+ {
+ "toast": _toast(approved),
+ "card": {"type": "raw", "data": _resolved_card(approved)},
+ },
+ )
+
+
+def _toast(approved: bool) -> dict:
+ """The toast payload for a decision.
+
+ Args:
+ approved (`bool`): The decision, selecting style and text.
+ """
+ return {
+ "type": "success" if approved else "info",
+ "content": "Allowed" if approved else "Denied",
+ }
+
+
+def _wrap_response(body: dict) -> Any:
+ """Wrap a response body in ``P2CardActionTriggerResponse`` when the
+ SDK is importable, else return the plain dict.
+
+ Args:
+ body (`dict`): The callback response body (``toast`` / ``card``).
+ """
+ try:
+ from lark_oapi.event.callback.model.p2_card_action_trigger import (
+ P2CardActionTriggerResponse,
+ )
+
+ return P2CardActionTriggerResponse(body)
+ except (ImportError, AttributeError):
+ return body
diff --git a/src/agentscope/app/channel/_feishu/_channel.py b/src/agentscope/app/channel/_feishu/_channel.py
new file mode 100644
index 000000000..27b1e11f6
--- /dev/null
+++ b/src/agentscope/app/channel/_feishu/_channel.py
@@ -0,0 +1,1322 @@
+# -*- coding: utf-8 -*-
+"""Feishu (Lark) channel — new ChannelBase interface.
+
+Translates the Feishu platform to/from normalised events and emits them
+via the injected gateway callback. On a card click the channel freezes
+its own card and emits a ``ChannelConfirmationResultEvent`` (same entry
+as messages) carrying the tool call's id. No in-process approval futures
+or attachment buffers — the awaiting confirmation lives in session state.
+
+The WebSocket runs in a background thread (the lark SDK owns its own
+event loop); inbound events are bridged to the app loop with
+``run_coroutine_threadsafe``. Connection/reconnect is driven via the
+SDK's public ``start()`` — the one place to adapt if the SDK changes.
+"""
+import asyncio
+import base64
+import json
+import threading
+import time
+from typing import Any, AsyncIterator, Awaitable, Callable, TYPE_CHECKING
+
+from pydantic import BaseModel, Field
+
+from ...._logging import logger
+from ....event import ReplyEndEvent, RequireUserConfirmEvent
+from ....message import Base64Source, DataBlock, Msg, TextBlock
+from .._base import (
+ ChannelBase,
+ ChannelCapability,
+ ChannelEvent,
+ ChannelConfirmationResultEvent,
+ ChannelStatus,
+ ChatKind,
+ _EVENT_ADAPTER,
+)
+from ._card_templates import (
+ _build_action_response,
+ _build_approval_card,
+ _build_toast,
+ _parse_action,
+)
+
+if TYPE_CHECKING:
+ import httpx
+ from lark_oapi.api.im.v1 import EventMessage, P2ImMessageReceiveV1
+ from lark_oapi.event.callback.model.p2_card_action_trigger import (
+ P2CardActionTrigger,
+ P2CardActionTriggerResponse,
+ )
+ from .....tool import ToolBase
+ from .....workspace import WorkspaceBase
+
+_API = "https://open.feishu.cn/open-apis"
+_TOKEN_EXPIRED_CODES = frozenset({99991663, 99991664})
+_MEDIA_TYPES = frozenset({"image", "audio", "media", "file"})
+_STREAM_ELEMENT_ID = "md"
+# Minimum seconds between live streaming-card updates (throttle).
+_STREAM_MIN_INTERVAL = 0.7
+
+
+class _ThreadLoopProxy:
+ """Forward attribute access to the *current thread's* event loop.
+
+ ``lark_oapi.ws.client`` drives ``client.start()`` off one module-
+ global ``loop``. Replacing that global with this proxy makes every
+ ``loop.<attr>`` resolve to the loop of whichever thread is calling —
+ so multiple Feishu WS threads (one per bot) each use their own loop
+ instead of sharing one global.
+ """
+
+ def __getattr__(self, name: str) -> Any:
+ """Resolve any attribute on the current thread's event loop.
+
+ Args:
+ name (`str`): The loop attribute the SDK is reaching for.
+
+ Returns:
+ `Any`: The attribute from ``asyncio.get_event_loop()``.
+ """
+ return getattr(asyncio.get_event_loop(), name)
+
+
+_THREAD_LOOP_PROXY = _ThreadLoopProxy()
+
+# Give up (and let the dispatcher disable the channel) after this many
+# consecutive connects that never came up — the credentials are bad.
+_MAX_CONNECT_ATTEMPTS = 2
+
+
+class FeishuChannel(ChannelBase):
+ """Feishu platform channel (SDK long-connection mode)."""
+
+ channel_type = "feishu"
+ display_name = "Feishu (Lark)"
+ description = "Group and direct-message bot with card interactions."
+ icon_url = "https://www.google.com/s2/favicons?domain=feishu.cn&sz=128"
+ platform_bot_id_field = "app_id"
+
+ class Credentials(BaseModel):
+ """Feishu bot application credentials."""
+
+ app_id: str = Field(title="App ID", description="Feishu App ID")
+ app_secret: str = Field(
+ title="App Secret",
+ description="Feishu App Secret",
+ json_schema_extra={"format": "password"},
+ )
+
+ class Config(BaseModel):
+ """Feishu 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",
+ )
+
+ capabilities = ChannelCapability(
+ text=True,
+ markdown=True,
+ image=True,
+ file=True,
+ interactive=True,
+ streaming=True,
+ max_message_length=4000,
+ )
+
+ def __init__(
+ self,
+ channel_id: str,
+ credentials: "FeishuChannel.Credentials",
+ config: "FeishuChannel.Config",
+ ) -> None:
+ """Read the credentials and options from the validated models.
+
+ Args:
+ channel_id (`str`):
+ This channel instance's unique id.
+ credentials (`FeishuChannel.Credentials`):
+ Validated app id + secret.
+ config (`FeishuChannel.Config`):
+ Validated platform options.
+ """
+ self._channel_id = channel_id
+ self._app_id = credentials.app_id
+ self._app_secret = credentials.app_secret
+ self._config = config
+ self.status = ChannelStatus()
+ self._http: "httpx.AsyncClient | None" = None
+ self._token: str | None = None
+ self._bot_open_id: str | None = None
+ self._ws_thread: threading.Thread | None = None
+ self._stop = threading.Event()
+ self._loop: asyncio.AbstractEventLoop | None = None
+ # The WS thread's own loop, captured so teardown can stop it and
+ # unblock lark's otherwise-forever ``client.start()``.
+ self._ws_loop: asyncio.AbstractEventLoop | None = None
+ self._stream_seq: dict[str, int] = {}
+ self._chat_name_cache: dict[str, str] = {}
+ self._user_name_cache: dict[str, str] = {}
+ self._chat_kind_cache: dict[str, ChatKind] = {}
+
+ @property
+ def channel_id(self) -> str:
+ """The unique channel instance identifier."""
+ return self._channel_id
+
+ # -- Lifecycle --
+
+ async def start_listening(
+ self,
+ emit: Callable[
+ [ChannelEvent | ChannelConfirmationResultEvent],
+ Awaitable[None],
+ ],
+ ) -> None:
+ """Open the HTTP client, run the WS client (reconnecting with
+ backoff), and close everything on exit.
+
+ Args:
+ emit (`Callable`): Gateway callback for inbound events.
+ """
+ import httpx
+
+ self._emit = emit
+ self.status.state = "connecting"
+ self._loop = asyncio.get_running_loop()
+ self._http = httpx.AsyncClient(timeout=30.0)
+ backoff = 1.0
+ attempts = 0
+ ever_connected = False
+ try:
+ while not self._stop.is_set():
+ uptime = 0.0
+ try:
+ await self._refresh_token()
+ if self._bot_open_id is None:
+ info = await self._api("GET", f"{_API}/bot/v3/info")
+ self._bot_open_id = (
+ (info or {}).get("bot", {}).get("open_id")
+ )
+ self._ws_thread = self._launch_ws_thread()
+ while (
+ not self._stop.is_set() and self._ws_thread.is_alive()
+ ):
+ await asyncio.sleep(5.0)
+ uptime += 5.0
+ self.status.state = "connected"
+ self.status.last_error = ""
+ ever_connected = True
+ attempts = 0
+ except Exception as e: # pylint: disable=broad-except
+ self.status.state = "retrying"
+ self.status.last_error = str(e)
+ logger.exception(
+ "Feishu WS '%s' connect failed",
+ self._channel_id,
+ )
+ if self._stop.is_set():
+ break
+ # Give up only when we have NEVER connected — bad credentials
+ # never will. Park in 'failed' (keep the task alive so the
+ # dispatcher won't restart it); editing the channel re-tries.
+ # Transient drops after a good connect keep retrying.
+ if not ever_connected:
+ attempts += 1
+ if attempts >= _MAX_CONNECT_ATTEMPTS:
+ self.status.state = "failed"
+ if not self.status.last_error:
+ self.status.last_error = "connect failed"
+ logger.error(
+ "Feishu WS '%s' giving up after %d attempts: %s",
+ self._channel_id,
+ attempts,
+ self.status.last_error,
+ )
+ while not self._stop.is_set():
+ await asyncio.sleep(30.0)
+ break
+ backoff = 1.0 if uptime >= 60.0 else min(backoff * 2, 30.0)
+ logger.warning(
+ "Feishu WS '%s' exited, reconnecting in %.1fs",
+ self._channel_id,
+ backoff,
+ )
+ await asyncio.sleep(backoff)
+ finally:
+ self._stop.set()
+ self.status.state = "stopped"
+ # Stop the WS thread's loop so lark's ``client.start()`` (parked
+ # forever on ``run_until_complete(_select())``) returns; without
+ # this the daemon thread lingers and keeps delivering events
+ # after the channel is disabled/updated.
+ ws_loop = self._ws_loop
+ if ws_loop is not None:
+ try:
+ ws_loop.call_soon_threadsafe(ws_loop.stop)
+ except RuntimeError:
+ pass # loop already closed
+ if self._ws_thread and self._ws_thread.is_alive():
+ self._ws_thread.join(timeout=5.0)
+ if self._http:
+ await self._http.aclose()
+ self._http = None
+
+ def _launch_ws_thread(self) -> threading.Thread:
+ """Start the lark WS client on a daemon thread with its own loop.
+
+ Returns:
+ `threading.Thread`: The started WS thread (daemon).
+ """
+ try:
+ import lark_oapi as lark
+ except ImportError as e:
+ raise ImportError(
+ "Feishu channel requires 'lark-oapi' "
+ "(pip install lark-oapi).",
+ ) from e
+
+ loop = self._loop
+ assert loop is not None # set in start_listening before this runs
+
+ def on_message(data: "P2ImMessageReceiveV1") -> None:
+ """Bridge an inbound message onto the app loop.
+
+ Args:
+ data (`P2ImMessageReceiveV1`): The SDK message event.
+ """
+ asyncio.run_coroutine_threadsafe(self._on_message(data), loop)
+
+ def on_card_action(
+ data: "P2CardActionTrigger",
+ ) -> "P2CardActionTriggerResponse":
+ """Handle a card click; return the toast ack.
+
+ Args:
+ data (`P2CardActionTrigger`): The SDK card-action event.
+ """
+ return self._on_card_action(data, loop)
+
+ def ignore(_data: object) -> None:
+ """No-op for subscribed events we don't act on, so the SDK
+ doesn't log 'processor not found'."""
+
+ handler = (
+ lark.EventDispatcherHandler.builder("", "")
+ .register_p2_im_message_receive_v1(on_message)
+ .register_p2_card_action_trigger(on_card_action)
+ .register_p2_im_message_reaction_created_v1(ignore)
+ .register_p2_im_message_reaction_deleted_v1(ignore)
+ .build()
+ )
+ client = lark.ws.Client(
+ self._app_id,
+ self._app_secret,
+ event_handler=handler,
+ log_level=lark.LogLevel.INFO,
+ )
+
+ def run() -> None:
+ """Run the blocking WS client on this thread's own loop."""
+ try:
+ # lark's ws client drives one import-time global loop; give
+ # this thread its own loop + a proxy so bots don't share it.
+ import lark_oapi.ws.client as _ws_client
+
+ thread_loop = asyncio.new_event_loop()
+ asyncio.set_event_loop(thread_loop)
+ self._ws_loop = thread_loop
+ _ws_client.loop = _THREAD_LOOP_PROXY
+ client.start() # blocks on this thread's loop until closed
+ except Exception as e: # pylint: disable=broad-except
+ if not self._stop.is_set():
+ self.status.state = "retrying"
+ self.status.last_error = str(e)
+ logger.exception(
+ "Feishu WS '%s' crashed",
+ self._channel_id,
+ )
+
+ thread = threading.Thread(
+ target=run,
+ name=f"feishu-ws:{self._channel_id}",
+ daemon=True,
+ )
+ thread.start()
+ return thread
+
+ # -- Inbound (WS thread → app loop) --
+
+ async def _on_message(self, data: "P2ImMessageReceiveV1") -> None:
+ """Normalise an inbound message and emit it (media or text).
+
+ Args:
+ data (`P2ImMessageReceiveV1`):
+ The inbound message-receive event from the SDK.
+ """
+ try:
+ event = await self._normalize(data)
+ if event and self._emit:
+ await self._emit(event)
+ except Exception: # pylint: disable=broad-except
+ logger.exception(
+ "Feishu '%s' message handling failed",
+ self._channel_id,
+ )
+
+ async def _normalize(
+ self,
+ data: "P2ImMessageReceiveV1",
+ ) -> ChannelEvent | None:
+ """Convert an inbound Feishu message into a ``ChannelEvent``,
+ downloading media and honouring ``only_at_reply`` in groups.
+
+ Args:
+ data (`P2ImMessageReceiveV1`):
+ The inbound message-receive event.
+
+ Returns:
+ `ChannelEvent | None`:
+ The normalised event, or ``None`` when there is nothing
+ to act on.
+ """
+ message = getattr(data.event, "message", None)
+ sender = getattr(data.event, "sender", None)
+ if message is None or sender is None:
+ return None
+
+ user_id = ""
+ if sender.sender_id:
+ user_id = sender.sender_id.open_id or ""
+ chat_id = message.chat_id or ""
+ chat_type = message.chat_type or ""
+ message_id = message.message_id or ""
+ meta = {
+ "chat_type": chat_type,
+ "tenant_key": data.header.tenant_key if data.header else "",
+ }
+ if chat_id and chat_type in ("group", "p2p"):
+ self._chat_kind_cache[chat_id] = (
+ ChatKind.GROUP if chat_type == "group" else ChatKind.PRIVATE
+ )
+
+ # @-gate up front so unmentioned group media is dropped too — it
+ # used to skip the check, get downloaded, and buffer into the
+ # sender's next @-mention.
+ if self._gated_out(message, chat_type):
+ return None
+
+ msg_type = message.message_type
+ content: list[TextBlock | DataBlock] = []
+ if msg_type in _MEDIA_TYPES:
+ block = await self._download_media(message, msg_type)
+ content = [block] if block else []
+ elif msg_type == "post":
+ content = await self._parse_post(
+ json.loads(message.content or "{}"),
+ message_id,
+ )
+ elif msg_type == "text":
+ text = (
+ json.loads(message.content or "{}").get("text") or ""
+ ).strip()
+ if chat_type == "group" and self._config.only_at_reply:
+ for mention in message.mentions or []:
+ text = text.replace(mention.key or "", "").strip()
+ content = [TextBlock(text=text)] if text else []
+ elif message_id or chat_id:
+ await self._send(
+ message_id,
+ chat_id,
+ "text",
+ json.dumps({"text": f"Unsupported message type: {msg_type}."}),
+ )
+
+ if not content:
+ return None
+ return ChannelEvent(
+ channel_id=self._channel_id,
+ channel_user_id=user_id,
+ channel_user_name=await self._user_name(user_id),
+ chat_id=chat_id,
+ chat_name=(
+ await self.chat_name(chat_id) if chat_type == "group" else ""
+ ),
+ channel_message_id=message_id,
+ content=content,
+ metadata=meta,
+ )
+
+ async def chat_name(self, chat_id: str) -> str:
+ """The chat's title (cached per chat); ``""`` when unavailable —
+ a 1:1 chat, a not-yet-named group, or a missing ``im:chat`` scope.
+
+ Args:
+ chat_id (`str`): The chat to look up.
+ """
+ if not chat_id:
+ return ""
+ cached = self._chat_name_cache.get(chat_id)
+ if cached:
+ return cached
+ # Only cache a non-empty result, so a missing scope / not-yet-named
+ # group is retried on the next message rather than stuck empty.
+ data = await self._api("GET", f"{_API}/im/v1/chats/{chat_id}")
+ name = (data or {}).get("data", {}).get("name", "") or ""
+ if name:
+ self._chat_name_cache[chat_id] = name
+ return name
+
+ async def chat_kind(self, chat_id: str) -> ChatKind | None:
+ """Group vs 1:1 for a chat — from the inbound cache, else the
+ get-chat API (``chat_mode``). ``None`` when unknown.
+
+ Args:
+ chat_id (`str`): The chat to classify.
+ """
+ if not chat_id:
+ return None
+ cached = self._chat_kind_cache.get(chat_id)
+ if cached is not None:
+ return cached
+ data = await self._api("GET", f"{_API}/im/v1/chats/{chat_id}")
+ mode = (data or {}).get("data", {}).get("chat_mode", "")
+ kind = {"group": ChatKind.GROUP, "p2p": ChatKind.PRIVATE}.get(mode)
+ if kind is not None:
+ self._chat_kind_cache[chat_id] = kind
+ return kind
+
+ async def _user_name(self, open_id: str) -> str:
+ """The sender's display name (cached per user); empty on failure.
+
+ Args:
+ open_id (`str`): The sender's open_id.
+ """
+ if not open_id:
+ return ""
+ cached = self._user_name_cache.get(open_id)
+ if cached:
+ return cached
+ data = await self._api(
+ "GET",
+ f"{_API}/contact/v3/users/{open_id}?user_id_type=open_id",
+ )
+ name = (data or {}).get("data", {}).get("user", {}).get("name", "")
+ name = name or ""
+ if name:
+ self._user_name_cache[open_id] = name
+ else:
+ logger.warning(
+ "Feishu user '%s' returned no name (check "
+ "contact:user.base:readonly scope)",
+ open_id,
+ )
+ return name
+
+ def _gated_out(self, message: "EventMessage", chat_type: str) -> bool:
+ """Whether a group message is dropped by ``only_at_reply`` — kept
+ only when the bot itself is @mentioned (mentions of other members
+ do not count).
+
+ Args:
+ message (`EventMessage`): The inbound message.
+ chat_type (`str`): ``"group"`` / ``"p2p"`` / etc.
+
+ Returns:
+ `bool`: ``True`` to ignore the message.
+ """
+ if chat_type != "group" or not self._config.only_at_reply:
+ return False
+ mentions = message.mentions or []
+ if self._bot_open_id:
+ return not any(
+ getattr(getattr(m, "id", None), "open_id", "")
+ == self._bot_open_id
+ for m in mentions
+ )
+ # Bot identity unknown (info fetch failed / lacked open_id): we
+ # cannot verify the @ was for us, so fail closed rather than let
+ # every group message through.
+ logger.warning(
+ "Feishu '%s' bot id unknown; dropping unverified group message",
+ self._channel_id,
+ )
+ return True
+
+ async def _parse_post(
+ self,
+ content: dict,
+ message_id: str,
+ ) -> list[TextBlock | DataBlock]:
+ """Flatten a Feishu ``post`` (nested rich-text rows) into ordered
+ text and image blocks, downloading each embedded resource.
+
+ Args:
+ content (`dict`): The parsed ``post`` content (title + rows).
+ message_id (`str`): The message id, for the resource endpoint.
+
+ Returns:
+ `list[TextBlock | DataBlock]`: Text and data blocks in order.
+ """
+ blocks: list[TextBlock | DataBlock] = []
+ parts: list[str] = []
+
+ def _flush() -> None:
+ text = "".join(parts).strip()
+ parts.clear()
+ if text:
+ blocks.append(TextBlock(text=text))
+
+ if content.get("title"):
+ parts.append(content["title"] + "\n")
+ for row in content.get("content") or []:
+ for element in row or []:
+ tag = element.get("tag")
+ if tag == "text":
+ parts.append(element.get("text", ""))
+ elif tag == "a":
+ parts.append(
+ element.get("text") or element.get("href") or "",
+ )
+ elif tag in ("img", "media"):
+ key = element.get("image_key") or element.get("file_key")
+ if not key:
+ continue
+ _flush()
+ block = await self._download_resource(
+ message_id,
+ key,
+ "image" if tag == "img" else "file",
+ "image/png" if tag == "img" else "video/mp4",
+ tag,
+ )
+ if block is not None:
+ blocks.append(block)
+ parts.append("\n")
+ _flush()
+ return blocks
+
+ def _on_card_action(
+ self,
+ data: "P2CardActionTrigger",
+ loop: asyncio.AbstractEventLoop,
+ ) -> "P2CardActionTriggerResponse":
+ """Emit the click as a decision event; ack with a toast.
+
+ Args:
+ data (`P2CardActionTrigger`):
+ The card-action event carrying the button value.
+ loop (`asyncio.AbstractEventLoop`):
+ The app loop to bridge the emitted event onto.
+
+ Returns:
+ `P2CardActionTriggerResponse`: The synchronous toast ack.
+ """
+ action = getattr(getattr(data.event, "action", None), "value", None)
+ parsed = _parse_action(action)
+ if parsed is None:
+ return _build_toast(False)
+ tool_call_id, chat_id, approved, agent_id, session_id = parsed
+ operator = getattr(data.event, "operator", None)
+ user_id = getattr(operator, "open_id", "") or ""
+ if self._emit:
+ asyncio.run_coroutine_threadsafe(
+ self._emit(
+ ChannelConfirmationResultEvent(
+ channel_id=self._channel_id,
+ chat_id=chat_id,
+ channel_user_id=user_id,
+ agent_id=agent_id,
+ session_id=session_id,
+ tool_call_id=tool_call_id,
+ approved=approved,
+ ),
+ ),
+ loop,
+ )
+ # Update the clicked card in place via the callback response —
+ # reliable even while the approved run floods the card API.
+ return _build_action_response(approved)
+
+ # -- Outbound (gateway → platform) --
+
+ async def send_response(
+ self,
+ event: ChannelEvent,
+ events: AsyncIterator[dict],
+ ) -> None:
+ """Stream the reply into a live CardKit card, presenting an
+ approval card when the run parks; fall back to one-shot text if
+ the streaming card cannot be created.
+
+ Args:
+ event (`ChannelEvent`): The send target (chat id).
+ events (`AsyncIterator[dict]`): The run's session events.
+ """
+ reply: Msg | None = None
+ confirm: RequireUserConfirmEvent | None = None
+ ref: str | None = None
+ failed = False
+ last = 0.0
+ async for raw in events:
+ evt = _EVENT_ADAPTER.validate_python(raw)
+ if isinstance(evt, RequireUserConfirmEvent):
+ confirm = evt
+ break
+ reply_id = getattr(evt, "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(evt)
+ if isinstance(evt, ReplyEndEvent):
+ break
+ if failed or reply is None:
+ continue
+ rendered = self._render(
+ reply,
+ show_thinking=self._config.show_thinking,
+ show_tool_process=self._config.show_tool_process,
+ )
+ text = "".join(
+ b.text for b in rendered if isinstance(b, TextBlock)
+ )
+ if not text:
+ continue
+ if ref is None:
+ ref = await self._card_open(event)
+ if ref is None:
+ failed = True
+ continue
+ now = time.monotonic()
+ if now - last >= _STREAM_MIN_INTERVAL:
+ last = now
+ await self._card_push(ref, text)
+ blocks = self._render(
+ reply,
+ show_thinking=self._config.show_thinking,
+ show_tool_process=self._config.show_tool_process,
+ )
+ text = "".join(b.text for b in blocks if isinstance(b, TextBlock))
+ await self._finish_card(event, ref, text)
+ for block in blocks:
+ if isinstance(block, DataBlock) and isinstance(
+ block.source,
+ Base64Source,
+ ):
+ data_bytes = base64.b64decode(block.source.data)
+ media_type = block.source.media_type or ""
+ if media_type.startswith("image/") and self.capabilities.image:
+ await self.send_image_to(
+ event.chat_id,
+ "chat_id",
+ data_bytes,
+ )
+ elif self.capabilities.file:
+ await self.send_file_to(
+ event.chat_id,
+ "chat_id",
+ data_bytes,
+ block.name or "file",
+ )
+ if confirm is not None:
+ await self._present_confirm(event, confirm)
+
+ async def _finish_card(
+ self,
+ event: ChannelEvent,
+ ref: str | None,
+ text: str,
+ ) -> None:
+ """Finalise the live card, or send ``text`` once if none was open.
+
+ Args:
+ event (`ChannelEvent`): The send target (chat id).
+ ref (`str | None`): The open card id, or ``None``.
+ text (`str`): The complete reply text.
+ """
+ if ref is not None:
+ await self._card_push(ref, text)
+ await self._close_stream(ref)
+ self._stream_seq.pop(ref, None)
+ elif text:
+ for part in self._split_long_message(text):
+ await self._send(
+ event.channel_message_id,
+ event.chat_id,
+ "text",
+ json.dumps({"text": part}),
+ )
+
+ # -- Streaming card (Feishu CardKit) --
+ # NOTE: needs a real bot to verify end-to-end; on any API failure
+ # ``_card_open`` returns None and ``send_response`` sends once instead.
+
+ async def _card_open(self, event: ChannelEvent) -> str | None:
+ """Create a streaming card and send it, returning its card id.
+
+ Args:
+ event (`ChannelEvent`): The send target (chat id).
+
+ Returns:
+ `str | None`: The card id, or ``None`` if streaming could not
+ be started (the caller then sends once).
+ """
+ card_json = json.dumps(
+ {
+ "schema": "2.0",
+ "config": {"streaming_mode": True},
+ "body": {
+ "elements": [
+ {
+ "tag": "markdown",
+ "element_id": _STREAM_ELEMENT_ID,
+ "content": "",
+ },
+ ],
+ },
+ },
+ )
+ created = await self._api(
+ "POST",
+ f"{_API}/cardkit/v1/cards",
+ {"type": "card_json", "data": card_json},
+ )
+ if not created or created.get("code") != 0:
+ return None
+ card_id = created.get("data", {}).get("card_id")
+ if not card_id:
+ return None
+ sent = await self._send(
+ event.channel_message_id,
+ event.chat_id,
+ "interactive",
+ json.dumps({"type": "card", "data": {"card_id": card_id}}),
+ )
+ if not sent or sent.get("code") != 0:
+ return None
+ self._stream_seq[card_id] = 0
+ return card_id
+
+ async def _card_push(self, card_id: str, text: str) -> None:
+ """Write the current text to the card with a rising sequence.
+
+ Args:
+ card_id (`str`): The streaming card id.
+ text (`str`): Text to render.
+ """
+ seq = self._stream_seq.get(card_id, 0) + 1
+ self._stream_seq[card_id] = seq
+ await self._api(
+ "PUT",
+ f"{_API}/cardkit/v1/cards/{card_id}/elements/"
+ f"{_STREAM_ELEMENT_ID}/content",
+ {"content": text, "sequence": seq},
+ )
+
+ async def _close_stream(self, card_id: str) -> None:
+ """End streaming mode so the card stops showing "generating…".
+
+ Args:
+ card_id (`str`): The streaming card to finalise.
+ """
+ seq = self._stream_seq.get(card_id, 0) + 1
+ self._stream_seq[card_id] = seq
+ await self._api(
+ "PATCH",
+ f"{_API}/cardkit/v1/cards/{card_id}/settings",
+ {
+ "settings": json.dumps({"config": {"streaming_mode": False}}),
+ "sequence": seq,
+ },
+ )
+
+ async def _present_confirm(
+ self,
+ event: ChannelEvent,
+ req: RequireUserConfirmEvent,
+ ) -> None:
+ """Post one approval card per tool call; each button carries its
+ ``tool_call_id`` and the ``chat_id`` for click routing.
+
+ Args:
+ event (`ChannelEvent`): The send target (chat id).
+ req (`RequireUserConfirmEvent`): The approval request to show.
+ """
+ for tool in req.tool_calls:
+ await self._send(
+ event.channel_message_id,
+ event.chat_id,
+ "interactive",
+ _build_approval_card(
+ tool.id,
+ event.chat_id,
+ tool.name,
+ str(tool.input)[:800],
+ event.metadata.get("agent_id", ""),
+ event.metadata.get("session_id", ""),
+ ),
+ )
+
+ async def send_reaction(
+ self,
+ event: ChannelEvent,
+ emoji_type: str,
+ ) -> str | None:
+ """Add an emoji reaction to the inbound message.
+
+ Args:
+ event (`ChannelEvent`): The message to react to.
+ emoji_type (`str`): The Feishu emoji type (e.g. ``"OnIt"``).
+
+ Returns:
+ `str | None`: The reaction id for removal, or ``None``.
+ """
+ if not event.channel_message_id:
+ return None
+ data = await self._api(
+ "POST",
+ f"{_API}/im/v1/messages/{event.channel_message_id}/reactions",
+ {"reaction_type": {"emoji_type": emoji_type}},
+ )
+ if data and data.get("code") == 0:
+ return data.get("data", {}).get("reaction_id")
+ return None
+
+ async def remove_reaction(
+ self,
+ event: ChannelEvent,
+ reaction_id: str,
+ ) -> None:
+ """Remove a reaction previously added by :meth:`send_reaction`.
+
+ Args:
+ event (`ChannelEvent`): The reacted-to message.
+ reaction_id (`str`): The reaction id to remove.
+ """
+ if not event.channel_message_id:
+ return
+ await self._api(
+ "DELETE",
+ f"{_API}/im/v1/messages/{event.channel_message_id}"
+ f"/reactions/{reaction_id}",
+ )
+
+ async def list_bot_chats(self) -> list[dict]:
+ """List the chats the bot is in as ``{chat_id, name, chat_type}``."""
+ results: list[dict] = []
+ page_token = ""
+ while True:
+ url = f"{_API}/im/v1/chats?page_size=50"
+ if page_token:
+ url += f"&page_token={page_token}"
+ data = await self._api("GET", url)
+ if not data or data.get("code") != 0:
+ break
+ payload = data.get("data", {})
+ for item in payload.get("items", []):
+ results.append(
+ {
+ "chat_id": item.get("chat_id", ""),
+ "name": item.get("name", ""),
+ "chat_type": item.get("chat_type", ""),
+ },
+ )
+ if not payload.get("has_more"):
+ break
+ page_token = payload.get("page_token", "")
+ return results
+
+ async def list_tools(
+ self,
+ workspace: "WorkspaceBase",
+ ) -> list["ToolBase"]:
+ """Expose the Feishu send/discovery tools to the agent.
+
+ Args:
+ workspace (`WorkspaceBase`):
+ The calling session's workspace; the send-file tools read
+ their payload from its backend by absolute path.
+
+ Returns:
+ `list[ToolBase]`: The Feishu agent tools.
+ """
+ from ._tools import (
+ ListChatMembers,
+ ListChats,
+ SendFile,
+ SendImage,
+ SendMessage,
+ )
+
+ backend = workspace.get_backend()
+ return [
+ ListChats(self, backend),
+ ListChatMembers(self, backend),
+ SendMessage(self, backend),
+ SendFile(self, backend),
+ SendImage(self, backend),
+ ]
+
+ # -- Agent-tool operations (act on chats/users other than the current) --
+
+ async def send_message_to(
+ self,
+ receive_id: str,
+ receive_id_type: str,
+ text: str,
+ ) -> dict | None:
+ """Send a plain-text message to an arbitrary receive_id.
+
+ Args:
+ receive_id (`str`): The recipient id.
+ receive_id_type (`str`): ``"chat_id"`` / ``"open_id"`` / etc.
+ text (`str`): The message text.
+
+ Returns:
+ `dict | None`: The Feishu API response, or ``None`` on error.
+ """
+ return await self._api(
+ "POST",
+ f"{_API}/im/v1/messages?receive_id_type={receive_id_type}",
+ {
+ "receive_id": receive_id,
+ "msg_type": "text",
+ "content": json.dumps({"text": text}),
+ },
+ )
+
+ async def send_file_to(
+ self,
+ receive_id: str,
+ receive_id_type: str,
+ data: bytes,
+ file_name: str,
+ ) -> dict | None:
+ """Upload a file (→ file_key) then send it to a receive_id.
+
+ Args:
+ receive_id (`str`): The recipient id.
+ receive_id_type (`str`): ``"chat_id"`` / ``"open_id"`` / etc.
+ data (`bytes`): The file bytes.
+ file_name (`str`): The file's display name.
+
+ Returns:
+ `dict | None`: The send response, or ``None`` on error.
+ """
+ file_key = await self._upload(
+ f"{_API}/im/v1/files",
+ {"file_type": "stream", "file_name": file_name},
+ {"file": (file_name, data)},
+ "file_key",
+ )
+ if not file_key:
+ return None
+ return await self._api(
+ "POST",
+ f"{_API}/im/v1/messages?receive_id_type={receive_id_type}",
+ {
+ "receive_id": receive_id,
+ "msg_type": "file",
+ "content": json.dumps({"file_key": file_key}),
+ },
+ )
+
+ async def send_image_to(
+ self,
+ receive_id: str,
+ receive_id_type: str,
+ data: bytes,
+ ) -> dict | None:
+ """Upload an image (→ image_key) then send it to a receive_id.
+
+ Args:
+ receive_id (`str`): The recipient id.
+ receive_id_type (`str`): ``"chat_id"`` / ``"open_id"`` / etc.
+ data (`bytes`): The image bytes.
+
+ Returns:
+ `dict | None`: The send response, or ``None`` on error.
+ """
+ image_key = await self._upload(
+ f"{_API}/im/v1/images",
+ {"image_type": "message"},
+ {"image": ("image", data)},
+ "image_key",
+ )
+ if not image_key:
+ return None
+ return await self._api(
+ "POST",
+ f"{_API}/im/v1/messages?receive_id_type={receive_id_type}",
+ {
+ "receive_id": receive_id,
+ "msg_type": "image",
+ "content": json.dumps({"image_key": image_key}),
+ },
+ )
+
+ async def list_chat_members(self, chat_id: str) -> list[dict]:
+ """List a group's members as ``{open_id, name}`` dicts.
+
+ Args:
+ chat_id (`str`): The group whose members to list.
+
+ Returns:
+ `list[dict]`: One ``{open_id, name}`` per member.
+ """
+ results: list[dict] = []
+ page_token = ""
+ while True:
+ url = (
+ f"{_API}/im/v1/chats/{chat_id}/members"
+ f"?member_id_type=open_id&page_size=100"
+ )
+ if page_token:
+ url += f"&page_token={page_token}"
+ data = await self._api("GET", url)
+ if not data or data.get("code") != 0:
+ break
+ payload = data.get("data", {})
+ for item in payload.get("items", []):
+ results.append(
+ {
+ "open_id": item.get("member_id", ""),
+ "name": item.get("name", ""),
+ },
+ )
+ if not payload.get("has_more"):
+ break
+ page_token = payload.get("page_token", "")
+ return results
+
+ # -- Feishu API helpers --
+
+ async def _upload(
+ self,
+ url: str,
+ data: dict,
+ files: dict,
+ key: str,
+ *,
+ _retried: bool = False,
+ ) -> str | None:
+ """Multipart upload (file/image), returning the resource key; the
+ JSON ``_api`` helper can't do multipart, so this posts directly.
+
+ Args:
+ url (`str`): The upload endpoint.
+ data (`dict`): The multipart form fields.
+ files (`dict`): The multipart file part(s).
+ key (`str`): The response data key to return (``file_key`` /
+ ``image_key``).
+ _retried (`bool`): Internal — set on the post-refresh retry.
+
+ Returns:
+ `str | None`: The resource key, or ``None`` on error.
+ """
+ if not self._http or not self._token:
+ return None
+ try:
+ resp = await self._http.post(
+ url,
+ headers={"Authorization": f"Bearer {self._token}"},
+ data=data,
+ files=files,
+ )
+ body = resp.json()
+ if body.get("code") == 0:
+ return body.get("data", {}).get(key)
+ if not _retried and body.get("code") in _TOKEN_EXPIRED_CODES:
+ await self._refresh_token()
+ return await self._upload(
+ url,
+ data,
+ files,
+ key,
+ _retried=True,
+ )
+ logger.warning("Feishu upload failed: %s", body.get("msg"))
+ return None
+ except Exception: # pylint: disable=broad-except
+ logger.debug("Feishu upload request failed")
+ return None
+
+ async def _refresh_token(self) -> None:
+ """Fetch a fresh tenant access token and cache it."""
+ resp = await self._http.post(
+ f"{_API}/auth/v3/tenant_access_token/internal",
+ json={"app_id": self._app_id, "app_secret": self._app_secret},
+ )
+ data = resp.json()
+ if data.get("code") == 0:
+ self._token = data.get("tenant_access_token")
+ else:
+ logger.error("Feishu token refresh failed: %s", data)
+
+ async def _api(
+ self,
+ method: str,
+ url: str,
+ body: dict | None = None,
+ *,
+ _retried: bool = False,
+ ) -> dict | None:
+ """Authenticated JSON Feishu request; refreshes token once on expiry.
+
+ Args:
+ method (`str`): HTTP method.
+ url (`str`): The full endpoint URL.
+ body (`dict | None`): The JSON body, if any.
+ _retried (`bool`): Internal — set on the post-refresh retry.
+
+ Returns:
+ `dict | None`: The parsed response, or ``None`` on error.
+ """
+ if not self._http or not self._token:
+ return None
+ headers = {
+ "Authorization": f"Bearer {self._token}",
+ "Content-Type": "application/json",
+ }
+ try:
+ resp = await self._http.request(
+ method,
+ url,
+ headers=headers,
+ json=body,
+ )
+ data = resp.json()
+ if data.get("code") == 0:
+ return data
+ if not _retried and data.get("code") in _TOKEN_EXPIRED_CODES:
+ await self._refresh_token()
+ return await self._api(method, url, body, _retried=True)
+ logger.warning("Feishu API %s failed: %s", method, data.get("msg"))
+ return data
+ except Exception: # pylint: disable=broad-except
+ logger.debug("Feishu API %s request failed", method)
+ return None
+
+ async def _send(
+ self,
+ reply_to: str | None,
+ chat_id: str,
+ msg_type: str,
+ content: str,
+ ) -> dict | None:
+ """Send a message — as a reply when possible, else to the chat.
+
+ Args:
+ reply_to (`str | None`):
+ Inbound message id to reply to; when falsy the message is
+ sent to ``chat_id`` instead.
+ chat_id (`str`):
+ Target chat id (used when not replying).
+ msg_type (`str`):
+ Feishu message type (``"text"`` / ``"interactive"`` / …).
+ content (`str`):
+ The already-serialised message content JSON.
+
+ Returns:
+ `dict | None`: The Feishu API response, or ``None`` on error.
+ """
+ if reply_to:
+ return await self._api(
+ "POST",
+ f"{_API}/im/v1/messages/{reply_to}/reply",
+ {"msg_type": msg_type, "content": content},
+ )
+ return await self._api(
+ "POST",
+ f"{_API}/im/v1/messages?receive_id_type=chat_id",
+ {"receive_id": chat_id, "msg_type": msg_type, "content": content},
+ )
+
+ async def _download_media(
+ self,
+ message: "EventMessage",
+ msg_type: str,
+ ) -> DataBlock | None:
+ """Download a media resource into a base64 ``DataBlock``.
+
+ Args:
+ message (`EventMessage`):
+ The inbound message carrying the resource key.
+ msg_type (`str`):
+ The Feishu message type (``image`` / ``file`` / ``audio``
+ / ``media``), selecting the resource endpoint + mime.
+
+ Returns:
+ `DataBlock | None`: The downloaded block, or ``None`` on error.
+ """
+ content = json.loads(getattr(message, "content", None) or "{}")
+ key = content.get("image_key") or content.get("file_key") or ""
+ if not key:
+ return None
+ default_mime = {
+ "image": "image/png",
+ "audio": "audio/ogg",
+ "media": "video/mp4",
+ }.get(msg_type, "application/octet-stream")
+ return await self._download_resource(
+ message.message_id,
+ key,
+ "image" if msg_type == "image" else "file",
+ default_mime,
+ content.get("file_name") or msg_type,
+ )
+
+ async def _download_resource(
+ self,
+ message_id: str,
+ key: str,
+ resource_type: str,
+ default_mime: str,
+ name: str,
+ ) -> DataBlock | None:
+ """Download one message resource (image/file) into a base64 block.
+
+ Args:
+ message_id (`str`): The message the resource belongs to.
+ key (`str`): The resource key (``image_key`` / ``file_key``).
+ resource_type (`str`): ``"image"`` or ``"file"`` endpoint type.
+ default_mime (`str`): Fallback media type.
+ name (`str`): Display name for the block.
+
+ Returns:
+ `DataBlock | None`: The block, or ``None`` on error.
+ """
+ url = (
+ f"{_API}/im/v1/messages/{message_id}"
+ f"/resources/{key}?type={resource_type}"
+ )
+ try:
+ resp = await self._http.get(
+ url,
+ headers={"Authorization": f"Bearer {self._token}"},
+ )
+ if resp.status_code != 200:
+ return None
+ return DataBlock(
+ source=Base64Source(
+ data=base64.b64encode(resp.content).decode("ascii"),
+ media_type=resp.headers.get("content-type", default_mime),
+ ),
+ name=name,
+ )
+ except Exception: # pylint: disable=broad-except
+ logger.debug("Feishu resource download failed")
+ return None
diff --git a/src/agentscope/app/channel/_feishu/_tools/__init__.py b/src/agentscope/app/channel/_feishu/_tools/__init__.py
new file mode 100644
index 000000000..a7b782d9a
--- /dev/null
+++ b/src/agentscope/app/channel/_feishu/_tools/__init__.py
@@ -0,0 +1,21 @@
+# -*- coding: utf-8 -*-
+"""Feishu agent tools, one per module.
+
+Two families forming a closed chain: **discovery** (``ListChats`` /
+``ListChatMembers``) hands back a ``receive_id`` + ``receive_id_type``
+pair that **send** (``SendMessage`` / ``SendFile`` / ``SendImage``)
+consumes to reach a chat/user other than the current conversation.
+"""
+from ._list_chat_members import ListChatMembers
+from ._list_chats import ListChats
+from ._send_file import SendFile
+from ._send_image import SendImage
+from ._send_message import SendMessage
+
+__all__ = [
+ "ListChatMembers",
+ "ListChats",
+ "SendFile",
+ "SendImage",
+ "SendMessage",
+]
diff --git a/src/agentscope/app/channel/_feishu/_tools/_base.py b/src/agentscope/app/channel/_feishu/_tools/_base.py
new file mode 100644
index 000000000..7465b12fb
--- /dev/null
+++ b/src/agentscope/app/channel/_feishu/_tools/_base.py
@@ -0,0 +1,79 @@
+# -*- coding: utf-8 -*-
+"""Shared base and reply helper for the Feishu 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 FeishuChannel
+
+
+def _ack(data: dict | None, what: str) -> ToolChunk:
+ """Turn a Feishu send response into a success/error chunk.
+
+ Args:
+ data (`dict | None`): The platform send response.
+ what (`str`): Short label of what was sent, for the message.
+ """
+ if data and data.get("code") == 0:
+ return ToolChunk(content=[TextBlock(text=f"Sent {what}.")])
+ msg = (data or {}).get("msg") or "the platform rejected the request"
+ return ToolChunk(
+ content=[TextBlock(text=f"Failed to send {what}: {msg}")],
+ state=ToolResultState.ERROR,
+ )
+
+
+class _FeishuToolBase(ToolBase):
+ """Base for every Feishu tool: holds the channel and the session
+ workspace, and asks before any send to another chat/user."""
+
+ 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: "FeishuChannel",
+ backend: BackendBase,
+ ) -> None:
+ """Bind the live channel and the session's workspace backend.
+
+ Args:
+ channel (`FeishuChannel`): The live channel to send / query.
+ backend (`BackendBase`): The session workspace backend; the
+ file tools read their payload from it (others ignore it).
+ """
+ super().__init__()
+ self._channel = channel
+ self._backend = backend
+
+ async def check_permissions(
+ self,
+ tool_input: dict[str, Any],
+ context: PermissionContext,
+ ) -> PermissionDecision:
+ """Allow reads; ask before sending to another chat/user.
+
+ Args:
+ tool_input (`dict[str, Any]`): The proposed tool call args.
+ context (`PermissionContext`): The session permission 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 Feishu chat/user needs the user's "
+ "confirmation.",
+ )
diff --git a/src/agentscope/app/channel/_feishu/_tools/_list_chat_members.py b/src/agentscope/app/channel/_feishu/_tools/_list_chat_members.py
new file mode 100644
index 000000000..fc996e9ac
--- /dev/null
+++ b/src/agentscope/app/channel/_feishu/_tools/_list_chat_members.py
@@ -0,0 +1,53 @@
+# -*- coding: utf-8 -*-
+"""ListChatMembers — discover a group's members as address pairs."""
+import json
+
+from pydantic import Field
+
+from .....message import TextBlock
+from .....tool import ParamsBase, ToolChunk
+from ._base import _FeishuToolBase
+
+
+class _ListChatMembersParams(ParamsBase):
+ chat_id: str = Field(
+ description="The group's chat_id, taken from a ListChats result.",
+ )
+
+
+class ListChatMembers(_FeishuToolBase):
+ """List a group's members as ready-to-send address pairs."""
+
+ name: str = "ListChatMembers"
+ description: str = """List the members of a Feishu group, to obtain a \
+person's id for a direct message.
+
+## When to Use
+- You need to message a *specific person* directly and must first find \
+their id. Get the group's ``chat_id`` from ``ListChats``, then call this.
+
+## Output
+A JSON array of ``{receive_id, receive_id_type, name}``. ``receive_id_type`` \
+is always ``"open_id"``. Copy the ``receive_id`` + ``receive_id_type`` of \
+the person you want into a Send* tool to message them directly."""
+ is_read_only: bool = True
+ input_schema: dict = _ListChatMembersParams.model_json_schema()
+
+ async def __call__(self, chat_id: str) -> ToolChunk:
+ """Return the members of ``chat_id`` as address pairs.
+
+ Args:
+ chat_id (`str`): The group's chat_id from a ListChats result.
+ """
+ members = await self._channel.list_chat_members(chat_id)
+ items = [
+ {
+ "receive_id": member.get("open_id", ""),
+ "receive_id_type": "open_id",
+ "name": member.get("name", ""),
+ }
+ for member in members
+ ]
+ return ToolChunk(
+ content=[TextBlock(text=json.dumps(items, ensure_ascii=False))],
+ )
diff --git a/src/agentscope/app/channel/_feishu/_tools/_list_chats.py b/src/agentscope/app/channel/_feishu/_tools/_list_chats.py
new file mode 100644
index 000000000..022bb8c6a
--- /dev/null
+++ b/src/agentscope/app/channel/_feishu/_tools/_list_chats.py
@@ -0,0 +1,58 @@
+# -*- coding: utf-8 -*-
+"""ListChats — discover the bot's Feishu groups as address pairs."""
+import json
+
+from pydantic import Field
+
+from .....message import TextBlock
+from .....tool import ParamsBase, ToolChunk
+from ._base import _FeishuToolBase
+
+
+class _ListChatsParams(ParamsBase):
+ query: str | None = Field(
+ default=None,
+ description="Optional case-insensitive substring to filter groups "
+ "by name. Omit to list all.",
+ )
+
+
+class ListChats(_FeishuToolBase):
+ """List the bot's Feishu groups as ready-to-send address pairs."""
+
+ name: str = "ListChats"
+ description: str = """List the Feishu groups this bot belongs to, to \
+obtain a target for sending.
+
+## When to Use
+- You need to message a *group* other than the current conversation and \
+must first find its id.
+
+## Output
+A JSON array of ``{receive_id, receive_id_type, name}``. ``receive_id_type`` \
+is always ``"chat_id"``. Copy ``receive_id`` + ``receive_id_type`` verbatim \
+into a Send* tool. To reach a specific *person* in a group, take that \
+group's ``receive_id`` and call ``ListChatMembers`` next."""
+ is_read_only: bool = True
+ input_schema: dict = _ListChatsParams.model_json_schema()
+
+ async def __call__(self, query: str | None = None) -> ToolChunk:
+ """Return the bot's chats filtered by ``query``.
+
+ Args:
+ query (`str | None`): Case-insensitive name filter, or all.
+ """
+ chats = await self._channel.list_bot_chats()
+ needle = (query or "").lower()
+ items = [
+ {
+ "receive_id": chat.get("chat_id", ""),
+ "receive_id_type": "chat_id",
+ "name": chat.get("name", ""),
+ }
+ 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/_feishu/_tools/_send_file.py b/src/agentscope/app/channel/_feishu/_tools/_send_file.py
new file mode 100644
index 000000000..6cd1a07f3
--- /dev/null
+++ b/src/agentscope/app/channel/_feishu/_tools/_send_file.py
@@ -0,0 +1,78 @@
+# -*- coding: utf-8 -*-
+"""SendFile — upload and send a workspace file to another chat/user."""
+from pathlib import Path
+
+from pydantic import Field
+
+from .....message import TextBlock, ToolResultState
+from .....tool import ParamsBase, ToolChunk
+from ._base import _FeishuToolBase, _ack
+
+
+class _SendFileParams(ParamsBase):
+ path: str = Field(
+ description="Absolute path to the file in your workspace, e.g. one "
+ "you just created with Write — the same absolute path you used "
+ "there.",
+ )
+ receive_id: str = Field(
+ description="Target id, taken verbatim from a ListChats / "
+ "ListChatMembers result.",
+ )
+ receive_id_type: str = Field(
+ description="Must match the id: 'chat_id' for a group, 'open_id' "
+ "for a person.",
+ json_schema_extra={"enum": ["chat_id", "open_id"]},
+ )
+
+
+class SendFile(_FeishuToolBase):
+ """Upload and send a file to another Feishu chat/user."""
+
+ name: str = "SendFile"
+ description: str = """Send a file to a Feishu chat or person OTHER than \
+the current conversation.
+
+## When to Use
+- The user asks you to deliver a file (a report, export, ...) to a \
+*different* group or person.
+
+## How to Use
+Give ``path`` — a file in your workspace (the one you produced it in). \
+Obtain ``receive_id`` via ``ListChats`` (group) or ``ListChatMembers`` \
+(person) and pass ``receive_id`` + ``receive_id_type`` verbatim. Sending \
+requires the user's confirmation.
+
+To send an image so it renders inline, use ``SendImage`` instead."""
+ is_read_only: bool = False
+ input_schema: dict = _SendFileParams.model_json_schema()
+
+ async def __call__(
+ self,
+ path: str,
+ receive_id: str,
+ receive_id_type: str,
+ ) -> ToolChunk:
+ """Read ``path`` from the workspace and send it to ``receive_id``.
+
+ Args:
+ path (`str`): Workspace path of the file to send.
+ receive_id (`str`): Target id from a discovery result.
+ receive_id_type (`str`): ``"chat_id"`` or ``"open_id"``.
+ """
+ try:
+ raw = await self._backend.read_file(path)
+ except Exception as e: # pylint: disable=broad-except
+ return ToolChunk(
+ content=[
+ TextBlock(text=f"SendFile: cannot read {path!r}: {e}"),
+ ],
+ state=ToolResultState.ERROR,
+ )
+ data = await self._channel.send_file_to(
+ receive_id,
+ receive_id_type,
+ raw,
+ Path(path).name,
+ )
+ return _ack(data, f"file {Path(path).name} to {receive_id}")
diff --git a/src/agentscope/app/channel/_feishu/_tools/_send_image.py b/src/agentscope/app/channel/_feishu/_tools/_send_image.py
new file mode 100644
index 000000000..e65b2e63b
--- /dev/null
+++ b/src/agentscope/app/channel/_feishu/_tools/_send_image.py
@@ -0,0 +1,71 @@
+# -*- coding: utf-8 -*-
+"""SendImage — upload and send a workspace image, rendered inline."""
+from pydantic import Field
+
+from .....message import TextBlock, ToolResultState
+from .....tool import ParamsBase, ToolChunk
+from ._base import _FeishuToolBase, _ack
+
+
+class _SendImageParams(ParamsBase):
+ path: str = Field(
+ description="Absolute path to the image file in your workspace — "
+ "the same absolute path you used to create it.",
+ )
+ receive_id: str = Field(
+ description="Target id, taken verbatim from a ListChats / "
+ "ListChatMembers result.",
+ )
+ receive_id_type: str = Field(
+ description="Must match the id: 'chat_id' for a group, 'open_id' "
+ "for a person.",
+ json_schema_extra={"enum": ["chat_id", "open_id"]},
+ )
+
+
+class SendImage(_FeishuToolBase):
+ """Upload and send an image to another Feishu chat/user."""
+
+ name: str = "SendImage"
+ description: str = """Send an image to a Feishu chat or person OTHER \
+than the current conversation, rendered inline.
+
+## When to Use
+- The user asks you to send a picture/chart to a *different* group or \
+person, and you want it shown inline (not as a file attachment).
+
+## How to Use
+Give ``path`` to the image file. Obtain ``receive_id`` via ``ListChats`` \
+(group) or ``ListChatMembers`` (person) and pass ``receive_id`` + \
+``receive_id_type`` verbatim. Sending requires the user's confirmation."""
+ is_read_only: bool = False
+ input_schema: dict = _SendImageParams.model_json_schema()
+
+ async def __call__(
+ self,
+ path: str,
+ receive_id: str,
+ receive_id_type: str,
+ ) -> ToolChunk:
+ """Read the image at ``path`` from the workspace and send it.
+
+ Args:
+ path (`str`): Workspace path of the image to send.
+ receive_id (`str`): Target id from a discovery result.
+ receive_id_type (`str`): ``"chat_id"`` or ``"open_id"``.
+ """
+ try:
+ raw = await self._backend.read_file(path)
+ except Exception as e: # pylint: disable=broad-except
+ return ToolChunk(
+ content=[
+ TextBlock(text=f"SendImage: cannot read {path!r}: {e}"),
+ ],
+ state=ToolResultState.ERROR,
+ )
+ data = await self._channel.send_image_to(
+ receive_id,
+ receive_id_type,
+ raw,
+ )
+ return _ack(data, f"image to {receive_id}")
diff --git a/src/agentscope/app/channel/_feishu/_tools/_send_message.py b/src/agentscope/app/channel/_feishu/_tools/_send_message.py
new file mode 100644
index 000000000..6ba924236
--- /dev/null
+++ b/src/agentscope/app/channel/_feishu/_tools/_send_message.py
@@ -0,0 +1,62 @@
+# -*- coding: utf-8 -*-
+"""SendMessage — send text to another Feishu chat/user."""
+from pydantic import Field
+
+from .....tool import ParamsBase, ToolChunk
+from ._base import _FeishuToolBase, _ack
+
+
+class _SendMessageParams(ParamsBase):
+ receive_id: str = Field(
+ description="Target id, taken verbatim from a ListChats / "
+ "ListChatMembers result.",
+ )
+ receive_id_type: str = Field(
+ description="Must match the id: 'chat_id' for a group, 'open_id' "
+ "for a person. Copy it from the same discovery result.",
+ json_schema_extra={"enum": ["chat_id", "open_id"]},
+ )
+ text: str = Field(description="The message text to send.")
+
+
+class SendMessage(_FeishuToolBase):
+ """Send text to another Feishu chat/user."""
+
+ name: str = "SendMessage"
+ description: str = """Send a text message to a Feishu chat or person \
+OTHER than the current conversation.
+
+## When to Use
+- The user asks you to notify or relay something to a *different* group or \
+person (e.g. "tell the finance group ...", "let Li Si know ...").
+
+## When NOT to Use
+- To answer the person you are talking with now — that reply is sent \
+automatically. Never use this tool for the current conversation.
+
+## How to Use
+Obtain ``receive_id`` first: a group's via ``ListChats``, a person's via \
+``ListChatMembers``. Pass ``receive_id`` and ``receive_id_type`` exactly as \
+returned. Sending requires the user's confirmation."""
+ is_read_only: bool = False
+ input_schema: dict = _SendMessageParams.model_json_schema()
+
+ async def __call__(
+ self,
+ receive_id: str,
+ receive_id_type: str,
+ text: str,
+ ) -> ToolChunk:
+ """Send ``text`` to ``receive_id``.
+
+ Args:
+ receive_id (`str`): Target id from a discovery result.
+ receive_id_type (`str`): ``"chat_id"`` or ``"open_id"``.
+ text (`str`): The message text to send.
+ """
+ data = await self._channel.send_message_to(
+ receive_id,
+ receive_id_type,
+ text,
+ )
+ return _ack(data, f"message to {receive_id}")
diff --git a/src/agentscope/app/channel/_gateway.py b/src/agentscope/app/channel/_gateway.py
new file mode 100644
index 000000000..b63fd0ecd
--- /dev/null
+++ b/src/agentscope/app/channel/_gateway.py
@@ -0,0 +1,295 @@
+# -*- coding: utf-8 -*-
+"""ChannelGateway — inbound-only orchestration (data plane).
+
+``process(event, channel)`` is the single entry point for both inbound
+messages and confirmation-card clicks. It is deliberately thin:
+
+- a **message** is routed to an ``(agent_id, session_id)`` and delivered
+ as run input (a user turn when the session is idle, or an inbox hint
+ when a reply is already in flight) — then the gateway returns;
+- a **card click** takes the parked request and resumes the run.
+
+The gateway does **not** collect or send the reply. Output flows the
+other way: a channel-bound run emits an outbound signal, and the
+:class:`~agentscope.app.channel.ChannelLifecycleDispatcher` (on the node
+hosting the channel) subscribes to the run's event stream and streams
+the reply back — so scheduled / background runs reach the channel too,
+not just inbound messages.
+"""
+import json
+
+from ..._logging import logger
+from ...message import DataBlock, HintBlock, TextBlock, UserMsg
+from ...permission import PermissionContext, PermissionMode
+from ...state import AgentState
+from .._bus_ops import enqueue_run_trigger
+from ..message_bus import MessageBus, MessageBusKeys
+from ..storage import (
+ ChannelRecord,
+ ChatModelConfig,
+ SessionConfig,
+ SessionScope,
+ SessionSource,
+ StorageBase,
+)
+from ..workspace_manager import WorkspaceManagerBase
+from ._base import ChannelEvent, ChannelConfirmationResultEvent
+from ._decision import resume_after_decision
+from ._routing import resolve
+
+# How long a media-only message waits for its accompanying text message.
+_MEDIA_BUFFER_TTL_SECS = 300
+# Max buffered attachments carried into one text message.
+_MEDIA_BUFFER_MAX = 9
+
+
+class ChannelGateway:
+ """Route inbound channel events into runs; resume on card clicks."""
+
+ def __init__(
+ self,
+ storage: StorageBase,
+ message_bus: MessageBus,
+ workspace_manager: WorkspaceManagerBase,
+ ) -> None:
+ """Bind storage, the message bus, and the workspace manager.
+
+ Args:
+ storage (`StorageBase`): Application storage.
+ message_bus (`MessageBus`): Application message bus.
+ workspace_manager (`WorkspaceManagerBase`): Assigns each
+ derived session its workspace under the isolation policy.
+ """
+ self._storage = storage
+ self._bus = message_bus
+ self._workspace_manager = workspace_manager
+
+ async def process(
+ self,
+ event: ChannelEvent | ChannelConfirmationResultEvent,
+ ) -> None:
+ """Handle one inbound event (message or confirmation decision).
+
+ Args:
+ event (`ChannelEvent | ChannelConfirmationResultEvent`): The
+ inbound message or card-click decision.
+ """
+ try:
+ if isinstance(event, ChannelConfirmationResultEvent):
+ await self._handle_decision(event)
+ else:
+ await self._handle_message(event)
+ except Exception: # pylint: disable=broad-except
+ logger.exception(
+ "ChannelGateway.process failed for channel %s",
+ event.channel_id,
+ )
+
+ async def _handle_decision(
+ self,
+ event: ChannelConfirmationResultEvent,
+ ) -> None:
+ """Resume the run for a card-click decision.
+
+ Routes the click to its session and resumes; the authoritative
+ tool call is read from session state, so a stale/forged click
+ simply finds nothing to answer.
+
+ Args:
+ event (`ChannelConfirmationResultEvent`): The click decision.
+ """
+ record = await self._storage.get_channel(event.channel_id)
+ if record is None or not record.enabled:
+ return
+ # Prefer the target pinned on the card at send time; re-resolving
+ # via routing here would misroute clicks whose original message
+ # matched on metadata, or in per-chat-user scope when a different
+ # member clicks. Fall back to routing only for older cards.
+ if event.agent_id and event.session_id:
+ agent_id, session_id = event.agent_id, event.session_id
+ else:
+ agent_id, session_id, _ = resolve(
+ ChannelEvent(
+ channel_id=event.channel_id,
+ channel_user_id=event.channel_user_id,
+ chat_id=event.chat_id,
+ ),
+ record,
+ )
+ await resume_after_decision(
+ self._bus,
+ self._storage,
+ user_id=record.user_id,
+ agent_id=agent_id,
+ session_id=session_id,
+ tool_call_id=event.tool_call_id,
+ approved=event.approved,
+ )
+
+ # -- Message path --
+
+ async def _handle_message(self, event: ChannelEvent) -> None:
+ """Aggregate buffered media, then inject a hint into a live run
+ or start a fresh user turn on an idle session.
+
+ Args:
+ event (`ChannelEvent`): The normalised inbound message.
+ """
+ record = await self._storage.get_channel(event.channel_id)
+ if record is None:
+ logger.error("No channel record for %s", event.channel_id)
+ return
+ if not record.enabled:
+ return # stale event from a since-disabled channel
+
+ agent_id, session_id, scope = resolve(event, record)
+ if event.chat_id:
+ await self._bus.registry_set(
+ MessageBusKeys.channel_seen_chats(event.channel_id),
+ event.chat_id,
+ "1",
+ )
+
+ content = await self._aggregate_media(event)
+ if content is None:
+ return # media buffered; nothing to run until a text message
+
+ # A reply already in flight → inject the input as a hint so the
+ # live run folds it in. Otherwise start a fresh user turn.
+ if await self._bus.is_locked(MessageBusKeys.session_lock(session_id)):
+ await self._bus.queue_push(
+ MessageBusKeys.inbox(session_id),
+ HintBlock(
+ hint=content,
+ source=json.dumps(
+ {
+ "label": "channel",
+ "sublabel": event.channel_user_name
+ or event.channel_user_id,
+ },
+ ensure_ascii=False,
+ ),
+ ).model_dump(mode="json"),
+ )
+ return
+
+ await self._ensure_session(record, agent_id, session_id, event, scope)
+ # Deliver as a genuine user turn; the run's output is streamed
+ # back by the dispatcher's forward loop, not collected here.
+ await enqueue_run_trigger(
+ self._bus,
+ user_id=record.user_id,
+ session_id=session_id,
+ agent_id=agent_id,
+ kind=MessageBusKeys.WAKEUP_KIND_MESSAGE,
+ inputs=UserMsg(name=event.channel_user_id, content=content),
+ )
+
+ async def _aggregate_media(
+ self,
+ event: ChannelEvent,
+ ) -> list[TextBlock | DataBlock] | None:
+ """Merge buffered attachments with this message: media-only
+ buffers and returns ``None``; the next text drains and combines.
+
+ Args:
+ event (`ChannelEvent`): The inbound message.
+ """
+ key = MessageBusKeys.channel_media_buffer(
+ event.channel_id,
+ event.chat_id,
+ event.channel_user_id,
+ )
+ has_text = any(isinstance(b, TextBlock) for b in event.content)
+ if not has_text:
+ for block in event.content:
+ if isinstance(block, DataBlock):
+ await self._bus.queue_push(
+ key,
+ block.model_dump(mode="json"),
+ ttl_secs=_MEDIA_BUFFER_TTL_SECS,
+ )
+ return None
+ entries = await self._bus.queue_drain(key, max_count=_MEDIA_BUFFER_MAX)
+ buffered = [DataBlock.model_validate(p) for _id, p in entries]
+ return [*buffered, *event.content]
+
+ # -- Session creation (deterministic id, idempotent) --
+
+ async def _ensure_session(
+ self,
+ record: ChannelRecord,
+ agent_id: str,
+ session_id: str,
+ event: ChannelEvent,
+ scope: SessionScope,
+ ) -> None:
+ """Create the derived session if absent (idempotent across nodes).
+
+ Args:
+ record (`ChannelRecord`): The owning channel record.
+ agent_id (`str`): The resolved target agent.
+ session_id (`str`): The derived session id.
+ event (`ChannelEvent`): The originating message.
+ scope (`SessionScope`): How the session is grouped.
+ """
+ existing = await self._storage.get_session(
+ user_id=record.user_id,
+ agent_id=agent_id,
+ session_id=session_id,
+ )
+ if existing is not None:
+ return
+
+ fallback = record.session.fallback_chat_model_config
+ session_config = SessionConfig(
+ workspace_id=self._workspace_manager.assign_workspace_id(
+ user_id=record.user_id,
+ agent_id=agent_id,
+ session_id=session_id,
+ ),
+ chat_model_config=ChatModelConfig(
+ **record.session.chat_model_config,
+ ),
+ fallback_chat_model_config=(
+ ChatModelConfig(**fallback) if fallback else None
+ ),
+ name=self._session_name(record, event, scope),
+ )
+ initial_state = AgentState(
+ permission_context=PermissionContext(
+ mode=PermissionMode(record.session.permission_mode),
+ ),
+ )
+ await self._storage.upsert_session(
+ user_id=record.user_id,
+ agent_id=agent_id,
+ config=session_config,
+ state=initial_state,
+ session_id=session_id,
+ source=SessionSource.CHANNEL,
+ source_chat_id=event.chat_id,
+ source_channel_id=record.id,
+ )
+
+ @staticmethod
+ def _session_name(
+ record: ChannelRecord,
+ event: ChannelEvent,
+ scope: SessionScope,
+ ) -> str:
+ """Compact, human-readable session name, e.g. ``Feishu/产品群/张三``.
+
+ Args:
+ record (`ChannelRecord`): The owning channel record.
+ event (`ChannelEvent`): The originating message.
+ scope (`SessionScope`): How the session is grouped.
+ """
+ platform = record.channel_type.capitalize()
+ where = event.chat_name or event.channel_user_name or event.chat_id
+ parts = [platform, where]
+ if scope is SessionScope.PER_CHAT_USER:
+ who = event.channel_user_name or event.channel_user_id
+ if who and who != where:
+ parts.append(who)
+ return "/".join(p for p in parts if p)
diff --git a/src/agentscope/app/channel/_registry.py b/src/agentscope/app/channel/_registry.py
new file mode 100644
index 000000000..c4e81ef02
--- /dev/null
+++ b/src/agentscope/app/channel/_registry.py
@@ -0,0 +1,166 @@
+# -*- coding: utf-8 -*-
+"""Channel type registry — the set of platform types a service allows.
+
+A channel *type* is fully described by its channel class (see
+:class:`~agentscope.app.channel.ChannelBase`): the class carries its
+``channel_type`` id, ``platform_bot_id_field``, and nested
+``Credentials`` / ``Config`` models. The registry is built from the
+channel classes passed to :func:`~agentscope.app.create_app` via
+``channels=[...]`` and exposes them to the service — frontend form
+schemas, bot-uniqueness checks, and per-record instance construction.
+"""
+from __future__ import annotations
+
+from typing import TYPE_CHECKING
+
+from pydantic import BaseModel
+
+if TYPE_CHECKING:
+ from ._base import ChannelBase
+
+
+class ChannelTypeSchema(BaseModel):
+ """Frontend-facing metadata for one channel type.
+
+ Generated from a channel class. ``credentials_schema`` /
+ ``config_schema`` are JSON Schemas the frontend renders as forms.
+ """
+
+ channel_type: str
+ display_name: str
+ description: str = ""
+ icon_url: str = ""
+ credentials_schema: dict
+ config_schema: dict
+ platform_bot_id_field: str
+
+
+class ChannelTypeRegistry:
+ """The channel types a service allows, keyed by ``channel_type``."""
+
+ def __init__(
+ self,
+ channels: list[type["ChannelBase"]] | None = None,
+ ) -> None:
+ """Build the registry from a list of channel classes.
+
+ Args:
+ channels (`list[type[ChannelBase]] | None`):
+ Channel classes to allow. Passed through from
+ ``create_app(channels=[...])``.
+ """
+ self._classes: dict[str, type["ChannelBase"]] = {}
+ for channel_cls in channels or []:
+ self.register(channel_cls)
+
+ def __bool__(self) -> bool:
+ """Whether any channel type is registered (feature enabled)."""
+ return bool(self._classes)
+
+ def register(self, channel_cls: type["ChannelBase"]) -> None:
+ """Register a channel class under its ``channel_type``.
+
+ Args:
+ channel_cls (`type[ChannelBase]`): The channel class to add.
+ """
+ channel_type = channel_cls.channel_type
+ if not channel_type:
+ raise ValueError(
+ f"{channel_cls.__name__} must set a non-empty "
+ f"'channel_type' to be registered.",
+ )
+ self._classes[channel_type] = channel_cls
+
+ def get(self, channel_type: str) -> type["ChannelBase"] | None:
+ """Return the channel class for a type, or ``None``.
+
+ Args:
+ channel_type (`str`): The platform type id.
+ """
+ return self._classes.get(channel_type)
+
+ def has_type(self, channel_type: str) -> bool:
+ """Whether a type is registered.
+
+ Args:
+ channel_type (`str`): The platform type id.
+ """
+ return channel_type in self._classes
+
+ def create_channel(
+ self,
+ channel_type: str,
+ channel_id: str,
+ credentials: dict,
+ config: dict,
+ ) -> "ChannelBase":
+ """Validate stored credentials/config against the class's nested
+ models and build the channel instance.
+
+ Args:
+ channel_type (`str`): The platform type id.
+ channel_id (`str`): The instance's unique id.
+ credentials (`dict`): Raw credentials to validate.
+ config (`dict`): Raw platform options to validate.
+
+ Raises:
+ `ValueError`: If ``channel_type`` is not registered.
+ """
+ channel_cls = self._classes.get(channel_type)
+ if channel_cls is None:
+ raise ValueError(
+ f"Channel type '{channel_type}' is not registered; pass it "
+ f"to create_app(channels=[...]).",
+ )
+ return channel_cls(
+ channel_id,
+ channel_cls.Credentials(**credentials),
+ channel_cls.Config(**config),
+ )
+
+ def schema_of(
+ self,
+ channel_cls: type["ChannelBase"],
+ ) -> ChannelTypeSchema:
+ """Build the frontend schema for one channel class.
+
+ Args:
+ channel_cls (`type[ChannelBase]`): The channel class.
+ """
+ return ChannelTypeSchema(
+ channel_type=channel_cls.channel_type,
+ display_name=channel_cls.display_name or channel_cls.channel_type,
+ description=channel_cls.description,
+ icon_url=channel_cls.icon_url,
+ credentials_schema=channel_cls.Credentials.model_json_schema(),
+ config_schema=channel_cls.Config.model_json_schema(),
+ platform_bot_id_field=channel_cls.platform_bot_id_field,
+ )
+
+ def list_types(self) -> list[ChannelTypeSchema]:
+ """List frontend schemas for all registered types."""
+ return [self.schema_of(c) for c in self._classes.values()]
+
+ def extract_platform_bot_id(
+ self,
+ channel_type: str,
+ credentials: dict,
+ ) -> str:
+ """Read the bot-identifying credential field, for uniqueness.
+
+ Args:
+ channel_type (`str`): The platform type id.
+ credentials (`dict`): Raw credentials to read the bot id from.
+ """
+ channel_cls = self._classes.get(channel_type)
+ if channel_cls is None or not channel_cls.platform_bot_id_field:
+ raise ValueError(
+ f"Cannot extract platform_bot_id for type '{channel_type}'.",
+ )
+ bot_id = credentials.get(channel_cls.platform_bot_id_field)
+ if not bot_id:
+ raise ValueError(
+ f"Missing '{channel_cls.platform_bot_id_field}' in "
+ f"credentials.",
+ )
+ return str(bot_id)
diff --git a/src/agentscope/app/channel/_routing.py b/src/agentscope/app/channel/_routing.py
new file mode 100644
index 000000000..16426f622
--- /dev/null
+++ b/src/agentscope/app/channel/_routing.py
@@ -0,0 +1,74 @@
+# -*- coding: utf-8 -*-
+"""Pure routing: resolve an inbound event to ``(agent_id, session_id)``.
+
+There is no persisted channel→session mapping table. Given the routing
+rules on the channel record, both the target agent and the session id
+are computed deterministically from the event — so every node derives
+the same result with zero coordination, and session creation is
+idempotent (``get_or_create`` on a derived id).
+"""
+from uuid import NAMESPACE_URL, uuid5
+
+from ..storage import ChannelRecord, ChannelBinding, SessionScope
+from ._base import ChannelEvent
+
+
+# Fixed namespace so derived session ids are stable across processes and
+# restarts. Do not change — it would orphan every existing session.
+_SESSION_NAMESPACE = uuid5(NAMESPACE_URL, "agentscope.channel.session")
+
+
+def _binding_matches(event: ChannelEvent, binding: ChannelBinding) -> bool:
+ """Whether ``binding`` matches ``event`` (``"*"`` matches anything).
+
+ Args:
+ event (`ChannelEvent`): The inbound event.
+ binding (`ChannelBinding`): The rule; ``chat_id``/``user_id`` map
+ to event fields, other keys to ``event.metadata``.
+ """
+ if binding.match_value == "*":
+ return True
+ if binding.match_key == "chat_id":
+ value: str | None = event.chat_id
+ elif binding.match_key == "user_id":
+ value = event.channel_user_id
+ else:
+ raw = event.metadata.get(binding.match_key)
+ value = str(raw) if raw is not None else None
+ return value == binding.match_value
+
+
+def resolve(
+ event: ChannelEvent,
+ record: ChannelRecord,
+) -> tuple[str, str, SessionScope]:
+ """Resolve an event to ``(agent_id, session_id, scope)`` via the first
+ matching binding and a stable id from ``(channel, agent, scope_key)``.
+
+ Args:
+ event (`ChannelEvent`): The inbound event.
+ record (`ChannelRecord`): The channel's configuration.
+
+ Returns:
+ `tuple[str, str, SessionScope]`: ``(agent_id, session_id, scope)``.
+ """
+ binding = record.routing.bindings[-1]
+ for candidate in record.routing.bindings:
+ if _binding_matches(event, candidate):
+ binding = candidate
+ break
+
+ # Session scope projects the (chat_id, user_id) pair; PER_CHAT is
+ # naturally per-user for a DM (its chat has only that user).
+ if binding.session_scope is SessionScope.PER_CHAT_USER:
+ scope_key = f"{event.chat_id}:{event.channel_user_id}"
+ else:
+ scope_key = event.chat_id
+
+ session_id = str(
+ uuid5(
+ _SESSION_NAMESPACE,
+ f"{record.id}:{binding.agent_id}:{scope_key}",
+ ),
+ )
+ return binding.agent_id, session_id, binding.session_scope
diff --git a/src/agentscope/app/deps.py b/src/agentscope/app/deps.py
index 78e93be9a..7f746d243 100644
--- a/src/agentscope/app/deps.py
+++ b/src/agentscope/app/deps.py
@@ -3,12 +3,17 @@
from fastapi import Header, HTTPException, Request, status
from .workspace_manager import WorkspaceManagerBase
+from .channel import (
+ ChannelLifecycleDispatcher,
+ ChannelTypeRegistry,
+)
from ._manager import (
BackgroundTaskManager,
ChatRunRegistry,
SchedulerManager,
)
from ._service import (
+ ChannelService,
ChatService,
KnowledgeBaseService,
ResourceAccessService,
@@ -356,3 +361,45 @@ async def get_skill_hubs(request: Request) -> dict[str, SkillHubBase]:
were passed to ``create_app``.
"""
return getattr(request.app.state, "skill_hubs", {})
+
+
+async def get_channel_service(request: Request) -> ChannelService:
+ """Return the application-wide channel CRUD service.
+
+ Args:
+ request (`Request`): The incoming FastAPI request.
+
+ Returns:
+ `ChannelService`: The service stored in ``app.state``.
+ """
+ return request.app.state.channel_service
+
+
+async def get_channel_dispatcher(
+ request: Request,
+) -> ChannelLifecycleDispatcher:
+ """Return this node's channel lifecycle dispatcher.
+
+ Args:
+ request (`Request`): The incoming FastAPI request.
+
+ Returns:
+ `ChannelLifecycleDispatcher`: The dispatcher stored in
+ ``app.state``, source of per-channel runtime status.
+ """
+ return request.app.state.channel_dispatcher
+
+
+async def get_channel_type_registry(
+ request: Request,
+) -> ChannelTypeRegistry:
+ """Return the registry of channel types allowed by this service.
+
+ Args:
+ request (`Request`): The incoming FastAPI request.
+
+ Returns:
+ `ChannelTypeRegistry`: The registry built in ``create_app`` from
+ the ``channels`` list (empty when none were passed).
+ """
+ return request.app.state.channel_type_registry
diff --git a/src/agentscope/app/message_bus/_base.py b/src/agentscope/app/message_bus/_base.py
index eb80823a2..aaf382d9f 100644
--- a/src/agentscope/app/message_bus/_base.py
+++ b/src/agentscope/app/message_bus/_base.py
@@ -368,6 +368,32 @@ class MessageBus(ABC): # pylint: disable=too-many-public-methods
``True`` if some process holds the lock right now.
"""
+ @abstractmethod
+ async def try_lock(self, key: str, *, ttl_secs: int = 600) -> bool:
+ """Claim ``key`` without blocking (non-blocking mutex).
+
+ Unlike :meth:`acquire_lock` (which waits until free), this
+ returns immediately: ``True`` if acquired, ``False`` if already
+ held. Release with :meth:`unlock`. Used to make an at-least-once
+ queue drain effectively once — the node that wins the claim for
+ a key does the work; the others skip.
+
+ Args:
+ key (`str`):
+ Lock identifier.
+ ttl_secs (`int`, defaults to ``600``):
+ Lease duration; the claim expires automatically so a
+ crashed holder cannot block the key forever.
+
+ Returns:
+ `bool`:
+ ``True`` if the lock was acquired.
+ """
+
+ @abstractmethod
+ async def unlock(self, key: str) -> None:
+ """Release a lock claimed via :meth:`try_lock` (best-effort)."""
+
# ------------------------------------------------------------------
# Mode F — registry map (hash-keyed namespace)
# ------------------------------------------------------------------
@@ -444,6 +470,26 @@ class MessageBus(ABC): # pylint: disable=too-many-public-methods
All entries. Empty dict when the namespace is absent.
"""
+ @abstractmethod
+ async def registry_get(
+ self,
+ namespace: str,
+ field: str,
+ ) -> str | None:
+ """Return the value of a single ``field`` in the registry at
+ ``namespace``, or ``None`` if absent.
+
+ Args:
+ namespace (`str`):
+ Registry key.
+ field (`str`):
+ Field to retrieve.
+
+ Returns:
+ `str | None`:
+ The stored value, or ``None`` if missing.
+ """
+
@abstractmethod
async def registry_drop(self, namespace: str) -> None:
"""Delete the entire registry at ``namespace``.
diff --git a/src/agentscope/app/message_bus/_in_memory_message_bus.py b/src/agentscope/app/message_bus/_in_memory_message_bus.py
index 3b09ea1f9..34e8f1937 100644
--- a/src/agentscope/app/message_bus/_in_memory_message_bus.py
+++ b/src/agentscope/app/message_bus/_in_memory_message_bus.py
@@ -17,6 +17,7 @@ dependency.
from __future__ import annotations
import asyncio
+import time
import uuid
from collections import defaultdict
from collections.abc import AsyncGenerator
@@ -58,7 +59,11 @@ class InMemoryMessageBus(MessageBus):
self._seq: int = 0
# Mode A — drain queues: key -> [(entry_id, payload), ...]
- self._queues: dict[str, list[tuple[str, dict]]] = defaultdict(list)
+ # (entry_id, payload, expire_at | None) — expire_at is monotonic.
+ self._queues: dict[
+ str,
+ list[tuple[str, dict, float | None]],
+ ] = defaultdict(list)
# Mode C — replay logs: key -> [(entry_id, payload), ...]
self._logs: dict[str, list[tuple[str, dict]]] = defaultdict(list)
@@ -127,8 +132,9 @@ class InMemoryMessageBus(MessageBus):
) -> str:
"""Append ``payload`` to the in-memory drain queue at ``key``.
- ``ttl_secs`` is accepted for API compatibility but ignored — the
- in-memory implementation does not expire keys.
+ When ``ttl_secs`` is set the entry expires after that many
+ seconds; expired entries are dropped here and on drain, so a
+ never-drained key stays bounded.
Args:
key (`str`):
@@ -136,14 +142,18 @@ class InMemoryMessageBus(MessageBus):
payload (`dict`):
JSON-serializable dict to enqueue.
ttl_secs (`int | None`, optional):
- Ignored (no-op).
+ Entry lifetime in seconds; ``None`` never expires.
Returns:
`str`:
The synthetic entry id assigned to this entry.
"""
entry_id = self._next_id()
- self._queues[key].append((entry_id, payload))
+ queue = self._queues[key]
+ now = time.monotonic()
+ queue[:] = [e for e in queue if e[2] is None or e[2] > now]
+ expire_at = now + ttl_secs if ttl_secs else None
+ queue.append((entry_id, payload, expire_at))
return entry_id
async def queue_drain(
@@ -168,9 +178,11 @@ class InMemoryMessageBus(MessageBus):
q = self._queues.get(key)
if not q:
return []
- drained = q[:max_count]
- del q[:max_count]
- return drained
+ now = time.monotonic()
+ alive = [e for e in q if e[2] is None or e[2] > now]
+ drained = alive[:max_count]
+ self._queues[key] = alive[max_count:]
+ return [(entry_id, payload) for entry_id, payload, _ in drained]
async def queue_delete(self, key: str) -> None:
"""Delete the drain queue at ``key``.
@@ -386,6 +398,17 @@ class InMemoryMessageBus(MessageBus):
"""
return key in self._lock_holders
+ async def try_lock(self, key: str, *, ttl_secs: int = 600) -> bool:
+ """Non-blocking claim on ``key``. See base."""
+ if key in self._lock_holders:
+ return False
+ self._lock_holders[key] = "1"
+ return True
+
+ async def unlock(self, key: str) -> None:
+ """Release a ``try_lock`` claim."""
+ self._lock_holders.pop(key, None)
+
# ------------------------------------------------------------------
# Mode F — registry map
# ------------------------------------------------------------------
@@ -460,6 +483,26 @@ class InMemoryMessageBus(MessageBus):
"""
return dict(self._registries.get(namespace, {}))
+ async def registry_get(
+ self,
+ namespace: str,
+ field: str,
+ ) -> str | None:
+ """Return a single field value from the registry at
+ ``namespace``, or ``None`` if absent.
+
+ Args:
+ namespace (`str`):
+ Registry key.
+ field (`str`):
+ Field to retrieve.
+
+ Returns:
+ `str | None`:
+ The stored value, or ``None`` if missing.
+ """
+ return self._registries.get(namespace, {}).get(field)
+
async def registry_drop(self, namespace: str) -> None:
"""Delete the entire registry at ``namespace``.
diff --git a/src/agentscope/app/message_bus/_keys.py b/src/agentscope/app/message_bus/_keys.py
index d1d336bb7..b20c267bb 100644
--- a/src/agentscope/app/message_bus/_keys.py
+++ b/src/agentscope/app/message_bus/_keys.py
@@ -16,8 +16,12 @@ Add new business keys here as needed. As legacy keys are migrated off
from typing import Final
-class MessageBusKeys:
- """Application-layer key conventions for the message bus."""
+class MessageBusKeys: # pylint: disable=too-many-public-methods
+ """Application-layer key conventions for the message bus.
+
+ A flat registry of key/namespace builders — it grows one method per
+ business key, so the public-method count is expected to be high.
+ """
# ------------------------------------------------------------------
# Run-trigger queue — the discriminator carried by each entry on the
@@ -38,6 +42,14 @@ class MessageBusKeys:
drop the entry while the session is running; it re-queues until the
parked run releases its lock."""
+ WAKEUP_KIND_MESSAGE: Final = "message"
+ """Trigger kind: start a new turn from a genuine user ``Msg`` (e.g. an
+ inbound channel message). The dispatcher spawns the run with the
+ carried message as ``input_msg`` so it is persisted and reasoned over
+ as a real user turn. Like ``resume`` (and unlike ``wake``) it carries
+ input, so it is re-queued rather than dropped while the session is
+ running."""
+
# ------------------------------------------------------------------
# Cross-session UI projection — a generic per-session Redis-hash
# store onto which one session can project UI cards owned by another
@@ -238,3 +250,65 @@ class MessageBusKeys:
subscriber happens to be offline.
"""
return cls._INDEX_TASKS_SIGNAL
+
+ # ------------------------------------------------------------------
+ # Channel output forwarding — a durable queue of "a channel session
+ # is producing output" signals. Each node running channel adapters
+ # drains it; the node that pops a signal (and hosts that channel)
+ # subscribes to the session's event stream and forwards the reply
+ # back to the platform chat. Queue + atomic pop → exactly one node
+ # forwards, even though every node runs the adapter.
+ # ------------------------------------------------------------------
+
+ _CHANNEL_OUTBOUND_QUEUE = "agentscope:channel:outbound"
+ _CHANNEL_OUTBOUND_SIGNAL = "agentscope:channel:outbound:wake"
+ _CHANNEL_LIFECYCLE = "agentscope:channel:lifecycle"
+ _CHANNEL_LIVENESS = "agentscope:channel:liveness:{cid}"
+ _CHANNEL_MEDIA = "agentscope:channel:media:{cid}:{chat}:{uid}"
+ _CHANNEL_FORWARD = "agentscope:channel:forward:{sid}"
+ _CHANNEL_SEEN_CHATS = "agentscope:channel:seen_chats:{cid}"
+
+ @classmethod
+ def channel_outbound_queue(cls) -> str:
+ """Durable queue of channel output-forward signals."""
+ return cls._CHANNEL_OUTBOUND_QUEUE
+
+ @classmethod
+ def channel_outbound_signal(cls) -> str:
+ """Pub/sub nudge for channel output-forward consumers."""
+ return cls._CHANNEL_OUTBOUND_SIGNAL
+
+ @classmethod
+ def channel_lifecycle(cls) -> str:
+ """Pub/sub channel that nudges every node to reconcile its
+ running channel instances against storage."""
+ return cls._CHANNEL_LIFECYCLE
+
+ @classmethod
+ def channel_liveness(cls, channel_id: str) -> str:
+ """Per-channel per-node status heartbeat namespace."""
+ return cls._CHANNEL_LIVENESS.format(cid=channel_id)
+
+ @classmethod
+ def channel_media_buffer(
+ cls,
+ channel_id: str,
+ chat_id: str,
+ user_id: str,
+ ) -> str:
+ """Queue key buffering media until the next text message."""
+ return cls._CHANNEL_MEDIA.format(
+ cid=channel_id,
+ chat=chat_id,
+ uid=user_id,
+ )
+
+ @classmethod
+ def channel_forward_lease(cls, session_id: str) -> str:
+ """Per-run lock so exactly one node forwards a reply."""
+ return cls._CHANNEL_FORWARD.format(sid=session_id)
+
+ @classmethod
+ def channel_seen_chats(cls, channel_id: str) -> str:
+ """Registry namespace of chat_ids the bot has been messaged in."""
+ return cls._CHANNEL_SEEN_CHATS.format(cid=channel_id)
diff --git a/src/agentscope/app/message_bus/_redis_message_bus.py b/src/agentscope/app/message_bus/_redis_message_bus.py
index 57341145f..af07e13ef 100644
--- a/src/agentscope/app/message_bus/_redis_message_bus.py
+++ b/src/agentscope/app/message_bus/_redis_message_bus.py
@@ -449,6 +449,25 @@ class RedisMessageBus(MessageBus):
"""
return await self._client.hgetall(namespace) or {}
+ async def registry_get(
+ self,
+ namespace: str,
+ field: str,
+ ) -> str | None:
+ """Return a single field value from the Hash at ``namespace``.
+
+ Args:
+ namespace (`str`):
+ Hash key.
+ field (`str`):
+ Field to retrieve.
+
+ Returns:
+ `str | None`:
+ The stored value, or ``None`` if absent.
+ """
+ return await self._client.hget(namespace, field)
+
async def registry_drop(self, namespace: str) -> None:
"""Delete the entire Hash at ``namespace``.
@@ -639,3 +658,13 @@ class RedisMessageBus(MessageBus):
"""
result = await self._client.exists(key)
return bool(result)
+
+ async def try_lock(self, key: str, *, ttl_secs: int = 600) -> bool:
+ """Non-blocking claim via ``SET key NX EX``. See base."""
+ return bool(
+ await self._client.set(key, "1", nx=True, ex=ttl_secs),
+ )
+
+ async def unlock(self, key: str) -> None:
+ """Release a ``try_lock`` claim (best-effort ``DEL``)."""
+ await self._client.delete(key)
diff --git a/src/agentscope/app/storage/__init__.py b/src/agentscope/app/storage/__init__.py
index e05f9f457..3fee8470c 100644
--- a/src/agentscope/app/storage/__init__.py
+++ b/src/agentscope/app/storage/__init__.py
@@ -7,6 +7,11 @@ from ._redis_storage import RedisStorage
from ._model import (
AgentData,
AgentRecord,
+ ChannelBinding,
+ ChannelRecord,
+ RoutingConfig,
+ SessionScope,
+ SessionSettings,
CredentialRecord,
KnowledgeBaseData,
KnowledgeBaseRecord,
@@ -67,6 +72,11 @@ __all__ = [
"InviteConfig",
"AgentData",
"AgentRecord",
+ "ChannelBinding",
+ "ChannelRecord",
+ "RoutingConfig",
+ "SessionScope",
+ "SessionSettings",
"CredentialRecord",
"KnowledgeBaseData",
"KnowledgeBaseRecord",
diff --git a/src/agentscope/app/storage/_base.py b/src/agentscope/app/storage/_base.py
index c99ab28cc..3fcce650a 100644
--- a/src/agentscope/app/storage/_base.py
+++ b/src/agentscope/app/storage/_base.py
@@ -8,6 +8,7 @@ from typing import Any, Self
from ._model import (
AgentRecord,
+ ChannelRecord,
CredentialRecord,
KnowledgeBaseRecord,
KnowledgeDocumentRecord,
@@ -371,6 +372,8 @@ class StorageBase(ABC):
session_id: str | None = None,
source: SessionSource = SessionSource.USER,
source_schedule_id: str | None = None,
+ source_chat_id: str | None = None,
+ source_channel_id: str | None = None,
) -> SessionRecord:
"""Create or update a session for a (user, agent) pair.
@@ -509,6 +512,23 @@ class StorageBase(ABC):
ordered by creation time (newest first).
"""
+ @abstractmethod
+ async def list_sessions_by_channel(
+ self,
+ user_id: str,
+ channel_id: str,
+ ) -> list[SessionRecord]:
+ """Return all sessions derived from a given channel.
+
+ Args:
+ user_id (`str`): The owner user id.
+ channel_id (`str`): The channel id.
+
+ Returns:
+ `list[SessionRecord]`: Sessions the channel spawned, ordered
+ by creation time (newest first).
+ """
+
@abstractmethod
async def upsert_schedule(
self,
@@ -582,6 +602,125 @@ class StorageBase(ABC):
`list[ScheduleRecord]`: All schedule records in the store.
"""
+ # ------------------------------------------------------------------
+ # Channel persistence
+ #
+ # Optional capability: channels require the distributed message bus
+ # (locks / pub-sub / queues), so only bus-backed stores (Redis)
+ # implement these. Other backends inherit the NotImplementedError
+ # default.
+ # ------------------------------------------------------------------
+
+ async def upsert_channel(
+ self,
+ record: ChannelRecord,
+ platform_bot_id: str,
+ ) -> str:
+ """Persist a channel record and refresh its indexes.
+
+ ``record.id`` is a globally unique UUID, so the record lives at a
+ single global key; ``record.user_id`` drives the per-user index
+ and ``platform_bot_id`` (extracted from credentials by the
+ caller) drives the uniqueness index.
+
+ Args:
+ record (`ChannelRecord`): The channel record to store.
+ platform_bot_id (`str`): The platform-side bot identifier,
+ used to maintain the dedup index.
+
+ Returns:
+ `str`: The id of the stored record.
+ """
+ raise NotImplementedError(
+ "This storage backend has no channel support.",
+ )
+
+ async def get_channel(
+ self,
+ channel_id: str,
+ ) -> ChannelRecord | None:
+ """Fetch a channel record by its global id.
+
+ This is the primary lookup, used both by the management API and
+ by the channel runtime (which only has a channel_id in hand).
+
+ Args:
+ channel_id (`str`): The channel id.
+
+ Returns:
+ `ChannelRecord | None`: The record, or ``None`` if not found.
+ """
+ raise NotImplementedError(
+ "This storage backend has no channel support.",
+ )
+
+ async def list_channels(
+ self,
+ user_id: str,
+ ) -> list[ChannelRecord]:
+ """Return all channel records owned by the given user.
+
+ Args:
+ user_id (`str`): The owner user id.
+
+ Returns:
+ `list[ChannelRecord]`: All channel records for the user.
+ """
+ raise NotImplementedError(
+ "This storage backend has no channel support.",
+ )
+
+ async def list_all_channels(self) -> list[ChannelRecord]:
+ """Return every channel record across all users.
+
+ Used on startup / reconcile to restore channel instances.
+
+ Returns:
+ `list[ChannelRecord]`: All channel records in the store.
+ """
+ raise NotImplementedError(
+ "This storage backend has no channel support.",
+ )
+
+ async def delete_channel(
+ self,
+ channel_id: str,
+ platform_bot_id: str,
+ ) -> bool:
+ """Delete a channel record and remove it from all indexes.
+
+ Args:
+ channel_id (`str`): The id of the channel to delete.
+ platform_bot_id (`str`): The bot identifier (re-extracted
+ from credentials by the caller) so the dedup index entry
+ can be removed.
+
+ Returns:
+ `bool`: ``True`` if deleted, ``False`` if not found.
+ """
+ raise NotImplementedError(
+ "This storage backend has no channel support.",
+ )
+
+ async def get_channel_id_by_platform_bot_id(
+ self,
+ platform_bot_id: str,
+ ) -> str | None:
+ """Return the channel id currently bound to a platform bot, if any.
+
+ Used for uniqueness validation — no two channels may share the
+ same platform_bot_id.
+
+ Args:
+ platform_bot_id (`str`): The platform-side bot identifier.
+
+ Returns:
+ `str | None`: The bound channel id, or ``None``.
+ """
+ raise NotImplementedError(
+ "This storage backend has no channel support.",
+ )
+
# ------------------------------------------------------------------
# Message persistence
# ------------------------------------------------------------------
diff --git a/src/agentscope/app/storage/_model/__init__.py b/src/agentscope/app/storage/_model/__init__.py
index 2ea1d6520..614dc0e9c 100644
--- a/src/agentscope/app/storage/_model/__init__.py
+++ b/src/agentscope/app/storage/_model/__init__.py
@@ -2,6 +2,13 @@
"""Storage models for persisted resources."""
from ._agent import AgentRecord, AgentData, InviteConfig
+from ._channel import (
+ ChannelBinding,
+ ChannelRecord,
+ RoutingConfig,
+ SessionScope,
+ SessionSettings,
+)
from ._credential import CredentialRecord
from ._knowledge_base import KnowledgeBaseData, KnowledgeBaseRecord
from ._knowledge_document import (
@@ -27,6 +34,11 @@ from ._user import UserRecord
__all__ = [
"AgentData",
"AgentRecord",
+ "ChannelBinding",
+ "ChannelRecord",
+ "RoutingConfig",
+ "SessionScope",
+ "SessionSettings",
"CredentialRecord",
"KnowledgeBaseData",
"KnowledgeBaseRecord",
diff --git a/src/agentscope/app/storage/_model/_channel.py b/src/agentscope/app/storage/_model/_channel.py
new file mode 100644
index 000000000..3e3493aa4
--- /dev/null
+++ b/src/agentscope/app/storage/_model/_channel.py
@@ -0,0 +1,181 @@
+# -*- coding: utf-8 -*-
+"""The channel storage model. Key points:
+
+- Routing is one concept: an ordered list of :class:`ChannelBinding`.
+ Each rule matches an inbound event and yields two outputs — which
+ agent handles it and how the session is grouped.
+- ``(agent_id, session_id)`` is derived by a pure function (see
+ :func:`agentscope.app.channel.resolve`); there is no persisted
+ channel→session mapping table.
+- ``platform_bot_id`` is NOT stored — it is extracted from
+ ``credentials`` on write for the uniqueness index.
+"""
+from enum import Enum
+from typing import Any
+
+from pydantic import BaseModel, Field, field_validator
+
+from ....permission import PermissionMode
+
+
+class SessionScope(str, Enum):
+ """How inbound messages are grouped into agent sessions.
+
+ Scope is chat-centric: the session key is a projection of the
+ ``(chat_id, user_id)`` pair.
+ """
+
+ PER_CHAT = "per_chat"
+ """One session per chat. A direct message is naturally per-user
+ (the chat has only that user); a group chat shares one session
+ across all members."""
+
+ PER_CHAT_USER = "per_chat_user"
+ """One session per (chat, user). Only meaningful for group chats —
+ isolates each member into their own session within the group."""
+
+
+class ChannelBinding(BaseModel):
+ """One routing rule: match an inbound event, then decide which agent
+ handles it and how its session is grouped.
+
+ Rules are evaluated in list order; the first match wins. The final
+ rule must be a catch-all (``match_value == "*"``) — it carries the
+ channel's defaults.
+ """
+
+ match_key: str = "chat_id"
+ """Which field of the event to match: ``chat_id``, ``user_id``, or a
+ key inside ``event.metadata`` (e.g. ``chat_type``)."""
+
+ match_value: str = "*"
+ """Exact value to match, or ``"*"`` to match anything (catch-all)."""
+
+ agent_id: str
+ """The agent that handles matched messages."""
+
+ session_scope: SessionScope = SessionScope.PER_CHAT
+ """How matched messages are grouped into sessions."""
+
+
+class RoutingConfig(BaseModel):
+ """Ordered routing rules for a channel.
+
+ Validated so routing is always total and unambiguous: exactly one
+ catch-all, placed last, with no duplicate ``(match_key,
+ match_value)`` pairs.
+ """
+
+ bindings: list[ChannelBinding] = Field(default_factory=list)
+
+ @field_validator("bindings")
+ @classmethod
+ def _validate_bindings(
+ cls,
+ bindings: list[ChannelBinding],
+ ) -> list[ChannelBinding]:
+ if not bindings:
+ raise ValueError(
+ "routing.bindings must contain at least a catch-all rule "
+ "(match_value='*').",
+ )
+ # Exactly one catch-all, and it must be last.
+ catch_all_indices = [
+ i for i, b in enumerate(bindings) if b.match_value == "*"
+ ]
+ if len(catch_all_indices) != 1:
+ raise ValueError(
+ "routing.bindings must contain exactly one catch-all rule "
+ "(match_value='*').",
+ )
+ if catch_all_indices[0] != len(bindings) - 1:
+ raise ValueError(
+ "The catch-all rule (match_value='*') must be the last "
+ "binding; rules after it would be unreachable.",
+ )
+ # No duplicate (match_key, match_value) pairs.
+ seen: set[tuple[str, str]] = set()
+ for b in bindings:
+ key = (b.match_key, b.match_value)
+ if key in seen:
+ raise ValueError(
+ f"Duplicate routing rule for {key}; the later one "
+ "would be unreachable.",
+ )
+ seen.add(key)
+ return bindings
+
+
+class SessionSettings(BaseModel):
+ """Settings applied when a channel creates an agent session."""
+
+ chat_model_config: dict[str, Any]
+ """Model configuration for channel-created sessions. Required — there
+ is no global fallback default."""
+
+ fallback_chat_model_config: dict[str, Any] | None = None
+ """Optional fallback model configuration, used when the primary
+ model fails."""
+
+ permission_mode: str = PermissionMode.DEFAULT.value
+ """Permission mode for channel sessions. Defaults to ``default`` so a
+ tool needing approval surfaces the confirmation card rather than being
+ auto-denied. Any :class:`PermissionMode` is accepted — the engine
+ resolves every mode server-side and the ASK path maps to the card."""
+
+ @field_validator("permission_mode")
+ @classmethod
+ def _validate_permission_mode(cls, v: str) -> str:
+ PermissionMode(v) # reject values outside the enum
+ return v
+
+
+class ChannelRecord(BaseModel):
+ """Persistent record for a channel instance — the single source of
+ truth. Running adapter instances are a projection of this record.
+ """
+
+ # -- Identity & ownership --
+
+ id: str
+ """Server-generated UUID."""
+
+ channel_type: str
+ """Platform adapter type: feishu / dingtalk / discord / wecom."""
+
+ name: str | None = None
+ """Optional display name, so two channels of the same platform are
+ distinguishable in the UI."""
+
+ user_id: str
+ """AgentScope-side owner. Not platform data; used for access
+ control (a user only sees their own channels)."""
+
+ enabled: bool = True
+
+ # -- Platform access --
+
+ credentials: dict[str, Any] = Field(default_factory=dict)
+ """Platform credentials (app_id, app_secret, ...). Fields marked
+ ``format: password`` in the type's credential schema are secret.
+
+ NOTE: at-rest encryption is a documented future hook; today these
+ are masked at the API boundary. ``platform_bot_id`` is NOT stored
+ here — it is extracted from these credentials on write for the
+ uniqueness index.
+ """
+
+ platform_config: dict[str, Any] = Field(default_factory=dict)
+ """Platform-specific configuration (e.g. only_at_reply for Feishu)."""
+
+ # -- Business configuration --
+
+ routing: RoutingConfig
+ session: SessionSettings
+
+ # -- Versioning (reconcile basis for the lifecycle dispatcher) --
+
+ created_at: str
+ updated_at: str
+ """Refreshed on every write; the dispatcher compares it to detect
+ that a running instance's config has changed."""
diff --git a/src/agentscope/app/storage/_model/_session.py b/src/agentscope/app/storage/_model/_session.py
index af30db18d..58964d9e5 100644
--- a/src/agentscope/app/storage/_model/_session.py
+++ b/src/agentscope/app/storage/_model/_session.py
@@ -14,6 +14,7 @@ class SessionSource(str, Enum):
USER = "user"
SCHEDULE = "schedule"
+ CHANNEL = "channel"
class ChatModelConfig(BaseModel):
@@ -161,6 +162,17 @@ class SessionRecord(_RecordBase):
source_schedule_id: str | None = None
"""The source schedule Id."""
+ source_chat_id: str | None = None
+ """For channel-created sessions, the platform chat this session maps
+ to. Recorded so agent output can be delivered back to the right chat
+ even on a background / scheduled wake, where no inbound message is
+ available to supply it."""
+
+ source_channel_id: str | None = None
+ """For channel-created sessions, the owning channel id. Lets the
+ output forwarder locate the channel adapter + presentation settings
+ on a background / scheduled wake."""
+
team_id: str | None = None
"""The team this session participates in, if any.
diff --git a/src/agentscope/app/storage/_redis_storage.py b/src/agentscope/app/storage/_redis_storage.py
index e958177ed..ee5b7cda8 100644
--- a/src/agentscope/app/storage/_redis_storage.py
+++ b/src/agentscope/app/storage/_redis_storage.py
@@ -11,6 +11,7 @@ from pydantic import BaseModel
from ._base import StorageBase
from ._model import (
AgentRecord,
+ ChannelRecord,
CredentialRecord,
KnowledgeBaseRecord,
KnowledgeDocumentRecord,
@@ -98,6 +99,18 @@ class RedisStorage(StorageBase):
"agentscope:user:{user_id}:schedule:{schedule_id}:sessions"
)
+ # channel_id is a globally unique UUID, so the record lives at a
+ # single global key. Indexes: per-user (management list),
+ # all-channels (reconcile enumeration), bot-id (uniqueness /
+ # dedup).
+ channel: str = "agentscope:channel_record:{channel_id}"
+ channel_index: str = "agentscope:user:{user_id}:channels"
+ channel_all_index: str = "agentscope:channels"
+ channel_botid_index: str = "agentscope:channel_botid:{platform_bot_id}"
+ channel_session_index: str = (
+ "agentscope:user:{user_id}:channel:{channel_id}:sessions"
+ )
+
team: str = "agentscope:user:{user_id}:team:{team_id}"
team_index: str = "agentscope:user:{user_id}:teams"
@@ -861,6 +874,8 @@ class RedisStorage(StorageBase):
session_id: str | None = None,
source: SessionSource = SessionSource.USER,
source_schedule_id: str | None = None,
+ source_chat_id: str | None = None,
+ source_channel_id: str | None = None,
) -> SessionRecord:
"""Create or update a session for a (user, agent) pair.
@@ -893,6 +908,8 @@ class RedisStorage(StorageBase):
config=config,
source=source,
source_schedule_id=source_schedule_id,
+ source_chat_id=source_chat_id,
+ source_channel_id=source_channel_id,
state=state if state is not None else AgentState(),
**new_id_kwargs,
)
@@ -917,6 +934,14 @@ class RedisStorage(StorageBase):
)
await self._client.sadd(schedule_session_key, record.id)
+ if source_channel_id:
+ channel_session_key = self._key(
+ self.key_config.channel_session_index,
+ user_id=user_id,
+ channel_id=source_channel_id,
+ )
+ await self._client.sadd(channel_session_key, record.id)
+
return record
async def update_session_state(
@@ -1080,6 +1105,14 @@ class RedisStorage(StorageBase):
)
await self._client.srem(schedule_session_key, session_id)
+ if record.source_channel_id:
+ channel_session_key = self._key(
+ self.key_config.channel_session_index,
+ user_id=user_id,
+ channel_id=record.source_channel_id,
+ )
+ await self._client.srem(channel_session_key, session_id)
+
return True
async def list_sessions_by_schedule(
@@ -1108,6 +1141,32 @@ class RedisStorage(StorageBase):
records.sort(key=lambda r: r.created_at, reverse=True)
return records
+ async def list_sessions_by_channel(
+ self,
+ user_id: str,
+ channel_id: str,
+ ) -> list[SessionRecord]:
+ """Return all sessions derived from a given channel."""
+ channel_session_key = self._key(
+ self.key_config.channel_session_index,
+ user_id=user_id,
+ channel_id=channel_id,
+ )
+ ids = await self._client.smembers(channel_session_key)
+ records = []
+ for session_id in ids:
+ raw = await self._client.get(
+ self._key(
+ self.key_config.session,
+ user_id=user_id,
+ session_id=session_id,
+ ),
+ )
+ if raw:
+ records.append(SessionRecord.model_validate_json(raw))
+ records.sort(key=lambda r: r.created_at, reverse=True)
+ return records
+
async def upsert_schedule(
self,
user_id: str,
@@ -1233,6 +1292,124 @@ class RedisStorage(StorageBase):
records.append(ScheduleRecord.model_validate_json(raw))
return records
+ # ------------------------------------------------------------------
+ # Channel persistence
+ # ------------------------------------------------------------------
+
+ async def upsert_channel(
+ self,
+ record: ChannelRecord,
+ platform_bot_id: str,
+ ) -> str:
+ """Persist a channel record and refresh its indexes."""
+ key = self._key(self.key_config.channel, channel_id=record.id)
+ index_key = self._key(
+ self.key_config.channel_index,
+ user_id=record.user_id,
+ )
+ botid_key = self._key(
+ self.key_config.channel_botid_index,
+ platform_bot_id=platform_bot_id,
+ )
+ await self._set_with_ttl(key, record.model_dump_json())
+ await self._client.sadd(index_key, record.id)
+ await self._client.sadd(self.key_config.channel_all_index, record.id)
+ await self._set_with_ttl(botid_key, record.id)
+ return record.id
+
+ async def get_channel(
+ self,
+ channel_id: str,
+ ) -> ChannelRecord | None:
+ """Fetch a channel record by its global id."""
+ raw = await self._client.get(
+ self._key(self.key_config.channel, channel_id=channel_id),
+ )
+ if not raw:
+ return None
+ return ChannelRecord.model_validate_json(raw)
+
+ async def list_channels(self, user_id: str) -> list[ChannelRecord]:
+ """Return all channel records owned by the given user.
+
+ Stale entries whose record key has expired are purged from the
+ user index (self-healing).
+ """
+ index_key = self._key(self.key_config.channel_index, user_id=user_id)
+ return await self._collect_channels(
+ index_key,
+ await self._client.smembers(index_key),
+ )
+
+ async def list_all_channels(self) -> list[ChannelRecord]:
+ """Return every channel record across all users."""
+ index_key = self.key_config.channel_all_index
+ return await self._collect_channels(
+ index_key,
+ await self._client.smembers(index_key),
+ )
+
+ async def _collect_channels(
+ self,
+ index_key: str,
+ ids: "set[str]",
+ ) -> list[ChannelRecord]:
+ """Load channel records for ``ids``, purging stale index entries."""
+ records: list[ChannelRecord] = []
+ stale: list[str] = []
+ for channel_id in ids:
+ raw = await self._client.get(
+ self._key(self.key_config.channel, channel_id=channel_id),
+ )
+ if raw:
+ records.append(ChannelRecord.model_validate_json(raw))
+ else:
+ stale.append(channel_id)
+ if stale:
+ await self._client.srem(index_key, *stale)
+ return records
+
+ async def delete_channel(
+ self,
+ channel_id: str,
+ platform_bot_id: str,
+ ) -> bool:
+ """Delete a channel record and clean up all indexes."""
+ key = self._key(self.key_config.channel, channel_id=channel_id)
+ raw = await self._client.get(key)
+ if not raw:
+ return False
+ record = ChannelRecord.model_validate_json(raw)
+
+ await self._client.delete(key)
+ await self._client.srem(
+ self._key(
+ self.key_config.channel_index,
+ user_id=record.user_id,
+ ),
+ channel_id,
+ )
+ await self._client.srem(self.key_config.channel_all_index, channel_id)
+ await self._client.delete(
+ self._key(
+ self.key_config.channel_botid_index,
+ platform_bot_id=platform_bot_id,
+ ),
+ )
+ return True
+
+ async def get_channel_id_by_platform_bot_id(
+ self,
+ platform_bot_id: str,
+ ) -> str | None:
+ """Return the channel id bound to a platform bot, if any."""
+ return await self._client.get(
+ self._key(
+ self.key_config.channel_botid_index,
+ platform_bot_id=platform_bot_id,
+ ),
+ )
+
# ------------------------------------------------------------------
# Message persistence
# ------------------------------------------------------------------
diff --git a/src/agentscope/app/storage/_sql/_storage.py b/src/agentscope/app/storage/_sql/_storage.py
index 381fa1b70..1d4666b6c 100644
--- a/src/agentscope/app/storage/_sql/_storage.py
+++ b/src/agentscope/app/storage/_sql/_storage.py
@@ -1050,6 +1050,8 @@ class AsyncSQLAlchemyStorage(StorageBase):
session_id: str | None = None,
source: SessionSource = SessionSource.USER,
source_schedule_id: str | None = None,
+ source_chat_id: str | None = None,
+ source_channel_id: str | None = None,
) -> SessionRecord:
"""Create or update a session — same shape as the Redis backend."""
if session_id:
@@ -1070,6 +1072,8 @@ class AsyncSQLAlchemyStorage(StorageBase):
config=config,
source=source,
source_schedule_id=source_schedule_id,
+ source_chat_id=source_chat_id,
+ source_channel_id=source_channel_id,
state=state if state is not None else AgentState(),
**new_id_kwargs,
)
@@ -1208,6 +1212,36 @@ class AsyncSQLAlchemyStorage(StorageBase):
)
return [_to_record(r, SessionRecord) for r in rows]
+ async def list_sessions_by_channel(
+ self,
+ user_id: str,
+ channel_id: str,
+ ) -> list[SessionRecord]:
+ """Sessions derived from *channel_id* — newest first.
+
+ ``source_channel_id`` lives in the JSON payload (not a promoted
+ column), so it is matched inside the payload.
+ """
+ from sqlalchemy import select
+
+ async with self._session() as sess:
+ rows = (
+ (
+ await sess.execute(
+ select(SessionRow)
+ .where(
+ SessionRow.user_id == user_id,
+ SessionRow.payload["source_channel_id"].as_string()
+ == channel_id,
+ )
+ .order_by(SessionRow.created_at.desc()),
+ )
+ )
+ .scalars()
+ .all()
+ )
+ return [_to_record(r, SessionRecord) for r in rows]
+
# ------------------------------------------------------------------
# Schedules
# ------------------------------------------------------------------
diff --git a/src/agentscope/workspace/_base.py b/src/agentscope/workspace/_base.py
index 86a173bad..e87e58656 100644
--- a/src/agentscope/workspace/_base.py
+++ b/src/agentscope/workspace/_base.py
@@ -493,7 +493,7 @@ class WorkspaceBase:
block.source,
Base64Source,
):
- block = await self._offload_data_block(block)
+ block = await self.offload_data_block(block)
content.append(block)
msg.content = content
lines.append(msg.model_dump_json())
@@ -555,7 +555,7 @@ class WorkspaceBase:
parts.append(block.text)
elif isinstance(block, DataBlock):
if isinstance(block.source, Base64Source):
- d = await self._offload_data_block(block)
+ d = await self.offload_data_block(block)
url = str(d.source.url)
else:
url = str(block.source.url)
@@ -567,7 +567,7 @@ class WorkspaceBase:
await backend.write_file(path, "".join(parts).encode("utf-8"))
return path
- async def _offload_data_block(self, block: DataBlock) -> DataBlock:
+ async def offload_data_block(self, block: DataBlock) -> DataBlock:
"""Persist a base64 :class:`DataBlock` under ``data/``.
The decoded payload is stored at
@@ -583,9 +583,9 @@ class WorkspaceBase:
Returns:
`DataBlock`:
- A new :class:`DataBlock` whose source is a ``file://``
- URL pointing at the persisted file inside the
- workspace.
+ A new :class:`DataBlock` whose source is a portable
+ ``workspace://`` URL pointing at the persisted file
+ inside the workspace.
"""
if not isinstance(block.source, Base64Source):
return block
@@ -593,6 +593,7 @@ class WorkspaceBase:
backend = self.get_backend()
hash_str = hashlib.sha256(block.source.data.encode()).hexdigest()
ext = mimetypes.guess_extension(block.source.media_type) or ".bin"
+ rel = f"{DEFAULT_DATA_DIR}/{hash_str}{ext}"
path = backend.join_path(self._data_dir, f"{hash_str}{ext}")
if not await backend.file_exists(path):
@@ -601,11 +602,16 @@ class WorkspaceBase:
base64.b64decode(block.source.data),
)
+ # A ``workspace://`` reference (workspace-relative path). Unlike a
+ # node-local ``file://`` path it is portable: a serving endpoint
+ # resolves the actual workspace from the request's session
+ # context and reads the relative path. See docs TODO (frontend
+ # ``workspace://`` rendering).
return DataBlock(
id=block.id,
name=block.name,
source=URLSource(
- url=AnyUrl(self._path_to_file_uri(path)),
+ url=AnyUrl(f"workspace:///{rel}"),
media_type=block.source.media_type,
),
)
diff --git a/src/agentscope/workspace/_offload_protocol.py b/src/agentscope/workspace/_offload_protocol.py
index 93a6ecbe5..5378b1279 100644
--- a/src/agentscope/workspace/_offload_protocol.py
+++ b/src/agentscope/workspace/_offload_protocol.py
@@ -2,12 +2,26 @@
"""The offload protocol."""
from typing import Protocol
-from ..message import Msg, ToolResultBlock
+from ..message import DataBlock, Msg, ToolResultBlock
class Offloader(Protocol):
"""The offloader protocol."""
+ async def offload_data_block(self, block: DataBlock) -> DataBlock:
+ """Persist a base64 data block to workspace storage.
+
+ Args:
+ block (`DataBlock`):
+ A data block. Blocks already backed by a URL source are
+ returned unchanged.
+
+ Returns:
+ `DataBlock`:
+ A data block whose source is a portable ``workspace://``
+ URL pointing at the persisted file inside the workspace.
+ """
+
async def offload_context(
self,
session_id: str,
diff --git a/tests/channel_gateway_test.py b/tests/channel_gateway_test.py
new file mode 100644
index 000000000..87a56b403
--- /dev/null
+++ b/tests/channel_gateway_test.py
@@ -0,0 +1,416 @@
+# -*- coding: utf-8 -*-
+"""Tests for channel data-plane internals that stand alone from a live run.
+
+Covers the channel's event-stream folding (``send_response`` driven off a
+seeded event list via a fake channel), the gateway's media aggregation,
+and the text-confirmation reply parser. Full two-phase orchestration
+needs a running agent and is exercised end-to-end against a real bot.
+"""
+# pylint: disable=protected-access,missing-function-docstring,unused-argument
+# pylint: disable=attribute-defined-outside-init
+from typing import Any, AsyncIterator
+from unittest import IsolatedAsyncioTestCase
+
+from agentscope.app.channel._base import (
+ ChannelBase,
+ ChannelEvent,
+ _EVENT_ADAPTER,
+)
+from agentscope.app.channel._gateway import ChannelGateway
+from agentscope.message import Msg
+from agentscope.app.message_bus import InMemoryMessageBus
+from agentscope.app.storage import (
+ ChannelBinding,
+ ChannelRecord,
+ RoutingConfig,
+ SessionScope,
+ SessionSettings,
+)
+from agentscope.app.workspace_manager import (
+ IsolationPolicy,
+ WorkspaceManagerBase,
+)
+from agentscope.event import (
+ DataBlockDeltaEvent,
+ DataBlockEndEvent,
+ DataBlockStartEvent,
+ ReplyEndEvent,
+ ReplyStartEvent,
+ RequireUserConfirmEvent,
+ TextBlockDeltaEvent,
+ TextBlockEndEvent,
+ TextBlockStartEvent,
+ ThinkingBlockDeltaEvent,
+ ThinkingBlockEndEvent,
+ ThinkingBlockStartEvent,
+)
+from agentscope.message import DataBlock, TextBlock
+from agentscope.message._block import Base64Source, URLSource
+from agentscope.types import ReplyFinishedReason
+
+_RID = "reply-1"
+
+
+class _WM(WorkspaceManagerBase):
+ """A workspace manager exercising only assign_workspace_id."""
+
+ async def get_workspace(self, *args: Any, **kwargs: Any) -> Any:
+ raise NotImplementedError
+
+ async def close(self, workspace_id: str) -> None:
+ pass
+
+ async def close_all(self) -> None:
+ pass
+
+
+def _event() -> ChannelEvent:
+ return ChannelEvent(channel_id="chan-1", channel_user_id="u", chat_id="c")
+
+
+async def _aiter(events: list) -> AsyncIterator[dict]:
+ for evt in events:
+ yield evt.model_dump(mode="json")
+
+
+class _FakeChannel(ChannelBase):
+ """A channel that records what ``send_response`` delivers."""
+
+ channel_type = "fake"
+ display_name = "Fake"
+ platform_bot_id_field = "id"
+
+ def __init__(self) -> None:
+ self.delivered: list = []
+ self.confirm: Any = None
+
+ @property
+ def channel_id(self) -> str:
+ return "chan-1"
+
+ async def start_listening(self, emit: Any) -> None:
+ pass
+
+ async def send_response(self, event: Any, events: Any) -> None:
+ reply = None
+ async for raw in events:
+ evt = _EVENT_ADAPTER.validate_python(raw)
+ if isinstance(evt, RequireUserConfirmEvent):
+ self.confirm = evt
+ break
+ reply_id = getattr(evt, "reply_id", None)
+ if reply_id is not None:
+ if reply is None:
+ reply = Msg(name="a", role="assistant", content=[])
+ reply.id = reply_id
+ reply.append_event(evt)
+ if isinstance(evt, ReplyEndEvent):
+ break
+ self.delivered.extend(
+ self._render(
+ reply,
+ show_thinking=self._show_thinking,
+ show_tool_process=self._show_tool_process,
+ ),
+ )
+
+
+async def _run(events: list, **presentation: Any) -> _FakeChannel:
+ channel = _FakeChannel()
+ channel._show_tool_process = presentation.get("show_tool_process", False)
+ channel._show_thinking = presentation.get("show_thinking", False)
+ await channel.send_response(_event(), _aiter(events))
+ return channel
+
+
+def _text(channel: _FakeChannel) -> str:
+ return "".join(
+ b.text for b in channel.delivered if isinstance(b, TextBlock)
+ )
+
+
+def _text_blocks(*deltas: str) -> list:
+ events: list = [TextBlockStartEvent(reply_id=_RID, block_id="t1")]
+ events += [
+ TextBlockDeltaEvent(reply_id=_RID, block_id="t1", delta=d)
+ for d in deltas
+ ]
+ events.append(TextBlockEndEvent(reply_id=_RID, block_id="t1"))
+ return events
+
+
+class SendResponseTest(IsolatedAsyncioTestCase):
+ """The event-stream accumulation (via Msg) + render in send_response."""
+
+ async def test_text_reply(self) -> None:
+ channel = await _run(
+ [
+ ReplyStartEvent(session_id="s", reply_id=_RID, name="a"),
+ *_text_blocks("Hello ", "world"),
+ ReplyEndEvent(session_id="s", reply_id=_RID),
+ ],
+ )
+ self.assertEqual(_text(channel), "Hello world")
+ self.assertIsNone(channel.confirm)
+
+ async def test_confirm_delivers_text_then_presents(self) -> None:
+ channel = await _run(
+ [
+ ReplyStartEvent(session_id="s", reply_id=_RID, name="a"),
+ *_text_blocks("working"),
+ RequireUserConfirmEvent(
+ id="req-1",
+ reply_id=_RID,
+ tool_calls=[],
+ ),
+ ReplyEndEvent(session_id="s", reply_id=_RID), # not reached
+ ],
+ )
+ self.assertEqual(_text(channel), "working")
+ self.assertIsNotNone(channel.confirm)
+ self.assertEqual(channel.confirm.id, "req-1")
+
+ async def test_error_reply_end(self) -> None:
+ channel = await _run(
+ [
+ ReplyStartEvent(session_id="s", reply_id=_RID, name="a"),
+ ReplyEndEvent(
+ session_id="s",
+ reply_id=_RID,
+ finished_reason=ReplyFinishedReason.ERROR,
+ ),
+ ],
+ )
+ self.assertIn("error", _text(channel).lower())
+
+ async def test_thinking_filtered_by_default(self) -> None:
+ channel = await _run(
+ [
+ ReplyStartEvent(session_id="s", reply_id=_RID, name="a"),
+ ThinkingBlockStartEvent(reply_id=_RID, block_id="k1"),
+ ThinkingBlockDeltaEvent(
+ reply_id=_RID,
+ block_id="k1",
+ delta="hmm",
+ ),
+ ThinkingBlockEndEvent(reply_id=_RID, block_id="k1"),
+ *_text_blocks("answer"),
+ ReplyEndEvent(session_id="s", reply_id=_RID),
+ ],
+ )
+ self.assertEqual(_text(channel), "answer")
+
+ async def test_thinking_shown_when_enabled(self) -> None:
+ channel = await _run(
+ [
+ ReplyStartEvent(session_id="s", reply_id=_RID, name="a"),
+ ThinkingBlockStartEvent(reply_id=_RID, block_id="k1"),
+ ThinkingBlockDeltaEvent(
+ reply_id=_RID,
+ block_id="k1",
+ delta="hmm",
+ ),
+ ThinkingBlockEndEvent(reply_id=_RID, block_id="k1"),
+ *_text_blocks("answer"),
+ ReplyEndEvent(session_id="s", reply_id=_RID),
+ ],
+ show_thinking=True,
+ )
+ self.assertIn("hmm", _text(channel))
+
+ async def test_data_block_reassembled_and_delivered(self) -> None:
+ channel = await _run(
+ [
+ ReplyStartEvent(session_id="s", reply_id=_RID, name="a"),
+ DataBlockStartEvent(
+ reply_id=_RID,
+ block_id="d1",
+ media_type="image/png",
+ ),
+ DataBlockDeltaEvent(
+ reply_id=_RID,
+ block_id="d1",
+ data="aW1n",
+ media_type="image/png",
+ ),
+ DataBlockEndEvent(reply_id=_RID, block_id="d1"),
+ ReplyEndEvent(session_id="s", reply_id=_RID),
+ ],
+ )
+ data = [b for b in channel.delivered if isinstance(b, DataBlock)]
+ self.assertEqual(len(data), 1)
+ self.assertIsInstance(data[0].source, Base64Source)
+ self.assertEqual(data[0].source.data, "aW1n")
+ self.assertEqual(data[0].source.media_type, "image/png")
+
+
+class MediaBufferTest(IsolatedAsyncioTestCase):
+ """Media-only messages buffer; a text message drains them."""
+
+ def _img(self, name: str) -> DataBlock:
+ return DataBlock(
+ source=URLSource(
+ url=f"https://example.com/{name}",
+ media_type="image/png",
+ ),
+ )
+
+ def _media_event(self, name: str) -> ChannelEvent:
+ return ChannelEvent(
+ channel_id="c",
+ channel_user_id="u",
+ chat_id="chat",
+ content=[self._img(name)],
+ )
+
+ async def test_aggregate_media_only_buffers(self) -> None:
+ bus = InMemoryMessageBus()
+ gw = ChannelGateway(
+ storage=None,
+ message_bus=bus,
+ workspace_manager=_WM(isolation=IsolationPolicy.PER_AGENT),
+ )
+ self.assertIsNone(
+ await gw._aggregate_media(self._media_event("a.png")),
+ )
+
+ async def test_aggregate_text_drains_buffered_media(self) -> None:
+ bus = InMemoryMessageBus()
+ gw = ChannelGateway(
+ storage=None,
+ message_bus=bus,
+ workspace_manager=_WM(isolation=IsolationPolicy.PER_AGENT),
+ )
+ await gw._aggregate_media(self._media_event("a.png"))
+ await gw._aggregate_media(self._media_event("b.png"))
+ content = await gw._aggregate_media(
+ ChannelEvent(
+ channel_id="c",
+ channel_user_id="u",
+ chat_id="chat",
+ content=[TextBlock(text="look")],
+ ),
+ )
+ assert content is not None
+ self.assertEqual(len(content), 3) # two buffered images + text
+ self.assertIsInstance(content[0], DataBlock)
+ self.assertIsInstance(content[-1], TextBlock)
+
+
+class _RecordingStorage:
+ """Storage stub capturing the workspace_id of upserted sessions."""
+
+ def __init__(self) -> None:
+ self.workspace_ids: list[str] = []
+
+ async def get_session(self, **kwargs: Any) -> None:
+ return None
+
+ async def upsert_session(self, *, config: Any, **kwargs: Any) -> None:
+ self.workspace_ids.append(config.workspace_id)
+
+
+def _channel_record(user_id: str) -> ChannelRecord:
+ return ChannelRecord(
+ id="chan-1",
+ channel_type="feishu",
+ user_id=user_id,
+ routing=RoutingConfig(
+ bindings=[ChannelBinding(match_value="*", agent_id="agent-x")],
+ ),
+ session=SessionSettings(
+ chat_model_config={
+ "type": "openai_chat",
+ "credential_id": "cred-1",
+ "model": "gpt-4",
+ "parameters": {},
+ },
+ ),
+ created_at="t",
+ updated_at="t",
+ )
+
+
+class WorkspaceIsolationTest(IsolatedAsyncioTestCase):
+ """Channel-created sessions get isolated workspaces, not a shared one."""
+
+ async def test_distinct_users_get_distinct_workspaces(self) -> None:
+ storage = _RecordingStorage()
+ gw = ChannelGateway(
+ storage=storage,
+ message_bus=InMemoryMessageBus(),
+ workspace_manager=_WM(isolation=IsolationPolicy.PER_USER),
+ )
+ await gw._ensure_session(
+ _channel_record("user-a"),
+ "agent-x",
+ "s-a",
+ ChannelEvent(
+ channel_id="c",
+ channel_user_id="u",
+ chat_id="chat-a",
+ ),
+ SessionScope.PER_CHAT,
+ )
+ await gw._ensure_session(
+ _channel_record("user-b"),
+ "agent-x",
+ "s-b",
+ ChannelEvent(
+ channel_id="c",
+ channel_user_id="u",
+ chat_id="chat-b",
+ ),
+ SessionScope.PER_CHAT,
+ )
+ self.assertEqual(len(storage.workspace_ids), 2)
+ # Different owners must not alias the same workspace.
+ self.assertNotEqual(
+ storage.workspace_ids[0],
+ storage.workspace_ids[1],
+ )
+
+
+class FeishuPostParseTest(IsolatedAsyncioTestCase):
+ """Feishu rich-text ``post`` flattens to ordered text + data blocks."""
+
+ async def test_mixed_text_image_link(self) -> None:
+ from agentscope.app.channel._feishu._channel import FeishuChannel
+
+ channel = FeishuChannel(
+ "c",
+ FeishuChannel.Credentials(app_id="a", app_secret="s"),
+ FeishuChannel.Config(),
+ )
+
+ async def _fake_download(
+ message_id: str,
+ key: str,
+ resource_type: str,
+ default_mime: str,
+ name: str,
+ ) -> DataBlock:
+ return DataBlock(
+ source=Base64Source(data="aW1n", media_type=default_mime),
+ name=name,
+ )
+
+ setattr(channel, "_download_resource", _fake_download)
+ post = {
+ "title": "T",
+ "content": [
+ [
+ {"tag": "text", "text": "hello "},
+ {"tag": "img", "image_key": "img-1"},
+ ],
+ [{"tag": "a", "text": "link", "href": "http://x"}],
+ ],
+ }
+ blocks = await channel._parse_post(post, "m1")
+ self.assertIsInstance(blocks[0], TextBlock)
+ self.assertIn("hello", blocks[0].text)
+ self.assertIsInstance(blocks[1], DataBlock)
+ self.assertEqual(blocks[1].source.data, "aW1n")
+ self.assertTrue(
+ any(isinstance(b, TextBlock) and "link" in b.text for b in blocks),
+ )
diff --git a/tests/channel_routing_test.py b/tests/channel_routing_test.py
new file mode 100644
index 000000000..362980e24
--- /dev/null
+++ b/tests/channel_routing_test.py
@@ -0,0 +1,172 @@
+# -*- coding: utf-8 -*-
+"""Tests for channel routing — the pure ``resolve`` function that maps an
+inbound event to ``(agent_id, session_id)``.
+
+Covers: catch-all default, first-match-wins ordering, per_chat vs
+per_chat_user session grouping, agent id embedded in the session id, and
+determinism across calls.
+"""
+from unittest import TestCase
+
+from agentscope.app.channel._base import ChannelEvent
+from agentscope.app.channel._routing import resolve
+from agentscope.app.storage import (
+ ChannelBinding,
+ ChannelRecord,
+ RoutingConfig,
+ SessionScope,
+ SessionSettings,
+)
+
+
+def _record(bindings: list[ChannelBinding]) -> ChannelRecord:
+ return ChannelRecord(
+ id="chan-1",
+ channel_type="feishu",
+ user_id="owner-1",
+ routing=RoutingConfig(bindings=bindings),
+ session=SessionSettings(chat_model_config={"type": "x"}),
+ created_at="t",
+ updated_at="t",
+ )
+
+
+def _event(
+ chat_id: str = "oc_group",
+ user_id: str = "ou_alice",
+ metadata: dict | None = None,
+) -> ChannelEvent:
+ return ChannelEvent(
+ channel_id="chan-1",
+ channel_user_id=user_id,
+ chat_id=chat_id,
+ metadata=metadata or {},
+ )
+
+
+class ChannelRoutingTest(TestCase):
+ """Unit tests for :func:`resolve`."""
+
+ def test_catch_all_default(self) -> None:
+ """A lone catch-all routes everything to its agent."""
+ rec = _record(
+ [ChannelBinding(match_value="*", agent_id="general")],
+ )
+ agent_id, session_id, _ = resolve(_event(), rec)
+ self.assertEqual(agent_id, "general")
+ self.assertTrue(session_id)
+
+ def test_first_match_wins(self) -> None:
+ """Earlier rules take precedence over later ones."""
+ rec = _record(
+ [
+ ChannelBinding(
+ match_key="chat_id",
+ match_value="oc_vip",
+ agent_id="vip",
+ ),
+ ChannelBinding(match_value="*", agent_id="general"),
+ ],
+ )
+ self.assertEqual(resolve(_event(chat_id="oc_vip"), rec)[0], "vip")
+ self.assertEqual(resolve(_event(chat_id="oc_x"), rec)[0], "general")
+
+ def test_match_on_metadata_key(self) -> None:
+ """match_key may reference an event.metadata field."""
+ rec = _record(
+ [
+ ChannelBinding(
+ match_key="chat_type",
+ match_value="p2p",
+ agent_id="assistant",
+ ),
+ ChannelBinding(match_value="*", agent_id="general"),
+ ],
+ )
+ agent_id, _, _ = resolve(
+ _event(metadata={"chat_type": "p2p"}),
+ rec,
+ )
+ self.assertEqual(agent_id, "assistant")
+
+ def test_per_chat_shares_across_users(self) -> None:
+ """PER_CHAT: different users in the same chat share a session."""
+ rec = _record(
+ [
+ ChannelBinding(
+ match_value="*",
+ agent_id="a",
+ session_scope=SessionScope.PER_CHAT,
+ ),
+ ],
+ )
+ s_alice = resolve(_event(user_id="ou_alice"), rec)[1]
+ s_bob = resolve(_event(user_id="ou_bob"), rec)[1]
+ self.assertEqual(s_alice, s_bob)
+
+ def test_per_chat_user_isolates_users(self) -> None:
+ """PER_CHAT_USER: users in the same chat get distinct sessions."""
+ rec = _record(
+ [
+ ChannelBinding(
+ match_value="*",
+ agent_id="a",
+ session_scope=SessionScope.PER_CHAT_USER,
+ ),
+ ],
+ )
+ s_alice = resolve(_event(user_id="ou_alice"), rec)[1]
+ s_bob = resolve(_event(user_id="ou_bob"), rec)[1]
+ self.assertNotEqual(s_alice, s_bob)
+
+ def test_different_chats_distinct_sessions(self) -> None:
+ """PER_CHAT: different chats never collide."""
+ rec = _record(
+ [ChannelBinding(match_value="*", agent_id="a")],
+ )
+ s1 = resolve(_event(chat_id="oc_1"), rec)[1]
+ s2 = resolve(_event(chat_id="oc_2"), rec)[1]
+ self.assertNotEqual(s1, s2)
+
+ def test_agent_embedded_in_session_id(self) -> None:
+ """Same scope key but different agents → different sessions."""
+ rec_a = _record([ChannelBinding(match_value="*", agent_id="a")])
+ rec_b = _record([ChannelBinding(match_value="*", agent_id="b")])
+ s_a = resolve(_event(), rec_a)[1]
+ s_b = resolve(_event(), rec_b)[1]
+ self.assertNotEqual(s_a, s_b)
+
+ def test_deterministic(self) -> None:
+ """resolve is a pure function — repeated calls agree."""
+ rec = _record([ChannelBinding(match_value="*", agent_id="a")])
+ self.assertEqual(resolve(_event(), rec), resolve(_event(), rec))
+
+ def test_routing_requires_catch_all(self) -> None:
+ """RoutingConfig rejects a rule set without a catch-all."""
+ with self.assertRaises(ValueError):
+ RoutingConfig(
+ bindings=[
+ ChannelBinding(match_value="oc_1", agent_id="a"),
+ ],
+ )
+
+ def test_routing_catch_all_must_be_last(self) -> None:
+ """A catch-all before other rules is rejected (unreachable)."""
+ with self.assertRaises(ValueError):
+ RoutingConfig(
+ bindings=[
+ ChannelBinding(match_value="*", agent_id="a"),
+ ChannelBinding(match_value="oc_1", agent_id="b"),
+ ],
+ )
+
+ def test_routing_rejects_duplicates(self) -> None:
+ """Duplicate (match_key, match_value) pairs are rejected."""
+ with self.assertRaises(ValueError):
+ RoutingConfig(
+ bindings=[
+ ChannelBinding(match_value="oc_1", agent_id="a"),
+ ChannelBinding(match_value="oc_1", agent_id="b"),
+ ChannelBinding(match_value="*", agent_id="c"),
+ ],
+ )
diff --git a/tests/service_agent_interrupt_test.py b/tests/service_agent_interrupt_test.py
index 9ae44fddd..744c3c419 100644
--- a/tests/service_agent_interrupt_test.py
+++ b/tests/service_agent_interrupt_test.py
@@ -25,6 +25,7 @@ from pydantic import BaseModel
from utils import MockModel
from agentscope.agent import Agent
+from agentscope.formatter import OpenAIChatFormatter
from agentscope.app._manager import (
CancelDispatcher,
ChatRunRegistry,
@@ -137,6 +138,9 @@ class ServiceAgentInterruptTest(IsolatedAsyncioTestCase):
self.stream = True
self.max_retries = 0
self.context_size = 1000
+ # The agent reads formatter.supported_input_media_types
+ # on every incoming message, like a real model exposes.
+ self.formatter = OpenAIChatFormatter()
async def __call__(
self,
diff --git a/tests/service_cancel_dispatcher_test.py b/tests/service_cancel_dispatcher_test.py
index 7be20a881..d37b2e83a 100644
--- a/tests/service_cancel_dispatcher_test.py
+++ b/tests/service_cancel_dispatcher_test.py
@@ -120,6 +120,17 @@ class _FakeBus(MessageBus):
async def is_locked(self, key: str) -> bool:
return key in self._locks
+ async def try_lock(
+ self,
+ key: str,
+ *,
+ ttl_secs: int = 600,
+ ) -> bool:
+ return True
+
+ async def unlock(self, key: str) -> None:
+ pass
+
# Mode F — registry (in-memory dict)
async def registry_set(
self,
@@ -141,6 +152,13 @@ class _FakeBus(MessageBus):
async def registry_getall(self, namespace: str) -> dict[str, str]:
return dict(self._registries.get(namespace, {}))
+ async def registry_get(
+ self,
+ namespace: str,
+ field: str,
+ ) -> str | None:
+ return self._registries.get(namespace, {}).get(field)
+
async def registry_drop(self, namespace: str) -> None:
self._registries.pop(namespace, None)
diff --git a/tests/service_inbox_middleware_test.py b/tests/service_inbox_middleware_test.py
index 13a59e1c1..04ae31c90 100644
--- a/tests/service_inbox_middleware_test.py
+++ b/tests/service_inbox_middleware_test.py
@@ -127,6 +127,17 @@ class _FakeBus(MessageBus):
async def is_locked(self, key: str) -> bool:
raise NotImplementedError
+ async def try_lock(
+ self,
+ key: str,
+ *,
+ ttl_secs: int = 600,
+ ) -> bool:
+ return True
+
+ async def unlock(self, key: str) -> None:
+ pass
+
# Mode F — registry (unused)
async def registry_set(
self,
@@ -147,6 +158,13 @@ class _FakeBus(MessageBus):
async def registry_getall(self, namespace: str) -> dict[str, str]:
raise NotImplementedError
+ async def registry_get(
+ self,
+ namespace: str,
+ field: str,
+ ) -> str | None:
+ raise NotImplementedError
+
async def registry_drop(self, namespace: str) -> None:
raise NotImplementedError
diff --git a/tests/service_index_task_consumer_test.py b/tests/service_index_task_consumer_test.py
index 839d2eb99..000008c13 100644
--- a/tests/service_index_task_consumer_test.py
+++ b/tests/service_index_task_consumer_test.py
@@ -132,6 +132,17 @@ class _FakeBus(MessageBus):
async def is_locked(self, key: str) -> bool:
return key in self._locks
+ async def try_lock(
+ self,
+ key: str,
+ *,
+ ttl_secs: int = 600,
+ ) -> bool:
+ return True
+
+ async def unlock(self, key: str) -> None:
+ pass
+
# Mode F — registry (unused by IndexTaskConsumer; raise so any
# accidental dependency surfaces immediately rather than silently
# passing through a stub).
@@ -154,6 +165,13 @@ class _FakeBus(MessageBus):
async def registry_getall(self, namespace: str) -> dict[str, str]:
raise NotImplementedError
+ async def registry_get(
+ self,
+ namespace: str,
+ field: str,
+ ) -> str | None:
+ raise NotImplementedError
+
async def registry_drop(self, namespace: str) -> None:
raise NotImplementedError
diff --git a/tests/service_wakeup_dispatcher_test.py b/tests/service_wakeup_dispatcher_test.py
index 66291af72..03b456485 100644
--- a/tests/service_wakeup_dispatcher_test.py
+++ b/tests/service_wakeup_dispatcher_test.py
@@ -148,6 +148,17 @@ class _FakeBus(MessageBus):
async def is_locked(self, key: str) -> bool:
return key in self._locks
+ async def try_lock(
+ self,
+ key: str,
+ *,
+ ttl_secs: int = 600,
+ ) -> bool:
+ return True
+
+ async def unlock(self, key: str) -> None:
+ pass
+
# Mode F — registry (unused by WakeupDispatcher; raise so any
# accidental dependency surfaces immediately rather than silently
# passing through a stub).
@@ -170,6 +181,13 @@ class _FakeBus(MessageBus):
async def registry_getall(self, namespace: str) -> dict[str, str]:
raise NotImplementedError
+ async def registry_get(
+ self,
+ namespace: str,
+ field: str,
+ ) -> str | None:
+ raise NotImplementedError
+
async def registry_drop(self, namespace: str) -> None:
raise NotImplementedError
diff --git a/tests/utils.py b/tests/utils.py
index 9eba25cc0..9f54e2fce 100644
--- a/tests/utils.py
+++ b/tests/utils.py
@@ -7,6 +7,7 @@ from pydantic import BaseModel
from agentscope.app.workspace_manager import WorkspaceManagerBase
from agentscope.credential import CredentialBase
+from agentscope.formatter import FormatterBase, OpenAIChatFormatter
from agentscope.message import Msg
from agentscope.model import ChatModelBase, ChatResponse, StructuredResponse
from agentscope.workspace import WorkspaceBase
@@ -60,6 +61,7 @@ class MockModel(ChatModelBase):
context_size: int = 1000,
mock_chat_responses: list | None = None,
mock_structured_response: Any = None,
+ formatter: FormatterBase | None = None,
) -> None:
"""Initialize the mock model."""
super().__init__(
@@ -69,6 +71,9 @@ class MockModel(ChatModelBase):
parameters=MockModel.Parameters(),
context_size=context_size,
)
+ # Mirror real models, which each expose a formatter; the agent reads
+ # ``formatter.supported_input_media_types`` on every incoming message.
+ self.formatter = formatter or OpenAIChatFormatter()
self.mock_chat_responses = mock_chat_responses or []
self.mock_structured_response = mock_structured_response
self.cnt = 0
diff --git a/tests/workspace_daytona_test.py b/tests/workspace_daytona_test.py
index e0c8f7817..e4a2679f4 100644
--- a/tests/workspace_daytona_test.py
+++ b/tests/workspace_daytona_test.py
@@ -1205,7 +1205,7 @@ class TestDaytonaWorkspaceBuiltinToolsMock(IsolatedAsyncioTestCase):
)
context_raw = await self.workspace._backend.read_file(context_path)
self.assertIn(
- "file:///home/daytona/data/",
+ "workspace:///data/",
context_raw.decode("utf-8"),
)
@@ -1505,7 +1505,7 @@ class TestDaytonaWorkspaceLive(IsolatedAsyncioTestCase):
)
context_raw = await ws._backend.read_file(context_path)
self.assertIn("live context", context_raw.decode("utf-8"))
- self.assertIn("file://", context_raw.decode("utf-8"))
+ self.assertIn("workspace://", context_raw.decode("utf-8"))
tool_path = await ws.offload_tool_result(
"session-live-reset",
@@ -1610,7 +1610,7 @@ class TestDaytonaWorkspaceLive(IsolatedAsyncioTestCase):
context_raw.decode("utf-8"),
)
self.assertIn(
- "file://",
+ "workspace://",
context_raw.decode("utf-8"),
)
tool_raw = await reattached._backend.read_file(tool_path)
diff --git a/tests/workspace_docker_test.py b/tests/workspace_docker_test.py
index 016f3e42b..3c6fe5248 100644
--- a/tests/workspace_docker_test.py
+++ b/tests/workspace_docker_test.py
@@ -17,10 +17,10 @@ Two practical differences vs. the local tests:
compose paths against ``self.temp_dir.name``, which is bind-mounted
to ``CONTAINER_WORKDIR`` inside the container.
-2. ``DataBlock`` URLs persisted by DockerWorkspace use the container
- path (``file:///workspace/data/<hash>.png``). We assert the URL
- string against the container path and verify the file's *bytes* via
- the corresponding host-side path.
+2. ``DataBlock`` URLs persisted by DockerWorkspace are portable
+ ``workspace:///data/<hash>.png`` references. We assert the URL
+ string and verify the file's *bytes* via the corresponding
+ host-side path.
The whole module is skipped when no Docker daemon is reachable.
"""
@@ -243,9 +243,9 @@ class TestDockerWorkspaceOffload(IsolatedAsyncioTestCase):
Verifies:
1. The decoded payload lands on disk under ``<workdir>/data/``
- (container-side ``/workspace/data/``).
+ (container-side ``/workspace/data/``, host-mirrored).
2. The offloaded JSONL line carries a ``URLSource`` whose URL is
- the *container* path (``file:///workspace/data/<hash>.<ext>``).
+ the portable ``workspace:///data/<hash>.<ext>`` reference.
3. Decoded bytes match the original.
"""
session_id = "test_session_datablock"
@@ -277,15 +277,15 @@ class TestDockerWorkspaceOffload(IsolatedAsyncioTestCase):
content = await f.read()
loaded_msg = Msg.model_validate_json(content.strip())
- # The DataBlock's source should now be URLSource pointing to a
- # container-side file://...
+ # The DataBlock's source should now be a URLSource with a
+ # portable workspace:// reference.
self.assertEqual(len(loaded_msg.content), 2)
data_url = str(loaded_msg.content[1].source.url)
- self.assertTrue(data_url.startswith("file:///workspace/data/"))
+ self.assertTrue(data_url.startswith("workspace:///data/"))
- # Verify the bytes via the host-side mirror.
- container_path = urlparse(data_url).path # /workspace/data/<hash>.png
- rel = os.path.relpath(container_path, "/workspace")
+ # Verify the bytes via the host-side mirror. The workspace-
+ # relative URL path (``/data/<hash>.png``) maps onto the mirror.
+ rel = urlparse(data_url).path.lstrip("/")
host_data_path = os.path.join(self.temp_dir.name, rel)
self.assertTrue(os.path.exists(host_data_path))
async with aiofiles.open(host_data_path, "rb") as f:
@@ -302,7 +302,7 @@ class TestDockerWorkspaceOffload(IsolatedAsyncioTestCase):
"""Two identical DataBlocks share a single persisted file.
Verifies:
- 1. Both ``_offload_data_block`` calls return DataBlocks pointing
+ 1. Both ``offload_data_block`` calls return DataBlocks pointing
at the same URL.
2. Only one file ends up in ``<workdir>/data/``.
"""
@@ -316,8 +316,8 @@ class TestDockerWorkspaceOffload(IsolatedAsyncioTestCase):
name="file2",
)
- result1 = await self.workspace._offload_data_block(block1)
- result2 = await self.workspace._offload_data_block(block2)
+ result1 = await self.workspace.offload_data_block(block1)
+ result2 = await self.workspace.offload_data_block(block2)
self.assertEqual(str(result1.source.url), str(result2.source.url))
# Check the host-mirror data dir has exactly one file.
@@ -334,7 +334,7 @@ class TestDockerWorkspaceOffload(IsolatedAsyncioTestCase):
"""A DataBlock that already has a URLSource is returned unchanged.
Verifies:
- 1. ``_offload_data_block`` is a no-op for URL-sourced blocks.
+ 1. ``offload_data_block`` is a no-op for URL-sourced blocks.
2. No file lands in ``<workdir>/data/``.
"""
from pydantic import AnyUrl
@@ -347,7 +347,7 @@ class TestDockerWorkspaceOffload(IsolatedAsyncioTestCase):
name="remote_image",
)
- result = await self.workspace._offload_data_block(block)
+ result = await self.workspace.offload_data_block(block)
self.assertDictEqual(result.model_dump(), block.model_dump())
host_data_dir = os.path.join(self.temp_dir.name, "data")
@@ -430,7 +430,7 @@ class TestDockerWorkspaceOffload(IsolatedAsyncioTestCase):
content = await f.read()
self.assertTrue(content.startswith("File created successfully: "))
- self.assertIn("<data url='file:///workspace/data/", content)
+ self.assertIn("<data url='workspace:///data/", content)
self.assertIn("name='output.txt'", content)
self.assertIn("media_type='text/plain'", content)
self.assertTrue(content.endswith("/>"))
@@ -438,8 +438,7 @@ class TestDockerWorkspaceOffload(IsolatedAsyncioTestCase):
# The data file is reachable via the host mirror.
match = re.search(r"url='([^']+)'", content)
self.assertIsNotNone(match)
- container_path = urlparse(match.group(1)).path
- rel = os.path.relpath(container_path, "/workspace")
+ rel = urlparse(match.group(1)).path.lstrip("/")
host_data_path = os.path.join(self.temp_dir.name, rel)
self.assertTrue(os.path.exists(host_data_path))
@@ -796,7 +795,7 @@ class TestDockerWorkspaceLifecycle(IsolatedAsyncioTestCase):
session_id,
[UserMsg(name="user", content="hi")],
)
- await ws._offload_data_block(
+ await ws.offload_data_block(
DataBlock(
source=Base64Source(
data=base64.b64encode(b"x").decode(),
diff --git a/tests/workspace_local_test.py b/tests/workspace_local_test.py
index 75eedef03..9f3069fe9 100644
--- a/tests/workspace_local_test.py
+++ b/tests/workspace_local_test.py
@@ -6,14 +6,12 @@ import json
import base64
import hashlib
import tempfile
-from pathlib import Path
from types import SimpleNamespace
from typing import Any
from unittest.async_case import IsolatedAsyncioTestCase
from unittest.mock import AsyncMock, patch
from dataclasses import asdict
from urllib.parse import urlparse
-from urllib.request import url2pathname
import aiofiles
from utils import AnyString, MockModel
@@ -309,9 +307,12 @@ class TestLocalWorkspaceOffload(IsolatedAsyncioTestCase):
self.assertIsInstance(loaded_msg.content, list)
self.assertEqual(len(loaded_msg.content), 2)
data_url = str(loaded_msg.content[1].source.url)
- self.assertTrue(data_url.startswith("file://"))
- # Convert file URL to local path (works on both Windows and Unix)
- data_file_path = url2pathname(urlparse(data_url).path)
+ self.assertTrue(data_url.startswith("workspace://"))
+ # Resolve the workspace-relative URL to its physical path.
+ data_file_path = os.path.join(
+ self.temp_dir.name,
+ urlparse(data_url).path.lstrip("/"),
+ )
self.assertTrue(os.path.exists(data_file_path))
# Verify the data file contains the correct content
@@ -365,16 +366,19 @@ class TestLocalWorkspaceOffload(IsolatedAsyncioTestCase):
)
# Offload both data blocks
- result1 = await self.workspace._offload_data_block(data_block1)
- result2 = await self.workspace._offload_data_block(data_block2)
+ result1 = await self.workspace.offload_data_block(data_block1)
+ result2 = await self.workspace.offload_data_block(data_block2)
# Verify both point to the same file by comparing source URLs
self.assertEqual(str(result1.source.url), str(result2.source.url))
# Verify the file exists
data_url = str(result1.source.url)
- # Convert file URL to local path (works on both Windows and Unix)
- data_file_path = url2pathname(urlparse(data_url).path)
+ # Resolve the workspace-relative URL to its physical path.
+ data_file_path = os.path.join(
+ self.temp_dir.name,
+ urlparse(data_url).path.lstrip("/"),
+ )
self.assertTrue(os.path.exists(data_file_path))
# Verify only one file was created in the data directory
@@ -400,7 +404,7 @@ class TestLocalWorkspaceOffload(IsolatedAsyncioTestCase):
)
# Offload the data block
- result = await self.workspace._offload_data_block(data_block)
+ result = await self.workspace.offload_data_block(data_block)
# Verify the data block is returned as-is by comparing full objects
self.assertDictEqual(result.model_dump(), data_block.model_dump())
@@ -493,7 +497,7 @@ class TestLocalWorkspaceOffload(IsolatedAsyncioTestCase):
# Verify the content structure (URL format varies by platform)
self.assertTrue(content.startswith("File created successfully: "))
- self.assertIn("<data url='file://", content)
+ self.assertIn("<data url='workspace://", content)
self.assertIn("name='output.txt'", content)
self.assertIn("media_type='text/plain'", content)
self.assertTrue(content.endswith("/>"))
@@ -505,8 +509,11 @@ class TestLocalWorkspaceOffload(IsolatedAsyncioTestCase):
url_match = re.search(r"url='([^']+)'", content)
self.assertIsNotNone(url_match)
data_url = url_match.group(1)
- # Convert file URL to local path (works on both Windows and Unix)
- data_file_path = url2pathname(urlparse(data_url).path)
+ # Resolve the workspace-relative URL to its physical path.
+ data_file_path = os.path.join(
+ self.temp_dir.name,
+ urlparse(data_url).path.lstrip("/"),
+ )
self.assertTrue(os.path.exists(data_file_path))
@@ -1066,7 +1073,7 @@ class TestLocalWorkspaceWithAgent(IsolatedAsyncioTestCase):
# The full text is "0" * 30000 followed by a base64 DataBlock;
# tool_result_limit=50 reserves ~200 chars of text in context, the
# remaining 29800 chars + the DataBlock placeholder are offloaded.
- data_url = Path(data_file_path).as_uri()
+ data_url = f"workspace:///data/{data_hash}.png"
expected_offload_content = (
"0" * 29800 + f"<data url='{data_url}' name='fake_image.png' "
f"media_type='image/png'/>"
@@ -1277,7 +1284,7 @@ class TestLocalWorkspaceWithAgent(IsolatedAsyncioTestCase):
# literally so a developer can read off exactly what gets
# persisted; only the temp-dir-dependent file URL is
# interpolated via ``data_url``.
- data_url = Path(data_file_path).as_uri()
+ data_url = f"workspace:///data/{data_hash}.png"
expected_user_msg_a_offloaded_json = (
'{"name":"user","content":['
'{"type":"data","id":"data_block_a","source":'