Build and run agents you can see, understand and trust.
Python agentchatbotlarge-language-modelsllmllm-agentmcpmulti-agentmulti-modalreact-agentrealtime-agentvoice-agentvoice-assistant
feat(agent_team): refactor the agent service to support agent team (#1776)
DavdGaobf6ad8eb3533
diff --git a/docs/NEWS.md b/docs/NEWS.mdindex 4a39a6f4d..3e2e1af6c 100644--- a/docs/NEWS.md+++ b/docs/NEWS.md@@ -2,4 +2,5 @@<!-- 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-06] `FEAT`:** Agent Team support. [Example](https://github.com/agentscope-ai/agentscope/tree/main/examples/agent_service) | [Docs](https://docs.agentscope.io/v2/deploy/agent-team)- **[2026-05] `RELS`:** AgentScope 2.0 released! [Docs](https://docs.agentscope.io/)\ No newline at end of filediff --git a/docs/NEWS_zh.md b/docs/NEWS_zh.mdindex 9b7453e35..b8885a620 100644--- a/docs/NEWS_zh.md+++ b/docs/NEWS_zh.md@@ -2,4 +2,5 @@<!-- 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-06] `功能`:** 支持 Agent Team。[样例](https://github.com/agentscope-ai/agentscope/tree/main/examples/agent_service) | [文档](https://docs.agentscope.io/zh/v2/deploy/agent-team)- **[2026-05] `发布`:** AgentScope 2.0 已发布\ No newline at end of filediff --git a/examples/agent_service/main.py b/examples/agent_service/main.pyindex fc2917d0c..c1325f016 100644--- a/examples/agent_service/main.py+++ b/examples/agent_service/main.py@@ -6,11 +6,10 @@ import uvicornfrom fastapi.middleware import Middlewarefrom fastapi.middleware.cors import CORSMiddleware-from agentscope.app import (- create_app,- RedisStorage,- LocalWorkspaceManager,-)+from agentscope.app import create_app+from agentscope.app.message_bus import RedisMessageBus+from agentscope.app.storage import RedisStorage+from agentscope.app.workspace_manager import LocalWorkspaceManagerfrom agentscope.mcp import MCPClient, StdioMCPConfig, HttpMCPConfig@@ -42,6 +41,10 @@ app = create_app(host="localhost",port=6379,),+ RedisMessageBus(+ host="localhost",+ port=6379,+ ),workspace_manager=LocalWorkspaceManager(basedir=os.path.join(os.path.dirname(os.path.abspath(__file__)),diff --git a/examples/web_ui/frontend/package.json b/examples/web_ui/frontend/package.jsonindex dda64f21e..90c71dc94 100644--- a/examples/web_ui/frontend/package.json+++ b/examples/web_ui/frontend/package.json@@ -11,7 +11,7 @@"preview": "vite preview"},"dependencies": {- "@agentscope-ai/agentscope": "^0.0.6",+ "@agentscope-ai/agentscope": "^0.0.8","@fontsource-variable/geist": "^5.2.8","@tailwindcss/vite": "^4.3.0","class-variance-authority": "^0.7.1",diff --git a/examples/web_ui/frontend/src/App.tsx b/examples/web_ui/frontend/src/App.tsxindex 5cf918fd1..07a901459 100644--- a/examples/web_ui/frontend/src/App.tsx+++ b/examples/web_ui/frontend/src/App.tsx@@ -1,6 +1,6 @@import { Onborda, OnbordaProvider } from 'onborda';import { useMemo, useState } from 'react';-import { createBrowserRouter, RouterProvider, useNavigate } from 'react-router-dom';+import { createBrowserRouter, Navigate, RouterProvider, useNavigate } from 'react-router-dom';import { Toaster } from 'sonner';import { AppLayout } from '@/components/layout/AppLayout';@@ -28,8 +28,11 @@ const router = createBrowserRouter([{element: <AppLayout />,children: [- { path: '/', element: <ChatPage /> },- { path: '/chat/:agentId/:sessionId', element: <ChatPage /> },+ { path: '/', element: <Navigate to="/chat" replace /> },+ {+ path: '/chat/:agentId?/:sessionId?/:memberId?',+ element: <ChatPage />,+ },{ path: '/schedule', element: <SchedulePage /> },{ path: '/credential', element: <CredentialPage /> },],diff --git a/examples/web_ui/frontend/src/api/chat.ts b/examples/web_ui/frontend/src/api/chat.tsindex 4bb4f6dc7..cdee46222 100644--- a/examples/web_ui/frontend/src/api/chat.ts+++ b/examples/web_ui/frontend/src/api/chat.ts@@ -1,28 +1,25 @@import { client } from './client';-import type { AgentEvent, ChatRequest } from './types';+import type { ChatRequest } from './types';+/**+ * Chat API — fire-and-forget trigger for chat runs.+ *+ * Events produced by the run are delivered via the session's SSE+ * stream endpoint (``GET /sessions/{sid}/stream``), not in the+ * response body of this POST.+ */export const chatApi = {- stream: async function* (body: ChatRequest, signal?: AbortSignal): AsyncGenerator<AgentEvent> {- const res = await client.stream('/chat/', { method: 'POST', body, signal });-- const reader = res.body!.getReader();- const decoder = new TextDecoder();- let buffer = '';-- while (true) {- const { done, value } = await reader.read();- if (done) break;-- buffer += decoder.decode(value, { stream: true });- const lines = buffer.split('\n');- buffer = lines.pop() ?? '';-- for (const line of lines) {- if (line.startsWith('data: ')) {- const json = line.slice(6).trim();- if (json) yield JSON.parse(json) as AgentEvent;- }- }- }- },+ /**+ * Trigger a chat run for the specified session.+ *+ * Accepts user messages, human-in-the-loop confirmation events,+ * or ``null`` (continue from current state). Returns immediately;+ * the caller should already be subscribed to the session's SSE+ * stream to receive the resulting events.+ *+ * @param body - The chat request payload.+ * @returns A confirmation object ``{ status, session_id }``.+ */+ trigger: (body: ChatRequest) =>+ client.post<{ status: string; session_id: string }>('/chat/', body),};diff --git a/examples/web_ui/frontend/src/api/schedule.ts b/examples/web_ui/frontend/src/api/schedule.tsindex 83c576d97..8a94b5eff 100644--- a/examples/web_ui/frontend/src/api/schedule.ts+++ b/examples/web_ui/frontend/src/api/schedule.ts@@ -4,7 +4,7 @@ import type {CreateScheduleResponse,ScheduleListResponse,ScheduleRecord,- SessionListResponse,+ ScheduleSessionsResponse,UpdateScheduleRequest,} from './types';@@ -20,5 +20,5 @@ export const scheduleApi = {delete: (scheduleId: string) => client.delete(`/schedule/${scheduleId}`),listSessions: (scheduleId: string) =>- client.get<SessionListResponse>(`/schedule/${scheduleId}/sessions`),+ client.get<ScheduleSessionsResponse>(`/schedule/${scheduleId}/sessions`),};diff --git a/examples/web_ui/frontend/src/api/session.ts b/examples/web_ui/frontend/src/api/session.tsindex aa8162a9a..2d679aacb 100644--- a/examples/web_ui/frontend/src/api/session.ts+++ b/examples/web_ui/frontend/src/api/session.ts@@ -1,5 +1,6 @@import { client } from './client';import type {+ AgentEvent,CreateSessionRequest,CreateSessionResponse,SessionListResponse,@@ -30,4 +31,58 @@ export const sessionApi = {offset: String(offset),limit: String(limit),}),++ /**+ * Subscribe to a session's live event stream via SSE.+ *+ * Opens a long-lived ``GET /sessions/{sid}/stream`` connection and+ * yields each ``AgentEvent`` as it arrives. The connection stays+ * open until the caller aborts via the ``signal`` or closes the+ * generator.+ *+ * Uses fetch-based SSE (not native ``EventSource``) so the+ * ``X-User-ID`` custom header is sent.+ *+ * @param sessionId - The session to subscribe to.+ * @param agentId - The agent that owns the session.+ * @param signal - Optional abort signal to close the connection.+ * @returns An async generator yielding ``AgentEvent`` objects.+ */+ streamEvents: async function* (+ sessionId: string,+ agentId: string,+ signal?: AbortSignal,+ ): AsyncGenerator<AgentEvent> {+ const res = await client.stream(`/sessions/${sessionId}/stream`, {+ method: 'GET',+ params: { agent_id: agentId },+ signal,+ });++ const reader = res.body!.getReader();+ const decoder = new TextDecoder();+ let buffer = '';++ try {+ while (true) {+ const { done, value } = await reader.read();+ if (done) break;++ buffer += decoder.decode(value, { stream: true });+ const lines = buffer.split('\n');+ buffer = lines.pop() ?? '';++ for (const line of lines) {+ if (line.startsWith('data: ')) {+ const json = line.slice(6).trim();+ if (json) yield JSON.parse(json) as AgentEvent;+ }+ // SSE comment frames (`:...\n`) are silently skipped+ // (used for heartbeats).+ }+ }+ } finally {+ reader.releaseLock();+ }+ },};diff --git a/examples/web_ui/frontend/src/api/types.ts b/examples/web_ui/frontend/src/api/types.tsindex 8496d49b4..400832cd6 100644--- a/examples/web_ui/frontend/src/api/types.ts+++ b/examples/web_ui/frontend/src/api/types.ts@@ -95,6 +95,13 @@ export interface SessionRecord extends RecordBase {agent_id: string;source: SessionSource;source_schedule_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+ * `TeamCreate`) or a worker spawned by `AgentCreate`. `null` for+ * regular standalone sessions.+ */+ team_id: string | null;config: SessionConfig;state: AgentState;}@@ -125,10 +132,77 @@ export interface UpdateSessionRequest {}export interface SessionListResponse {+ sessions: SessionView[];+ total: number;+}++/**+ * Response body for `GET /schedule/{id}/sessions`. Returns plain+ * `SessionRecord[]` (no team / is_running enrichment) because+ * scheduled-execution sessions are listed for audit purposes only,+ * not for opening in the chat UI.+ */+export interface ScheduleSessionsResponse {sessions: SessionRecord[];total: number;}+// ─── Team ─────────────────────────────────────────────────────────────────────++export interface TeamData {+ name: string;+ description: string;+ /** Worker agent ids belonging to the team. */+ member_ids: string[];+}++export interface TeamRecord extends RecordBase {+ user_id: string;+ /** The leader session id — the session that called `TeamCreate`. */+ session_id: string;+ data: TeamData;+}++/**+ * One member entry inside `TeamDetailResponse.members`. Pairs the+ * worker's `AgentRecord` with its single `session_id` so the UI can+ * navigate straight to the worker's chat.+ */+export interface TeamMemberInfo {+ agent: AgentRecord;+ /** `null` if the agent is in an inconsistent state (no session). */+ session_id: string | null;+}++/**+ * Resolved team detail returned inline inside `SessionView.team`.+ *+ * The leader's `AgentRecord` is looked up from the team's+ * `session_id` → `session.agent_id` chain on the server side.+ */+export interface TeamDetailResponse {+ team: TeamRecord;+ leader_agent: AgentRecord | null;+ members: TeamMemberInfo[];+}++/**+ * Per-session bundle returned by `GET /sessions/?agent_id=...`.+ *+ * Bundles three pieces of information so the chat UI can render a+ * session without follow-up requests: the persisted record (incl.+ * `state`), whether a chat run is active, and — when the session+ * participates in a team — the resolved team detail.+ *+ * Messages are intentionally separate (`GET /sessions/{id}/messages`)+ * since they paginate independently.+ */+export interface SessionView {+ session: SessionRecord;+ is_running: boolean;+ team: TeamDetailResponse | null;+}+// ─── JSON Schema ──────────────────────────────────────────────────────────────/**diff --git a/examples/web_ui/frontend/src/components/chat/MessageBubble.tsx b/examples/web_ui/frontend/src/components/chat/MessageBubble.tsxindex 6da38abfd..a81666082 100644--- a/examples/web_ui/frontend/src/components/chat/MessageBubble.tsx+++ b/examples/web_ui/frontend/src/components/chat/MessageBubble.tsx@@ -1,5 +1,22 @@-import type { ContentBlock, Msg, ToolCallBlock } from '@agentscope-ai/agentscope/message';-import { ArrowDown, ArrowUp, CheckCircle, Copy, Loader2 } from 'lucide-react';+import type {+ ContentBlock,+ DataBlock,+ Msg,+ TextBlock,+ ToolCallBlock,+} from '@agentscope-ai/agentscope/message';+import {+ ArrowDown,+ ArrowUp,+ Bot,+ CalendarClock,+ CheckCircle,+ ChevronDownIcon,+ Copy,+ Loader2,+ MessageSquareQuote,+ Wrench,+} from 'lucide-react';import { useEffect, useState } from 'react';import ReactMarkdown from 'react-markdown';import remarkGfm from 'remark-gfm';@@ -9,6 +26,12 @@ import { renderToolGroup } from './tool-renderers';import type { TFunction, ToolCallWithResult } from './tool-renderers/types';import { Badge } from '@/components/ui/badge';import { Button } from '@/components/ui/button';+import {+ Collapsible,+ CollapsibleContent,+ CollapsibleTrigger,+} from '@/components/ui/collapsible.tsx';+import { Item, ItemContent } from '@/components/ui/item.tsx';import { useTranslation } from '@/i18n/useI18n';import { formatNumber, formatTime } from '@/utils/common';@@ -22,12 +45,46 @@ interface ToolCallGroupBlock {type ExtendedContentBlock = ContentBlock | ToolCallGroupBlock;/**- * Group consecutive tool_call blocks of the same name into a single- * `tool_call_group`. tool_result blocks are matched by id back onto the- * call inside the current group. Any non-tool block (or a tool_call with- * a different name) flushes the current group.+ * Group tool_call blocks of the same name into a single+ * `tool_call_group`, with each call paired to its matching+ * tool_result by id.+ *+ * Unlike the previous implementation this does NOT require calls of+ * the same name to be consecutive. When the agent issues multiple+ * concurrent tool calls (e.g. Glob + Grep), the content layout is+ * `[call_Glob, call_Grep, result_Glob, result_Grep]` — the old+ * "consecutive-same-name" approach would split call and result into+ * separate groups. This version collects all calls first (preserving+ * encounter order), then matches results, and finally emits groups+ * in the order the first call of each tool name appeared,+ * interleaved with non-tool blocks at their original positions.*/function groupToolCalls(content: ContentBlock[]): ExtendedContentBlock[] {+ // Pass 1: pair calls ↔ results by id, track non-tool blocks.+ const callMap = new Map<string, ToolCallWithResult>();+ const resultMap = new Map<string, ContentBlock>();+ const ordering: Array<{ type: 'tool'; id: string } | { type: 'other'; block: ContentBlock }> =+ [];++ for (const block of content) {+ if (block.type === 'tool_call') {+ const entry: ToolCallWithResult = { call: block };+ callMap.set(block.id, entry);+ ordering.push({ type: 'tool', id: block.id });+ } else if (block.type === 'tool_result') {+ const matching = callMap.get(block.id);+ if (matching) {+ matching.result = block;+ } else {+ resultMap.set(block.id, block);+ }+ } else {+ ordering.push({ type: 'other', block });+ }+ }++ // Pass 2: walk the ordering, group consecutive same-name calls+ // (now that results are already attached).const result: ExtendedContentBlock[] = [];let currentGroup: ToolCallWithResult[] = [];let currentToolName: string | null = null;@@ -45,41 +102,45 @@ function groupToolCalls(content: ContentBlock[]): ExtendedContentBlock[] {}};- for (const block of content) {- if (block.type === 'tool_call') {- if (currentToolName !== null && currentToolName !== block.name) {+ for (const item of ordering) {+ if (item.type === 'other') {+ flush();+ result.push(item.block);+ } else {+ const entry = callMap.get(item.id);+ if (!entry) continue;+ if (currentToolName !== null && currentToolName !== entry.call.name) {flush();}- currentToolName = block.name;- currentGroup.push({ call: block });- } else if (block.type === 'tool_result') {- const matchingCall = currentGroup.find((item) => item.call.id === block.id);- if (matchingCall) {- matchingCall.result = block;- } else {- // No matching call in the current group — emit a synthetic group- // so the result still renders. Should not happen in practice.- flush();- currentToolName = block.name;- currentGroup.push({- call: {- type: 'tool_call',- id: block.id,- name: block.name,- input: '',- state: 'finished',+ currentToolName = entry.call.name;+ currentGroup.push(entry);+ }+ }+ flush();++ // Orphan results (no matching call) — render as synthetic groups.+ for (const [id, block] of resultMap) {+ if (block.type === 'tool_result') {+ result.push({+ type: 'tool_call_group',+ id: crypto.randomUUID(),+ toolName: block.name,+ calls: [+ {+ call: {+ type: 'tool_call',+ id,+ name: block.name,+ input: '',+ state: 'finished' as const,+ },+ result: block,},- result: block,- });- flush();- }- } else {- flush();- result.push(block);+ ],+ });}}- flush();return result;}@@ -120,7 +181,7 @@ function renderBlock(}case 'text':return (- <div key={index} className="prose text-sm w-full min-w-full">+ <div key={index} className="prose w-full min-w-full"><ReactMarkdownremarkPlugins={[remarkGfm]}components={{@@ -166,7 +227,7 @@ function renderBlock(case 'thinking':return (- <details key={index} className="text-xs text-muted-foreground">+ <details key={index} className="text-muted-foreground"><summary className="cursor-pointer select-none">{t('messageBubble.thinking')}</summary>@@ -192,6 +253,61 @@ function renderBlock(}return null;}++ case 'hint': {+ // Parse source: try JSON, fall back to plain string, default to t('common.message').+ let hintLabel: string;+ let hintSublabel: string | null = null;+ let HintIcon = MessageSquareQuote;++ if (block.source) {+ try {+ const parsed = JSON.parse(block.source) as {+ label?: string;+ sublabel?: string;+ };+ hintLabel = parsed.label+ ? t(`messageBubble.hintSource.${parsed.label}`)+ : block.source;+ hintSublabel = parsed.sublabel ?? null;+ if (parsed.label === 'team_message') HintIcon = Bot;+ else if (parsed.label === 'schedule') HintIcon = CalendarClock;+ else if (parsed.label === 'tool_output') HintIcon = Wrench;+ } catch {+ hintLabel = block.source;+ }+ } else {+ hintLabel = t('common.message');+ }+ const items: (TextBlock | DataBlock)[] =+ typeof block.hint === 'string'+ ? [{ type: 'text', id: `${block.id}-text`, text: block.hint }]+ : block.hint;+ return (+ <Item variant={'outline'} className="max-w-full">+ <ItemContent className="max-w-full">+ <Collapsible>+ <CollapsibleTrigger asChild>+ <Button className="group w-full max-w-full" variant="ghost">+ <HintIcon className="size-3.5" />+ <span className="tracking-tight">{hintLabel}</span>+ {hintSublabel && (+ <span className="text-muted-foreground font-normal truncate max-w-[200px]">+ {hintSublabel}+ </span>+ )}+ <ChevronDownIcon className="ml-auto group-data-[state=open]:rotate-180" />+ </Button>+ </CollapsibleTrigger>+ <CollapsibleContent className="p-2.5 pt-0 max-w-full overflow-hidden break-all text-muted-foreground">+ {items.map((inner, i) => renderBlock(inner, i, t))}+ </CollapsibleContent>+ </Collapsible>+ </ItemContent>+ </Item>+ );+ }+default:return null;}diff --git a/examples/web_ui/frontend/src/components/chat/TaskPanel.tsx b/examples/web_ui/frontend/src/components/chat/TaskPanel.tsxnew file mode 100644index 000000000..b4cded7b8--- /dev/null+++ b/examples/web_ui/frontend/src/components/chat/TaskPanel.tsx@@ -0,0 +1,154 @@+import type { Task, TaskContext } from '@agentscope-ai/agentscope/state';+import { Ellipsis, Loader2, Square, SquareCheck } from 'lucide-react';+import { useState } from 'react';++import { Badge } from '@/components/ui/badge';+import { Button } from '@/components/ui/button';+import { useTranslation } from '@/i18n/useI18n';+import { cn } from '@/lib/utils';++interface TaskPanelProps {+ /**+ * The task context to render. Pass ``null`` when no data is+ * available yet (renders nothing).+ */+ tasksContext: TaskContext | null;+ className?: string;+}++/**+ * State icon for a single task row.+ *+ * @param state - The task's current state.+ * @returns An icon element sized for inline display.+ */+function StateIcon({ state }: { state: Task['state'] }) {+ switch (state) {+ case 'completed':+ return <SquareCheck className="size-3 shrink-0" />;+ case 'in_progress':+ return <Loader2 className="size-3 animate-spin shrink-0" />;+ default:+ return <Square className="size-3 shrink-0" />;+ }+}++/**+ * Filters the task list so that only the last 3 of any leading run of+ * completed tasks are shown; earlier ones are replaced by a single+ * ellipsis sentinel.+ *+ * @param tasks - The full ordered task array.+ * @returns An object with the visible task slice and a boolean flag+ * indicating whether the ellipsis row should be rendered.+ */+function filterTasksWithEllipsis(tasks: Task[]): {+ showEllipsis: boolean;+ visibleTasks: Task[];+} {+ // Count how many consecutive completed tasks appear at the front.+ let consecutiveCompleted = 0;+ for (const task of tasks) {+ if (task.state === 'completed') {+ consecutiveCompleted++;+ } else {+ break;+ }+ }++ const MAX_VISIBLE_COMPLETED = 3;+ if (consecutiveCompleted <= MAX_VISIBLE_COMPLETED) {+ return { showEllipsis: false, visibleTasks: tasks };+ }++ // Discard all but the last MAX_VISIBLE_COMPLETED completed tasks.+ return {+ showEllipsis: true,+ visibleTasks: tasks.slice(consecutiveCompleted - MAX_VISIBLE_COMPLETED),+ };+}++/**+ * Compact, read-only panel listing the agent's current tasks with+ * their status and dependency information.+ *+ * Each row shows ``#id [icon] subject [← blocked by #x, #y]``.+ * The panel header displays a progress summary like ``Tasks (3/5)``.+ * When there are more than 3 leading completed tasks, the earlier ones+ * are collapsed into a single ``…`` separator row.+ *+ * @param tasksContext - The full ``TaskContext`` from ``AgentState``.+ * ``null`` hides the panel entirely.+ * @param className - The className+ * @returns A panel element, or ``null`` when there are no tasks.+ */+export function TaskPanel({ tasksContext, className }: TaskPanelProps) {+ const { t } = useTranslation();+ const [expanded, setExpanded] = useState(false);++ if (!tasksContext || tasksContext.tasks.length === 0) {+ return null;+ }++ const { tasks } = tasksContext;+ const completed = tasks.filter((task) => task.state === 'completed').length;+ const { showEllipsis, visibleTasks } = filterTasksWithEllipsis(tasks);++ const displayedTasks = expanded ? tasks : visibleTasks;++ return (+ <div className={cn('hidden md:flex flex-col text-sm py-2 px-0', className)}>+ <div className="flex flex-row justify-between">+ <span className="font-bold text-muted-foreground">{t('task-panel.heading')}</span>+ <Badge variant={'secondary'} className="tracking-wide">+ {completed}/{tasks.length}+ </Badge>+ </div>++ <ul className="flex flex-col gap-y-0.5 text-xs overflow-y-auto h-full">+ {showEllipsis && !expanded && (+ <Button+ size={'xs'}+ variant={'ghost'}+ className="flex items-center justify-center w-full"+ onClick={() => setExpanded(true)}+ >+ <Ellipsis className="size-3 text-muted-foreground" />+ </Button>+ )}+ {displayedTasks.map((task) => (+ <li+ key={task.id}+ className={cn(+ 'flex gap-2 rounded px-2 py-1 items-center',+ task.state === 'completed' && 'opacity-60',+ )}+ >+ <StateIcon state={task.state} />+ <div className="flex flex-col min-w-0 gap-0.5">+ <span className="flex items-center gap-1.5">+ <span className="text-xs font-mono text-muted-foreground">+ #{task.id}+ </span>+ <span+ className={cn(+ 'truncate ',+ task.state === 'completed' && 'line-through',+ )}+ >+ {task.subject}+ </span>+ </span>+ {task.blocked_by.length > 0 && (+ <span className="text-xs text-muted-foreground">+ ← {t('task-panel.blockedBy')}{' '}+ {task.blocked_by.map((id) => `#${id}`).join(', ')}+ </span>+ )}+ </div>+ </li>+ ))}+ </ul>+ </div>+ );+}diff --git a/examples/web_ui/frontend/src/components/chat/TextInput.tsx b/examples/web_ui/frontend/src/components/chat/TextInput.tsxindex 202abbe78..f48661df2 100644--- a/examples/web_ui/frontend/src/components/chat/TextInput.tsx+++ b/examples/web_ui/frontend/src/components/chat/TextInput.tsx@@ -315,7 +315,7 @@ export const TextInput = forwardRef<TextInputRef, TextInputProps>(<Buttontype="button"variant="ghost"- size="icon-sm"+ size="icon"onClick={() => fileInputRef.current?.click()}disabled={attachDisabled}className="shrink-0 rounded-full"@@ -337,7 +337,7 @@ export const TextInput = forwardRef<TextInputRef, TextInputProps>(type="button"onClick={handleSend}disabled={disabled || !value.trim() || hasProcessing}- size="icon-sm"+ size="icon"className="shrink-0 rounded-full"><Send className="h-4 w-4" />diff --git a/examples/web_ui/frontend/src/components/chat/tool-renderers/TaskCreateRenderer.tsx b/examples/web_ui/frontend/src/components/chat/tool-renderers/TaskCreateRenderer.tsxnew file mode 100644index 000000000..e4340b7eb--- /dev/null+++ b/examples/web_ui/frontend/src/components/chat/tool-renderers/TaskCreateRenderer.tsx@@ -0,0 +1,91 @@+/* eslint-disable react-refresh/only-export-components -- renderer constant is co-located with its inline component by design */+import { useState } from 'react';++import { CornerLine, ToolStateIcon } from './_shared';+import type { TFunction, ToolCallWithResult, ToolRenderer } from './types';+import { Collapsible, CollapsibleContent, CollapsibleTrigger } from '@/components/ui/collapsible';++function parseInput(input: string): Record<string, unknown> {+ try {+ return JSON.parse(input);+ } catch {+ return {};+ }+}++/**+ * Collapsed: "TaskCreate Created 3 tasks ..."+ * Expanded:+ * TaskCreate Created 3 tasks+ * Research duck facts+ * Find five interesting facts about ducks+ * Write summary+ * Compile the research into a brief summary+ * Review code+ * Check for bugs and style issues+ */+function TaskCreateGroup({ calls, t }: { calls: ToolCallWithResult[]; t: TFunction }) {+ const [open, setOpen] = useState(false);++ return (+ <Collapsible open={open} onOpenChange={setOpen} className="flex flex-col w-full">+ <CollapsibleTrigger className="flex flex-row gap-x-2 w-full max-w-full items-center cursor-pointer text-left">+ <ToolStateIcon states={calls.map((c) => c.result?.state)} />+ <span className="text-sm flex-1 min-w-0 truncate">+ <strong className="text-primary">{t('tool.taskCreate.label')}</strong>{' '}+ {t('tool.taskCreate.count', { count: calls.length })}+ {!open && <span className="text-muted-foreground"> ...</span>}+ </span>+ </CollapsibleTrigger>+ <CollapsibleContent className="pl-6 pt-2 flex flex-col gap-y-2 text-sm">+ {calls.map(({ call, result }) => {+ const input = parseInput(call.input);+ const subject = (input.subject as string) || '(untitled)';+ const description = (input.description as string) || '';+ // Extract the numeric task id from result text:+ // "Task (id=3) created successfully: ..."+ const resultText =+ typeof result?.output === 'string'+ ? result.output+ : Array.isArray(result?.output)+ ? result.output.map((b) => ('text' in b ? b.text : '')).join('')+ : '';+ const idMatch = resultText.match(/^Task \(id=(\d+)\)/);+ const taskId = idMatch ? idMatch[1] : null;+ return (+ <div key={call.id} className="flex flex-col min-w-0">+ <span className="text-xs break-all font-medium">+ {taskId && (+ <span className="text-muted-foreground font-mono">+ #{taskId}+ </span>+ )}+ {taskId && ' '}+ {subject}+ </span>+ {description && (+ <div className="flex flex-row gap-x-2 items-start pl-2 text-xs">+ <CornerLine />+ <span className="text-muted-foreground break-all">+ {description}+ </span>+ </div>+ )}+ </div>+ );+ })}+ </CollapsibleContent>+ </Collapsible>+ );+}++export const TaskCreateRenderer: ToolRenderer = {+ getDisplayName: (_call, t) => t('tool.taskCreate.name'),++ renderCallArgs: (call) => {+ const input = parseInput(call.input);+ return (input.subject as string) || '';+ },++ renderGroup: (calls, t) => <TaskCreateGroup calls={calls} t={t} />,+};diff --git a/examples/web_ui/frontend/src/components/chat/tool-renderers/index.ts b/examples/web_ui/frontend/src/components/chat/tool-renderers/index.tsindex 3a63a6a2d..fa0f16479 100644--- a/examples/web_ui/frontend/src/components/chat/tool-renderers/index.ts+++ b/examples/web_ui/frontend/src/components/chat/tool-renderers/index.ts@@ -13,6 +13,7 @@ import { EditRenderer } from './EditRenderer';import { GlobRenderer } from './GlobRenderer';import { GrepRenderer } from './GrepRenderer';import { ReadRenderer } from './ReadRenderer';+import { TaskCreateRenderer } from './TaskCreateRenderer';import type { TFunction, ToolCallWithResult, ToolRenderer } from './types';import { WriteRenderer } from './WriteRenderer';@@ -23,6 +24,7 @@ const renderers: Record<string, ToolRenderer> = {Edit: EditRenderer,Glob: GlobRenderer,Grep: GrepRenderer,+ TaskCreate: TaskCreateRenderer,};function getRenderer(toolName: string): ToolRenderer {diff --git a/examples/web_ui/frontend/src/components/dialog/AddSkillDialog.tsx b/examples/web_ui/frontend/src/components/dialog/AddSkillDialog.tsxindex 53234533b..75141f9c5 100644--- a/examples/web_ui/frontend/src/components/dialog/AddSkillDialog.tsx+++ b/examples/web_ui/frontend/src/components/dialog/AddSkillDialog.tsx@@ -1,3 +1,4 @@+import { CircleAlert, Loader2, PlusCircle } from 'lucide-react';import { useState, type ReactNode } from 'react';import { Button } from '@/components/ui/button';@@ -12,6 +13,7 @@ import {} from '@/components/ui/dialog';import { Input } from '@/components/ui/input';import { Label } from '@/components/ui/label';+import { useTranslation } from '@/i18n/useI18n';interface AddSkillDialogProps {children: ReactNode;@@ -19,6 +21,7 @@ interface AddSkillDialogProps {}export function AddSkillDialog({ children, onAdd }: AddSkillDialogProps) {+ const { t } = useTranslation();const [open, setOpen] = useState(false);const [skillPath, setSkillPath] = useState('');const [loading, setLoading] = useState(false);@@ -42,18 +45,16 @@ export function AddSkillDialog({ children, onAdd }: AddSkillDialogProps) {return (<Dialog open={open} onOpenChange={setOpen}><DialogTrigger asChild>{children}</DialogTrigger>- <DialogContent>+ <DialogContent className="!w-[500px] !max-w-[500px]"><DialogHeader>- <DialogTitle>Add Skill</DialogTitle>- <DialogDescription>- Enter the path to a skill directory to add it to the workspace.- </DialogDescription>+ <DialogTitle>{t('dialog-skill-add.title')}</DialogTitle>+ <DialogDescription>{t('dialog-skill-add.description')}</DialogDescription></DialogHeader><div className="flex flex-col gap-y-2">- <Label htmlFor="skill-path">Skill Path</Label>+ <Label htmlFor="skill-path">{t('dialog-skill-add.pathLabel')}</Label><Inputid="skill-path"- placeholder="/path/to/skill"+ placeholder={t('dialog-skill-add.pathPlaceholder')}value={skillPath}onChange={(e) => setSkillPath(e.target.value)}onKeyDown={(e) => {@@ -63,11 +64,17 @@ export function AddSkillDialog({ children, onAdd }: AddSkillDialogProps) {{error && <p className="text-destructive text-sm">{error}</p>}</div><DialogFooter>- <Button variant="outline" onClick={() => setOpen(false)} disabled={loading}>- Cancel+ <Button variant="ghost" onClick={() => setOpen(false)} disabled={loading}>+ <CircleAlert className="size-3.5" />+ {t('common.cancel')}</Button><Button onClick={handleSubmit} disabled={loading || !skillPath.trim()}>- {loading ? 'Adding…' : 'Add'}+ {loading ? (+ <Loader2 className="size-3.5 animate-spin" />+ ) : (+ <PlusCircle className="size-3.5" />+ )}+ {loading ? t('dialog-mcp-create.adding') : t('common.add')}</Button></DialogFooter></DialogContent>diff --git a/examples/web_ui/frontend/src/components/dialog/AgentDialog.tsx b/examples/web_ui/frontend/src/components/dialog/AgentDialog.tsxindex e8301a526..cd62a3e41 100644--- a/examples/web_ui/frontend/src/components/dialog/AgentDialog.tsx+++ b/examples/web_ui/frontend/src/components/dialog/AgentDialog.tsx@@ -1,4 +1,4 @@-import { PlusCircle } from 'lucide-react';+import { CircleAlert, Loader2, PlusCircle } from 'lucide-react';import { useEffect, useState } from 'react';import { useTranslation } from 'react-i18next';@@ -72,12 +72,12 @@ export function AgentDialog({ onCreated, triggerId }: Props) {return (<Dialog open={open} onOpenChange={setOpen}><DialogTrigger asChild>- <Button id={triggerId} size="sm">+ <Button id={triggerId}><PlusCircle /><span>{t('dialog-agent-create.trigger')}</span></Button></DialogTrigger>- <DialogContent className="w-[500px]! max-w-[500px]!">+ <DialogContent className="!w-[500px] !max-w-[500px]"><DialogHeader><DialogTitle>{t('dialog-agent-create.title')}</DialogTitle></DialogHeader>@@ -89,15 +89,19 @@ export function AgentDialog({ onCreated, triggerId }: Props) {)}</div><DialogFooter>- <Button size="sm" variant="outline" onClick={() => setOpen(false)}>+ <Button variant="ghost" onClick={() => setOpen(false)} disabled={submitting}>+ <CircleAlert className="size-3.5" />{t('common.cancel')}</Button><Button- size="sm"onClick={handleSubmit}disabled={!nameValid || submitting || !schema || !values}>- <PlusCircle />+ {submitting ? (+ <Loader2 className="size-3.5 animate-spin" />+ ) : (+ <PlusCircle className="size-3.5" />+ )}{submitting ? t('common.creating') : t('common.create')}</Button></DialogFooter>diff --git a/examples/web_ui/frontend/src/components/dialog/CreateCredentialDialog.tsx b/examples/web_ui/frontend/src/components/dialog/CreateCredentialDialog.tsxindex 3a787acd5..330db5f44 100644--- a/examples/web_ui/frontend/src/components/dialog/CreateCredentialDialog.tsx+++ b/examples/web_ui/frontend/src/components/dialog/CreateCredentialDialog.tsx@@ -1,3 +1,4 @@+import { CircleAlert, Loader2, PlusCircle } from 'lucide-react';import { useState, useEffect } from 'react';import { credentialApi } from '@/api';@@ -82,7 +83,7 @@ export function CreateCredentialDialog({ open, onOpenChange, onCreated, defaultTreturn (<Dialog open={open} onOpenChange={onOpenChange}>- <DialogContent>+ <DialogContent className="!w-[500px] !max-w-[500px]"><DialogHeader><DialogTitle>{t('dialog-credential-create.title')}</DialogTitle></DialogHeader>@@ -124,10 +125,20 @@ export function CreateCredentialDialog({ open, onOpenChange, onCreated, defaultT)}</FieldGroup><DialogFooter>- <Button variant="outline" onClick={() => onOpenChange(false)}>+ <Button+ variant="ghost"+ onClick={() => onOpenChange(false)}+ disabled={submitting}+ >+ <CircleAlert className="size-3.5" />{t('common.cancel')}</Button><Button onClick={handleSubmit} disabled={submitting || !selectedSchema}>+ {submitting ? (+ <Loader2 className="size-3.5 animate-spin" />+ ) : (+ <PlusCircle className="size-3.5" />+ )}{submitting ? t('common.creating') : t('common.create')}</Button></DialogFooter>diff --git a/examples/web_ui/frontend/src/components/dialog/DeleteAgentDialog.tsx b/examples/web_ui/frontend/src/components/dialog/DeleteAgentDialog.tsxdeleted file mode 100644index b51101616..000000000--- a/examples/web_ui/frontend/src/components/dialog/DeleteAgentDialog.tsx+++ /dev/null@@ -1,37 +0,0 @@-import { useTranslation } from 'react-i18next';--import { DeleteDialog } from './DeleteDialog';-import type { AgentRecord } from '@/api';-import { useAgents } from '@/hooks/useAgents';--interface Props {- open: boolean;- onOpenChange: (open: boolean) => void;- agent: AgentRecord;- onDeleted?: () => void;-}--export function DeleteAgentDialog({ open, onOpenChange, agent, onDeleted }: Props) {- const { remove } = useAgents();- const { t } = useTranslation();-- return (- <DeleteDialog- open={open}- onOpenChange={onOpenChange}- title={t('dialog-agent-delete.title')}- description={- <>- <span className="font-medium text-foreground">{agent.data.name}</span>- {' — '}- {t('dialog-agent-delete.description')}- </>- }- confirmLabel={t('dialog-agent-delete.confirm')}- onConfirm={async () => {- await remove(agent.id);- onDeleted?.();- }}- />- );-}diff --git a/examples/web_ui/frontend/src/components/dialog/EditAgentDialog.tsx b/examples/web_ui/frontend/src/components/dialog/EditAgentDialog.tsxindex 48b347908..96c169cd8 100644--- a/examples/web_ui/frontend/src/components/dialog/EditAgentDialog.tsx+++ b/examples/web_ui/frontend/src/components/dialog/EditAgentDialog.tsx@@ -1,3 +1,4 @@+import { CircleAlert, Loader2, Save } from 'lucide-react';import { useEffect, useState } from 'react';import { useTranslation } from 'react-i18next';@@ -83,7 +84,7 @@ export function EditAgentDialog({ open, onOpenChange, agent, onUpdated }: Props)return (<Dialog open={open} onOpenChange={onOpenChange}>- <DialogContent className="w-[720px] max-w-[720px]">+ <DialogContent className="!w-[500px] !max-w-[500px]"><DialogHeader><DialogTitle>{t('dialog-agent-edit.title')}</DialogTitle></DialogHeader>@@ -95,14 +96,23 @@ export function EditAgentDialog({ open, onOpenChange, agent, onUpdated }: Props))}</div><DialogFooter>- <Button size="sm" variant="outline" onClick={() => onOpenChange(false)}>+ <Button+ variant="ghost"+ onClick={() => onOpenChange(false)}+ disabled={submitting}+ >+ <CircleAlert className="size-3.5" />{t('common.cancel')}</Button><Button- size="sm"onClick={handleSubmit}disabled={!nameValid || submitting || !schema || !values}>+ {submitting ? (+ <Loader2 className="size-3.5 animate-spin" />+ ) : (+ <Save className="size-3.5" />+ )}{submitting ? t('common.saving') : t('common.save')}</Button></DialogFooter>diff --git a/examples/web_ui/frontend/src/components/dialog/EditCredentialDialog.tsx b/examples/web_ui/frontend/src/components/dialog/EditCredentialDialog.tsxindex 9e6d4791b..687af8702 100644--- a/examples/web_ui/frontend/src/components/dialog/EditCredentialDialog.tsx+++ b/examples/web_ui/frontend/src/components/dialog/EditCredentialDialog.tsx@@ -1,3 +1,4 @@+import { CircleAlert, Loader2, Save } from 'lucide-react';import { useState, useEffect } from 'react';import { credentialApi } from '@/api';@@ -78,7 +79,7 @@ export function EditCredentialDialog({ open, onOpenChange, credential, onUpdatedreturn (<Dialog open={open} onOpenChange={onOpenChange}>- <DialogContent>+ <DialogContent className="!w-[500px] !max-w-[500px]"><DialogHeader><DialogTitle>{t('dialog-credential-edit.title')}</DialogTitle></DialogHeader>@@ -92,10 +93,20 @@ export function EditCredentialDialog({ open, onOpenChange, credential, onUpdated/>) : null}<DialogFooter>- <Button variant="outline" onClick={() => onOpenChange(false)}>+ <Button+ variant="ghost"+ onClick={() => onOpenChange(false)}+ disabled={submitting}+ >+ <CircleAlert className="size-3.5" />{t('common.cancel')}</Button><Button onClick={handleSubmit} disabled={submitting || !schema}>+ {submitting ? (+ <Loader2 className="size-3.5 animate-spin" />+ ) : (+ <Save className="size-3.5" />+ )}{submitting ? t('common.saving') : t('common.save')}</Button></DialogFooter>diff --git a/examples/web_ui/frontend/src/components/dialog/MCPDialog.tsx b/examples/web_ui/frontend/src/components/dialog/MCPDialog.tsxindex f5be36df4..03d6bff2a 100644--- a/examples/web_ui/frontend/src/components/dialog/MCPDialog.tsx+++ b/examples/web_ui/frontend/src/components/dialog/MCPDialog.tsx@@ -134,7 +134,7 @@ export const CreateMCPDialog = ({ children, onAdd }: Props) => {return (<Dialog open={open} onOpenChange={handleOpenChange}><DialogTrigger asChild>{children}</DialogTrigger>- <DialogContent>+ <DialogContent className="!w-[500px] !max-w-[500px]"><DialogHeader><DialogTitle>{t('dialog-mcp-create.title')}</DialogTitle><DialogDescription>{t('dialog-mcp-create.description')}</DialogDescription>@@ -180,22 +180,25 @@ export const CreateMCPDialog = ({ children, onAdd }: Props) => {</Alert>)}<DialogFooter>+ <Button variant="ghost" onClick={() => handleOpenChange(false)}>+ <CircleAlert className="size-3.5" />+ {t('common.cancel')}+ </Button><ButtononClick={handleAdd}disabled={status === 'loading' || status === 'success'}>- {status === 'loading' && <Loader2 className="animate-spin" />}- {status === 'success' && <Check />}- {status !== 'loading' && status !== 'success' && <PlusCircle />}+ {status === 'loading' && <Loader2 className="size-3.5 animate-spin" />}+ {status === 'success' && <Check className="size-3.5" />}+ {status !== 'loading' && status !== 'success' && (+ <PlusCircle className="size-3.5" />+ )}{status === 'loading'? t('dialog-mcp-create.adding'): status === 'success'? t('dialog-mcp-create.added'): t('common.add')}</Button>- <Button variant="ghost" onClick={() => handleOpenChange(false)}>- {t('common.cancel')}- </Button></DialogFooter></DialogContent></Dialog>diff --git a/examples/web_ui/frontend/src/components/dialog/RenameSessionDialog.tsx b/examples/web_ui/frontend/src/components/dialog/RenameSessionDialog.tsxindex 14e63243d..b3b42f243 100644--- a/examples/web_ui/frontend/src/components/dialog/RenameSessionDialog.tsx+++ b/examples/web_ui/frontend/src/components/dialog/RenameSessionDialog.tsx@@ -1,3 +1,4 @@+import { CheckCircle, CircleAlert, Loader2 } from 'lucide-react';import { useState, useEffect } from 'react';import { Button } from '@/components/ui/button';@@ -60,15 +61,17 @@ export function RenameSessionDialog({ open, onOpenChange, currentName, onConfirm</Field></FieldGroup><DialogFooter>- <Button- variant="outline"- onClick={() => onOpenChange(false)}- disabled={loading}- >+ <Button variant="ghost" onClick={() => onOpenChange(false)} disabled={loading}>+ <CircleAlert className="size-3.5" />{t('common.cancel')}</Button><Button onClick={handleConfirm} disabled={loading || !name.trim()}>- {loading ? t('common.saving') : t('dialog-session-rename.confirm')}+ {loading ? (+ <Loader2 className="size-3.5 animate-spin" />+ ) : (+ <CheckCircle className="size-3.5" />+ )}+ {t('common.confirm')}</Button></DialogFooter></DialogContent>diff --git a/examples/web_ui/frontend/src/components/drawer/WorkspaceDrawer.tsx b/examples/web_ui/frontend/src/components/drawer/WorkspaceDrawer.tsxindex bb158d9da..a9e5b6515 100644--- a/examples/web_ui/frontend/src/components/drawer/WorkspaceDrawer.tsx+++ b/examples/web_ui/frontend/src/components/drawer/WorkspaceDrawer.tsx@@ -209,8 +209,11 @@ export function WorkspaceDrawer({<DeleteDialogopen={deleteOpen}onOpenChange={setDeleteOpen}- title={t('dialog-mcp-delete.title', { name: deleteTarget ?? '' })}- description={t('dialog-mcp-delete.description')}+ title={t('common.deleteTitle', {+ entity: t('dialog-mcp-delete.entity'),+ name: deleteTarget ?? '',+ })}+ description={t('common.deleteDescription')}onConfirm={async () => {if (deleteTarget) await onRemove(deleteTarget);}}@@ -218,8 +221,11 @@ export function WorkspaceDrawer({<DeleteDialogopen={skillDeleteOpen}onOpenChange={setSkillDeleteOpen}- title={`Remove skill "${skillDeleteTarget ?? ''}"`}- description="Are you sure you want to remove this skill from the workspace?"+ title={t('common.deleteTitle', {+ entity: t('dialog-mcp-delete.skillEntity'),+ name: skillDeleteTarget ?? '',+ })}+ description={t('dialog-mcp-delete.skillDescription')}onConfirm={async () => {if (skillDeleteTarget) await onRemoveSkill(skillDeleteTarget);}}diff --git a/examples/web_ui/frontend/src/components/layout/AppSidebar.tsx b/examples/web_ui/frontend/src/components/layout/AppSidebar.tsxindex eec4e3d90..e92eb4e2f 100644--- a/examples/web_ui/frontend/src/components/layout/AppSidebar.tsx+++ b/examples/web_ui/frontend/src/components/layout/AppSidebar.tsx@@ -25,11 +25,11 @@ export function AppSidebar() {const { startOnborda } = useOnborda();const handleStartTour = () => {- if (location.pathname !== '/') {+ if (!location.pathname.startsWith('/chat')) {// Page not mounted yet — leave a flag, navigate, and let the// ChatTourController auto-trigger after ChatPage mounts.sessionStorage.setItem('force_tour', '1');- navigate('/');+ navigate('/chat');} else {startOnborda(CHAT_TOUR_NAME);}@@ -54,8 +54,11 @@ export function AppSidebar() {<SidebarMenuItem key={'chat'}><SidebarMenuButtontooltip={{ children: t('common.chat'), hidden: false }}- isActive={location.pathname === '/'}- onClick={() => navigate('/')}+ isActive={+ location.pathname === '/chat' ||+ location.pathname.startsWith('/chat/')+ }+ onClick={() => navigate('/chat')}className="px-2.5 md:px-2"><BotMessageSquare />diff --git a/examples/web_ui/frontend/src/components/team/TeamSidebar.tsx b/examples/web_ui/frontend/src/components/team/TeamSidebar.tsxnew file mode 100644index 000000000..bbbfdb8f5--- /dev/null+++ b/examples/web_ui/frontend/src/components/team/TeamSidebar.tsx@@ -0,0 +1,131 @@+import { Bot, Crown } from 'lucide-react';+import { useNavigate } from 'react-router-dom';++import type { TeamDetailResponse, TeamMemberInfo, AgentRecord } from '@/api';+import {+ Sidebar,+ SidebarContent,+ SidebarFooter,+ SidebarGroup,+ SidebarGroupContent,+ SidebarGroupLabel,+ SidebarHeader,+ SidebarMenu,+ SidebarMenuButton,+ SidebarMenuItem,+} from '@/components/ui/sidebar';+import { useTranslation } from '@/i18n/useI18n';++interface TeamSidebarProps {+ /** Resolved team detail (leader + members) — drives all rendering. */+ team: TeamDetailResponse;+ /**+ * The session id currently shown in the chat area. Used both for+ * highlighting the active row and for deciding whether the row+ * being clicked is already the current one.+ */+ currentSessionId: string;+}++/**+ * Secondary sidebar shown next to the chat area whenever the open+ * session participates in a team.+ *+ * Built on the shared shadcn `Sidebar` primitives so it visually+ * matches the main page sidebar (same paddings, item heights,+ * active-row treatment, etc.). Renders the leader at the top+ * followed by every member; all rows are clickable.+ *+ * Clicking the leader row navigates to+ * `/chat/<leaderAgentId>/<leaderSessionId>` (drops the URL's+ * optional `:memberId` slot so the chat area falls back to the+ * leader session). Clicking a member row navigates to+ * `/chat/<leaderAgentId>/<leaderSessionId>/<memberAgentId>` — the+ * outer URL slots stay the same so the main page sidebar does not+ * collapse; only the chat area reroutes to the member's session.+ *+ * Both `leaderAgentId` and `leaderSessionId` are derived from the+ * passed `team` prop, so the parent only needs to know which+ * session is currently active.+ *+ * @param team - Resolved team detail.+ * @param currentSessionId - Session id currently shown in the chat+ * area; used to drive row highlighting.+ * @returns A vertical sidebar element.+ */+export function TeamSidebar({ team, currentSessionId }: TeamSidebarProps) {+ const { t } = useTranslation();+ const navigate = useNavigate();++ const leaderAgentId = team.leader_agent?.id ?? null;+ const leaderSessionId = team.team.session_id;++ const goToLeader = () => {+ if (!leaderAgentId) return;+ navigate(`/chat/${leaderAgentId}/${leaderSessionId}`);+ };++ const goToMember = (memberAgentId: string) => {+ if (!leaderAgentId) return;+ navigate(`/chat/${leaderAgentId}/${leaderSessionId}/${memberAgentId}`);+ };++ const renderLeader = (leader: AgentRecord) => (+ <SidebarMenuItem>+ <SidebarMenuButton isActive={currentSessionId === leaderSessionId} onClick={goToLeader}>+ <Crown />+ <span className="truncate">{leader.data.name}</span>+ </SidebarMenuButton>+ </SidebarMenuItem>+ );++ const renderMember = (member: TeamMemberInfo) => (+ <SidebarMenuItem key={member.agent.id}>+ <SidebarMenuButton+ isActive={member.session_id === currentSessionId}+ disabled={member.session_id === null}+ onClick={() => goToMember(member.agent.id)}+ >+ <Bot />+ <span className="truncate">{member.agent.data.name}</span>+ </SidebarMenuButton>+ </SidebarMenuItem>+ );++ return (+ <Sidebar collapsible="none" className="w-56 border-r">+ <SidebarHeader>+ <div className="flex flex-col gap-y-1 px-2 py-1">+ <span className="text-muted-foreground text-xs uppercase tracking-wide">+ {t('common.team')}+ </span>+ <span className="truncate text-sm font-medium">{team.team.data.name}</span>+ </div>+ </SidebarHeader>+ <SidebarContent>+ {team.leader_agent && (+ <SidebarGroup>+ <SidebarGroupLabel>{t('common.leader')}</SidebarGroupLabel>+ <SidebarGroupContent>+ <SidebarMenu>{renderLeader(team.leader_agent)}</SidebarMenu>+ </SidebarGroupContent>+ </SidebarGroup>+ )}++ <SidebarGroup>+ <SidebarGroupLabel>{t('team-sidebar.membersHeading')}</SidebarGroupLabel>+ <SidebarGroupContent>+ {team.members.length === 0 ? (+ <p className="px-3 py-2 text-xs text-muted-foreground">+ {t('team-sidebar.noMembers')}+ </p>+ ) : (+ <SidebarMenu>{team.members.map(renderMember)}</SidebarMenu>+ )}+ </SidebarGroupContent>+ </SidebarGroup>+ </SidebarContent>+ <SidebarFooter />+ </Sidebar>+ );+}diff --git a/examples/web_ui/frontend/src/context/ChatContext.tsx b/examples/web_ui/frontend/src/context/ChatContext.tsxdeleted file mode 100644index 48ac64fe6..000000000--- a/examples/web_ui/frontend/src/context/ChatContext.tsx+++ /dev/null@@ -1,45 +0,0 @@-import { createContext, useContext, useState } from 'react';-import type { ReactNode } from 'react';--interface ChatContextValue {- /** Currently selected agent ID, or null if none selected. */- selectedAgentId: string | null;- setSelectedAgentId: (id: string | null) => void;- /** Currently selected session ID, or null if none selected. */- selectedSessionId: string | null;- setSelectedSessionId: (id: string | null) => void;-}--const ChatContext = createContext<ChatContextValue | null>(null);--/**- * Provides shared chat state (selected agent and session) to the component tree.- * Wrap the chat page root with this provider.- */-export function ChatProvider({ children }: { children: ReactNode }) {- const [selectedAgentId, setSelectedAgentId] = useState<string | null>(null);- const [selectedSessionId, setSelectedSessionId] = useState<string | null>(null);-- return (- <ChatContext.Provider- value={{- selectedAgentId,- setSelectedAgentId,- selectedSessionId,- setSelectedSessionId,- }}- >- {children}- </ChatContext.Provider>- );-}--/**- * Consumes ChatContext. Must be called inside a ChatProvider.- * @throws if used outside of ChatProvider- */-export function useChatContext() {- const ctx = useContext(ChatContext);- if (!ctx) throw new Error('useChatContext must be used within <ChatProvider>');- return ctx;-}diff --git a/examples/web_ui/frontend/src/hooks/useChat.ts b/examples/web_ui/frontend/src/hooks/useChat.tsindex 8eaa22542..d39b812a3 100644--- a/examples/web_ui/frontend/src/hooks/useChat.ts+++ b/examples/web_ui/frontend/src/hooks/useChat.ts@@ -1,37 +1,35 @@-import { useState, useCallback, useRef } from 'react';+import { useState, useCallback } from 'react';import { chatApi } from '@/api';-import type { AgentEvent, ChatRequest } from '@/api';+import type { ChatRequest } from '@/api';/**- * Drives a streaming chat session with an agent.+ * Fire-and-forget chat trigger.*- * Collects SSE AgentEvent frames into `events` as they arrive.- * Call `abort()` to cancel an in-flight stream.+ * Sends a ``POST /chat/`` request that kicks off a chat run on the+ * backend. Events are **not** returned here — they arrive via the+ * session's SSE stream (``GET /sessions/{sid}/stream``), consumed by+ * :func:`useMessages`.+ *+ * This hook is a thin wrapper around ``chatApi.trigger``; it mainly+ * exists for parity with the previous ``useChat`` API shape.*/export function useChat() {- const [events, setEvents] = useState<AgentEvent[]>([]);const [streaming, setStreaming] = useState(false);const [error, setError] = useState<Error | null>(null);- const abortRef = useRef<AbortController | null>(null);/**- * Sends a message and streams the agent's reply into `events`.- * Cancels any previous in-flight stream before starting.+ * Trigger a chat run. Returns when the POST completes (not when+ * the run finishes).+ *+ * @param body - The chat request payload.*/const send = useCallback(async (body: ChatRequest) => {- abortRef.current?.abort();- const controller = new AbortController();- abortRef.current = controller;-- setEvents([]);setStreaming(true);setError(null);try {- for await (const event of chatApi.stream(body, controller.signal)) {- setEvents((prev) => [...prev, event]);- }+ await chatApi.trigger(body);} catch (e) {if ((e as Error).name !== 'AbortError') setError(e as Error);} finally {@@ -39,10 +37,5 @@ export function useChat() {}}, []);- /** Cancels the current in-flight stream. */- const abort = useCallback(() => {- abortRef.current?.abort();- }, []);-- return { events, streaming, error, send, abort };+ return { streaming, error, send };}diff --git a/examples/web_ui/frontend/src/hooks/useMessages.ts b/examples/web_ui/frontend/src/hooks/useMessages.tsindex 398ef66a2..3b9c9b130 100644--- a/examples/web_ui/frontend/src/hooks/useMessages.ts+++ b/examples/web_ui/frontend/src/hooks/useMessages.ts@@ -1,6 +1,7 @@import { EventType } from '@agentscope-ai/agentscope/event';import type {AgentEvent,+ CustomEvent,ReplyStartEvent,UserConfirmResultEvent,} from '@agentscope-ai/agentscope/event';@@ -11,9 +12,54 @@ import { useState, useCallback, useRef, useEffect } from 'react';import { sessionApi } from '@/api';import { chatApi } from '@/api';-import type { ChatRequest } from '@/api/types';-export function useMessages(agentId: string | null, sessionId: string | null) {+/**+ * Manages messages for a single ``(agentId, sessionId)`` pair.+ *+ * Event delivery has two independent channels:+ *+ * - **History** — ``GET /sessions/{sid}/messages`` fetches persisted+ * ``Msg`` objects (each a complete reply).+ * - **Live stream** — ``GET /sessions/{sid}/stream`` is a long-lived+ * SSE connection that pushes ``AgentEvent`` deltas as they are+ * produced by any chat run on this session (user-triggered,+ * background retrigger, team member message, …).+ *+ * The hook opens the SSE connection immediately after fetching+ * history. User input and human-in-the-loop confirmations are sent+ * via ``POST /chat/`` (fire-and-forget); the resulting events arrive+ * through the already-open SSE connection.+ *+ * ``streaming`` is driven by event content, not HTTP lifecycle:+ * ``true`` after receiving ``ReplyStartEvent``, ``false`` after+ * ``ReplyEndEvent``.+ *+ * @param agentId - The agent whose session to subscribe. ``null`` to+ * skip.+ * @param sessionId - The session to subscribe. ``null`` to skip.+ * @returns Object with ``msgs``, ``loading``, ``streaming``, ``error``,+ * ``send``, ``onUserConfirm``, and ``abort``.+ */+export function useMessages(+ agentId: string | null,+ sessionId: string | null,+ options?: {+ /**+ * Called when a ``CUSTOM`` event with ``name="team_updated"``+ * arrives — the team membership has changed (TeamCreate /+ * AgentCreate / TeamDelete ran). The typical response is to+ * refetch the session list so the team sidebar updates.+ */+ onTeamUpdated?: () => void;+ /**+ * Called when a ``CUSTOM`` event with ``name="state_updated"``+ * arrives — agent state (tasks / permission) changed during a+ * tool call. The ``value`` payload contains the latest+ * ``tasks_context`` and ``permission_context``.+ */+ onStateUpdated?: (value: Record<string, unknown>) => void;+ },+) {const [msgs, setMsgs] = useState<Msg[]>([]);const [loading, setLoading] = useState(false);const [streaming, setStreaming] = useState(false);@@ -24,6 +70,19 @@ export function useMessages(agentId: string | null, sessionId: string | null) {const abortRef = useRef<AbortController | null>(null);const rafRef = useRef<number | null>(null);+ // Mirror `options` into a ref so `processEvent` (a single-creation+ // useCallback to keep the SSE stable) always reads the freshest+ // callbacks. Without this, the closure freezes the first render's+ // `options` — typically captured when `agentId` is still `null` —+ // so `team_updated` / `state_updated` events fire stale no-op+ // handlers, which in turn call `useSessions(null).refetch`+ // (`if (!agentId) setSessions([])`) and blank out the session list.+ const optionsRef = useRef(options);+ useEffect(() => {+ optionsRef.current = options;+ }, [options]);++ /** Batch UI updates via requestAnimationFrame. */const scheduleUpdate = useCallback(() => {if (rafRef.current !== null) return;rafRef.current = requestAnimationFrame(() => {@@ -32,13 +91,32 @@ export function useMessages(agentId: string | null, sessionId: string | null) {});}, []);+ /** Apply a single AgentEvent to the in-progress reply. */const processEvent = useCallback((event: AgentEvent) => {+ // Custom events are service-layer notifications, not agent+ // reply content — route them to callbacks and skip appendEvent.+ if (event.type === EventType.CUSTOM) {+ const custom = event as CustomEvent;+ if (custom.name === 'team_updated') {+ optionsRef.current?.onTeamUpdated?.();+ } else if (custom.name === 'state_updated' && custom.value) {+ optionsRef.current?.onStateUpdated?.(custom.value as Record<string, unknown>);+ }+ return;+ }if (event.type === EventType.REPLY_START) {const e = event as ReplyStartEvent;const msg = AssistantMsg({ id: e.reply_id, name: e.name, content: [] });msgsRef.current = [...msgsRef.current, msg];currentReplyRef.current = msg;+ setStreaming(true);+ } else if (event.type === EventType.REPLY_END) {+ if (currentReplyRef.current) {+ appendEvent(currentReplyRef.current, event);+ }+ setStreaming(false);+ currentReplyRef.current = null;} else if (currentReplyRef.current) {appendEvent(currentReplyRef.current, event);}@@ -47,59 +125,66 @@ export function useMessages(agentId: string | null, sessionId: string | null) {[scheduleUpdate],);- // Load history when sessionId changes+ // ── Lifecycle: fetch history + open SSE stream ──────────────────useEffect(() => {msgsRef.current = [];currentReplyRef.current = null;setMsgs([]);setError(null);+ setStreaming(false);if (!agentId || !sessionId) return;+ const controller = new AbortController();+ abortRef.current = controller;let cancelled = false;- setLoading(true);+(async () => {+ // 1. Fetch persisted history+ setLoading(true);try {- const { messages, is_running } = await sessionApi.messages(sessionId, agentId);+ const { messages } = await sessionApi.messages(sessionId, agentId);if (cancelled) return;msgsRef.current = messages;- setStreaming(is_running);scheduleUpdate();} catch (e) {if (!cancelled) setError(e as Error);+ return;} finally {if (!cancelled) setLoading(false);}- })();-- return () => {- cancelled = true;- };- }, [agentId, sessionId, scheduleUpdate]);-- const runStream = useCallback(- async (request: ChatRequest) => {- abortRef.current?.abort();- const controller = new AbortController();- abortRef.current = controller;-- setStreaming(true);- setError(null);+ // 2. Open SSE long connection for live eventstry {- for await (const event of chatApi.stream(request, controller.signal)) {+ for await (const event of sessionApi.streamEvents(+ sessionId,+ agentId,+ controller.signal,+ )) {+ if (cancelled) break;processEvent(event);}} catch (e) {- if ((e as Error).name !== 'AbortError') setError(e as Error);- } finally {- setStreaming(false);- currentReplyRef.current = null;+ if ((e as Error).name !== 'AbortError' && !cancelled) {+ setError(e as Error);+ }}- },- [processEvent],- );+ })();++ return () => {+ cancelled = true;+ controller.abort();+ abortRef.current = null;+ };+ }, [agentId, sessionId, scheduleUpdate, processEvent]);+ /**+ * Send a user message. Appends the message to the local list+ * optimistically, then fires a ``POST /chat/`` trigger. Events+ * arrive via the already-open SSE connection.+ *+ * @param content - The message content blocks.+ */const send = useCallback(async (content: ContentBlock[]) => {if (!agentId || !sessionId) return;@@ -108,11 +193,29 @@ export function useMessages(agentId: string | null, sessionId: string | null) {msgsRef.current = [...msgsRef.current, userMsg];scheduleUpdate();- await runStream({ agent_id: agentId, session_id: sessionId, input: userMsg });+ try {+ await chatApi.trigger({+ agent_id: agentId,+ session_id: sessionId,+ input: userMsg,+ });+ } catch (e) {+ setError(e as Error);+ }},- [agentId, sessionId, scheduleUpdate, runStream],+ [agentId, sessionId, scheduleUpdate],);+ /**+ * Confirm or deny a tool call (human-in-the-loop). Fires a+ * ``POST /chat/`` with a ``UserConfirmResultEvent``; events+ * arrive via SSE.+ *+ * @param toolCall - The tool call block to confirm/deny.+ * @param confirm - Whether the user confirmed.+ * @param replyId - The reply id the tool call belongs to.+ * @param rules - Optional permission rules to attach.+ */const onUserConfirm = useCallback(async (toolCall: ToolCallBlock,@@ -122,7 +225,8 @@ export function useMessages(agentId: string | null, sessionId: string | null) {) => {if (!agentId || !sessionId) return;- // Restore the ref so continuation events (no REPLY_START) have a target+ // Restore the ref so continuation events (no REPLY_START)+ // have a target.currentReplyRef.current = msgsRef.current.find((m) => m.id === replyId) ?? null;const event: UserConfirmResultEvent = {@@ -135,11 +239,20 @@ export function useMessages(agentId: string | null, sessionId: string | null) {],};- await runStream({ agent_id: agentId, session_id: sessionId, input: event });+ try {+ await chatApi.trigger({+ agent_id: agentId,+ session_id: sessionId,+ input: event,+ });+ } catch (e) {+ setError(e as Error);+ }},- [agentId, sessionId, runStream],+ [agentId, sessionId],);+ /** Abort the current SSE connection. */const abort = useCallback(() => {abortRef.current?.abort();}, []);diff --git a/examples/web_ui/frontend/src/hooks/useSessions.ts b/examples/web_ui/frontend/src/hooks/useSessions.tsindex 9b1fcc841..e7b788104 100644--- a/examples/web_ui/frontend/src/hooks/useSessions.ts+++ b/examples/web_ui/frontend/src/hooks/useSessions.ts@@ -1,16 +1,22 @@import { useState, useEffect, useCallback } from 'react';import { sessionApi } from '../api';-import type { SessionRecord, CreateSessionRequest, UpdateSessionRequest } from '../api';+import type { SessionView, CreateSessionRequest, UpdateSessionRequest } from '../api';/**- * Manages sessions for a given agent.- * Clears and re-fetches whenever agentId changes.+ * Manages session views for a given agent.+ *+ * Each entry is a `SessionView` (record + is_running + optional team+ * detail) — the same shape the backend returns. The hook clears and+ * re-fetches whenever agentId changes.** @param agentId - The agent whose sessions to load. Pass null to skip fetching.+ * @returns Object with the loaded `sessions` array plus `loading` /+ * `error` flags and `refetch` / `create` / `update` / `remove`+ * helpers that all keep the local list in sync.*/export function useSessions(agentId: string | null) {- const [sessions, setSessions] = useState<SessionRecord[]>([]);+ const [sessions, setSessions] = useState<SessionView[]>([]);const [loading, setLoading] = useState(false);const [error, setError] = useState<Error | null>(null);diff --git a/examples/web_ui/frontend/src/i18n/locales/en.json b/examples/web_ui/frontend/src/i18n/locales/en.jsonindex ff9736fb4..7f1345e55 100644--- a/examples/web_ui/frontend/src/i18n/locales/en.json+++ b/examples/web_ui/frontend/src/i18n/locales/en.json@@ -33,8 +33,13 @@"switchToZh": "切换为中文","switchToEn": "Switch to English","success": "Success",+ "team": "Team",+ "leader": "Leader",+ "worker": "Worker","time": "Time",- "yes": "Yes"+ "yes": "Yes",+ "deleteTitle": "Delete {{entity}} \"{{name}}\"?",+ "deleteDescription": "This action cannot be undone."},"tool": {"moreLines": "... {{count}} more lines",@@ -48,6 +53,12 @@"glob": {"name": "Glob"},+ "taskCreate": {+ "name": "TaskCreate",+ "label": "Create",+ "count_one": "{{count}} task",+ "count_other": "{{count}} tasks"+ },"grep": {"name": "Grep"}@@ -65,7 +76,12 @@},"messageBubble": {"thinking": "Thinking",- "running": "Running..."+ "running": "Running...",+ "hintSource": {+ "tool_output": "Tool Output",+ "team_message": "Team Message",+ "schedule": "Schedule"+ }},"chat": {"inputPlaceholder": "Type a message...",@@ -119,19 +135,17 @@"title": "Edit agent"},"dialog-agent-delete": {- "title": "Delete agent",- "description": "This action cannot be undone.",+ "entity": "agent","confirm": "Delete"},"dialog-session-delete": {- "title": "Delete session",- "description": "This action cannot be undone."+ "entity": "session",+ "confirm": "Delete"},"dialog-session-rename": {"title": "Rename session","label": "Name",- "placeholder": "Session name",- "confirm": "Rename"+ "placeholder": "Session name"},"session-menu": {"rename": "Rename",@@ -154,8 +168,7 @@"availableModels": "Available Models","noModels": "No models available","noModelsDescription": "This provider returned no models.",- "deleteTitle": "Delete \"{{name}}\"?",- "deleteDescription": "This action cannot be undone. The credential will be permanently removed.",+ "deleteEntity": "credential","subtitle": "Model API credential configuration","reasoning": "Reasoning","maxContext": "Max. Context",@@ -199,8 +212,15 @@"emptyMcpServers": "No MCP servers found in configuration."},"dialog-mcp-delete": {- "title": "Delete MCP server \"{{name}}\"?",- "description": "This action cannot be undone."+ "entity": "MCP server",+ "skillEntity": "skill",+ "skillDescription": "Are you sure you want to remove this skill from the workspace?"+ },+ "dialog-skill-add": {+ "title": "Add skill",+ "description": "Enter the path to a skill directory to add it to the workspace.",+ "pathLabel": "Skill path",+ "pathPlaceholder": "/path/to/skill"},"schedule": {"calendar": "Calendar",@@ -212,9 +232,8 @@"title": "Create Schedule"},"deleteSchedule": {- "description": "This action cannot be undone. The scheduled task will be permanently removed.",- "successToast": "Schedule deleted successfully.",- "title": "Delete Schedule"+ "entity": "schedule",+ "successToast": "Schedule deleted successfully."},"endAt": "End Date","end_at": "End At",@@ -297,5 +316,20 @@"title": "Start chatting","content": "Type a message and press Enter. Paperclip attaches files."}+ },+ "task-panel": {+ "heading": "Tasks",+ "noTasks": "No tasks yet.",+ "pending": "Pending",+ "inProgress": "In Progress",+ "completed": "Completed",+ "blockedBy": "blocked by"+ },+ "team-sidebar": {+ "membersHeading": "Members",+ "noMembers": "No members yet — ask the leader to spawn one with AgentCreate.",+ "running": "Running",+ "idle": "Idle",+ "missingSession": "(no session)"}}diff --git a/examples/web_ui/frontend/src/i18n/locales/zh.json b/examples/web_ui/frontend/src/i18n/locales/zh.jsonindex 262fac779..1388d67ea 100644--- a/examples/web_ui/frontend/src/i18n/locales/zh.json+++ b/examples/web_ui/frontend/src/i18n/locales/zh.json@@ -33,8 +33,13 @@"switchToZh": "切换为中文","switchToEn": "Switch to English","success": "成功",+ "team": "团队",+ "leader": "队长",+ "worker": "成员","time": "时间",- "yes": "是"+ "yes": "是",+ "deleteTitle": "删除{{entity}} \"{{name}}\"?",+ "deleteDescription": "此操作无法撤销。"},"tool": {"moreLines": "... 还有 {{count}} 行",@@ -48,6 +53,12 @@"glob": {"name": "Glob"},+ "taskCreate": {+ "name": "TaskCreate",+ "label": "创建",+ "count_one": "{{count}} 个任务",+ "count_other": "{{count}} 个任务"+ },"grep": {"name": "Grep"}@@ -65,7 +76,12 @@},"messageBubble": {"thinking": "思考中",- "running": "运行中..."+ "running": "运行中...",+ "hintSource": {+ "tool_output": "工具输出",+ "team_message": "团队消息",+ "schedule": "定时任务"+ }},"chat": {"inputPlaceholder": "输入消息...",@@ -119,19 +135,17 @@"title": "编辑 Agent"},"dialog-agent-delete": {- "title": "删除 Agent",- "description": "此操作无法撤销。",+ "entity": "Agent","confirm": "删除"},"dialog-session-delete": {- "title": "删除会话",- "description": "此操作无法撤销。"+ "entity": "会话",+ "confirm": "删除"},"dialog-session-rename": {"title": "重命名会话","label": "名称",- "placeholder": "会话名称",- "confirm": "重命名"+ "placeholder": "会话名称"},"session-menu": {"rename": "重命名",@@ -154,8 +168,7 @@"availableModels": "可用模型","noModels": "暂无可用模型","noModelsDescription": "该提供商未返回任何模型。",- "deleteTitle": "确定要删除 API 凭证 \"{{name}}\" 吗?",- "deleteDescription": "此操作无法撤销",+ "deleteEntity": "凭证","subtitle": "模型 API 授权配置","reasoning": "推理模型","maxContext": "最大上下文",@@ -199,8 +212,15 @@"emptyMcpServers": "配置中未找到 MCP 服务器。"},"dialog-mcp-delete": {- "title": "确定要删除 MCP 服务器 \"{{name}}\" 吗?",- "description": "此操作无法撤销。"+ "entity": "MCP 服务器",+ "skillEntity": "技能",+ "skillDescription": "确定要将该技能从工作区中移除吗?"+ },+ "dialog-skill-add": {+ "title": "添加技能",+ "description": "输入技能目录的路径以添加到工作区。",+ "pathLabel": "技能路径",+ "pathPlaceholder": "/path/to/skill"},"schedule": {"calendar": "日历",@@ -212,9 +232,8 @@"title": "创建日程"},"deleteSchedule": {- "description": "此操作无法撤销,计划任务将被永久删除。",- "successToast": "日程已删除。",- "title": "删除日程"+ "entity": "日程",+ "successToast": "日程已删除。"},"endAt": "结束日期","end_at": "结束时间",@@ -297,5 +316,20 @@"title": "开始对话","content": "输入消息回车发送,回形针可附加文件。"}+ },+ "task-panel": {+ "heading": "任务",+ "noTasks": "暂无任务。",+ "pending": "待处理",+ "inProgress": "进行中",+ "completed": "已完成",+ "blockedBy": "依赖"+ },+ "team-sidebar": {+ "membersHeading": "成员",+ "noMembers": "还没有成员——让队长用 AgentCreate 添加一个。",+ "running": "运行中",+ "idle": "空闲",+ "missingSession": "(无会话)"}}diff --git a/examples/web_ui/frontend/src/index.css b/examples/web_ui/frontend/src/index.cssindex 76003e9ad..5e9595773 100644--- a/examples/web_ui/frontend/src/index.css+++ b/examples/web_ui/frontend/src/index.css@@ -30,7 +30,7 @@ body,--heading: system-ui, 'Segoe UI', Roboto, sans-serif;--mono: ui-monospace, Consolas, monospace;- font: 18px/145% var(--sans);+ /*font: 18px/145% var(--sans);*/letter-spacing: 0.18px;color-scheme: light dark;color: var(--text);@@ -124,66 +124,6 @@ body,}}-#root {- width: 100%;- max-width: 100%;- margin: 0 auto;- text-align: left;- border-inline: 1px solid var(--border);- min-height: 100svh;- display: flex;- flex-direction: column;- box-sizing: border-box;-}--body {- margin: 0;-}--h1,-h2 {- font-family: var(--heading);- font-weight: 500;- color: var(--text-h);-}--h1 {- font-size: 56px;- letter-spacing: -1.68px;- margin: 32px 0;- @media (max-width: 1024px) {- font-size: 36px;- margin: 20px 0;- }-}-h2 {- font-size: 24px;- line-height: 118%;- letter-spacing: -0.24px;- margin: 0 0 8px;- @media (max-width: 1024px) {- font-size: 16px;- }-}-p {- margin: 0;-}--/*code,*/-/*.counter {*/-/* font-family: var(--mono);*/-/* display: inline-flex;*/-/* border-radius: 4px;*/-/* color: var(--text-h);*/-/*}*/--/*code {*/-/* font-size: 15px;*/-/* line-height: 135%;*/-/* padding: 4px 8px;*/-/* background: var(--code-bg);*/-/*}*/-@theme inline {--font-heading: var(--font-sans);--font-sans: 'Geist Variable', sans-serif;diff --git a/examples/web_ui/frontend/src/pages/chat/ChatViewport.tsx b/examples/web_ui/frontend/src/pages/chat/ChatViewport.tsxnew file mode 100644index 000000000..af22962f8--- /dev/null+++ b/examples/web_ui/frontend/src/pages/chat/ChatViewport.tsx@@ -0,0 +1,396 @@+import type { TaskContext } from '@agentscope-ai/agentscope/state';+import { Toolbox } from 'lucide-react';+import { useCallback, useEffect, useMemo, useState } from 'react';++import type { ChatModelConfig } from '@/api';+import { sessionApi } from '@/api';+import { ChatContent } from '@/components/chat/ChatContent.tsx';+import { TaskPanel } from '@/components/chat/TaskPanel';+import { CreateCredentialDialog } from '@/components/dialog/CreateCredentialDialog';+import { WorkspaceDrawer } from '@/components/drawer/WorkspaceDrawer.tsx';+import { ModelParametersPopover } from '@/components/popover/ModelParametersPopover';+import { LlmSelect } from '@/components/select/LlmSelect';+import { PermissionModeSelect } from '@/components/select/PermissionModeSelect.tsx';+import { Button } from '@/components/ui/button';+import { useAvailableModels } from '@/hooks/useAvailableModels';+import { useMessages } from '@/hooks/useMessages';+import { useSessions } from '@/hooks/useSessions';+import { useWorkspace } from '@/hooks/useWorkspace.ts';++interface ChatViewportProps {+ /**+ * The agent that owns the session being viewed. May be the+ * user-facing leader agent or — when drilled into a team member+ * via the URL's `:memberId` slot — a worker agent.+ */+ agentId: string | null;+ /**+ * The session whose messages, model config, permission mode, and+ * workspace drive every control rendered here.+ */+ sessionId: string | null;+ /**+ * Optional hook invoked when a team membership change arrives on+ * this viewport's SSE stream. The outer page owns the session list+ * that backs the team sidebar, so it must be told to refetch too;+ * passing this callback wires that signal up.+ */+ onTeamUpdated?: () => void;+}++/**+ * The right-hand main panel of the chat page — every UI element that+ * operates on a single `(agentId, sessionId)` pair lives here:+ * model selector, permission mode select, message stream, workspace+ * drawer, and the team sidebar.+ *+ * Self-contained by design. The outer page passes in the+ * `(agentId, sessionId)` it wants displayed (which may be the leader+ * session or a focused team member's session) and this component+ * does the rest — fetching the session view, syncing local UI state+ * with it, and writing changes back to the same session. Switching+ * between leader and member is just a prop change; no internal+ * branching is needed.+ *+ * @param agentId - The agent to operate on. `null` while no agent is+ * selected yet (renders an empty / disabled state).+ * @param sessionId - The session to operate on. `null` while no+ * session is selected yet.+ * @returns The right-side main JSX of the chat page.+ */+export function ChatViewport({ agentId, sessionId, onTeamUpdated }: ChatViewportProps) {+ const { sessions, refetch: refetchSessions } = useSessions(agentId);+ const { groups } = useAvailableModels();++ // When the viewport agent differs from the outer page's selected+ // agent (i.e. user drilled into a team member), `refetchSessions`+ // only refreshes the member's session list. The team sidebar is+ // driven by the leader's session list owned by the outer page, so+ // we also fire the parent's refetch to keep that in sync.+ const handleTeamUpdated = useCallback(() => {+ refetchSessions();+ onTeamUpdated?.();+ }, [refetchSessions, onTeamUpdated]);++ const [selectedModel, setSelectedModel] = useState<ChatModelConfig | null>(null);+ const [selectedFallbackModel, setSelectedFallbackModel] = useState<ChatModelConfig | null>(+ null,+ );+ const [selectedPermissionMode, setSelectedPermissionMode] = useState<string>('default');+ const [credentialOpen, setCredentialOpen] = useState(false);+ const [credentialRefetchTrigger, setCredentialRefetchTrigger] = useState(0);+ const [tasksContext, setTasksContext] = useState<TaskContext | null>(null);++ const handleStateUpdated = useCallback((value: Record<string, unknown>) => {+ if (value.tasks_context) {+ setTasksContext(value.tasks_context as TaskContext);+ }+ // TODO: handle permission_context updates when permission UI is built+ }, []);++ const { msgs, streaming, send, onUserConfirm } = useMessages(agentId, sessionId, {+ onTeamUpdated: handleTeamUpdated,+ onStateUpdated: handleStateUpdated,+ });+ const {+ mcps,+ loading: mcpsLoading,+ addMcps,+ removeMcp,+ skills,+ skillsLoading,+ addSkill,+ removeSkill,+ } = useWorkspace(agentId, sessionId);++ const view = sessions.find((v) => v.session.id === sessionId) ?? null;++ // ChatViewport keeps its own `useSessions(agentId)` instance (the+ // outer page has a separate one). Its built-in fetch only fires on+ // `agentId` change, so when the outer page creates a new session+ // under the same agent, this list doesn't auto-refresh. Without+ // this refetch, `view` would stay `null` for the brand-new session+ // id and every effect below would early-return on `!view`,+ // leaving the model select and friends pinned to whatever the+ // previously-viewed session had configured.+ useEffect(() => {+ if (!sessionId) return;+ if (view) return;+ refetchSessions();+ }, [sessionId, view, refetchSessions]);++ // Reset local UI state when the target session changes. Otherwise+ // the model select (and disabled-state guards on `send`) would+ // show the previous session's model during the in-flight window+ // before `view` repopulates — and an immediate send would post to+ // a session whose backend config doesn't actually have that model.+ useEffect(() => {+ setSelectedModel(null);+ setSelectedFallbackModel(null);+ }, [sessionId]);++ const selectedModelCard = useMemo(() => {+ if (!selectedModel) return null;+ const items = groups[selectedModel.type];+ if (!items) return null;+ for (const { models } of items) {+ const card = models.find((m) => m.name === selectedModel.model);+ if (card) return card;+ }+ return null;+ }, [groups, selectedModel?.type, selectedModel?.model]);++ /**+ * Pick the first model the available-models endpoint surfaces, used+ * as a sensible default when the current session has no model+ * configured yet.+ *+ * @returns The first available `ChatModelConfig`, or `null` when+ * no credentials / models are configured.+ */+ const getFirstAvailableModel = (): ChatModelConfig | null => {+ const firstType = Object.keys(groups)[0];+ if (!firstType) return null;+ const items = groups[firstType];+ if (!items || items.length === 0) return null;+ const firstItem = items[0];+ const firstModel = (firstItem.models as { name?: string; id?: string }[])[0];+ if (!firstModel) return null;+ const modelName = firstModel.name ?? firstModel.id ?? null;+ if (!modelName) return null;+ return {+ type: firstType,+ credential_id: firstItem.credential.id,+ model: modelName,+ parameters: {},+ };+ };++ // Sync tasksContext from the session snapshot. Real-time updates+ // arrive via the CustomEvent(name="state_updated") → the+ // onStateUpdated callback above. We always mirror the snapshot+ // (including clearing to null when the session is gone or has no+ // tasks yet) so that switching sessions doesn't leak stale tasks+ // from the previous one.+ useEffect(() => {+ if (!view) {+ setTasksContext(null);+ return;+ }+ const tc = (view.session.state as Record<string, unknown>)?.tasks_context as+ | TaskContext+ | undefined;+ setTasksContext(tc ?? null);+ }, [view]);++ // Sync selectedModel + selectedFallbackModel from the session+ // record. If the session has no model configured yet, auto-pick+ // the first available one and persist it back so subsequent+ // reasoning has a model to call.+ //+ // Important: skip while `view` is still loading. Otherwise the+ // in-flight window between "agentId changed" and "useSessions+ // returned the new list" looks like "session has no model" and+ // we would racily auto-select + persist the first available+ // model, clobbering whatever the user had configured.+ useEffect(() => {+ if (!view) return;+ const sessionModel = view.session.config.chat_model_config;++ if (sessionModel) {+ setSelectedModel(sessionModel);+ } else {+ const firstModel = getFirstAvailableModel();+ if (firstModel) {+ setSelectedModel(firstModel);+ if (sessionId && agentId) {+ sessionApi+ .update(sessionId, agentId, { chat_model_config: firstModel })+ .then(() => refetchSessions())+ .catch(() => {});+ }+ } else {+ setSelectedModel(null);+ }+ }++ setSelectedFallbackModel(view.session.config.fallback_chat_model_config ?? null);+ }, [view, groups, sessionId, agentId]);++ // Sync selectedPermissionMode when the session changes. Same+ // loading-window guard as above — don't reset the displayed mode+ // to "default" while the new session view is still on the wire.+ useEffect(() => {+ if (!view) return;+ const mode = (view.session.state?.permission_context as Record<string, unknown>)+ ?.mode as string;+ setSelectedPermissionMode(mode ?? 'default');+ }, [sessionId, view]);++ /**+ * Persist a model change to the session and refetch so the local+ * view picks up the new value.+ *+ * @param config - New chat model config; `null` is ignored+ * because the primary selector does not allow clearing.+ */+ const handleLlmChange = async (config: ChatModelConfig | null) => {+ if (!config || !sessionId || !agentId) return;+ setSelectedModel(config);+ await sessionApi.update(sessionId, agentId, { chat_model_config: config });+ await refetchSessions();+ };++ /**+ * Persist a parameter change on the currently selected model.+ *+ * @param parameters - New parameter map (model-provider specific).+ */+ const handleParametersChange = async (parameters: Record<string, unknown>) => {+ if (!selectedModel || !sessionId || !agentId) return;+ const updated = { ...selectedModel, parameters };+ setSelectedModel(updated);+ await sessionApi.update(sessionId, agentId, { chat_model_config: updated });+ await refetchSessions();+ };++ /**+ * Persist a fallback-model change. `null` clears the fallback.+ *+ * @param config - New fallback config or `null` to clear.+ */+ const handleFallbackChange = async (config: ChatModelConfig | null) => {+ if (!sessionId || !agentId) return;+ setSelectedFallbackModel(config);+ await sessionApi.update(sessionId, agentId, { fallback_chat_model_config: config });+ await refetchSessions();+ };++ /**+ * Persist a permission-mode change.+ *+ * @param mode - New permission mode (e.g. `default`, `explore`).+ */+ const handlePermissionModeChange = async (mode: string) => {+ setSelectedPermissionMode(mode);+ if (!sessionId || !agentId) return;+ await sessionApi.update(sessionId, agentId, { permission_mode: mode });+ await refetchSessions();+ };++ return (+ <>+ <main className="flex size-full">+ <div className="flex flex-col flex-1 min-h-0 p-2">+ <div className="flex flex-row gap-x-2 justify-between">+ <div id="tour-llm-select" className="flex flex-row items-center gap-x-1">+ <LlmSelect+ value={selectedModel}+ onChange={handleLlmChange}+ onAddCredential={() => setCredentialOpen(true)}+ refetchTrigger={credentialRefetchTrigger}+ />+ <ModelParametersPopover+ selectedModel={selectedModel}+ modelCard={selectedModelCard}+ onChange={handleParametersChange}+ selectedFallbackModel={selectedFallbackModel}+ onFallbackChange={handleFallbackChange}+ />+ </div>+ <div id="tour-permission-mode" className="flex flex-row gap-x-2">+ <PermissionModeSelect+ value={selectedPermissionMode}+ disabled={!sessionId}+ onChange={handlePermissionModeChange}+ />+ </div>+ </div>+ <div className="flex flex-1 justify-center min-h-0 overflow-hidden relative [--chat-content-w:36rem]">+ <TaskPanel+ className="absolute left-0 top-0 h-full max-w-[calc(50%-var(--chat-content-w)/2)]"+ tasksContext={tasksContext}+ />+ <ChatContent+ className={'max-w-[var(--chat-content-w)] w-full'}+ msgs={msgs}+ sending={streaming}+ disabled={selectedModel === null}+ onSend={send}+ onUserConfirm={onUserConfirm}+ allowedInputTypes={(selectedModelCard?.input_types ?? []).filter(+ (t) =>+ /^(image|video|audio|text)\/.+/.test(t) ||+ t === 'application/pdf' ||+ t.startsWith('application/vnd.') ||+ t.startsWith('application/msword') ||+ t.startsWith('application/vnd.openxmlformats'),+ )}+ fileProcessor={async (file) => {+ const filePath = (file as File & { path?: string }).path;+ if (filePath) {+ return {+ id: crypto.randomUUID(),+ type: 'data' as const,+ source: {+ type: 'url' as const,+ url: `file://${filePath}`,+ media_type: file.type || 'application/octet-stream',+ },+ name: file.name,+ };+ }+ if (file.type === 'text/plain') {+ const text = await file.text();+ return {+ id: crypto.randomUUID(),+ type: 'text' as const,+ text: `[File: ${file.name}]\n${text}`,+ };+ }+ const buffer = await file.arrayBuffer();+ const bytes = new Uint8Array(buffer);+ let binary = '';+ for (let i = 0; i < bytes.byteLength; i++) {+ binary += String.fromCharCode(bytes[i]);+ }+ const base64 = btoa(binary);+ return {+ id: crypto.randomUUID(),+ type: 'data' as const,+ source: {+ type: 'base64' as const,+ media_type: file.type || 'application/octet-stream',+ data: base64,+ },+ name: file.name,+ };+ }}+ />+ </div>+ </div>+ <div className="flex flex-col h-full gap-2 p-2">+ <WorkspaceDrawer+ mcps={mcps}+ loading={mcpsLoading}+ onAdd={addMcps}+ onRemove={removeMcp}+ skills={skills}+ skillsLoading={skillsLoading}+ onAddSkill={addSkill}+ onRemoveSkill={removeSkill}+ >+ <Button size="icon-sm" variant="ghost">+ <Toolbox />+ </Button>+ </WorkspaceDrawer>+ </div>+ </main>+ <CreateCredentialDialog+ open={credentialOpen}+ onOpenChange={setCredentialOpen}+ onCreated={() => setCredentialRefetchTrigger((n) => n + 1)}+ />+ </>+ );+}diff --git a/examples/web_ui/frontend/src/pages/chat/index.tsx b/examples/web_ui/frontend/src/pages/chat/index.tsxindex c386394b3..cfa6cbe5b 100644--- a/examples/web_ui/frontend/src/pages/chat/index.tsx+++ b/examples/web_ui/frontend/src/pages/chat/index.tsx@@ -1,29 +1,23 @@import {+ BotMessageSquare,+ CalendarClock,Ellipsis,MessageSquareDashed,- PanelLeft,- PanelLeftClose,Pencil,Plus,Settings2,- Toolbox,Trash2,} from 'lucide-react';-import { useState, useEffect, useMemo } from 'react';-import { useParams } from 'react-router-dom';+import { useEffect, useState } from 'react';+import { useNavigate, useParams } from 'react-router-dom';-import type { ChatModelConfig } from '@/api';+import { ChatViewport } from './ChatViewport';import type { SessionRecord } from '@/api';-import { ChatContent } from '@/components/chat/ChatContent.tsx';import { AgentDialog } from '@/components/dialog/AgentDialog';-import { CreateCredentialDialog } from '@/components/dialog/CreateCredentialDialog';-import { DeleteAgentDialog } from '@/components/dialog/DeleteAgentDialog';+import { DeleteDialog } from '@/components/dialog/DeleteDialog';import { EditAgentDialog } from '@/components/dialog/EditAgentDialog';import { RenameSessionDialog } from '@/components/dialog/RenameSessionDialog';-import { WorkspaceDrawer } from '@/components/drawer/WorkspaceDrawer.tsx';-import { ModelParametersPopover } from '@/components/popover/ModelParametersPopover';-import { LlmSelect } from '@/components/select/LlmSelect';-import { PermissionModeSelect } from '@/components/select/PermissionModeSelect.tsx';+import { TeamSidebar } from '@/components/team/TeamSidebar';import { ChatTourController } from '@/components/tour/ChatTourController';import { Button } from '@/components/ui/button';import {@@ -61,211 +55,140 @@ import {SidebarMenuButton,SidebarMenuItem,} from '@/components/ui/sidebar';-import { ChatProvider, useChatContext } from '@/context/ChatContext';import { useAgents } from '@/hooks/useAgents';-import { useAvailableModels } from '@/hooks/useAvailableModels';-import { useMessages } from '@/hooks/useMessages';import { useSessions } from '@/hooks/useSessions';-import { useWorkspace } from '@/hooks/useWorkspace.ts';import { useTranslation } from '@/i18n/useI18n.ts';+/**+ * The chat page's outer shell. Responsibilities split cleanly:+ *+ * - **This component** owns *which* `(agent, session)` is being+ * viewed. The URL is the single source of truth: every selection+ * (agent dropdown, session row, team member, new session) is a+ * ``navigate(...)`` call. State is derived from ``useParams``,+ * never duplicated in React state. Renders the main left sidebar+ * (agent picker + session list + create/rename/delete actions) and+ * computes the ``effective`` ids to feed the chat viewport.+ * - **`ChatViewport`** owns *what* to render for that pair: messages,+ * model selector, permission mode, workspace drawer, team sidebar.+ *+ * Splitting along this seam means switching between the leader's+ * session and a focused team member is just a prop change for the+ * viewport — the leader's session list stays anchored in this outer+ * sidebar. Driving everything off URL also gets us browser back /+ * forward, shareable links, and refresh-preserving state for free.+ *+ * @returns The chat page JSX.+ */const ChatPageInner = () => {- const { selectedAgentId, setSelectedAgentId, selectedSessionId, setSelectedSessionId } =- useChatContext();- const { agentId: urlAgentId, sessionId: urlSessionId } = useParams<{+ const navigate = useNavigate();+ const {+ agentId: urlAgentId,+ sessionId: urlSessionId,+ memberId: urlMemberId,+ } = useParams<{agentId?: string;sessionId?: string;+ memberId?: string;}>();const { t } = useTranslation();- const { agents, refetch: refetchAgents } = useAgents();+ const { agents, refetch: refetchAgents, remove: removeAgent } = useAgents();const {sessions,+ refetch: refetchSessions,create: createSession,update: updateSession,remove: removeSession,- } = useSessions(selectedAgentId);-- // Fetch available model list, used to auto-select the first model when none is specified- const { groups } = useAvailableModels();+ } = useSessions(urlAgentId ?? null);const [sidebarOpen, setSidebarOpen] = useState(true);- const [selectedModel, setSelectedModel] = useState<ChatModelConfig | null>(null);- // Fallback model used when the primary model fails. `null` means none.- // Unlike the primary model, we never auto-select a fallback — the user- // must opt in explicitly.- const [selectedFallbackModel, setSelectedFallbackModel] = useState<ChatModelConfig | null>(- null,- );- const [selectedPermissionMode, setSelectedPermissionMode] = useState<string>('default');const [editOpen, setEditOpen] = useState(false);const [deleteOpen, setDeleteOpen] = useState(false);- const [credentialOpen, setCredentialOpen] = useState(false);- const [credentialRefetchTrigger, setCredentialRefetchTrigger] = useState(0);const [renameOpen, setRenameOpen] = useState(false);const [renameSession, setRenameSession] = useState<SessionRecord | null>(null);+ const [deleteSessionOpen, setDeleteSessionOpen] = useState(false);+ const [sessionToDelete, setSessionToDelete] = useState<SessionRecord | null>(null);- const { msgs, streaming, send, onUserConfirm } = useMessages(- selectedAgentId,- selectedSessionId,- );- const {- mcps,- loading: mcpsLoading,- addMcps,- removeMcp,- skills,- skillsLoading,- addSkill,- removeSkill,- } = useWorkspace(selectedAgentId, selectedSessionId);-- const selectedAgent = agents.find((a) => a.id === selectedAgentId) ?? null;-- const selectedModelCard = useMemo(() => {- if (!selectedModel) return null;- const items = groups[selectedModel.type];- if (!items) return null;- for (const { models } of items) {- const card = models.find((m) => m.name === selectedModel.model);- if (card) return card;- }- return null;- }, [groups, selectedModel?.type, selectedModel?.model]);-- // Auto-select agent on load — prefer URL param, fallback to first agent- useEffect(() => {- if (!selectedAgentId && agents.length > 0) {- const target = urlAgentId && agents.find((a) => a.id === urlAgentId);- setSelectedAgentId(target ? target.id : agents[0].id);- }- }, [agents, selectedAgentId, setSelectedAgentId, urlAgentId]);-- // Keep selectedSessionId in sync when sessions list changes — prefer URL param- useEffect(() => {- if (sessions.length === 0) {- setSelectedSessionId(null);- } else if (!sessions.find((s) => s.id === selectedSessionId)) {- const target = urlSessionId && sessions.find((s) => s.id === urlSessionId);- setSelectedSessionId(target ? target.id : sessions[0].id);- }- }, [sessions]);-- // Extract the first available model from groups, used as the fallback default selection.- // groups shape: { [type]: { credential, models[] }[] }- const getFirstAvailableModel = (): ChatModelConfig | null => {- const firstType = Object.keys(groups)[0];- if (!firstType) return null;-- const items = groups[firstType];- if (!items || items.length === 0) return null;-- const firstItem = items[0];- const firstModel = (firstItem.models as { name?: string; id?: string }[])[0];- if (!firstModel) return null;+ 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');- const modelName = firstModel.name ?? firstModel.id ?? null;- if (!modelName) return null;+ // "Inner focus" — when the URL carries a third `:memberId` segment+ // the user is drilling into a team member's chat. The main sidebar+ // stays anchored on the outer (leader) session; only the chat+ // viewport follows this inner focus. When `urlMemberId` is+ // undefined or doesn't resolve to a known team member, the inner+ // focus collapses back to the outer (leader) session.+ const focusedMember = urlMemberId+ ? (currentView?.team?.members.find((m) => m.agent.id === urlMemberId) ?? null)+ : null;+ const effectiveAgentId =+ focusedMember && focusedMember.session_id ? focusedMember.agent.id : (urlAgentId ?? null);+ const effectiveSessionId =+ focusedMember && focusedMember.session_id+ ? focusedMember.session_id+ : (urlSessionId ?? null);- return {- type: firstType,- credential_id: firstItem.credential.id,- model: modelName,- parameters: {},- };- };-- // Sync selectedModel with the current session's chat_model_config.- // Re-runs when: the selected session changes, the sessions list changes,- // or the available models list finishes loading.+ // Redirect: URL is missing an agent → pick the first one and rewrite+ // the URL in-place (replace so we don't pollute history).useEffect(() => {- const session = sessions.find((s) => s.id === selectedSessionId);- const sessionModel = session?.config.chat_model_config ?? null;-- if (sessionModel) {- // Case 1: the current session already has a model configured — use it directly.- setSelectedModel(sessionModel);- } else {- // Case 2: no model configured on the current session (or no session selected).- // Try to auto-select the first available model to reduce manual work.- const firstModel = getFirstAvailableModel();- if (firstModel) {- // A model is available — set it as the current selection.- // Persistence notes:- // - If a session exists, persist the selection via updateSession below.- // - If no session exists yet, handleCreateSession will carry selectedModel on creation.- setSelectedModel(firstModel);-- // If there is an active session without a model, persist the auto-selected model to it.- if (selectedSessionId && selectedAgentId) {- updateSession(selectedSessionId, { chat_model_config: firstModel });- }- } else {- // Case 3: no model configured and no credentials added yet — clear the selection.- setSelectedModel(null);- }+ if (!urlAgentId && agents.length > 0) {+ navigate(`/chat/${agents[0].id}`, { replace: true });}+ }, [agents, urlAgentId, navigate]);- // Fallback is purely opt-in: mirror what's persisted, never auto-select.- setSelectedFallbackModel(session?.config.fallback_chat_model_config ?? null);- }, [selectedSessionId, sessions, groups]);-- // Sync selectedPermissionMode when switching sessions.+ // Redirect: URL has an agent but no session, or its sessionId no+ // longer exists for this agent → pick the first available session.useEffect(() => {- const session = sessions.find((s) => s.id === selectedSessionId);- const mode = (session?.state?.permission_context as Record<string, unknown>)- ?.mode as string;- setSelectedPermissionMode(mode ?? 'default');- }, [selectedSessionId]);-- // Primary selector does not enable `allowClear`, so `config` is always- // non-null in practice; the union below just satisfies the shared- // `LlmSelect` callback signature.- const handleLlmChange = async (config: ChatModelConfig | null) => {- if (!config) return;- setSelectedModel(config);- if (selectedSessionId && selectedAgentId) {- await updateSession(selectedSessionId, { chat_model_config: config });- }- };-- const handleParametersChange = async (parameters: Record<string, unknown>) => {- if (!selectedModel) return;- const updated = { ...selectedModel, parameters };- setSelectedModel(updated);- if (selectedSessionId && selectedAgentId) {- await updateSession(selectedSessionId, { chat_model_config: updated });- }- };-- // Fallback selector emits `null` when the user clears the selection.- // Persist the change to the active session if one exists.- const handleFallbackChange = async (config: ChatModelConfig | null) => {- setSelectedFallbackModel(config);- if (selectedSessionId && selectedAgentId) {- await updateSession(selectedSessionId, {- fallback_chat_model_config: config,- });- }- };+ if (!urlAgentId || sessions.length === 0) return;+ const matches = urlSessionId && sessions.some((v) => v.session.id === urlSessionId);+ if (matches) return;+ navigate(`/chat/${urlAgentId}/${sessions[0].session.id}`, { replace: true });+ }, [urlAgentId, urlSessionId, sessions, navigate]);+ /**+ * Create a new session under the currently selected agent and+ * pre-fill it with the model + fallback the currently open session+ * is using (so "new chat" inherits whatever the user just had+ * configured). Falls back to any other session under this agent+ * when there is no current one — keeps the model choice sticky+ * across "delete last → create new" instead of dropping back to+ * whatever ChatViewport's auto-pick happens to land on. Navigates+ * to the freshly created session.+ */const handleCreateSession = async () => {- if (!selectedAgentId) return;+ if (!urlAgentId) return;+ const seedConfig = currentView?.session.config ?? sessions[0]?.session.config;const res = await createSession({- agent_id: selectedAgentId,- ...(selectedModel ? { chat_model_config: selectedModel } : {}),- ...(selectedFallbackModel ? { fallback_chat_model_config: selectedFallbackModel } : {}),+ agent_id: urlAgentId,+ ...(seedConfig?.chat_model_config+ ? { chat_model_config: seedConfig.chat_model_config }+ : {}),+ ...(seedConfig?.fallback_chat_model_config+ ? { fallback_chat_model_config: seedConfig.fallback_chat_model_config }+ : {}),});- setSelectedSessionId(res.session_id);+ navigate(`/chat/${urlAgentId}/${res.session_id}`);};const handleAgentDeleted = async () => {- setSelectedAgentId(null);- setSelectedSessionId(null);+ navigate('/chat', { replace: true });await refetchAgents();};const handleDeleteSession = async (sessionId: string) => {await removeSession(sessionId);+ // If we just removed the session the URL is pointing at, fall+ // back to the parent /chat/:agentId path; the redirect effect+ // will then pick the next available session.+ if (sessionId === urlSessionId && urlAgentId) {+ navigate(`/chat/${urlAgentId}`, { replace: true });+ }+ };++ const requestDeleteSession = (session: SessionRecord) => {+ setSessionToDelete(session);+ setDeleteSessionOpen(true);};const handleRenameConfirm = async (name: string) => {@@ -276,7 +199,7 @@ const ChatPageInner = () => {return (<div className="flex h-full w-full">{sidebarOpen && (- <Sidebar collapsible="none" className="w-80">+ <Sidebar collapsible="none" className="border-r"><SidebarHeader><div className="flex flex-col gap-y-2"><span className="text-muted-foreground text-xs">@@ -284,8 +207,8 @@ const ChatPageInner = () => {</span><div className="flex flex-row gap-x-2 items-center"><Select- value={selectedAgentId ?? ''}- onValueChange={setSelectedAgentId}+ value={urlAgentId ?? ''}+ onValueChange={(id) => navigate(`/chat/${id}`)}><SelectTrigger className="w-full" size="sm"><SelectValue@@ -314,17 +237,17 @@ const ChatPageInner = () => {</SelectContent></Select><Button- size="icon-sm"+ size="icon"variant="ghost"- disabled={!selectedAgentId}+ disabled={!urlAgentId}onClick={() => setEditOpen(true)}><Settings2 /></Button><Button- size="icon-sm"+ size="icon"variant="ghost"- disabled={!selectedAgentId}+ disabled={!urlAgentId}onClick={() => setDeleteOpen(true)}><Trash2 className="text-destructive" />@@ -334,17 +257,6 @@ const ChatPageInner = () => {</div></SidebarHeader><SidebarContent className="my-5">- {/*<SidebarGroup>*/}- {/* <SidebarGroupContent>*/}- {/* <Tabs defaultValue="mcp" onValueChange={() => {}}>*/}- {/* <TabsList className={'w-full'}>*/}- {/* <TabsTrigger value={'mcp'}>会话</TabsTrigger>*/}- {/* <TabsTrigger value={'skill'}>定时任务</TabsTrigger>*/}- {/* </TabsList>*/}- {/* <TabsContent value={'mcp'} asChild></TabsContent>*/}- {/* </Tabs>*/}- {/* </SidebarGroupContent>*/}- {/*</SidebarGroup>*/}<SidebarGroup><SidebarGroupLabel>{t('chat.session.label')}</SidebarGroupLabel><SidebarGroupAction>@@ -352,7 +264,7 @@ const ChatPageInner = () => {id="tour-create-session"size="icon-xs"variant="default"- disabled={!selectedAgentId}+ disabled={!urlAgentId}onClick={handleCreateSession}><Plus />@@ -367,7 +279,7 @@ const ChatPageInner = () => {</EmptyMedia><EmptyTitle>{t('chat.session.emptyTitle')}</EmptyTitle><EmptyDescription>- {selectedAgentId+ {urlAgentId? t('chat.session.emptyHasAgent'): t('chat.session.emptyNoAgent')}</EmptyDescription>@@ -376,7 +288,7 @@ const ChatPageInner = () => {<Buttonvariant="outline"size="sm"- disabled={!selectedAgentId}+ disabled={!urlAgentId}onClick={handleCreateSession}>Create Session@@ -385,48 +297,63 @@ const ChatPageInner = () => {</Empty>) : (<SidebarMenu>- {sessions.map((session) => (- <SidebarMenuItem key={session.id}>- <SidebarMenuButton- isActive={selectedSessionId === session.id}- onClick={() => setSelectedSessionId(session.id)}- >- <span className="truncate">- {session.config.name || session.id}- </span>- </SidebarMenuButton>- <SidebarMenuAction showOnHover>- <DropdownMenu>- <DropdownMenuTrigger asChild>- <Ellipsis />- </DropdownMenuTrigger>- <DropdownMenuContent- side="right"- align="start"- >- <DropdownMenuItem- onClick={() => {- setRenameSession(session);- setRenameOpen(true);- }}- >- <Pencil />- {t('session-menu.rename')}- </DropdownMenuItem>- <DropdownMenuItem- variant="destructive"- onClick={() =>- handleDeleteSession(session.id)- }+ {sessions.map((view) => {+ const session = view.session;+ return (+ <SidebarMenuItem key={session.id}>+ <SidebarMenuButton+ isActive={urlSessionId === session.id}+ onClick={() =>+ navigate(+ `/chat/${urlAgentId}/${session.id}`,+ )+ }+ >+ {hasScheduleSessions &&+ (session.source === 'schedule' ? (+ <CalendarClock />+ ) : (+ <BotMessageSquare />+ ))}+ <span className="truncate">+ {session.config.name || session.id}+ </span>+ </SidebarMenuButton>+ <SidebarMenuAction showOnHover>+ <DropdownMenu>+ <DropdownMenuTrigger asChild>+ <Ellipsis />+ </DropdownMenuTrigger>+ <DropdownMenuContent+ side="right"+ align="start">- <Trash2 />- {t('session-menu.delete')}- </DropdownMenuItem>- </DropdownMenuContent>- </DropdownMenu>- </SidebarMenuAction>- </SidebarMenuItem>- ))}+ <DropdownMenuItem+ onClick={() => {+ setRenameSession(session);+ setRenameOpen(true);+ }}+ >+ <Pencil />+ {t('session-menu.rename')}+ </DropdownMenuItem>+ <DropdownMenuItem+ variant="destructive"+ onClick={() =>+ requestDeleteSession(+ session,+ )+ }+ >+ <Trash2 />+ {t('session-menu.delete')}+ </DropdownMenuItem>+ </DropdownMenuContent>+ </DropdownMenu>+ </SidebarMenuAction>+ </SidebarMenuItem>+ );+ })}</SidebarMenu>)}</SidebarGroupContent>@@ -435,140 +362,24 @@ const ChatPageInner = () => {<SidebarFooter /></Sidebar>)}- <main className="flex size-full pt-2">- <Button- variant="ghost"- size="icon-sm"- onClick={() => setSidebarOpen((prev) => !prev)}- className="ml-2 mr-4"- >- {sidebarOpen ? (- <PanelLeftClose className="size-4" />- ) : (- <PanelLeft className="size-4" />- )}- </Button>- <div className="flex flex-col flex-1 min-h-0">- <div className="flex flex-row gap-x-2 justify-between">- <div id="tour-llm-select" className="flex flex-row items-center gap-x-1">- <LlmSelect- value={selectedModel}- onChange={handleLlmChange}- onAddCredential={() => setCredentialOpen(true)}- refetchTrigger={credentialRefetchTrigger}- />- {/*- * Combined settings dropdown: fallback model + parameter- * editing for the primary model. Disabled until a primary- * model is selected.- */}- <ModelParametersPopover- selectedModel={selectedModel}- modelCard={selectedModelCard}- onChange={handleParametersChange}- selectedFallbackModel={selectedFallbackModel}- onFallbackChange={handleFallbackChange}- />- </div>- <div id="tour-permission-mode" className="flex flex-row gap-x-2">- <PermissionModeSelect- value={selectedPermissionMode}- disabled={!selectedSessionId}- onChange={(mode) => {- setSelectedPermissionMode(mode);- if (selectedSessionId) {- updateSession(selectedSessionId, { permission_mode: mode });- }- }}- />- </div>- </div>- <div className="flex flex-1 justify-center min-h-0 overflow-hidden">- <ChatContent- className={'max-w-xl'}- msgs={msgs}- sending={streaming}- disabled={selectedModel === null}- onSend={send}- onUserConfirm={onUserConfirm}- allowedInputTypes={(selectedModelCard?.input_types ?? []).filter(- (t) =>- /^(image|video|audio|text)\/.+/.test(t) ||- t === 'application/pdf' ||- t.startsWith('application/vnd.') ||- t.startsWith('application/msword') ||- t.startsWith('application/vnd.openxmlformats'),- )}- fileProcessor={async (file) => {- const filePath = (file as File & { path?: string }).path;-- // ── Electron environment: have real local path ──- if (filePath) {- return {- id: crypto.randomUUID(),- type: 'data' as const,- source: {- type: 'url' as const,- url: `file://${filePath}`,- media_type: file.type || 'application/octet-stream',- },- name: file.name,- };- }-- // ── Browser environment: only File object in memory ──- // text/plain → read as text, wrap in TextBlock- if (file.type === 'text/plain') {- const text = await file.text();- // TODO: handle oversized text files — e.g. truncate, split into- // chunks, or warn the user when text.length exceeds the model's- // context window limit.- return {- id: crypto.randomUUID(),- type: 'text' as const,- text: `[File: ${file.name}]\n${text}`,- };- }-- // image/audio/video → read as base64, wrap in DataBlock- const buffer = await file.arrayBuffer();- const bytes = new Uint8Array(buffer);- let binary = '';- for (let i = 0; i < bytes.byteLength; i++) {- binary += String.fromCharCode(bytes[i]);- }- const base64 = btoa(binary);- return {- id: crypto.randomUUID(),- type: 'data' as const,- source: {- type: 'base64' as const,- media_type: file.type || 'application/octet-stream',- data: base64,- },- name: file.name,- };- }}- />- </div>- </div>- <div className="flex h-full px-2">- <WorkspaceDrawer- mcps={mcps}- loading={mcpsLoading}- onAdd={addMcps}- onRemove={removeMcp}- skills={skills}- skillsLoading={skillsLoading}- onAddSkill={addSkill}- onRemoveSkill={removeSkill}- >- <Button size="icon-sm" variant="ghost">- <Toolbox />- </Button>- </WorkspaceDrawer>- </div>- </main>+ {/*+ * Team sidebar lives at the outer page level (not inside+ * ChatViewport) so navigating between leader and member+ * sessions does NOT unmount it. The team data comes from+ * the leader's session view, which is stable across that+ * navigation; only `currentSessionId` changes to drive+ * row highlighting.+ */}+ {currentView?.team && effectiveSessionId && (+ <TeamSidebar team={currentView.team} currentSessionId={effectiveSessionId} />+ )}+ <div className="flex flex-1 min-w-0">+ <ChatViewport+ agentId={effectiveAgentId}+ sessionId={effectiveSessionId}+ onTeamUpdated={refetchSessions}+ />+ </div>{selectedAgent && (<><EditAgentDialog@@ -577,25 +388,43 @@ const ChatPageInner = () => {agent={selectedAgent}onUpdated={refetchAgents}/>- <DeleteAgentDialog+ <DeleteDialogopen={deleteOpen}onOpenChange={setDeleteOpen}- agent={selectedAgent}- onDeleted={handleAgentDeleted}+ title={t('common.deleteTitle', {+ entity: t('dialog-agent-delete.entity'),+ name: selectedAgent.data.name,+ })}+ description={t('common.deleteDescription')}+ confirmLabel={t('dialog-agent-delete.confirm')}+ onConfirm={async () => {+ await removeAgent(selectedAgent.id);+ await handleAgentDeleted();+ }}/></>)}- <CreateCredentialDialog- open={credentialOpen}- onOpenChange={setCredentialOpen}- onCreated={() => setCredentialRefetchTrigger((n) => n + 1)}- /><RenameSessionDialogopen={renameOpen}onOpenChange={setRenameOpen}currentName={renameSession?.config.name ?? renameSession?.id ?? ''}onConfirm={handleRenameConfirm}/>+ <DeleteDialog+ open={deleteSessionOpen}+ onOpenChange={setDeleteSessionOpen}+ title={t('common.deleteTitle', {+ entity: t('dialog-session-delete.entity'),+ name: sessionToDelete?.config.name || sessionToDelete?.id || '',+ })}+ description={t('common.deleteDescription')}+ confirmLabel={t('dialog-session-delete.confirm')}+ onConfirm={async () => {+ if (sessionToDelete) {+ await handleDeleteSession(sessionToDelete.id);+ }+ }}+ /><ChatTourControlleragentsCount={agents.length}sessionsCount={sessions.length}@@ -605,8 +434,4 @@ const ChatPageInner = () => {);};-export const ChatPage = () => (- <ChatProvider>- <ChatPageInner />- </ChatProvider>-);+export const ChatPage = () => <ChatPageInner />;diff --git a/examples/web_ui/frontend/src/pages/credential/index.tsx b/examples/web_ui/frontend/src/pages/credential/index.tsxindex 007727704..e951d3a45 100644--- a/examples/web_ui/frontend/src/pages/credential/index.tsx+++ b/examples/web_ui/frontend/src/pages/credential/index.tsx@@ -382,12 +382,13 @@ export const CredentialPage = () => {<DeleteDialogopen={deleteOpen}onOpenChange={setDeleteOpen}- title={t('credential.deleteTitle', {+ title={t('common.deleteTitle', {+ entity: t('credential.deleteEntity'),name:(selectedCredential.data.name as string | undefined) ??selectedCredential.id,})}- description={t('credential.deleteDescription')}+ description={t('common.deleteDescription')}onConfirm={handleDelete}/></>diff --git a/examples/web_ui/frontend/src/pages/schedule/create-schedule-dialog.tsx b/examples/web_ui/frontend/src/pages/schedule/create-schedule-dialog.tsxindex a14d503eb..679a224a7 100644--- a/examples/web_ui/frontend/src/pages/schedule/create-schedule-dialog.tsx+++ b/examples/web_ui/frontend/src/pages/schedule/create-schedule-dialog.tsx@@ -1,5 +1,5 @@import { format } from 'date-fns';-import { ChevronDownIcon } from 'lucide-react';+import { ChevronDownIcon, CircleAlert, Loader2, PlusCircle } from 'lucide-react';import * as React from 'react';import type { ChatModelConfig, PermissionMode } from '@/api';@@ -181,7 +181,7 @@ export function CreateScheduleDialog({ open, onOpenChange, onCreated }: Props) {return (<Dialog open={open} onOpenChange={onOpenChange}>- <DialogContent className="w-[560px] max-w-[560px]">+ <DialogContent className="!w-[500px] !max-w-[500px]"><DialogHeader><DialogTitle>{t('schedule.createSchedule.title')}</DialogTitle><DialogDescription className="tracking-tight">@@ -329,11 +329,17 @@ export function CreateScheduleDialog({ open, onOpenChange, onCreated }: Props) {</div><DialogFooter>- <Button size="sm" variant="outline" onClick={() => onOpenChange(false)}>+ <Button variant="ghost" onClick={() => onOpenChange(false)} disabled={loading}>+ <CircleAlert className="size-3.5" />{t('common.cancel')}</Button>- <Button size="sm" onClick={handleSubmit} disabled={loading || !isValid}>- {t('common.create')}+ <Button onClick={handleSubmit} disabled={loading || !isValid}>+ {loading ? (+ <Loader2 className="size-3.5 animate-spin" />+ ) : (+ <PlusCircle className="size-3.5" />+ )}+ {loading ? t('common.creating') : t('common.create')}</Button></DialogFooter></DialogContent>diff --git a/examples/web_ui/frontend/src/pages/schedule/schedule-detail-drawer.tsx b/examples/web_ui/frontend/src/pages/schedule/schedule-detail-drawer.tsxindex 4313bb321..e102b185b 100644--- a/examples/web_ui/frontend/src/pages/schedule/schedule-detail-drawer.tsx+++ b/examples/web_ui/frontend/src/pages/schedule/schedule-detail-drawer.tsx@@ -208,8 +208,11 @@ export function ScheduleDetailDrawer({<DeleteDialogopen={openDeleteDialog}onOpenChange={setOpenDeleteDialog}- title={t('schedule.deleteSchedule.title')}- description={t('schedule.deleteSchedule.description')}+ title={t('common.deleteTitle', {+ entity: t('schedule.deleteSchedule.entity'),+ name: data.name,+ })}+ description={t('common.deleteDescription')}onConfirm={handleDelete}/></>diff --git a/examples/web_ui/frontend/src/utils/common.ts b/examples/web_ui/frontend/src/utils/common.tsindex aab8b8bf8..5ad509ae7 100644--- a/examples/web_ui/frontend/src/utils/common.ts+++ b/examples/web_ui/frontend/src/utils/common.ts@@ -90,7 +90,7 @@ export const formatTime = (seconds: number): string => {if (total < 3600) {const minutes = Math.floor(total / 60);const remaining = total % 60;- return remaining === 0 ? `${minutes}min` : `${minutes}min${remaining}s`;+ return remaining === 0 ? `${minutes}m` : `${minutes}m${remaining}s`;}return `${Math.floor(total / 3600)}h`;};diff --git a/examples/web_ui/package.json b/examples/web_ui/package.jsonindex 607a4e714..734284126 100644--- a/examples/web_ui/package.json+++ b/examples/web_ui/package.json@@ -1,5 +1,5 @@{- "name": "new-studio",+ "name": "agentscope-web-ui","version": "1.0.0","private": true,"scripts": {diff --git a/examples/web_ui/pnpm-lock.yaml b/examples/web_ui/pnpm-lock.yamlindex 0408d9766..aa04b72a7 100644--- a/examples/web_ui/pnpm-lock.yaml+++ b/examples/web_ui/pnpm-lock.yaml@@ -58,8 +58,8 @@ importers:frontend:dependencies:'@agentscope-ai/agentscope':- specifier: ^0.0.6- version: 0.0.6+ specifier: ^0.0.8+ version: 0.0.8'@fontsource-variable/geist':specifier: ^5.2.8version: 5.2.8@@ -123,6 +123,9 @@ importers:react-router-dom:specifier: ^7.15.1+ rehype-raw:+ specifier: ^7.0.0+ version: 7.0.0remark-gfm:specifier: ^4.0.1version: 4.0.1@@ -199,8 +202,8 @@ importers:packages:- '@agentscope-ai/[email protected]':- resolution: {integrity: sha512-qQdcXK9GT6kkxsXKhpKg8MuEFjPJHci8NKXCqoCr3Fx/r2bHK7jzhkJblzXM+kmmrzC/4OXmjCWcvUbEP0pkgQ==}+ '@agentscope-ai/[email protected]':+ resolution: {integrity: sha512-Z0hcvCekvsbOxhEkgrT5+epMImfiUrt5cdeY8aGt73MWrSVxg0opErk6KrPVd1/WK+zPs5yIvhuaZ/sslJRFxQ==}'@babel/[email protected]':resolution: {integrity: sha512-9NhCeYjq9+3uxgdtp20LSiJXJvN0FeCtNGpJxuMFZ1Kv3cWUNb6DOhJwUvcVCzKGR66cw4njwM6hrJLqgOwbcw==}@@ -2139,6 +2142,11 @@ packages:engines: {node: '>=6.0.0'}hasBin: true+ resolution: {integrity: sha512-bA6+tcSLpz2tIEdDXZPpPTIuxBcC4+w6SieaYyfigIa4h8GlFxbA17v22Vx3JUtuZQj9SgOsnbK+aTBzyDyEuw==}+ engines: {node: '>=6.0.0'}+ hasBin: true+resolution: {integrity: sha512-Ceh+7ox5qe7LJuLHoY0feh3pHuUDHAcRUeyL2VYghZwfpkNIy/+8Ocg0a3UuSoYzavmylwuLWQOf3hl0jjMMIw==}engines: {node: '>=8'}@@ -2191,6 +2199,9 @@ packages:resolution: {integrity: sha512-hVLMUZFgR4JJ6ACt1uEESvQN1/dBVqPAKY0hgrV70eN3391K6juAfTjKZLKvOMsx8PxA7gsY1/tLMMTcfFLLpw==}+ resolution: {integrity: sha512-iwSsYWaCOoh26cV8NwNRViHlrfUvYsHDfRVcbtmw0Kg6PJIZZXwMkj1442FYLBGkeUf1juAsU3DTfxW579mrPA==}+resolution: {integrity: sha512-eyrF0jiFpY+3drT6383f1qhkbGsLSifNAjA61IUjZjmLCWjItY6LB9ft9YhoDgwfmclB2zhu51Lc7+95b8NRAg==}@@ -2480,6 +2491,10 @@ packages:resolution: {integrity: sha512-V0hjH4dGPh9Ao5p0MoRY6BVqtwCjhz6vI5LT8AJ55H+4g9/4vbHx1I54fS0XuclLhDHArPQCiMjDxjaL8fPxhw==}engines: {node: '>=0.12'}+ resolution: {integrity: sha512-aN97NXWF6AWBTahfVOIrB/NShkzi5H7F9r1s9mD3cDj4Ko5f2qhhVoYMibXF7GlLveb/D2ioWay8lxI97Ven3g==}+ engines: {node: '>=0.12'}+resolution: {integrity: sha512-+h1lkLKhZMTYjog1VEpJNG7NZJWcuc2DDk/qsqSTRRCOXiLjeQ1d1/udrUGhqMxUgAlwKNZ0cf2uqan5GLuS2A==}engines: {node: '>=6'}@@ -2870,12 +2885,27 @@ packages:resolution: {integrity: sha512-ej4AhfhfL2Q2zpMmLo7U1Uv9+PyhIZpgQLGT1F9miIGmiCJIoCgSmczFdrc97mWT4kVY72KA+WnnhJ5pghSvSg==}engines: {node: '>= 0.4'}+ resolution: {integrity: sha512-3kxEVkEKt0zvcZ3hCRYI8rqrgwtlIOFMWkbclACvjlDw8Li9S2hk/d51OI0nr/gIpdMHNepwgOKqZ/sy0Clpyg==}++ resolution: {integrity: sha512-wkQCkSYoOGCRKERFWcxMVMOcYE2K1AaNLU8DXS9arxnLOUEWbOXKXiJUNzEpqZ3JOKpnha3jkFrumEjVliDe7A==}++ resolution: {integrity: sha512-Y8/SBAHkZGoNkpzqqfCldijcuUKh7/su31kEBp67cFY09Wy0mTRgtsLYsiIxMJxlu0f6AA5SUTbDR8K0rxnbUw==}+resolution: {integrity: sha512-zl6s8LwNyo1P9uw+XJGvZtdFF1GdAkOg8ujOw+4Pyb76874fLps4ueHXDhXWdk6YHQ6OgUtinliG7RsYvCbbBg==}+ resolution: {integrity: sha512-MlWT6Pjt4CG9lFCjiz4BH7l9wmrMkfkJYCxFwKQic8+RTZgWPuWxwAfjJElsXkex7DJjfSJsQIt931ilUgmwdA==}+resolution: {integrity: sha512-88JUN06ipLwsnv+dVn+OIYOvAuvBMy/Qoi6O7mQHxdPXpjy+Cd6xRkWwux7DKO+4sYILtLBRIKgsdpS2gQc7qw==}+ resolution: {integrity: sha512-g7df9rMFX/SPi34tyGCyUBREQoKkapwdY/T04Qn9TDWfHhAYt4/I0gMVirzK5wEzeUqIjEB+LXC/ypb7Aqno5w==}+resolution: {integrity: sha512-1TJ6Fih/b8h5TIcv+1+Hw0PDQWJTKDKzFZzcKOiW1wJza3XoAQlkCuXLbymPYB8+ZQyw8mHvdw560e8zVFIWyA==}@@ -2895,6 +2925,9 @@ packages:resolution: {integrity: sha512-ol6UPyBWqsrO6EJySPz2O7ZSr856WDrEzM5zMqp+FJJLGMW35cLYmmZnl0vztAZxRUoNZJFTCohfjuIJ8I4QBQ==}+ resolution: {integrity: sha512-bEqo66MRXsUGxWHV5IP0PUiAWwoEjba4VCzg0LjFJBpchPaTfyfCKTG6bc5F8ucKec3q5y6qOdGyYTSBEvhCrg==}+resolution: {integrity: sha512-4FbRdAX+bSdmo4AUFuS0WNiPz8NgFt+r8ThgNWmlrjQjt1Q7ZR9+zTlce2859x4KSXrwIsaeTqDoKQmtP8pLmQ==}engines: {node: '>= 0.8'}@@ -3625,9 +3658,8 @@ packages:resolution: {integrity: sha512-smsWv2LzFjP03xmvFoJ331ss6h+jixfA4UUV/Bsiyuu4YJPfN+FIQGOIiv4w9/+MoHkfkJ22UIaQWRVFRfH6Vw==}engines: {node: '>=20'}- resolution: {integrity: sha512-O61LIsimY3acVabwvomwFhwrnN36yvHY2quIfy9keEcFytGgWeV35yLHQ6NVMLSBxRpHmcg2yuhCnlu2HT4pLQ==}- hasBin: true+ resolution: {integrity: sha512-IGWPopZq6Rjoynjfb3NSLf/z2MTw7UiOsm9TAjPGAjUESH7Uq41Trg4QWehBEn58p74i+m7uoRPV2vXcpPXhyA==}peerDependencies:ws: ^8.18.0zod: ^3.25 || ^4.0@@ -3671,6 +3703,9 @@ packages:resolution: {integrity: sha512-TXfryirbmq34y8QBwgqCVLi+8oA3oWx2eAnSn62ITyEhEYaWRlVZ2DvMM9eZbMs/RfxPu/PK/aBLyGj4IrqMHw==}engines: {node: '>=18'}+ resolution: {integrity: sha512-IInvU7fabl34qmi9gY8XOVxhYyMyuH2xUNpb2q8/Y+7552KlejkRvqvD19nMoUW/uQGGbqNpA6Tufu5FL5BZgw==}+resolution: {integrity: sha512-CiyeOxFT/JZyN5m0z9PfXw4SCBJ6Sygz1Dpl0wqjlhDEGGBP1GnsUVEL0p63hoG1fcj3fHynXi9NYO4nWOL+qQ==}engines: {node: '>= 0.8'}@@ -3901,6 +3936,9 @@ packages:resolution: {integrity: sha512-YTUo+Flmw4ZXiWfQKGcwwc11KnoRAYgzAE2E7mXKCjSviTKShtxBsN6YUUBB2gtaBzKzeKunxhUwNHQuRryhWA==}engines: {node: '>= 4'}+ resolution: {integrity: sha512-/aE8hCfKlQeA8LmyeyQvQF3eBiLRGNlfBJEvWH7ivp9sBqs7TNqBL5X3v157rM4IFETqDnIOO+z5M/biZbo9Ww==}+resolution: {integrity: sha512-1quofZ2RQ9EWdeN34S79+KExV1764+wCUGop5CPL1WGdD0ocPpu91lzPGbwWMECpEpd42kJGQwzRfyov9j4yNg==}@@ -3983,6 +4021,11 @@ packages:engines: {node: '>=10'}hasBin: true+ resolution: {integrity: sha512-rkVq3IXh+4FDGch+KwzX3aV9W3kO54GyEgpvBzSyctDA6Xtd7RJQV1xmXbeQp5v7+VzLOfVqiutSE6GICgPFvg==}+ engines: {node: '>=10'}+ hasBin: true+resolution: {integrity: sha512-VMbMxbDeehAxpOtWJXlcUS5E8iXh6QmN+BkRX1GARS3wRaXEEgzCcB10gTQazO42tpNIya8xIyNx8fll1OFPrg==}engines: {node: '>= 0.8.0'}@@ -4430,6 +4473,9 @@ packages:react: ^16.8 || ^17.0 || ^18.0 || ^19.0.0 || ^19.0.0-rcreact-dom: ^16.8 || ^17.0 || ^18.0 || ^19.0.0 || ^19.0.0-rc+ resolution: {integrity: sha512-5yXvWDEgqeiYiBe1lbxYF7UMAIm/IcopxMHrMQDq3nvKcjPKIhZklUKL+AE7J7uApI4kwe2snsK+eI6UTj9EHg==}+resolution: {integrity: sha512-QTHzsGd1EhbZs4AsQ20JX1rC3cOlt/IWJruk893DfLRr57lcnOeMaWG4K0JrRta4mIJZKth2Au3mM3u03/JWKw==}@@ -4488,6 +4534,9 @@ packages:resolution: {integrity: sha512-Dhxzh5HZuiHQhbvTW9AMetFfBHDMYpo23Uo9btPXgdYP+3T5S+p+jgNy7spra+veYhBP2dCSgxR/i2Y02h5/6w==}engines: {node: '>=0.10.0'}+ resolution: {integrity: sha512-bKr1DkiNa2krS7qxNtdrtHAmzuYGFQLiQ13TsorsdT6ULTkPLKuu5+GsFpDlg6JFjUTwX2DyhMPG2be8uPrqsQ==}+resolution: {integrity: sha512-d2JWLCivmZYTSIoge9MsgFCZrt571BikcWGYkjC1khllbTeDlGqZ2D8vD8E/lJa8WGWbb7Plm8/XJYV7IJHZZw==}engines: {node: '>= 8'}@@ -4586,7 +4635,7 @@ packages:snapshots:- '@agentscope-ai/[email protected]':+ '@agentscope-ai/[email protected]':dependencies:'@cfworker/json-schema': 4.1.1'@modelcontextprotocol/sdk': 1.29.0(@cfworker/[email protected])([email protected])@@ -4594,7 +4643,7 @@ snapshots:jsonrepair: 3.14.0mime-types: 3.0.2ollama: 0.6.3- openai: 6.39.0([email protected])+ openai: 6.41.0([email protected])string-format: 2.0.0uuid: 13.0.2zod: 4.4.3@@ -6507,6 +6556,8 @@ snapshots:+ [email protected]: {}+@@ -6578,6 +6629,8 @@ snapshots:+ [email protected]: {}+@@ -6813,6 +6866,8 @@ snapshots:+ [email protected]: {}+@@ -7271,6 +7326,37 @@ snapshots:dependencies:function-bind: 1.1.2+ dependencies:+ '@types/hast': 3.0.4+ '@types/unist': 3.0.3+ devlop: 1.1.0+ hastscript: 9.0.1+ property-information: 7.1.0+ vfile: 6.0.3+ vfile-location: 5.0.3+ web-namespaces: 2.0.1++ dependencies:+ '@types/hast': 3.0.4++ dependencies:+ '@types/hast': 3.0.4+ '@types/unist': 3.0.3+ '@ungap/structured-clone': 1.3.1+ hast-util-from-parse5: 8.0.3+ hast-util-to-parse5: 8.0.1+ html-void-elements: 3.0.0+ mdast-util-to-hast: 13.2.1+ parse5: 7.3.0+ unist-util-position: 5.0.0+ unist-util-visit: 5.1.0+ vfile: 6.0.3+ web-namespaces: 2.0.1+ zwitch: 2.0.4+dependencies:'@types/estree': 1.0.9@@ -7291,10 +7377,28 @@ snapshots:transitivePeerDependencies:- supports-color+ dependencies:+ '@types/hast': 3.0.4+ comma-separated-tokens: 2.0.3+ devlop: 1.1.0+ property-information: 7.1.0+ space-separated-tokens: 2.0.2+ web-namespaces: 2.0.1+ zwitch: 2.0.4+dependencies:'@types/hast': 3.0.4+ dependencies:+ '@types/hast': 3.0.4+ comma-separated-tokens: 2.0.3+ hast-util-parse-selector: 4.0.0+ property-information: 7.1.0+ space-separated-tokens: 2.0.2+dependencies:'@types/set-cookie-parser': 2.4.10@@ -7314,6 +7418,8 @@ snapshots:+ [email protected]: {}+dependencies:depd: 2.0.0@@ -8053,8 +8159,8 @@ snapshots:dependencies:'@next/env': 16.2.6'@swc/helpers': 0.5.15- baseline-browser-mapping: 2.10.29- caniuse-lite: 1.0.30001792+ baseline-browser-mapping: 2.10.33+ caniuse-lite: 1.0.30001793postcss: 8.4.31react: 19.2.6react-dom: 19.2.6([email protected])@@ -8155,7 +8261,7 @@ snapshots:powershell-utils: 0.1.0wsl-utils: 0.3.1optionalDependencies:zod: 4.4.3@@ -8213,6 +8319,10 @@ snapshots:+ dependencies:+ entities: 6.0.1+@@ -8473,6 +8583,12 @@ snapshots:tiny-invariant: 1.3.3tslib: 2.8.1+ dependencies:+ '@types/hast': 3.0.4+ hast-util-raw: 9.1.0+ vfile: 6.0.3+dependencies:'@types/mdast': 4.0.4@@ -8582,6 +8698,9 @@ snapshots:+ optional: true+dependencies:debug: 2.6.9@@ -8689,7 +8808,7 @@ snapshots:dependencies:'@img/colour': 1.1.0detect-libc: 2.1.2- semver: 7.8.0+ semver: 7.8.1optionalDependencies:'@img/sharp-darwin-arm64': 0.34.5'@img/sharp-darwin-x64': 0.34.5@@ -9115,6 +9234,11 @@ snapshots:- '@types/react'- '@types/react-dom'+ dependencies:+ '@types/unist': 3.0.3+ vfile: 6.0.3+dependencies:'@types/unist': 3.0.3@@ -9151,6 +9275,8 @@ snapshots:+ [email protected]: {}+diff --git a/src/agentscope/_version.py b/src/agentscope/_version.pyindex 6c3922053..bd524339f 100644--- a/src/agentscope/_version.py+++ b/src/agentscope/_version.py@@ -1,4 +1,4 @@# -*- coding: utf-8 -*-"""The version of agentscope."""-__version__ = "2.0.0"+__version__ = "2.0.1"diff --git a/src/agentscope/agent/_agent.py b/src/agentscope/agent/_agent.pyindex aa8097295..8e44cb199 100644--- a/src/agentscope/agent/_agent.py+++ b/src/agentscope/agent/_agent.py@@ -83,7 +83,7 @@ from ..permission import (PermissionEngine,PermissionDecision,)-from ..workspace import Offloader+from ..workspace import Offloader, WorkspaceBaseif TYPE_CHECKING:from ..middleware import MiddlewareBase@@ -676,6 +676,20 @@ class Agent:reply_id=self.state.reply_id,name=self.name,)+ logger.warning(+ "Agent %s exceeds the max iteration numbers %d. "+ "Stop the react loop.",+ self.name,+ self.react_config.max_iters,+ )++ # Mirror the normal-exit path so subscribers (e.g. SSE clients+ # waiting on a terminal event) don't hang when the loop bails+ # out on max_iters.+ yield ReplyEndEvent(+ session_id=self.state.session_id,+ reply_id=self.state.reply_id,+ )yield AssistantMsg(id=self.state.reply_id,@@ -1962,6 +1976,12 @@ class Agent:if skill_instructions:prompt.append(skill_instructions)+ # Workspace & offloader instructions+ if isinstance(self.offloader, WorkspaceBase):+ offload_instructions = await self.offloader.get_instructions()+ if offload_instructions:+ prompt.append(offload_instructions)+result = "\n".join(prompt)# Apply system_prompt middlewares sequentially (transformer pattern)diff --git a/src/agentscope/app/__init__.py b/src/agentscope/app/__init__.pyindex 262f2e226..127537e33 100644--- a/src/agentscope/app/__init__.py+++ b/src/agentscope/app/__init__.py@@ -4,46 +4,7 @@ components and a configurable FastAPI app factory."""from ._app import create_app-from ._middleware import (- ProtocolMiddlewareBase,- AGUIProtocolMiddleware,- ToolOffloadMiddleware,-)-from .storage import (- RedisStorage,- AgentRecord,- CredentialRecord,- SessionConfig,- SessionRecord,- UserRecord,-)-from ._manager import (- WorkspaceManagerBase,- LocalWorkspaceManager,- DockerWorkspaceManager,- E2BWorkspaceManager,- BackgroundTaskManager,- SchedulerManager,- SessionManager,-)__all__ = ["create_app",- "ProtocolMiddlewareBase",- "AGUIProtocolMiddleware",- "ToolOffloadMiddleware",- "RedisStorage",- "AgentRecord",- "CredentialRecord",- "SessionConfig",- "SessionRecord",- "UserRecord",- "WorkspaceManagerBase",- "BackgroundTaskManager",- "LocalWorkspaceManager",- "DockerWorkspaceManager",- "E2BWorkspaceManager",- "BackgroundTaskManager",- "SchedulerManager",- "SessionManager",]diff --git a/src/agentscope/app/_app.py b/src/agentscope/app/_app.pyindex a6bc71bb9..e1bde2917 100644--- a/src/agentscope/app/_app.py+++ b/src/agentscope/app/_app.py@@ -3,10 +3,9 @@from typing import Type, TYPE_CHECKING, Anyfrom ._lifespan import lifespan-from ._manager import WorkspaceManagerBase+from .workspace_manager import WorkspaceManagerBasefrom ._router import (agent_router,- background_task_router,chat_router,credential_router,model_router,@@ -15,8 +14,11 @@ from ._router import (workspace_router,)from ._types import AgentMiddlewareFactory, AgentToolFactory+from .message_bus import MessageBusfrom .storage import StorageBasefrom ..credential import CredentialFactory, CredentialBase+from .._version import __version__+if TYPE_CHECKING:from fastapi import FastAPI@@ -28,14 +30,15 @@ else:def create_app(storage: StorageBase,+ message_bus: MessageBus,+ workspace_manager: WorkspaceManagerBase,*,- workspace_manager: WorkspaceManagerBase | None = None,extra_credentials: list[Type[CredentialBase]] | None = None,extra_middlewares: list[FastAPIMiddleware] | None = None,extra_agent_middlewares: AgentMiddlewareFactory | None = None,extra_agent_tools: AgentToolFactory | None = None,title: str = "AgentScope",- version: str = "2.0.0",+ version: str = __version__,) -> FastAPI:"""Create and configure a FastAPI application.@@ -45,24 +48,39 @@ def create_app(Usage — standalone::- app = create_app(storage=RedisStorage())+ app = create_app(+ storage=RedisStorage(),+ message_bus=RedisMessageBus(),+ workspace_manager=LocalWorkspaceManager(),+ )uvicorn.run(app, host="0.0.0.0", port=8000)Usage — mount onto an existing app::root = FastAPI()- agentscope_app = create_app(storage=RedisStorage())+ agentscope_app = create_app(+ storage=RedisStorage(),+ message_bus=RedisMessageBus(),+ workspace_manager=LocalWorkspaceManager(),+ )root.mount("/agentscope", agentscope_app)Args:storage (`StorageBase`):The storage backend. Its lifecycle (``__aenter__`` /``__aexit__``) is managed by the app lifespan.- workspace_manager (`WorkspaceManagerBase | None`, optional):- The workspace manager. When provided, its ``close_all`` is called- on shutdown. Pass a :class:`~agentscope.app._manager.- LocalWorkspaceManager`- for local-directory workspaces.+ message_bus (`MessageBus`):+ The live message bus used for cross-session inbox delivery+ and idle-session triggers. Required — the bus is intentionally+ decoupled from ``storage`` so the persistence backend (e.g.+ SQL) can differ from the transport backend (Redis). Its+ lifecycle is also managed by the app lifespan.+ workspace_manager (`WorkspaceManagerBase`):+ The workspace manager. Required — every chat run and every+ ``/workspace`` endpoint depends on it. Its lifecycle (+ ``__aenter__`` / ``__aexit__``) is managed by the app+ lifespan. Pass a :class:`~agentscope.app._manager.+ LocalWorkspaceManager` for local-directory workspaces.extra_credentials (`list[Type[CredentialBase]] | None`, optional):Additional :class:`~agentscope.credential.CredentialBase`subclasses to register before the app starts. Equivalent to@@ -89,7 +107,7 @@ def create_app(the workspace-derived tools in the toolkit's ``"basic"`` group.title (`str`, defaults to ``"AgentScope"``):OpenAPI title shown in the docs UI.- version (`str`, defaults to ``"2.0.0"``):+ version (`str`, defaults to the package version):API version shown in the docs UI.Returns:@@ -105,6 +123,7 @@ def create_app(# Attach shared state that lifespan and dependencies read from app.stateapp.state.storage = storage+ app.state.message_bus = message_busapp.state.workspace_manager = workspace_managerapp.state.extra_agent_middlewares = extra_agent_middlewaresapp.state.extra_agent_tools = extra_agent_tools@@ -112,7 +131,6 @@ def create_app(# Built-in routersfor router in (agent_router,- background_task_router,chat_router,credential_router,schedule_router,diff --git a/src/agentscope/app/_lifespan.py b/src/agentscope/app/_lifespan.pyindex 7175fb4b3..f9f69889f 100644--- a/src/agentscope/app/_lifespan.py+++ b/src/agentscope/app/_lifespan.py@@ -1,9 +1,16 @@# -*- coding: utf-8 -*-"""The lifespan of the agent service."""-from contextlib import AsyncExitStack, asynccontextmanager, nullcontext+from contextlib import AsyncExitStack, asynccontextmanagerfrom typing import TYPE_CHECKING, Any, AsyncIterator-from ._manager import BackgroundTaskManager, SchedulerManager, SessionManager+from ._manager import (+ BackgroundTaskManager,+ CancelDispatcher,+ ChatRunRegistry,+ SchedulerManager,+ WakeupDispatcher,+)+from ._service import ChatService, SessionServiceif TYPE_CHECKING:from fastapi import FastAPI@@ -15,49 +22,78 @@ else:async def lifespan(app: FastAPI) -> AsyncIterator[None]:"""Manage startup and shutdown of all application-wide resources.- On startup:- - Opens the storage connection pool.- - Enters the workspace manager (starts its TTL sweeper, if any).- - Starts the session manager, background task manager, and scheduler.- - Restores persisted schedules from storage into the in-memory scheduler.-- On shutdown:- - Cancels in-flight sessions and background tasks.- - Shuts down the scheduler (waits for running jobs to finish).- - Exits the workspace manager (stops its sweeper and closes every- cached workspace).+ Every resource with a lifecycle is an async context manager and is+ entered through a single :class:`AsyncExitStack`. The stack tears+ them down in reverse order on shutdown — including when an entry+ later in the sequence raises during startup, so no resource leaks+ on partial failure.++ Service-layer ``ChatService`` and ``SessionService`` have no+ lifecycle of their own and are constructed inline."""+ storage = app.state.storage+ message_bus = app.state.message_busworkspace_manager = app.state.workspace_manager- workspace_ctx = (- workspace_manager if workspace_manager is not None else nullcontext()- )async with AsyncExitStack() as stack:- await stack.enter_async_context(app.state.storage)- await stack.enter_async_context(workspace_ctx)+ await stack.enter_async_context(storage)+ await stack.enter_async_context(message_bus)+ await stack.enter_async_context(workspace_manager)++ bg_manager = await stack.enter_async_context(BackgroundTaskManager())+ app.state.background_task_manager = bg_manager++ # Per-process registry of in-flight chat-run asyncio tasks.+ # Entered before the wake-up + cancel dispatchers so they can+ # share the same registry; exited last so its shutdown can+ # cancel any leftover runs after the dispatchers stop.+ chat_run_registry = await stack.enter_async_context(ChatRunRegistry())+ app.state.chat_run_registry = chat_run_registry- session_manager = SessionManager()- app.state.session_manager = session_manager- app.state.background_task_manager = BackgroundTaskManager()+ # Scheduler is independent of ChatService now (its fire path+ # pushes to inbox + enqueues wakeup via the bus), so we build it+ # before ChatService and inject it via the constructor.+ scheduler = await stack.enter_async_context(+ SchedulerManager(+ storage=storage,+ message_bus=message_bus,+ ),+ )+ app.state.scheduler_manager = scheduler- scheduler = SchedulerManager(- storage=app.state.storage,- session_manager=session_manager,- background_task_manager=app.state.background_task_manager,+ chat_service = ChatService(+ storage=storage,workspace_manager=workspace_manager,+ scheduler_manager=scheduler,+ background_task_manager=bg_manager,+ message_bus=message_bus,extra_agent_middlewares=app.state.extra_agent_middlewares,extra_agent_tools=app.state.extra_agent_tools,)- app.state.scheduler_manager = scheduler- await scheduler.start()+ app.state.chat_service = chat_service- # Restore persisted schedules so they survive server restarts- all_schedules = await app.state.storage.list_all_schedules()- if all_schedules:- await scheduler.restore(all_schedules)+ app.state.session_service = SessionService(+ storage=storage,+ message_bus=message_bus,+ )- yield+ # Dispatchers need live references somewhere, or they would be+ # garbage-collected; the AsyncExitStack holds those references+ # for us, so we don't need local bindings or app.state slots.+ await stack.enter_async_context(+ WakeupDispatcher(+ message_bus=message_bus,+ storage=storage,+ chat_service=chat_service,+ chat_run_registry=chat_run_registry,+ ),+ )+ await stack.enter_async_context(+ CancelDispatcher(+ message_bus=message_bus,+ registry=chat_run_registry,+ bg_manager=bg_manager,+ ),+ )- app.state.session_manager.cancel()- app.state.background_task_manager.cancel()- await scheduler.shutdown()+ yielddiff --git a/src/agentscope/app/_manager/__init__.py b/src/agentscope/app/_manager/__init__.pyindex b0b755cd9..f4facb0e2 100644--- a/src/agentscope/app/_manager/__init__.py+++ b/src/agentscope/app/_manager/__init__.py@@ -2,20 +2,16 @@"""The agent service managers, used in FastAPI lifespan to manageapplication-wide resources."""-from ._background_task_manager import BackgroundTaskManager-from ._docker_workspace_manager import DockerWorkspaceManager-from ._e2b_workspace_manager import E2BWorkspaceManagerfrom ._scheduler import SchedulerManager-from ._session_manager import SessionManager-from ._workspace_manager import WorkspaceManagerBase, LocalWorkspaceManager-+from ._wakeup_dispatcher import WakeupDispatcher+from ._cancel_dispatcher import CancelDispatcher+from ._chat_run_registry import ChatRunRegistry+from ._background_task_manager import BackgroundTaskManager__all__ = ["BackgroundTaskManager",- "DockerWorkspaceManager",- "E2BWorkspaceManager",- "LocalWorkspaceManager",+ "CancelDispatcher",+ "ChatRunRegistry","SchedulerManager",- "SessionManager",- "WorkspaceManagerBase",+ "WakeupDispatcher",]diff --git a/src/agentscope/app/_manager/_background_task_manager.py b/src/agentscope/app/_manager/_background_task_manager.pyindex 72a4826be..6cf772b69 100644--- a/src/agentscope/app/_manager/_background_task_manager.py+++ b/src/agentscope/app/_manager/_background_task_manager.py@@ -3,19 +3,19 @@import asynciofrom collections import OrderedDictfrom dataclasses import dataclass, field-from typing import Any, Callable, Coroutine+from typing import Any, Selfimport shortuuidfrom pydantic import BaseModel, Field-from ...message import TextBlock, ToolResultState-from ...permission import (+from agentscope.message import TextBlock, ToolResultState+from agentscope.permission import (PermissionContext,PermissionDecision,PermissionBehavior,)-from ...tool import ToolBase, ToolChunk-from ..._logging import logger+from agentscope.tool import ToolBase, ToolChunk+from agentscope._logging import logger@dataclass@@ -149,63 +149,24 @@ class TaskStop(ToolBase):class BackgroundTaskManager:- """Manages background asyncio task lifecycle within the agent services.+ """Tracks background asyncio task lifecycle within the agent service.Responsibilities:- - **Task registry**: track running tasks so they can be cancelled via- :class:`TaskStop`.- - **Task scheduling**: convenience method for creating a task from a- plain coroutine with an optional completion callback.- - **Result storage**: completed task results are stored here so that- middleware can pull them on the next reasoning step.+ - **Task registry**: track running tasks so they can be cancelled+ via :class:`TaskStop` and on application shutdown.+ - **Task scheduling**: convenience method for creating a task from+ a plain coroutine with an optional completion callback.++ Completion results are **not** stored here — producers deliver them+ via the :class:`MessageBus` inbox + wakeup path (same as team+ messages), so any process's :class:`WakeupDispatcher` can pick up+ the result and drive the next chat run."""def __init__(self) -> None:"""Initialise the background task manager."""self.tasks: OrderedDict[str, BackgroundTask] = OrderedDict()- self._completed_results: dict[str, list[Any]] = {}-- # ------------------------------------------------------------------- # Result storage API- # -------------------------------------------------------------------- def push_result(self, session_id: str, result: Any) -> None:- """Store a completed task result for *session_id*.-- Args:- session_id (`str`):- The target session.- result (`Any`):- The result object (type determined by the producer).- """- self._completed_results.setdefault(session_id, []).append(result)-- def pop_results(self, session_id: str) -> list[Any]:- """Return and clear all completed results for *session_id*.-- Args:- session_id (`str`):- The session to query.-- Returns:- `list[Any]`:- Accumulated results, or ``[]`` if none.- """- return self._completed_results.pop(session_id, [])-- def has_results(self, session_id: str) -> bool:- """Check whether *session_id* has pending completed results.-- Args:- session_id (`str`):- The session to check.-- Returns:- `bool`:- ``True`` if there are unconsumed results.- """- return bool(self._completed_results.get(session_id))# ------------------------------------------------------------------# Task registration@@ -217,13 +178,14 @@ class BackgroundTaskManager:session_id: str,agent_id: str,user_id: str,- on_complete: Callable[[], Coroutine] | None = None,) -> str:"""Register an already-running asyncio task and return its id.- A watcher coroutine is spawned that awaits *asyncio_task*; when it- finishes *on_complete* (if provided) is awaited and the task entry- is removed from the registry.+ The task auto-removes from the registry when it finishes (via+ ``add_done_callback``). Post-completion work (e.g. delivering+ the result back through the message bus) is the caller's+ responsibility — typically by spawning a separate watcher+ coroutine that awaits the same task.Args:asyncio_task (`asyncio.Task`):@@ -231,16 +193,13 @@ class BackgroundTaskManager:session_id (`str`):The originating session id.agent_id (`str`):- The name of the agent that owns the task.+ The agent record id that owns the task.user_id (`str`):The user id of the originating request.- on_complete (`Callable[[], Coroutine] | None`, optional):- An async callable invoked when the task finishes normally.- Not called when the task is cancelled.Returns:`str`:- The generated task ID.+ The generated task id."""bg_task = BackgroundTask(asyncio_task=asyncio_task,@@ -257,49 +216,9 @@ class BackgroundTaskManager:session_id,agent_id,)-- async def _watch() -> None:- logger.info(- "Background task started: task_id=%s, session_id=%s, "- "agent_id=%s",- task_id,- session_id,- agent_id,- )- try:- await asyncio_task- except asyncio.CancelledError:- logger.info(- "Background task cancelled: task_id=%s, session_id=%s, "- "agent_id=%s",- task_id,- session_id,- agent_id,- )- return- except Exception: # pylint: disable=broad-except- logger.warning(- "Background task failed with exception: task_id=%s, "- "session_id=%s, agent_id=%s",- task_id,- session_id,- agent_id,- exc_info=True,- )- finally:- self.tasks.pop(task_id, None)-- logger.info(- "Background task completed: task_id=%s, session_id=%s, "- "agent_id=%s",- task_id,- session_id,- agent_id,- )- if on_complete is not None:- await on_complete()-- asyncio.create_task(_watch())+ asyncio_task.add_done_callback(+ lambda _t: self.tasks.pop(task_id, None),+ )return task_idasync def list_tools(self) -> list[ToolBase]:@@ -311,11 +230,67 @@ class BackgroundTaskManager:"""return [TaskStop(self.tasks)]- def cancel(self) -> None:- """Cancel all running background tasks on application shutdown.+ # ------------------------------------------------------------------+ # Session-scoped cancel+ # ------------------------------------------------------------------++ def cancel_session_tasks(self, session_id: str) -> int:+ """Cancel every locally-tracked task whose owner session matches.++ Called by :class:`CancelDispatcher` on each incoming cancel+ broadcast. The dispatcher fires this on every process; each+ process only cancels the tasks it actually holds, so a session+ whose BG tasks all live on other processes is a silent no-op+ here. Returns the number of tasks cancelled on this process so+ callers can log the local effect.++ The matching tasks' ``add_done_callback`` from+ :meth:`register_task` removes them from ``self.tasks`` once the+ cancel actually takes effect, so no explicit pop is needed.+ Watcher coroutines (e.g.+ :class:`~agentscope.app._middleware.ToolOffloadMiddleware`'s+ ``_deliver_when_done``) catch :class:`asyncio.CancelledError`+ and skip result delivery, so cancelling here will not push a+ stale inbox/wakeup for a session being deleted.++ Args:+ session_id (`str`):+ The session whose tasks should be cancelled on this+ process.++ Returns:+ `int`:+ Number of tasks cancelled locally.+ """+ cancelled = 0+ for bg_task in list(self.tasks.values()):+ if bg_task.session_id != session_id:+ continue+ logger.info(+ "Cancelling background task for deleted/cancelled "+ "session: task_id=%s, session_id=%s, agent_id=%s",+ bg_task.id,+ bg_task.session_id,+ bg_task.agent_id,+ )+ bg_task.asyncio_task.cancel()+ cancelled += 1+ return cancelled++ async def __aenter__(self) -> Self:+ """Enter the async context. No setup required.++ Returns:+ `Self`: This manager instance.+ """+ return self++ async def __aexit__(self, *exc: object) -> None:+ """Cancel all running background tasks on context exit.- Each task's asyncio task is cancelled. The ``on_complete``- callback will **not** be invoked for cancelled tasks.+ Each task's asyncio task is cancelled. Any watcher coroutine+ awaiting these tasks will see ``CancelledError`` and skip its+ post-completion work (e.g. result delivery)."""count = len(self.tasks)logger.info(diff --git a/src/agentscope/app/_manager/_cancel_dispatcher.py b/src/agentscope/app/_manager/_cancel_dispatcher.pynew file mode 100644index 000000000..999d0845a--- /dev/null+++ b/src/agentscope/app/_manager/_cancel_dispatcher.py@@ -0,0 +1,159 @@+# -*- coding: utf-8 -*-+"""Single per-process dispatcher for cross-process session cancels.++Subscribes to the bus's shared cancel-broadcast channel. For each+incoming ``session_id``, performs every session-scoped cancel a worker+process can do locally:++1. Look the session up in the local :class:`ChatRunRegistry` — if a+ chat-run task is tracked here, cancel it.+2. Ask the local :class:`BackgroundTaskManager` to cancel every BG+ task it tracks for that session.++Processes whose registry / BG-manager do not hold anything for the+session simply do no work — the publisher does not need to know which+worker holds which piece; it broadcasts and lets each holder self-select.++Symmetric to :class:`WakeupDispatcher`: both are one asyncio task per+process; one starts runs in response to wake-ups, the other ends them+in response to cancels.+"""+import asyncio+from typing import TYPE_CHECKING, Self++from ..._logging import logger++if TYPE_CHECKING:+ from ..message_bus import MessageBus+ from ._background_task_manager import BackgroundTaskManager+ from ._chat_run_registry import ChatRunRegistry+++class CancelDispatcher:+ """Subscribes to the bus cancel channel and cancels every local+ session-scoped task (chat run + BG tasks) on match.++ Args:+ message_bus (`MessageBus`):+ Application message bus. Used for+ :meth:`~agentscope.app.message_bus.MessageBus.+ session_subscribe_cancel`.+ registry (`ChatRunRegistry`):+ The per-process chat-run registry whose tasks may be+ cancelled.+ bg_manager (`BackgroundTaskManager`):+ The per-process background task manager. Its+ :meth:`~BackgroundTaskManager.cancel_session_tasks` is+ invoked on every incoming cancel; it returns silently when+ no local BG task matches the session.+ """++ def __init__(+ self,+ message_bus: "MessageBus",+ registry: "ChatRunRegistry",+ bg_manager: "BackgroundTaskManager",+ ) -> None:+ """Bind dependencies.++ Args:+ message_bus (`MessageBus`):+ Application message bus.+ registry (`ChatRunRegistry`):+ The per-process chat-run registry.+ bg_manager (`BackgroundTaskManager`):+ The per-process background task manager.+ """+ self._bus = message_bus+ self._registry = registry+ self._bg_manager = bg_manager+ self._task: asyncio.Task | None = None++ async def __aenter__(self) -> Self:+ """Start the dispatcher loop and wait until its bus+ subscription is live.++ Blocking on the readiness signal means a process that publishes+ a cancel immediately after the dispatcher starts will not lose+ the message to a SUBSCRIBE/PUBLISH race.++ Returns:+ `Self`: This dispatcher instance.+ """+ ready = asyncio.Event()+ self._task = asyncio.create_task(+ self._loop(ready),+ name="cancel-dispatcher",+ )+ await ready.wait()+ return self++ async def __aexit__(self, *exc: object) -> None:+ """Cancel the dispatcher loop on context exit."""+ if self._task is None:+ return+ self._task.cancel()+ try:+ await self._task+ except asyncio.CancelledError:+ pass+ self._task = None++ # ------------------------------------------------------------------+ # Internals+ # ------------------------------------------------------------------++ async def _loop(self, ready: asyncio.Event) -> None:+ """Long-lived loop: yield each incoming cancel and act on it.++ Args:+ ready (`asyncio.Event`):+ Signalled after the underlying SUBSCRIBE completes.+ :meth:`__aenter__` blocks on this so callers can+ publish a cancel immediately after start without+ racing the subscription.+ """+ try:+ async for session_id in self._bus.session_subscribe_cancel(+ on_ready=ready.set,+ ):+ self._cancel_local(session_id)+ except Exception: # pylint: disable=broad-except+ logger.exception(+ "CancelDispatcher loop crashed; subscription ended.",+ )++ def _cancel_local(self, session_id: str) -> None:+ """Cancel every locally-tracked task for ``session_id``.++ Fans out to:++ - the chat-run task in :class:`ChatRunRegistry`, if registered+ on this process;+ - every BG task in :class:`BackgroundTaskManager` whose owner+ session matches.++ Both lookups are silent no-ops when the local process holds no+ matching state.++ Args:+ session_id (`str`):+ The session whose runs and BG tasks should be cancelled.+ """+ task = self._registry.get(session_id)+ if task is not None and not task.done():+ logger.info(+ "CancelDispatcher: cancelling local chat run for "+ "session %s",+ session_id,+ )+ task.cancel()++ bg_cancelled = self._bg_manager.cancel_session_tasks(session_id)+ if bg_cancelled:+ logger.info(+ "CancelDispatcher: cancelled %d local BG task(s) for "+ "session %s",+ bg_cancelled,+ session_id,+ )diff --git a/src/agentscope/app/_manager/_chat_run_registry.py b/src/agentscope/app/_manager/_chat_run_registry.pynew file mode 100644index 000000000..8659bbfd5--- /dev/null+++ b/src/agentscope/app/_manager/_chat_run_registry.py@@ -0,0 +1,134 @@+# -*- coding: utf-8 -*-+"""Per-process registry of in-flight ``ChatService.run`` asyncio tasks.++Owns the asyncio.Task handles only — it is not the public cancel+entry point. The cross-process cancel path goes through the bus's+:meth:`~agentscope.app.message_bus.MessageBus.session_publish_cancel`+broadcast, picked up locally by+:class:`~agentscope.app._manager.CancelDispatcher`, which then looks+up the task here and calls ``.cancel()`` on it.++A given ``session_id`` can have at most one entry. Concurrent runs for+the same session are already prevented at a cluster level by+:meth:`~agentscope.app.message_bus.MessageBus.session_run` (the+distributed lock), so a second :meth:`spawn` for the same id is treated+as a programming error.+"""+import asyncio+from typing import Coroutine, Self++from ..._logging import logger+++class ChatRunRegistry:+ """In-process index of active chat-run asyncio tasks, keyed by+ session id.++ Used by :class:`~agentscope.app._manager.CancelDispatcher` to find+ and cancel the local task for a given session, and by the lifespan+ to cancel any leftover runs on application shutdown.+ """++ def __init__(self) -> None:+ """Initialise an empty registry."""+ self._tasks: dict[str, asyncio.Task] = {}++ def spawn(+ self,+ coro: Coroutine,+ *,+ session_id: str,+ name: str | None = None,+ ) -> asyncio.Task:+ """Create and register an asyncio task that runs ``coro``.++ The task auto-removes from the registry when it finishes (via+ ``add_done_callback``).++ Args:+ coro (`Coroutine`):+ A coroutine — typically ``chat_service.run(...)`` — to+ run as a background task.+ session_id (`str`):+ The session this run belongs to. Used as the registry+ key for later cancel lookup.+ name (`str | None`, optional):+ Optional task name passed through to+ :func:`asyncio.create_task`. Defaults to+ ``f"chat-run:{session_id}"``.++ Returns:+ `asyncio.Task`:+ The created task. Callers normally do not need to keep+ the reference — the registry holds it for the task's+ lifetime.++ Raises:+ `RuntimeError`:+ When a non-finished task is already registered for+ ``session_id``. Callers are expected to coordinate via+ the distributed session lock before spawning.+ """+ existing = self._tasks.get(session_id)+ if existing is not None and not existing.done():+ raise RuntimeError(+ f"Session {session_id!r} already has an active chat run "+ "in this process.",+ )++ task = asyncio.create_task(+ coro,+ name=name or f"chat-run:{session_id}",+ )+ self._tasks[session_id] = task++ def _cleanup(t: asyncio.Task) -> None:+ # Only remove the entry if it still points at this task —+ # a fresh spawn for the same sid may have replaced it.+ if self._tasks.get(session_id) is t:+ self._tasks.pop(session_id, None)++ task.add_done_callback(_cleanup)+ return task++ def get(self, session_id: str) -> asyncio.Task | None:+ """Return the registered task for ``session_id``, or ``None``.++ Args:+ session_id (`str`):+ The session whose task to look up.++ Returns:+ `asyncio.Task | None`:+ The task if one is currently registered for the+ session, else ``None``.+ """+ return self._tasks.get(session_id)++ async def __aenter__(self) -> Self:+ """No-op enter; the registry has no startup work.++ Returns:+ `Self`: This registry instance.+ """+ return self++ async def __aexit__(self, *exc: object) -> None:+ """Cancel every still-running task on application shutdown.++ Each task is cancelled and awaited so its ``finally`` blocks+ and any ``async with`` cleanups (notably the bus's session+ run-lock release) execute before the process exits.+ """+ if not self._tasks:+ return+ logger.info(+ "ChatRunRegistry shutdown: cancelling %d in-flight chat run(s).",+ len(self._tasks),+ )+ tasks = list(self._tasks.values())+ for task in tasks:+ task.cancel()+ # Wait for every cancel to land; swallow CancelledError per task.+ await asyncio.gather(*tasks, return_exceptions=True)+ self._tasks.clear()diff --git a/src/agentscope/app/_manager/_scheduler/_scheduler_manager.py b/src/agentscope/app/_manager/_scheduler/_scheduler_manager.pyindex 8ca2ed7f9..b96597ae8 100644--- a/src/agentscope/app/_manager/_scheduler/_scheduler_manager.py+++ b/src/agentscope/app/_manager/_scheduler/_scheduler_manager.py@@ -1,24 +1,24 @@# -*- coding: utf-8 -*-"""The cron scheduler manager class."""+import jsonfrom collections.abc import Callable, Coroutine-from typing import TYPE_CHECKING+from typing import Self-from ....message import UserMsg+from ....message import HintBlock+from ....permission import PermissionContext+from ....state import AgentStatefrom ....tool import ToolBasefrom ...._logging import logger-from ._tools import ScheduleCreate, ScheduleList, ScheduleStop, ScheduleView+from ._tools import ScheduleCreate, ScheduleDelete, ScheduleList, ScheduleView+from ...message_bus import MessageBusfrom ...storage import (StorageBase,ScheduleRecord,ChatModelConfig,+ SessionConfig,+ SessionSource,)-from .._background_task_manager import BackgroundTaskManager-from .._session_manager import SessionManager-from .._workspace_manager import WorkspaceManagerBase--if TYPE_CHECKING:- from ..._types import AgentMiddlewareFactory, AgentToolFactoryclass SchedulerManager:@@ -26,64 +26,63 @@ class SchedulerManager:lifecycle within the agent service.The manager owns both the in-memory APScheduler instance and the trigger- logic that runs agents on schedule. Inject it with ``storage`` and- ``session_manager`` so it can build self-contained trigger coroutines- without external callbacks.+ logic that fires scheduled tasks. Triggers do not call ``ChatService``+ directly; instead they push a :class:`HintBlock` to the target session's+ inbox and enqueue a wakeup, so that the application-wide+ :class:`WakeupDispatcher` (running on any process) picks up the work.+ This keeps the scheduler decoupled from ``ChatService`` and makes the+ fire path consistent with team / background-tool result delivery."""def __init__(self,storage: StorageBase,- session_manager: SessionManager,- background_task_manager: BackgroundTaskManager,- workspace_manager: WorkspaceManagerBase,- extra_agent_middlewares: "AgentMiddlewareFactory | None" = None,- extra_agent_tools: "AgentToolFactory | None" = None,+ message_bus: MessageBus,) -> None:"""Initialize the scheduler manager.Args:storage (`StorageBase`):- The storage backend used for persistence and session creation.- session_manager (`SessionManager`):- The session manager used when running agent chat sessions.- background_task_manager (`BackgroundTaskManager`):- The background task manager passed through to- :class:`ChatService` so triggered agents can offload- long-running tools.- workspace_manager (`WorkspaceManagerBase`):- The workspace manager passed through to :class:`ChatService`- so triggered agents get the configured toolkit and MCPs.- extra_agent_middlewares (`AgentMiddlewareFactory | None`, \-optional):- Async factory passed through to :class:`ChatService` to- produce extra agent middlewares per scheduled trigger.- extra_agent_tools (`AgentToolFactory | None`, optional):- Async factory passed through to :class:`ChatService` to- produce extra agent tools per scheduled trigger.+ The storage backend used for persistence and session+ creation.+ message_bus (`MessageBus`):+ The application message bus. Each scheduled fire pushes+ a :class:`HintBlock` to the target session's inbox and+ enqueues a wakeup via this bus."""from apscheduler.schedulers.asyncio import AsyncIOSchedulerself._storage = storage- self._session_manager = session_manager- self._background_task_manager = background_task_manager- self._workspace_manager = workspace_manager- self._extra_agent_middlewares = extra_agent_middlewares- self._extra_agent_tools = extra_agent_tools+ self._message_bus = message_busself._scheduler = AsyncIOScheduler()# ------------------------------------------------------------------# Lifecycle# ------------------------------------------------------------------- async def start(self) -> None:- """Start the underlying APScheduler."""+ async def __aenter__(self) -> Self:+ """Start APScheduler and re-register persisted schedules.++ Reading all schedules from storage and restoring them is the+ only thing a caller would ever do right after starting this+ manager, so the work lives inside the context entry — the+ lifespan does not need to remember to call :meth:`restore`.++ Returns:+ `Self`: This manager instance.+ """logger.info("SchedulerManager starting APScheduler")self._scheduler.start()logger.info("SchedulerManager APScheduler started")- async def shutdown(self) -> None:- """Shut down the underlying APScheduler."""+ records = await self._storage.list_all_schedules()+ if records:+ await self.restore(records)++ return self++ async def __aexit__(self, *exc: object) -> None:+ """Shut down the underlying APScheduler on context exit."""logger.info("SchedulerManager shutting down APScheduler")self._scheduler.shutdown()logger.info("SchedulerManager APScheduler shut down")@@ -117,16 +116,10 @@ optional):`Callable[[], Coroutine]`:A zero-argument async callable suitable for APScheduler."""- # Collect closure-friendly references to avoid re-looking them up- # on every fire. ChatService is imported lazily inside the closure to- # break the circular dependency:- # _manager._scheduler → _service._chat → _manager+ # Closure-friendly references so APScheduler doesn't have to+ # re-look these up on every fire.storage = self._storage- session_manager = self._session_manager- background_task_manager = self._background_task_manager- workspace_manager = self._workspace_manager- extra_agent_middlewares = self._extra_agent_middlewares- extra_agent_tools = self._extra_agent_tools+ message_bus = self._message_busasync def _trigger() -> None:logger.info(@@ -143,17 +136,6 @@ optional):)return- # Lazy import to break circular dependency- from ..._service._chat import ChatService # noqa: PLC0415- from ....permission._context import (- PermissionContext,- ) # noqa: PLC0415- from ....state import AgentState # noqa: PLC0415- from ...storage._model._session import ( # noqa: PLC0415- SessionConfig,- SessionSource,- )-try:if record.data.stateful:stateful_session_id = f"{record.id}_stateful"@@ -226,36 +208,42 @@ optional):logger.info("[Schedule:%s(%s)] Session ready: %s, "- "starting chat execution",+ "delivering prompt via inbox + wakeup",record.id,record.data.name,session.id,)- input_msg = UserMsg(- name=record.user_id,- content=record.data.description,+ # Wrap the schedule prompt in an XML tag so the LLM+ # recognises it as a system-driven trigger rather than+ # a regular user turn — same shape as team / system+ # notification hints.+ hint = HintBlock(+ hint=(+ f"<scheduled-task>\n"+ f"{record.data.description}\n"+ f"</scheduled-task>"+ ),+ source=json.dumps(+ {+ "label": "schedule",+ "sublabel": record.data.name,+ },+ ensure_ascii=False,+ ),)-- chat_service = ChatService(- storage=storage,- session_manager=session_manager,- background_task_manager=background_task_manager,- workspace_manager=workspace_manager,- extra_agent_middlewares=extra_agent_middlewares,- extra_agent_tools=extra_agent_tools,+ await message_bus.inbox_push(+ session.id,+ hint.model_dump(mode="json"),)- async for _ in chat_service.stream_chat(+ await message_bus.enqueue_wakeup(user_id=record.user_id,session_id=session.id,agent_id=record.agent_id,- input_msg=input_msg,- ):- pass+ )logger.info(- "[Schedule:%s(%s)] Chat execution completed "- "for session %s",+ "[Schedule:%s(%s)] Wakeup enqueued for session %s",record.id,record.data.name,session.id,@@ -300,12 +288,30 @@ optional):record.data.timezone,)+ # ``CronTrigger.from_crontab`` is a thin helper that only forwards+ # the 5 parsed fields and ``timezone`` — it has no parameter for+ # ``start_date`` / ``end_date``. Parse the expression ourselves so+ # the configured activation window is honoured.+ fields = record.data.cron_expression.split()+ if len(fields) != 5:+ raise ValueError(+ "Expected a 5-field cron expression, got "+ f"{record.data.cron_expression!r}",+ )+ minute, hour, day, month, day_of_week = fields+trigger = self._build_trigger(record)job = self._scheduler.add_job(trigger,- trigger=CronTrigger.from_crontab(- record.data.cron_expression,+ trigger=CronTrigger(+ minute=minute,+ hour=hour,+ day=day,+ month=month,+ day_of_week=day_of_week,timezone=record.data.timezone,+ start_date=record.data.started_at,+ end_date=record.data.ended_at,),id=record.id,name=record.data.name,@@ -394,7 +400,7 @@ optional):Returns:`list[ToolBase]`:The four schedule tools: :class:`ScheduleCreate`,- :class:`ScheduleView`, :class:`ScheduleStop`, and+ :class:`ScheduleView`, :class:`ScheduleDelete`, and:class:`ScheduleList`."""return [@@ -410,10 +416,11 @@ optional):scheduler=self._scheduler,storage=self._storage,),- ScheduleStop(+ ScheduleDelete(user_id=user_id,scheduler=self._scheduler,storage=self._storage,+ message_bus=self._message_bus,),ScheduleList(user_id=user_id,diff --git a/src/agentscope/app/_manager/_scheduler/_tools/__init__.py b/src/agentscope/app/_manager/_scheduler/_tools/__init__.pyindex 49015fa04..beb4b69e2 100644--- a/src/agentscope/app/_manager/_scheduler/_tools/__init__.py+++ b/src/agentscope/app/_manager/_scheduler/_tools/__init__.py@@ -2,13 +2,13 @@"""The schedule related tools."""from ._schedule_create import ScheduleCreate+from ._schedule_delete import ScheduleDeletefrom ._schedule_list import ScheduleList-from ._schedule_stop import ScheduleStopfrom ._schedule_view import ScheduleView__all__ = ["ScheduleCreate",+ "ScheduleDelete","ScheduleList",- "ScheduleStop","ScheduleView",]diff --git a/src/agentscope/app/_manager/_scheduler/_tools/_schedule_create.py b/src/agentscope/app/_manager/_scheduler/_tools/_schedule_create.pyindex 9aa20aea0..36c773ff0 100644--- a/src/agentscope/app/_manager/_scheduler/_tools/_schedule_create.py+++ b/src/agentscope/app/_manager/_scheduler/_tools/_schedule_create.py@@ -1,5 +1,6 @@# -*- coding: utf-8 -*-"""The schedule create tool."""+from datetime import datetimefrom typing import Anyfrom pydantic import BaseModel, Field@@ -41,6 +42,24 @@ class _ScheduleCreateParams(BaseModel):"e.g. 'America/New_York' or 'Asia/Shanghai'.",)+ enabled: bool = Field(+ default=True,+ description="Whether the schedule is active immediately after "+ "creation. Set to False to create a disabled schedule.",+ )++ started_at: datetime | None = Field(+ default=None,+ description="ISO-8601 datetime at which the schedule becomes active. "+ "Defaults to the current time when not specified.",+ )++ ended_at: datetime | None = Field(+ default=None,+ description="ISO-8601 datetime at which the schedule stops firing. "+ "If not set the schedule runs indefinitely.",+ )+stateful: bool = Field(default=False,description="If True, consecutive executions share the same session "@@ -71,11 +90,26 @@ class ScheduleCreate(ToolBase):name: str = "ScheduleCreate"- description: str = (- "Create a new recurring scheduled task for the current agent. "- "The agent will be executed automatically according to the given "- "cron expression. Returns the new schedule ID on success."- )+ description: str = """Create a new recurring scheduled task for yourself. \+You will be notified in a new session each time the schedule is triggered.++**About the cron expression:**+- Determine your current timezone first, that's very important for setting a \+correct cron expression. Get it by bash command like `date +%z`, \+`cat /etc/timezone` or directly ask the user.+- Determine whether the task should run once or recur at an interval, \+then set the cron expression accordingly.+- For a one-off task, query the current time first and set the cron \+expression to fire at that specific moment.+- Set `started_at` and `ended_at` to match the user's requirements. \+When in doubt, ask for clarification before creating the schedule.++**About the description field:**+- The `description` is the only context available to you when the \+schedule fires in a new session. Include all necessary details: the goal, \+expected output, constraints, relevant file paths, and anything else needed \+to complete the task independently.+"""input_schema: dict = _ScheduleCreateParams.model_json_schema()@@ -132,6 +166,9 @@ class ScheduleCreate(ToolBase):cron_expression: str,description: str = "",timezone: str = "UTC",+ enabled: bool = True,+ started_at: datetime | None = None,+ ended_at: datetime | None = None,stateful: bool = False,permission_mode: str = PermissionMode.DONT_ASK.value,_agent_state: AgentState | None = None,@@ -147,6 +184,14 @@ class ScheduleCreate(ToolBase):Human-readable description of what this schedule does.timezone (`str`, optional):IANA timezone name, e.g. ``'Asia/Shanghai'``.+ enabled (`bool`, optional):+ Whether the schedule is active immediately after creation.+ started_at (`datetime | None`, optional):+ Datetime at which the schedule becomes active. Defaults to+ the current time when not specified.+ ended_at (`datetime | None`, optional):+ Datetime at which the schedule stops firing. If not set the+ schedule runs indefinitely.stateful (`bool`, optional):Whether consecutive executions share the same session context.permission_mode (`str`, optional):@@ -174,8 +219,11 @@ class ScheduleCreate(ToolBase):data=ScheduleData(name=name,description=description,+ enabled=enabled,cron_expression=cron_expression,timezone=timezone,+ started_at=started_at or datetime.now(),+ ended_at=ended_at,stateful=stateful,permission_mode=perm_mode,source=ScheduleSource.AGENT,@@ -194,6 +242,9 @@ class ScheduleCreate(ToolBase):f"Schedule {name!r} created successfully.\n"f"Schedule ID: {record.id}\n"f"Cron: {cron_expression} (timezone: {timezone})\n"+ f"Enabled: {enabled}\n"+ f"Started at: {record.data.started_at}\n"+ f"Ended at: {ended_at or '(no end time)'}\n"f"Stateful: {stateful}"),),diff --git a/src/agentscope/app/_manager/_scheduler/_tools/_schedule_stop.py b/src/agentscope/app/_manager/_scheduler/_tools/_schedule_delete.pysimilarity index 56%rename from src/agentscope/app/_manager/_scheduler/_tools/_schedule_stop.pyrename to src/agentscope/app/_manager/_scheduler/_tools/_schedule_delete.pyindex aac8c19cf..aa1a8605e 100644--- a/src/agentscope/app/_manager/_scheduler/_tools/_schedule_stop.py+++ b/src/agentscope/app/_manager/_scheduler/_tools/_schedule_delete.py@@ -1,5 +1,5 @@# -*- coding: utf-8 -*--"""Schedule stop tool – removes a job from the scheduler and storage."""+"""Schedule delete tool – removes a job from the scheduler and storage."""from typing import Anyfrom pydantic import BaseModel, Field@@ -12,33 +12,35 @@ from .....permission import (PermissionBehavior,)from .....tool import ToolBase, ToolChunk+from ....message_bus import MessageBusfrom ....storage._base import StorageBase-class _ScheduleStopParams(BaseModel):- """The params for the schedule stop tool."""+class _ScheduleDeleteParams(BaseModel):+ """The params for the schedule delete tool."""schedule_id: str = Field(- description="The schedule ID to stop (remove).",+ description="The schedule ID to delete (permanently remove).",)-class ScheduleStop(ToolBase):- """The schedule stop tool.+class ScheduleDelete(ToolBase):+ """The schedule delete tool.- Permanently removes the given scheduled job from both the in-memory- APScheduler and the persistent storage. The job cannot be recovered- after removal.+ Permanently removes the given scheduled job from APScheduler,+ storage, and the message bus. Every execution session spawned by+ the schedule is cancelled (if running) and has its bus state+ purged. The job cannot be recovered after removal."""- name: str = "ScheduleStop"+ name: str = "ScheduleDelete"description: str = (- "Stop (permanently remove) a scheduled task by its schedule ID. "+ "Permanently delete a scheduled task by its schedule ID. ""After this call the task will no longer be executed and its record ""will be deleted from storage.")- input_schema: dict = _ScheduleStopParams.model_json_schema()+ input_schema: dict = _ScheduleDeleteParams.model_json_schema()is_concurrency_safe: bool = Falseis_read_only: bool = False@@ -52,8 +54,9 @@ class ScheduleStop(ToolBase):user_id: str,scheduler: Any,storage: StorageBase,+ message_bus: MessageBus,) -> None:- """Initialize the schedule stop tool.+ """Initialize the schedule delete tool.Args:user_id (`str`):@@ -62,10 +65,15 @@ class ScheduleStop(ToolBase):The ``AsyncIOScheduler`` instance whose job will be removed.storage (`StorageBase`):The storage backend used to delete the persisted record.+ message_bus (`MessageBus`):+ The message bus used to cancel in-flight chat runs for+ any execution session spawned by this schedule and to+ purge their per-session bus state."""self._user_id = user_idself._scheduler = schedulerself._storage = storage+ self._message_bus = message_busasync def check_permissions(self,@@ -82,15 +90,22 @@ class ScheduleStop(ToolBase):self,schedule_id: str,) -> ToolChunk: # type: ignore[override]- """Stop (remove) the scheduled task with the given ID.+ """Permanently delete the scheduled task with the given ID.++ Delegates the storage + bus cascade to+ :meth:`SessionService.delete_schedule`, which cancels in-flight+ runs for any session this schedule spawned and purges their+ bus state before dropping the schedule record. The APScheduler+ job is removed separately because it lives in-process and the+ service layer is bus/storage-only.Args:schedule_id (`str`):- The unique identifier of the schedule to stop.+ The unique identifier of the schedule to delete.Returns:`ToolChunk`:- A chunk describing the result of the stop operation.+ A chunk describing the result of the delete operation."""# Remove from the in-memory scheduler (best-effort; may already be@@ -100,8 +115,15 @@ class ScheduleStop(ToolBase):except JobLookupError:pass- # Delete from persistent storage- deleted = await self._storage.delete_schedule(+ # Local import to avoid a circular dependency between+ # ``_manager`` and ``_service`` at module load.+ from ...._service import SessionService # noqa: PLC0415++ session_service = SessionService(+ storage=self._storage,+ message_bus=self._message_bus,+ )+ deleted = await session_service.delete_schedule(self._user_id,schedule_id,)@@ -123,8 +145,8 @@ class ScheduleStop(ToolBase):content=[TextBlock(text=(- f"Schedule {schedule_id!r} has been stopped "- f"and permanently removed."+ f"Schedule {schedule_id!r} has been permanently "+ f"deleted."),),],diff --git a/src/agentscope/app/_manager/_session_manager.py b/src/agentscope/app/_manager/_session_manager.pydeleted file mode 100644index 9ac8804d0..000000000--- a/src/agentscope/app/_manager/_session_manager.py+++ /dev/null@@ -1,197 +0,0 @@-# -*- coding: utf-8 -*--"""The session manager for--- session replay: replaying persisted logs and in-flight buffered outputs- to a client that joins a session mid-execution-- session monitor: tracking which sessions are currently running and- serialising concurrent requests for the same session-"""-import asyncio-from collections.abc import AsyncGenerator-from contextlib import asynccontextmanager-from dataclasses import dataclass, field--from ...event import AgentEvent--_SENTINEL = object()-# Sentinel pushed to subscriber queues to signal end-of-stream.---@dataclass-class _SessionRun:- """State for a single in-flight agent run."""-- buffer: list[AgentEvent] = field(default_factory=list)- """All events produced so far; used to replay to late-joining clients."""-- subscribers: list[asyncio.Queue] = field(default_factory=list)- """One queue per active SSE subscriber; each receives every new event."""-- async def publish(self, event: AgentEvent) -> None:- """Append *event* to the replay buffer and fan it out to all- subscribers.-- Args:- event (`AgentEvent`):- The event to publish.- """- self.buffer.append(event)- for q in self.subscribers:- await q.put(event)-- async def close_subscribers(self) -> None:- """Push the sentinel to every subscriber queue to signal- end-of-stream."""- for q in self.subscribers:- await q.put(_SENTINEL)---class SessionManager:- """Manages in-flight agent runs per session.-- Responsibilities:-- - **Serialisation**: at most one active run per ``session_id`` at a time;- additional callers queue on an ``asyncio.Lock`` and run in order.- - **Fan-out buffer**: every event produced during a run is appended to a- replay buffer *and* pushed to all active SSE subscriber queues so that- clients joining mid-run receive the full event history.- - **Lifecycle**: the buffer and subscriber list are created when a run- starts and discarded when it ends, keeping memory bounded.- """-- def __init__(self) -> None:- """Initialise the session manager."""- self._locks: dict[str, asyncio.Lock] = {}- self._runs: dict[str, _SessionRun] = {}-- # ------------------------------------------------------------------- # Internal helpers- # -------------------------------------------------------------------- def _get_lock(self, session_id: str) -> asyncio.Lock:- """Return (creating if necessary) the per-session serialisation- lock."""- if session_id not in self._locks:- self._locks[session_id] = asyncio.Lock()- return self._locks[session_id]-- # ------------------------------------------------------------------- # Producer API (used by the chat endpoint)- # -------------------------------------------------------------------- @asynccontextmanager- async def run(self, session_id: str) -> AsyncGenerator[_SessionRun, None]:- """Async context manager that serialises runs for *session_id*.-- Acquires the per-session lock (queuing if another run is active),- creates a fresh :class:`_SessionRun`, and tears it down on exit.-- Usage::-- async with session_manager.run(session_id) as run:- async for event in agent.reply(msg):- await run.publish(event)- yield f"data: {event.model_dump_json()}\\n\\n"-- Args:- session_id (`str`): The session to run against.-- Yields:- `_SessionRun`: The active run object;- call :meth:`_SessionRun.publish` to broadcast each event.- """- lock = self._get_lock(session_id)- async with lock:- session_run = _SessionRun()- self._runs[session_id] = session_run- try:- yield session_run- finally:- await session_run.close_subscribers()- self._runs.pop(session_id, None)-- # ------------------------------------------------------------------- # Consumer API (used by the stream endpoint)- # -------------------------------------------------------------------- def is_running(self, session_id: str) -> bool:- """Return ``True`` if *session_id* has an active run.-- Args:- session_id (`str`): The session to check.-- Returns:- `bool`: Whether a run is currently active.- """- return session_id in self._runs-- def get_buffered_events(self, session_id: str) -> list[AgentEvent]:- """Return a snapshot of all events buffered for the active run.-- Used by the stream endpoint to replay events to clients that join- mid-execution.-- Args:- session_id (`str`): The session to query.-- Returns:- `list[AgentEvent]`: Copy of buffered events, or empty list if- no active run.- """- run = self._runs.get(session_id)- return list(run.buffer) if run else []-- async def subscribe(- self,- session_id: str,- ) -> AsyncGenerator[AgentEvent, None]:- """Async generator that yields all events for an active run.-- Replays events already in the buffer, then streams new events as they- arrive. Yields nothing if *session_id* has no active run.-- The replay/subscribe handoff is race-free: the subscriber queue is- registered *before* the buffer snapshot is taken, so no event can be- missed between the two steps (asyncio is single-threaded; no ``await``- separates the two operations).-- Args:- session_id (`str`): The session to subscribe to.-- Yields:- `AgentEvent`: Events in arrival order.- """- run = self._runs.get(session_id)- if run is None:- return-- queue: asyncio.Queue = asyncio.Queue()- # Register BEFORE snapshotting the buffer length so that events- # added after this point go to the queue, not the buffer only.- run.subscribers.append(queue)- replay_until = len(run.buffer)-- # Replay events that existed before we subscribed.- for event in run.buffer[:replay_until]:- yield event-- # Stream events produced after we subscribed.- while True:- item = await queue.get()- if item is _SENTINEL:- break- yield item-- # ------------------------------------------------------------------- # Lifecycle- # -------------------------------------------------------------------- def cancel(self) -> None:- """Cancel all active runs on application shutdown.-- Clears internal state; in-flight SSE generators will receive- ``StopAsyncIteration`` when their queues are garbage-collected.- """- self._runs.clear()- self._locks.clear()diff --git a/src/agentscope/app/_manager/_wakeup_dispatcher.py b/src/agentscope/app/_manager/_wakeup_dispatcher.pynew file mode 100644index 000000000..6d9ef3953--- /dev/null+++ b/src/agentscope/app/_manager/_wakeup_dispatcher.py@@ -0,0 +1,191 @@+# -*- coding: utf-8 -*-+"""Single per-process dispatcher for cross-session wake-ups.++One asyncio task per process. Subscribes to the shared wake-up signal+channel and drains the durable wake-up queue on each signal. For each+queued entry whose session is idle, spawns a background+:meth:`ChatService.run` call through the shared+:class:`ChatRunRegistry`, so the spawned task can be looked up and+cancelled by :class:`CancelDispatcher`.++All bus keys live on the :class:`MessageBus` base class (see+``enqueue_wakeup``, ``dequeue_wakeups``, ``subscribe_wakeup_signal``,+``session_is_running``), so this file has no hard-coded key strings.+"""+import asyncio+from typing import TYPE_CHECKING, Self++from ..._logging import logger++if TYPE_CHECKING:+ from ..message_bus import MessageBus+ from ..storage import StorageBase+ from .._service import ChatService+ from ._chat_run_registry import ChatRunRegistry+++class WakeupDispatcher:+ """One asyncio task per process, draining the shared wake-up queue.++ Args:+ message_bus (`MessageBus`):+ Application message bus. Used for signal subscription,+ queue drain, and ``session_is_running`` checks.+ storage (`StorageBase`):+ Persistent storage backend. Consulted before spawning a+ run so wake-ups whose target session has been deleted are+ dropped instead of crashing :class:`ChatService.run`.+ chat_service (`ChatService`):+ Drives the actual chat run when waking an idle session.+ chat_run_registry (`ChatRunRegistry`):+ Per-process registry that holds the spawned task handle so+ it can be located by :class:`CancelDispatcher`.+ """++ def __init__(+ self,+ message_bus: "MessageBus",+ storage: "StorageBase",+ chat_service: "ChatService",+ chat_run_registry: "ChatRunRegistry",+ ) -> None:+ """Bind dependencies.++ Args:+ message_bus (`MessageBus`):+ Application message bus.+ storage (`StorageBase`):+ Persistent storage backend.+ chat_service (`ChatService`):+ Drives idle-session wake-ups via :meth:`ChatService.run`.+ chat_run_registry (`ChatRunRegistry`):+ Shared chat-run registry to spawn into.+ """+ self._bus = message_bus+ self._storage = storage+ self._chat_service = chat_service+ self._registry = chat_run_registry+ self._task: asyncio.Task | None = None++ async def __aenter__(self) -> Self:+ """Start the dispatcher loop and wait until its bus+ subscription is live.++ Also performs an initial drain right after subscription so+ wake-ups produced while this process was down (durable in+ the queue) are picked up immediately on startup.++ Returns:+ `Self`: This dispatcher instance.+ """+ ready = asyncio.Event()+ self._task = asyncio.create_task(+ self._loop(ready),+ name="wakeup-dispatcher",+ )+ await ready.wait()+ await self._drain_and_dispatch()+ return self++ async def __aexit__(self, *exc: object) -> None:+ """Cancel the dispatcher loop on context exit."""+ if self._task is None:+ return+ self._task.cancel()+ try:+ await self._task+ except asyncio.CancelledError:+ pass+ self._task = None++ # ------------------------------------------------------------------+ # Internals+ # ------------------------------------------------------------------++ async def _loop(self, ready: asyncio.Event) -> None:+ """Long-lived loop: subscribe to the signal channel and drain+ the queue on every received signal.++ Args:+ ready (`asyncio.Event`):+ Signalled after the underlying SUBSCRIBE completes.+ :meth:`start` blocks on this so callers can publish a+ wake-up immediately after start without racing.+ """+ try:+ async for _signal in self._bus.subscribe_wakeup_signal(+ on_ready=ready.set,+ ):+ await self._drain_and_dispatch()+ except Exception: # pylint: disable=broad-except+ logger.exception(+ "WakeupDispatcher loop crashed; subscription ended.",+ )++ async def _drain_and_dispatch(self) -> None:+ """Read up to a batch of wake-up entries and dispatch them."""+ try:+ entries = await self._bus.dequeue_wakeups(max_count=64)+ except Exception: # pylint: disable=broad-except+ logger.exception("WakeupDispatcher: dequeue_wakeups failed.")+ return++ for payload in entries:+ try:+ user_id = payload["user_id"]+ session_id = payload["session_id"]+ agent_id = payload["agent_id"]+ except (KeyError, TypeError):+ logger.warning(+ "WakeupDispatcher: skipping malformed wake-up entry %r",+ payload,+ )+ continue++ if await self._bus.session_is_running(session_id):+ continue++ # Orphan guard: the wake-up queue is unaware of session+ # lifecycle. A wake-up enqueued before the session was+ # deleted (e.g. by a BG task completion callback or a+ # schedule trigger) will still arrive here. Drop it+ # rather than letting ChatService.run crash on a missing+ # storage record.+ if (+ await self._storage.get_session(+ user_id,+ agent_id,+ session_id,+ )+ is None+ ):+ logger.warning(+ "WakeupDispatcher: dropping wake-up for session %s "+ "(agent %s, user %s) — session no longer exists in "+ "storage; the wake-up was likely enqueued before "+ "the session was deleted.",+ session_id,+ agent_id,+ user_id,+ )+ continue++ try:+ self._registry.spawn(+ self._chat_service.run(+ user_id=user_id,+ session_id=session_id,+ agent_id=agent_id,+ input_msg=None,+ ),+ session_id=session_id,+ name=f"wakeup-run:{session_id}",+ )+ except RuntimeError:+ # Another spawn won the race for this session in this+ # process; the existing run will drain the inbox.+ logger.debug(+ "WakeupDispatcher: skipping wake-up for session %s; "+ "a local run is already registered.",+ session_id,+ )diff --git a/src/agentscope/app/_router/__init__.py b/src/agentscope/app/_router/__init__.pyindex 358a5fcf4..73f2fb145 100644--- a/src/agentscope/app/_router/__init__.py+++ b/src/agentscope/app/_router/__init__.py@@ -1,7 +1,6 @@# -*- coding: utf-8 -*-"""App routers."""from ._agent import agent_router-from ._background_task import background_task_routerfrom ._chat import chat_routerfrom ._credential import credential_routerfrom ._schedule import schedule_router@@ -11,7 +10,6 @@ from ._workspace import workspace_router__all__ = ["agent_router",- "background_task_router","model_router","chat_router","credential_router",diff --git a/src/agentscope/app/_router/_agent.py b/src/agentscope/app/_router/_agent.pyindex b6cac72a5..6f3135c4d 100644--- a/src/agentscope/app/_router/_agent.py+++ b/src/agentscope/app/_router/_agent.py@@ -5,14 +5,15 @@ from datetime import datetimefrom fastapi import APIRouter, Depends, HTTPException, statusfrom ...agent import ContextConfig, ReActConfig-from .._deps import get_current_user_id, get_storage-from .._schema import (+from ..deps import get_current_user_id, get_session_service, get_storage+from ._schema import (AgentSchemaResponse,ListAgentsResponse,CreateAgentRequest,CreateAgentResponse,UpdateAgentRequest,)+from .._service import SessionServicefrom ..storage import StorageBase, AgentData, AgentRecordagent_router = APIRouter(@@ -188,20 +189,24 @@ async def update_agent(async def delete_agent(agent_id: str,user_id: str = Depends(get_current_user_id),- storage: StorageBase = Depends(get_storage),+ session_service: SessionService = Depends(get_session_service),) -> None:"""Permanently delete an agent configuration.+ Cascades through every session owned by this agent (and, for team+ leaders, through every worker session) — cancelling any in-flight+ chat run, removing storage records, and purging bus state.+Args:agent_id (`str`): The agent to delete.user_id (`str`): Injected authenticated user ID.- storage (`StorageBase`): Injected storage backend.+ session_service (`SessionService`): Injected session service.Raises:`HTTPException`: 404 if the agent does not exist or does not belongto the authenticated user."""- deleted = await storage.delete_agent(user_id, agent_id)+ deleted = await session_service.delete_agent(user_id, agent_id)if not deleted:raise HTTPException(status_code=status.HTTP_404_NOT_FOUND,diff --git a/src/agentscope/app/_router/_background_task.py b/src/agentscope/app/_router/_background_task.pydeleted file mode 100644index 413cf4287..000000000--- a/src/agentscope/app/_router/_background_task.py+++ /dev/null@@ -1,96 +0,0 @@-# -*- coding: utf-8 -*--"""Background-task router — list and cancel per-session background tasks."""-from fastapi import APIRouter, Depends, HTTPException, status--from .._deps import get_background_task_manager, get_current_user_id-from .._manager import BackgroundTaskManager-from .._schema import (- BackgroundTaskInfo,- ListBackgroundTasksResponse,-)--background_task_router = APIRouter(- prefix="/background-tasks",- tags=["background-tasks"],- responses={404: {"description": "Not found"}},-)---@background_task_router.get(- "/{session_id}",- response_model=ListBackgroundTasksResponse,- summary="List running background tasks for a session",-)-async def list_background_tasks(- session_id: str,- _: str = Depends(get_current_user_id),- bg_manager: BackgroundTaskManager = Depends(get_background_task_manager),-) -> ListBackgroundTasksResponse:- """List all currently running background tasks for *session_id*.-- Args:- session_id (`str`):- The session to query.- _ (`str`):- The authenticated user ID (unused, required for auth check).- bg_manager (`BackgroundTaskManager`):- The application-wide background task manager.-- Returns:- `ListBackgroundTasksResponse`:- Tasks belonging to *session_id* and their total count.- """- tasks = [- BackgroundTaskInfo(- task_id=task.id,- session_id=task.session_id,- agent_id=task.agent_id,- )- for task in bg_manager.tasks.values()- if task.session_id == session_id- ]- return ListBackgroundTasksResponse(tasks=tasks, total=len(tasks))---@background_task_router.delete(- "/{session_id}/{task_id}",- status_code=status.HTTP_204_NO_CONTENT,- summary="Cancel a running background task",-)-async def cancel_background_task(- session_id: str,- task_id: str,- _: str = Depends(get_current_user_id),- bg_manager: BackgroundTaskManager = Depends(get_background_task_manager),-) -> None:- """Cancel a running background task by *task_id*.-- The underlying asyncio task is cancelled immediately. The- ``on_complete`` callback will **not** be invoked, so no result- notification is injected into the agent context.-- Args:- session_id (`str`):- The owning session (used to scope the lookup).- task_id (`str`):- The task to cancel.- _ (`str`):- The authenticated user ID (unused, required for auth check).- bg_manager (`BackgroundTaskManager`):- The application-wide background task manager.-- Raises:- `HTTPException`:- 404 if *task_id* is not found or does not belong to- *session_id*.- """- task = bg_manager.tasks.get(task_id)- if task is None or task.session_id != session_id:- raise HTTPException(- status_code=status.HTTP_404_NOT_FOUND,- detail=f"Background task '{task_id}' not found for session "- f"'{session_id}'.",- )-- bg_manager.tasks.pop(task_id, None)- task.asyncio_task.cancel()diff --git a/src/agentscope/app/_router/_chat.py b/src/agentscope/app/_router/_chat.pyindex c04917039..f66b585ea 100644--- a/src/agentscope/app/_router/_chat.py+++ b/src/agentscope/app/_router/_chat.py@@ -1,28 +1,22 @@# -*- coding: utf-8 -*--"""Chat router providing a streaming SSE chat endpoint."""-from collections.abc import AsyncGenerator+"""Chat router — fire-and-forget trigger for chat runs.-from fastapi import APIRouter, Depends-from fastapi.responses import StreamingResponse+The endpoint no longer returns an SSE stream. Instead, it kicks off a+chat run as a background task and returns immediately. Events produced+by the run are published to the message bus and delivered to the+frontend via the long-lived ``GET /sessions/{sid}/stream`` SSE+connection provided by the session router.+"""+from fastapi import APIRouter, Depends, HTTPException, status-from .._deps import (+from ..deps import (+ get_chat_run_registry,+ get_chat_service,get_current_user_id,- get_extra_agent_middlewares,- get_extra_agent_tools,- get_session_manager,- get_storage,- get_workspace_manager,- get_background_task_manager,)-from .._manager import (- SessionManager,- WorkspaceManagerBase,- BackgroundTaskManager,-)-from .._schema import ChatRequest+from ._schema import ChatRequest, ChatTriggerResponse+from .._manager import ChatRunRegistryfrom .._service import ChatService-from .._types import AgentMiddlewareFactory, AgentToolFactory-from ..storage import StorageBasechat_router = APIRouter(prefix="/chat",@@ -31,100 +25,67 @@ chat_router = APIRouter()-async def _stream_events(- user_id: str,- request: ChatRequest,- storage: StorageBase,- session_manager: SessionManager,- workspace_manager: WorkspaceManagerBase,- background_task_manager: BackgroundTaskManager,- extra_agent_middlewares: AgentMiddlewareFactory | None,- extra_agent_tools: AgentToolFactory | None,-) -> AsyncGenerator[str, None]:- """Encode :class:`~agentscope.event.AgentEvent` objects as SSE frames.-- All execution + persistence lives in :class:`ChatService`; this is just- the HTTP-side encoder.-- Each yielded string is a complete SSE frame: ``data: <json>\\n\\n``.- """- service = ChatService(- storage=storage,- session_manager=session_manager,- background_task_manager=background_task_manager,- workspace_manager=workspace_manager,- extra_agent_middlewares=extra_agent_middlewares,- extra_agent_tools=extra_agent_tools,- )- async for event in service.stream_chat(- user_id=user_id,- session_id=request.session_id,- agent_id=request.agent_id,- input_msg=request.input,- ):- yield f"data: {event.model_dump_json()}\n\n"--@chat_router.post("/",- summary="Chat with an agent (streaming)",- response_description="Server-Sent Events stream of AgentEvent objects",+ response_model=ChatTriggerResponse,+ summary="Trigger a chat run (fire-and-forget)",)async def chat(request: ChatRequest,user_id: str = Depends(get_current_user_id),- storage: StorageBase = Depends(get_storage),- session_manager: SessionManager = Depends(get_session_manager),- workspace_manager: WorkspaceManagerBase = Depends(get_workspace_manager),- background_task_manager: BackgroundTaskManager = Depends(- get_background_task_manager,- ),- extra_agent_middlewares: AgentMiddlewareFactory- | None = Depends(- get_extra_agent_middlewares,- ),- extra_agent_tools: AgentToolFactory- | None = Depends(- get_extra_agent_tools,- ),-) -> StreamingResponse:- """Send a message to an agent and stream back the reply as SSE events.+ chat_service: ChatService = Depends(get_chat_service),+ chat_run_registry: ChatRunRegistry = Depends(get_chat_run_registry),+) -> ChatTriggerResponse:+ """Trigger a chat run for the specified session.++ The run executes as a background task tracked by+ :class:`ChatRunRegistry`. Events produced during the run are+ published to the message bus and delivered to any active+ ``GET /sessions/{session_id}/stream`` SSE subscriber. The caller+ does **not** receive events from this endpoint's response body.- The response is a ``text/event-stream`` where each frame carries a- JSON-serialised :class:`~agentscope.event.AgentEvent`.+ Accepts the same ``input`` payloads as before:++ - ``Msg`` / ``list[Msg]``: new user message(s).+ - ``UserConfirmResultEvent`` / ``ExternalExecutionResultEvent``:+ resume a paused tool call (human-in-the-loop).+ - ``None``: continue from current state.Args:request (`ChatRequest`):JSON body with ``agent_id``, ``session_id``, and ``input``.user_id (`str`):Injected user id.- storage (`StorageBase`):- Injected application storage backend.- session_manager (`SessionManager`):- Injected session manager.- workspace_manager (`WorkspaceManagerBase`):- Injected workspace manager.- background_task_manager (`BackgroundTaskManager`):- Injected background task manager.+ chat_service (`ChatService`):+ Injected application-wide chat service.+ chat_run_registry (`ChatRunRegistry`):+ Injected per-process chat-run registry.Returns:- `StreamingResponse`:- SSE stream of AgentEvent frames.+ `ChatTriggerResponse`:+ Confirms the run was scheduled.++ Raises:+ `HTTPException`:+ 409 if a chat run for this session is already in flight in+ this process (the registry enforces single-run-per-session)."""- return StreamingResponse(- _stream_events(- user_id,- request,- storage,- session_manager,- workspace_manager,- background_task_manager,- extra_agent_middlewares,- extra_agent_tools,- ),- media_type="text/event-stream",- headers={- "Cache-Control": "no-cache",- "X-Accel-Buffering": "no",- },+ try:+ chat_run_registry.spawn(+ chat_service.run(+ user_id=user_id,+ session_id=request.session_id,+ agent_id=request.agent_id,+ input_msg=request.input,+ ),+ session_id=request.session_id,+ )+ except RuntimeError as e:+ raise HTTPException(+ status_code=status.HTTP_409_CONFLICT,+ detail=str(e),+ ) from e+ return ChatTriggerResponse(+ status="started",+ session_id=request.session_id,)diff --git a/src/agentscope/app/_router/_credential.py b/src/agentscope/app/_router/_credential.pyindex 574269c4e..395af678c 100644--- a/src/agentscope/app/_router/_credential.py+++ b/src/agentscope/app/_router/_credential.py@@ -2,8 +2,8 @@"""Credential router — CRUD endpoints for API key credentials."""from fastapi import APIRouter, Depends, HTTPException, status-from .._deps import get_current_user_id, get_storage-from .._schema import (+from ..deps import get_current_user_id, get_storage+from ._schema import (CreateCredentialRequest,CreateCredentialResponse,ListCredentialsResponse,diff --git a/src/agentscope/app/_router/_model.py b/src/agentscope/app/_router/_model.pyindex 5a71c2742..b42943100 100644--- a/src/agentscope/app/_router/_model.py+++ b/src/agentscope/app/_router/_model.py@@ -3,7 +3,7 @@from fastapi import APIRouter, Depends, HTTPException, status-from .._schema import ListModelsResponse, ListModelsRequest+from ._schema import ListModelsResponse, ListModelsRequestfrom ...credential import CredentialFactorymodel_router = APIRouter(diff --git a/src/agentscope/app/_router/_schedule.py b/src/agentscope/app/_router/_schedule.pyindex ab8fc184a..dac15247c 100644--- a/src/agentscope/app/_router/_schedule.py+++ b/src/agentscope/app/_router/_schedule.py@@ -4,15 +4,21 @@ from datetime import datetimefrom fastapi import APIRouter, Depends, HTTPException, status-from .._deps import get_current_user_id, get_scheduler_manager, get_storagefrom .._manager import SchedulerManager-from .._schema import (+from ..deps import (+ get_current_user_id,+ get_scheduler_manager,+ get_session_service,+ get_storage,+)+from ._schema import (CreateScheduleRequest,CreateScheduleResponse,ListSchedulesResponse,ScheduleSessionsResponse,UpdateScheduleRequest,)+from .._service import SessionServicefrom ..storage import (StorageBase,ScheduleData,@@ -77,8 +83,8 @@ async def create_schedule(Raises:`HTTPException`: 404 if the specified agent does not exist."""- agents = await storage.list_agents(user_id)- if not any(a.id == body.agent_id for a in agents):+ agent = await storage.get_agent(user_id, body.agent_id)+ if agent is None or agent.user_id != user_id:raise HTTPException(status_code=status.HTTP_404_NOT_FOUND,detail=f"Agent '{body.agent_id}' not found.",@@ -171,23 +177,25 @@ async def update_schedule(async def delete_schedule(schedule_id: str,user_id: str = Depends(get_current_user_id),- storage: StorageBase = Depends(get_storage),+ session_service: SessionService = Depends(get_session_service),scheduler: SchedulerManager = Depends(get_scheduler_manager),) -> None:"""Permanently delete a schedule.- Removes the record from storage and unregisters the APScheduler job.+ Cancels any in-flight chat run for sessions this schedule has+ triggered, removes their records via the session service, and+ finally unregisters the APScheduler job.Args:schedule_id (`str`): ID of the schedule to delete.user_id (`str`): Authenticated user ID.- storage (`StorageBase`): Storage instance.+ session_service (`SessionService`): Injected session service.scheduler (`SchedulerManager`): Scheduler manager.Raises:`HTTPException`: 404 if the schedule does not exist."""- deleted = await storage.delete_schedule(user_id, schedule_id)+ deleted = await session_service.delete_schedule(user_id, schedule_id)if not deleted:raise HTTPException(status_code=status.HTTP_404_NOT_FOUND,diff --git a/src/agentscope/app/_schema/__init__.py b/src/agentscope/app/_router/_schema/__init__.pysimilarity index 88%rename from src/agentscope/app/_schema/__init__.pyrename to src/agentscope/app/_router/_schema/__init__.pyindex 57677d53d..e9132450c 100644--- a/src/agentscope/app/_schema/__init__.py+++ b/src/agentscope/app/_router/_schema/__init__.py@@ -1,7 +1,7 @@# -*- coding: utf-8 -*-"""Schema models for the agent service."""-from ._chat import ChatRequest+from ._chat import ChatRequest, ChatTriggerResponsefrom ._model import ListModelsResponse, ListModelsRequestfrom ._schedule import (CreateScheduleRequest,@@ -17,10 +17,6 @@ from ._agent import (CreateAgentResponse,UpdateAgentRequest,)-from ._background_task import (- ListBackgroundTasksResponse,- BackgroundTaskInfo,-)from ._credential import (CreateCredentialRequest,CreateCredentialResponse,@@ -34,6 +30,9 @@ from ._session import (UpdateSessionRequest,ListSessionsResponse,ListMessagesResponse,+ SessionView,+ TeamDetailResponse,+ TeamMemberView,)__all__ = [@@ -44,11 +43,9 @@ __all__ = ["CreateAgentResponse","UpdateAgentRequest","ListSchedulesResponse",- # Background Task- "ListBackgroundTasksResponse",- "BackgroundTaskInfo",# Chat"ChatRequest",+ "ChatTriggerResponse",# Credential"CreateCredentialRequest","CreateCredentialResponse",@@ -70,4 +67,7 @@ __all__ = ["UpdateSessionRequest","ListSessionsResponse","ListMessagesResponse",+ "SessionView",+ "TeamDetailResponse",+ "TeamMemberView",]diff --git a/src/agentscope/app/_schema/_agent.py b/src/agentscope/app/_router/_schema/_agent.pysimilarity index 96%rename from src/agentscope/app/_schema/_agent.pyrename to src/agentscope/app/_router/_schema/_agent.pyindex a252b653d..4dc396cef 100644--- a/src/agentscope/app/_schema/_agent.py+++ b/src/agentscope/app/_router/_schema/_agent.py@@ -2,8 +2,8 @@"""Request / response schemas for the agent router."""from pydantic import BaseModel, Field-from ...agent import ContextConfig, ReActConfig-from ..storage import AgentRecord+from ....agent import ContextConfig, ReActConfig+from ...storage import AgentRecordclass CreateAgentRequest(BaseModel):diff --git a/src/agentscope/app/_schema/_chat.py b/src/agentscope/app/_router/_schema/_chat.pysimilarity index 50%rename from src/agentscope/app/_schema/_chat.pyrename to src/agentscope/app/_router/_schema/_chat.pyindex 65b4d954b..5bb68a3ea 100644--- a/src/agentscope/app/_schema/_chat.py+++ b/src/agentscope/app/_router/_schema/_chat.py@@ -3,8 +3,8 @@from pydantic import BaseModel, Field-from ...message import Msg-from ...event import UserConfirmResultEvent, ExternalExecutionResultEvent+from ....message import Msg+from ....event import UserConfirmResultEvent, ExternalExecutionResultEventclass ChatRequest(BaseModel):@@ -27,3 +27,19 @@ class ChatRequest(BaseModel):) = Field(description="The input message(s), or agent event, or None.",)+++class ChatTriggerResponse(BaseModel):+ """Response body for the fire-and-forget chat trigger.++ Confirms that the chat run was scheduled. Events produced by the+ run arrive separately via the session's SSE stream endpoint.+ """++ status: str = Field(+ default="started",+ description='Always ``"started"`` when the trigger succeeded.',+ )+ session_id: str = Field(+ description="Echo of the session id the run was started for.",+ )diff --git a/src/agentscope/app/_schema/_credential.py b/src/agentscope/app/_router/_schema/_credential.pysimilarity index 96%rename from src/agentscope/app/_schema/_credential.pyrename to src/agentscope/app/_router/_schema/_credential.pyindex ee91c55a4..249bbd3b3 100644--- a/src/agentscope/app/_schema/_credential.py+++ b/src/agentscope/app/_router/_schema/_credential.py@@ -2,7 +2,7 @@"""Request / response schemas for the credential router."""from pydantic import BaseModel, Field-from ..storage import CredentialRecord+from ...storage import CredentialRecordclass CreateCredentialRequest(BaseModel):diff --git a/src/agentscope/app/_schema/_mcp.py b/src/agentscope/app/_router/_schema/_mcp.pysimilarity index 98%rename from src/agentscope/app/_schema/_mcp.pyrename to src/agentscope/app/_router/_schema/_mcp.pyindex 072b5513e..023f94132 100644--- a/src/agentscope/app/_schema/_mcp.py+++ b/src/agentscope/app/_router/_schema/_mcp.py@@ -4,7 +4,7 @@ from enum import Enumfrom pydantic import BaseModel, Field-from ...mcp import StdioMCPConfig, HttpMCPConfig+from ....mcp import StdioMCPConfig, HttpMCPConfigclass ConnectionScope(str, Enum):diff --git a/src/agentscope/app/_schema/_model.py b/src/agentscope/app/_router/_schema/_model.pysimilarity index 94%rename from src/agentscope/app/_schema/_model.pyrename to src/agentscope/app/_router/_schema/_model.pyindex 21d5f93ee..23c24decc 100644--- a/src/agentscope/app/_schema/_model.py+++ b/src/agentscope/app/_router/_schema/_model.py@@ -3,7 +3,7 @@from pydantic import BaseModel, Field-from ...model import ModelCard+from ....model import ModelCardclass ListModelsResponse(BaseModel):diff --git a/src/agentscope/app/_schema/_schedule.py b/src/agentscope/app/_router/_schema/_schedule.pysimilarity index 98%rename from src/agentscope/app/_schema/_schedule.pyrename to src/agentscope/app/_router/_schema/_schedule.pyindex 9531c9d31..472b57111 100644--- a/src/agentscope/app/_schema/_schedule.py+++ b/src/agentscope/app/_router/_schema/_schedule.py@@ -2,12 +2,12 @@"""Request / response schemas for the schedule router."""from pydantic import BaseModel, Field-from ..storage import (+from ...storage import (ScheduleRecord,SessionRecord,ChatModelConfig,)-from ...permission import PermissionMode+from ....permission import PermissionModeclass CreateScheduleRequest(BaseModel):diff --git a/src/agentscope/app/_router/_schema/_session.py b/src/agentscope/app/_router/_schema/_session.pynew file mode 100644index 000000000..260af5561--- /dev/null+++ b/src/agentscope/app/_router/_schema/_session.py@@ -0,0 +1,157 @@+# -*- coding: utf-8 -*-+"""Request / response schemas for the session router."""+from pydantic import BaseModel, Field++from ....permission import PermissionMode+from ...storage import AgentRecord, ChatModelConfig, SessionRecord, TeamRecord+++class TeamMemberView(BaseModel):+ """One row in :attr:`TeamDetailResponse.members`.++ Pairs each member's :class:`AgentRecord` with its single+ ``session_id`` so the UI can subscribe to the worker's chat+ stream without a separate lookup.+ """++ agent: AgentRecord = Field(+ description="The worker agent record.",+ )+ session_id: str | None = Field(+ default=None,+ description=(+ "The worker's session id. ``None`` if the agent is in an "+ "inconsistent state (worker without a session)."+ ),+ )+++class TeamDetailResponse(BaseModel):+ """Resolved team detail embedded inside :class:`SessionView.team`."""++ team: TeamRecord = Field(description="The team record.")+ leader_agent: AgentRecord | None = Field(+ default=None,+ description=(+ "Leader's agent record (resolved from the team's "+ "``session_id`` → session.agent_id)."+ ),+ )+ members: list[TeamMemberView] = Field(+ default_factory=list,+ description=(+ "Worker agents listed in :attr:`TeamData.member_ids`, each "+ "paired with its single session id when available."+ ),+ )+++class CreateSessionRequest(BaseModel):+ """Request body for creating a new session."""++ agent_id: str = Field(description="Agent this session belongs to.")+ workspace_id: str | None = Field(+ default=None,+ description="Workspace this session belongs to.",+ )+ name: str | None = Field(+ default=None,+ description="Display name. Defaults to current datetime if omitted.",+ )+ chat_model_config: ChatModelConfig | None = Field(+ default=None,+ description="Model provider and parameters. "+ "Can be set later via PATCH.",+ )+ fallback_chat_model_config: ChatModelConfig | None = Field(+ default=None,+ description="Fallback model used when the primary model fails. "+ "Can be set later via PATCH.",+ )+++class CreateSessionResponse(BaseModel):+ """Response body after creating a session."""++ session_id: str = Field(description="Server-assigned session identifier.")+++class UpdateSessionRequest(BaseModel):+ """Request body for updating an existing session.++ Omit any field to keep its current value.+ """++ name: str | None = Field(+ default=None,+ description="New display name.",+ )+ chat_model_config: ChatModelConfig | None = Field(+ default=None,+ description="New model configuration. "+ "Replaces the existing one entirely. "+ "Pass null to clear; omit to leave unchanged.",+ )+ fallback_chat_model_config: ChatModelConfig | None = Field(+ default=None,+ description="New fallback model configuration. "+ "Pass null to clear; omit to leave unchanged.",+ )+ permission_mode: PermissionMode | None = Field(+ default=None,+ description="New permission mode for the session.",+ )+++class SessionView(BaseModel):+ """Per-session bundle with everything the frontend needs to+ render either the list view or open a session.++ Bundles three orthogonal pieces of information so opening a+ session does not require a waterfall of follow-up requests:++ - the persisted :class:`SessionRecord` itself (config + state),+ - whether the session has an active chat run right now,+ - the team detail (resolved leader + members) when the session+ participates in a team.++ Messages are intentionally **not** included here — they are+ paginated separately via ``GET /sessions/{id}/messages``.+ """++ session: SessionRecord = Field(+ description=(+ "The persisted session record. Includes ``state`` "+ "(``permission_context`` / ``tool_context`` / "+ "``tasks_context``) inline."+ ),+ )+ is_running: bool = Field(+ description="Whether a chat run is currently active on this session.",+ )+ team: TeamDetailResponse | None = Field(+ default=None,+ description=(+ "Resolved team detail when ``session.team_id`` is set "+ "(leader agent + member agents with their session ids). "+ "``None`` when the session does not participate in any team."+ ),+ )+++class ListSessionsResponse(BaseModel):+ """Response body for listing sessions."""++ sessions: list[SessionView] = Field(+ description="Session views (record + is_running + team).",+ )+ total: int = Field(description="Total number of sessions.")+++class ListMessagesResponse(BaseModel):+ """Response body for listing messages in a session."""++ messages: list = Field(description="Messages in chronological order.")+ is_running: bool = Field(+ description="Whether the session is currently running.",+ )diff --git a/src/agentscope/app/_router/_session.py b/src/agentscope/app/_router/_session.pyindex 344c00e55..e8846f737 100644--- a/src/agentscope/app/_router/_session.py+++ b/src/agentscope/app/_router/_session.py@@ -1,25 +1,87 @@# -*- coding: utf-8 -*--"""Session router — create, list, update, delete, and get messages."""+"""Session router — create, list, update, delete, stream, and get messages."""+import asyncio+import jsonimport uuid+from typing import AsyncGeneratorfrom fastapi import APIRouter, Depends, HTTPException, Query, status+from fastapi.responses import StreamingResponse-from .._deps import get_current_user_id, get_session_manager, get_storage-from .._manager import SessionManager-from .._schema import (+from ..deps import (+ get_current_user_id,+ get_message_bus,+ get_session_service,+ get_storage,+)+from ._schema import (CreateSessionRequest,CreateSessionResponse,ListMessagesResponse,ListSessionsResponse,+ SessionView,+ TeamDetailResponse,+ TeamMemberView,UpdateSessionRequest,)+from ..message_bus import MessageBus+from .._service import SessionServicefrom ..storage import (+ AgentRecord,ChatModelConfig,SessionConfig,SessionRecord,StorageBase,+ TeamRecord,)++async def _build_team_detail(+ storage: StorageBase,+ user_id: str,+ team: TeamRecord,+) -> TeamDetailResponse:+ """Resolve a team's leader agent + member agents into a+ :class:`TeamDetailResponse` for the session list endpoint.++ Args:+ storage (`StorageBase`):+ Application storage. Used to look up the leader session,+ each member agent, and each member's session.+ user_id (`str`):+ The owner user id.+ team (`TeamRecord`):+ The team to resolve. Caller has already loaded it.++ Returns:+ `TeamDetailResponse`:+ The team plus its resolved leader and member agents (each+ member paired with its session id when available).+ """+ leader_agent: AgentRecord | None = None+ leader_session = await storage.get_session(user_id, "", team.session_id)+ if leader_session is not None:+ leader_agent = await storage.get_agent(+ user_id,+ leader_session.agent_id,+ )++ members: list[TeamMemberView] = []+ for member_id in team.data.member_ids:+ agent = await storage.get_agent(user_id, member_id)+ if agent is None:+ continue+ sessions = await storage.list_sessions(user_id, member_id)+ session_id = sessions[0].id if sessions else None+ members.append(TeamMemberView(agent=agent, session_id=session_id))++ return TeamDetailResponse(+ team=team,+ leader_agent=leader_agent,+ members=members,+ )++session_router = APIRouter(prefix="/sessions",tags=["sessions"],@@ -64,31 +126,66 @@ async def list_sessions(agent_id: str = Query(description="Filter sessions by agent ID."),user_id: str = Depends(get_current_user_id),storage: StorageBase = Depends(get_storage),+ message_bus: MessageBus = Depends(get_message_bus),) -> ListSessionsResponse:- """Return all sessions belonging to the authenticated user for a given- agent.+ """Return all sessions for an agent as enriched+ :class:`SessionView` entries.++ Each entry bundles three things the chat UI needs to render+ without follow-up requests: the session record (incl.+ ``state``), whether a chat run is currently active, and — when+ the session participates in a team — the resolved team detail+ (leader agent + member agents with their session ids).Args:- agent_id (`str`): Agent whose sessions to list.- user_id (`str`): Injected authenticated user ID.- storage (`StorageBase`): Injected storage backend.+ agent_id (`str`):+ Agent whose sessions to list.+ user_id (`str`):+ Injected authenticated user ID.+ storage (`StorageBase`):+ Injected storage backend.+ message_bus (`MessageBus`):+ Injected message bus (used for ``session_is_running``).Returns:- `ListSessionsResponse`: All matching session records and their count.+ `ListSessionsResponse`:+ Enriched session views and their count.Raises:- `HTTPException`: 404 if the agent does not exist or does not belong- to the authenticated user.+ `HTTPException`: 404 if the agent does not exist or does not+ belong to the authenticated user."""- agents = await storage.list_agents(user_id)- if not any(a.id == agent_id for a in agents):+ # Direct ownership check via get_agent — handles both source=user+ # and source=team agents (the latter aren't returned by+ # storage.list_agents but are still owned by the user; reachable+ # via team navigation).+ agent = await storage.get_agent(user_id, agent_id)+ if agent is None or agent.user_id != user_id:raise HTTPException(status_code=status.HTTP_404_NOT_FOUND,detail=f"Agent '{agent_id}' not found.",)sessions = await storage.list_sessions(user_id, agent_id)- return ListSessionsResponse(sessions=sessions, total=len(sessions))+ views: list[SessionView] = []+ for session in sessions:+ team_detail = None+ if session.team_id:+ team_record = await storage.get_team(user_id, session.team_id)+ if team_record is not None:+ team_detail = await _build_team_detail(+ storage,+ user_id,+ team_record,+ )+ views.append(+ SessionView(+ session=session,+ is_running=await message_bus.session_is_running(session.id),+ team=team_detail,+ ),+ )+ return ListSessionsResponse(sessions=views, total=len(views))@session_router.post(@@ -120,8 +217,8 @@ async def create_session(`HTTPException`: 404 if the agent or credential does not exist ordoes not belong to the authenticated user."""- agents = await storage.list_agents(user_id)- if not any(a.id == body.agent_id for a in agents):+ agent = await storage.get_agent(user_id, body.agent_id)+ if agent is None or agent.user_id != user_id:raise HTTPException(status_code=status.HTTP_404_NOT_FOUND,detail=f"Agent '{body.agent_id}' not found.",@@ -156,20 +253,31 @@ async def delete_session(session_id: str,agent_id: str = Query(description="Agent the session belongs to."),user_id: str = Depends(get_current_user_id),- storage: StorageBase = Depends(get_storage),+ session_service: SessionService = Depends(get_session_service),) -> None:"""Permanently delete a session and all its associated state.+ Cancels any in-flight chat run for this session (and for every+ worker session if this one is a team leader) before dropping+ storage records and bus state. The cancel path is cross-process:+ whichever worker is actually running the session will receive the+ cancel broadcast and abort.+Args:session_id (`str`): The session to delete.+ agent_id (`str`): The agent the session belongs to.user_id (`str`): Injected authenticated user ID.- storage (`StorageBase`): Injected storage backend.+ session_service (`SessionService`): Injected session service.Raises:`HTTPException`: 404 if the session does not exist or does not belongto the authenticated user."""- deleted = await storage.delete_session(user_id, agent_id, session_id)+ deleted = await session_service.delete_session(+ user_id,+ agent_id,+ session_id,+ )if not deleted:raise HTTPException(status_code=status.HTTP_404_NOT_FOUND,@@ -265,7 +373,7 @@ async def list_messages(limit: int = Query(50, ge=1, le=200, description="Max messages."),user_id: str = Depends(get_current_user_id),storage: StorageBase = Depends(get_storage),- session_manager: SessionManager = Depends(get_session_manager),+ message_bus: MessageBus = Depends(get_message_bus),) -> ListMessagesResponse:"""Return persisted messages for a session.@@ -276,7 +384,7 @@ async def list_messages(limit: Maximum number of messages to return.user_id: Injected authenticated user ID.storage: Injected storage backend.- session_manager: Injected session manager.+ message_bus: Injected message bus.Returns:Messages and running status.@@ -296,5 +404,128 @@ async def list_messages()return ListMessagesResponse(messages=messages,- is_running=session_manager.is_running(session_id),+ is_running=await message_bus.session_is_running(session_id),+ )+++# ----------------------------------------------------------------------+# Stream: live SSE connection for session events+# ----------------------------------------------------------------------++_HEARTBEAT_INTERVAL_SECS = 30+# Interval between SSE heartbeat comment frames (``:\\n\\n``).+++@session_router.get(+ "/{session_id}/stream",+ summary="Subscribe to a session's event stream (SSE)",+ response_description="Server-Sent Events stream of AgentEvent objects",+)+async def stream_session_events(+ session_id: str,+ agent_id: str = Query(description="Agent the session belongs to."),+ user_id: str = Depends(get_current_user_id),+ storage: StorageBase = Depends(get_storage),+ message_bus: MessageBus = Depends(get_message_bus),+) -> StreamingResponse:+ """Subscribe to a session's live event stream.++ Returns a ``text/event-stream`` that first replays any buffered+ events from the current run's replay log (if a run is in progress+ or just finished), then streams live events as they are produced+ by :meth:`ChatService.run`. The connection stays open+ until the client disconnects — subsequent runs on the same session+ are delivered over the same connection.++ A heartbeat comment frame (``:\\n\\n``) is sent every 30 seconds to+ keep the connection alive through reverse proxies.++ Args:+ session_id (`str`):+ The session to subscribe to.+ agent_id (`str`):+ The agent that owns the session (used for ownership+ validation).+ user_id (`str`):+ Injected authenticated user id.+ storage (`StorageBase`):+ Injected storage backend (ownership check only).+ message_bus (`MessageBus`):+ Injected message bus (replay + live subscription).++ Returns:+ `StreamingResponse`:+ SSE stream of AgentEvent frames + periodic heartbeats.+ """+ existing = await storage.get_session(user_id, agent_id, session_id)+ if existing is None:+ raise HTTPException(+ status_code=status.HTTP_404_NOT_FOUND,+ detail=f"Session '{session_id}' not found.",+ )++ async def _sse_generator() -> AsyncGenerator[str, None]:+ # 1. Replay buffered events from the current run (if any).+ for _entry_id, event in await message_bus.session_read_events(+ session_id,+ ):+ yield f"data: {json.dumps(event)}\n\n"++ # 2. Live subscribe via a background feeder task that pushes+ # events into a queue. The main loop reads from the queue+ # with a timeout so we can interleave heartbeat frames.+ #+ # We avoid calling ``wait_for(__anext__())`` on the async+ # generator directly because cancelling a suspended+ # ``__anext__`` leaves the generator in a "running" state+ # that prevents ``aclose()`` from working.+ queue: asyncio.Queue[dict | None] = asyncio.Queue()++ async def _feeder() -> None:+ """Read from the bus subscription and forward to the queue.++ Pushes ``None`` as a sentinel when the subscription ends+ (which in practice only happens if the bus shuts down).+ """+ try:+ async for evt in message_bus.session_subscribe_events(+ session_id,+ ):+ await queue.put(evt)+ except asyncio.CancelledError:+ pass+ finally:+ await queue.put(None)++ feeder_task = asyncio.create_task(+ _feeder(),+ name=f"sse-feeder:{session_id}",+ )++ try:+ while True:+ try:+ item = await asyncio.wait_for(+ queue.get(),+ timeout=_HEARTBEAT_INTERVAL_SECS,+ )+ if item is None:+ break+ yield f"data: {json.dumps(item)}\n\n"+ except asyncio.TimeoutError:+ yield ":\n\n"+ finally:+ feeder_task.cancel()+ try:+ await feeder_task+ except asyncio.CancelledError:+ pass++ return StreamingResponse(+ _sse_generator(),+ media_type="text/event-stream",+ headers={+ "Cache-Control": "no-cache",+ "X-Accel-Buffering": "no",+ },)diff --git a/src/agentscope/app/_router/_workspace.py b/src/agentscope/app/_router/_workspace.pyindex f663b9e0f..eb3236cce 100644--- a/src/agentscope/app/_router/_workspace.py+++ b/src/agentscope/app/_router/_workspace.py@@ -3,12 +3,12 @@from fastapi import APIRouter, Depends, HTTPException, Query, statusfrom pydantic import BaseModel, Field-from .._deps import (+from ..deps import (get_current_user_id,get_storage,get_workspace_manager,)-from .._manager import WorkspaceManagerBase+from ..workspace_manager import WorkspaceManagerBasefrom ..storage import StorageBasefrom ...mcp import MCPClientfrom ...skill import Skilldiff --git a/src/agentscope/app/_schema/_background_task.py b/src/agentscope/app/_schema/_background_task.pydeleted file mode 100644index 643e69c1c..000000000--- a/src/agentscope/app/_schema/_background_task.py+++ /dev/null@@ -1,20 +0,0 @@-# -*- coding: utf-8 -*--"""Request / response schemas for the background-task router."""-from pydantic import BaseModel, Field---class BackgroundTaskInfo(BaseModel):- """Summary of a single running background task."""-- task_id: str = Field(description="Unique task identifier.")- session_id: str = Field(description="Session that owns this task.")- agent_id: str = Field(description="Agent that triggered this task.")---class ListBackgroundTasksResponse(BaseModel):- """Response body for listing background tasks of a session."""-- tasks: list[BackgroundTaskInfo] = Field(- description="Running background tasks for the requested session.",- )- total: int = Field(description="Total number of running tasks.")diff --git a/src/agentscope/app/_schema/_session.py b/src/agentscope/app/_schema/_session.pydeleted file mode 100644index ea9aa1a5c..000000000--- a/src/agentscope/app/_schema/_session.py+++ /dev/null@@ -1,79 +0,0 @@-# -*- coding: utf-8 -*--"""Request / response schemas for the session router."""-from pydantic import BaseModel, Field--from ...permission import PermissionMode-from ..storage._model._session import ChatModelConfig, SessionRecord---class CreateSessionRequest(BaseModel):- """Request body for creating a new session."""-- agent_id: str = Field(description="Agent this session belongs to.")- workspace_id: str | None = Field(- default=None,- description="Workspace this session belongs to.",- )- name: str | None = Field(- default=None,- description="Display name. Defaults to current datetime if omitted.",- )- chat_model_config: ChatModelConfig | None = Field(- default=None,- description="Model provider and parameters. "- "Can be set later via PATCH.",- )- fallback_chat_model_config: ChatModelConfig | None = Field(- default=None,- description="Fallback model used when the primary model fails. "- "Can be set later via PATCH.",- )---class CreateSessionResponse(BaseModel):- """Response body after creating a session."""-- session_id: str = Field(description="Server-assigned session identifier.")---class UpdateSessionRequest(BaseModel):- """Request body for updating an existing session.-- Omit any field to keep its current value.- """-- name: str | None = Field(- default=None,- description="New display name.",- )- chat_model_config: ChatModelConfig | None = Field(- default=None,- description="New model configuration. "- "Replaces the existing one entirely. "- "Pass null to clear; omit to leave unchanged.",- )- fallback_chat_model_config: ChatModelConfig | None = Field(- default=None,- description="New fallback model configuration. "- "Pass null to clear; omit to leave unchanged.",- )- permission_mode: PermissionMode | None = Field(- default=None,- description="New permission mode for the session.",- )---class ListSessionsResponse(BaseModel):- """Response body for listing sessions."""-- sessions: list[SessionRecord] = Field(description="Session records.")- total: int = Field(description="Total number of sessions.")---class ListMessagesResponse(BaseModel):- """Response body for listing messages in a session."""-- messages: list = Field(description="Messages in chronological order.")- is_running: bool = Field(- description="Whether the session is currently running.",- )diff --git a/src/agentscope/app/_service/__init__.py b/src/agentscope/app/_service/__init__.pyindex 25d73ebc1..280b55644 100644--- a/src/agentscope/app/_service/__init__.py+++ b/src/agentscope/app/_service/__init__.py@@ -2,6 +2,12 @@"""Service layer for the AgentScope app."""from ._chat import ChatServicefrom ._model import get_model-from ._agent import get_agent+from ._session import SessionService+from ._toolkit import get_toolkit-__all__ = ["ChatService", "get_model", "get_agent"]+__all__ = [+ "ChatService",+ "SessionService",+ "get_model",+ "get_toolkit",+]diff --git a/src/agentscope/app/_service/_agent.py b/src/agentscope/app/_service/_agent.pydeleted file mode 100644index 8958cd7a8..000000000--- a/src/agentscope/app/_service/_agent.py+++ /dev/null@@ -1,152 +0,0 @@-# -*- coding: utf-8 -*--"""The agent service layer, responsible for getting the agent class."""-from fastapi import HTTPException--from ._model import get_model-from .._manager import WorkspaceManagerBase-from .._types import AgentMiddlewareFactory, AgentToolFactory-from ..storage import StorageBase-from ...agent import Agent, ModelConfig-from ...middleware import MiddlewareBase-from ...tool import Toolkit---async def get_agent(- storage: StorageBase,- workspace_manager: WorkspaceManagerBase,- user_id: str,- agent_id: str,- session_id: str,- middlewares: list[MiddlewareBase] | None = None,- extra_agent_middlewares: AgentMiddlewareFactory | None = None,- extra_agent_tools: AgentToolFactory | None = None,-) -> Agent:- """Assemble the agent for ``(user_id, agent_id, session_id)``.-- Loads the agent configuration and session state from storage, resolves- the chat model, materialises the per-session workspace (tools / skills- / MCPs), and wires in any caller-supplied middlewares plus extras- produced by the supplied factories.-- Args:- storage (`StorageBase`):- Application storage backend used to fetch the agent record and- session record.- workspace_manager (`WorkspaceManagerBase`):- Workspace manager used to obtain the per-session workspace.- user_id (`str`):- The authenticated caller's user ID.- agent_id (`str`):- The agent record ID to assemble.- session_id (`str`):- The session ID whose persisted state will be restored onto the- agent.- middlewares (`list[MiddlewareBase] | None`, optional):- Framework-supplied middlewares (e.g.- ``ToolOffloadMiddleware``) to attach to the agent. Extras- produced by ``extra_agent_middlewares`` are appended to this- list.- extra_agent_middlewares (`AgentMiddlewareFactory | None`, optional):- Async factory ``(user_id, agent_id, session_id) -> list[- MiddlewareBase]``. Awaited once per call; results are- appended to ``middlewares``.- extra_agent_tools (`AgentToolFactory | None`, optional):- Async factory ``(user_id, agent_id, session_id) -> list[- ToolBase]``. Awaited once per call; results are merged into- the toolkit's ``"basic"`` group alongside workspace tools.-- Returns:- `Agent`: The fully-assembled agent ready to reply.- """-- # ====================================================================- # Step 1. Get the agent configuration- # ====================================================================- agent_record = await storage.get_agent(- user_id=user_id,- agent_id=agent_id,- )-- cfg = agent_record.data-- # ====================================================================- # Step 2. Get the agent state from the session- # ====================================================================- # TODO: get_session需要agent_id- session_record = await storage.get_session(user_id, agent_id, session_id)-- # ====================================================================- # Step 2.1. Get the model instance- # ====================================================================- model_cfg = session_record.config.chat_model_config-- if not model_cfg:- # Raise error to the frontend- raise HTTPException(- status_code=404,- detail=f"No model configuration found for agent {agent_id}",- )-- model = await get_model(user_id, model_cfg, storage)-- # ====================================================================- # Step 2.1.1. Build the optional fallback model- # ====================================================================- # The fallback model is invoked by the agent when the primary model- # fails. ``None`` means no fallback is configured for this session.- fallback_cfg = session_record.config.fallback_chat_model_config- fallback_model = (- await get_model(user_id, fallback_cfg, storage)- if fallback_cfg is not None- else None- )-- # ====================================================================- # Step 2.2. Get the session data, i.e. the agent state- # ====================================================================- agent_state = session_record.state- agent_state.session_id = session_id-- # ====================================================================- # Step 2.3. Get the workspace from the manager- # ====================================================================- workspace = await workspace_manager.get_workspace(- user_id,- agent_id,- session_id,- session_record.config.workspace_id,- )-- # ====================================================================- # Step 3. Resolve caller-supplied factories for tools and middlewares- # ====================================================================- tools = await workspace.list_tools()- if extra_agent_tools is not None:- tools = tools + await extra_agent_tools(- user_id,- agent_id,- session_id,- )-- final_middlewares = list(middlewares or [])- if extra_agent_middlewares is not None:- final_middlewares.extend(- await extra_agent_middlewares(user_id, agent_id, session_id),- )-- return Agent(- name=cfg.name,- system_prompt=cfg.system_prompt,- model=model,- toolkit=Toolkit(- tools=tools,- skills_or_loaders=await workspace.list_skills(),- mcps=await workspace.list_mcps(),- ),- model_config=ModelConfig(fallback_model=fallback_model),- context_config=cfg.context_config,- react_config=cfg.react_config,- state=agent_state,- middlewares=final_middlewares,- offloader=workspace,- )diff --git a/src/agentscope/app/_service/_chat.py b/src/agentscope/app/_service/_chat.pyindex 7c49fe308..7bbb41e0d 100644--- a/src/agentscope/app/_service/_chat.py+++ b/src/agentscope/app/_service/_chat.py@@ -1,46 +1,63 @@# -*- coding: utf-8 -*-"""Chat service encapsulating agent execution + persistence logic.-This is the single source of truth for running an agent against a session.-Both the HTTP chat endpoint and the schedule trigger call-:meth:`ChatService.stream_chat`, guaranteeing identical message-persistence, ``ToolOffloadMiddleware`` wiring, and state handling.+This is the single source of truth for running an agent against a+session. Both the HTTP chat endpoint and the wakeup dispatcher call+:meth:`ChatService.run`, guaranteeing identical message persistence,+middleware wiring, and state handling.++Events produced by the agent are not exposed back through this method+— they are published to the message bus inside the run, and any client+that wants them subscribes through the+``GET /sessions/{sid}/stream`` SSE endpoint."""-from collections.abc import AsyncGenerator+from fastapi import HTTPException+from ..message_bus import MessageBusfrom ..storage import StorageBase-from .._manager import (- BackgroundTaskManager,- SessionManager,- WorkspaceManagerBase,+from .._manager import BackgroundTaskManager, SchedulerManager+from ..workspace_manager import WorkspaceManagerBase+from ..middleware import (+ InboxMiddleware,+ StateChangeMiddleware,+ ToolOffloadMiddleware,)-from .._middleware import ToolOffloadMiddlewarefrom .._types import AgentMiddlewareFactory, AgentToolFactory-from ._agent import get_agent+from ._model import get_model+from ._toolkit import get_toolkit+from ..._logging import logger+from ...agent import Agent, ModelConfigfrom ...event import (- AgentEvent,ReplyStartEvent,UserConfirmResultEvent,ExternalExecutionResultEvent,)-from ...message import AssistantMsg, Msg+from ...message import AssistantMsg, Msg, ToolCallStateclass ChatService:- """Run an agent against a session, streaming events while persisting- input/reply messages and updated agent state.+ """Run an agent against a session, persisting input/reply messages+ and updated agent state.- Shared by the HTTP chat endpoint and the schedule trigger so both+ Shared by the HTTP chat endpoint and the wakeup dispatcher so bothpaths go through identical validation, assembly, and persistence.++ Session serialisation and event fan-out are both handled by the+ :class:`MessageBus`: :meth:`bus.session_run` acquires a distributed+ lock (guaranteeing at most one chat run per session across all+ processes), and :meth:`bus.session_publish_event` writes each event+ to both a replay log (for late-joining subscribers) and a live+ Pub/Sub channel."""def __init__(self,storage: StorageBase,- session_manager: SessionManager,- background_task_manager: BackgroundTaskManager,workspace_manager: WorkspaceManagerBase,+ scheduler_manager: SchedulerManager,+ background_task_manager: BackgroundTaskManager,+ message_bus: MessageBus,extra_agent_middlewares: AgentMiddlewareFactory | None = None,extra_agent_tools: AgentToolFactory | None = None,) -> None:@@ -49,15 +66,22 @@ class ChatService:Args:storage (`StorageBase`):Application storage backend.- session_manager (`SessionManager`):- Per-session run serializer and event buffer for SSE- subscribers.- background_task_manager (`BackgroundTaskManager`):- Tracks offloaded long-running tool tasks and queues their- results for re-injection on the next reasoning step.workspace_manager (`WorkspaceManagerBase`):Provides per-session workspace (tools, MCPs, skills) usedduring agent assembly.+ scheduler_manager (`SchedulerManager`):+ Application scheduler — passed through to+ :func:`get_toolkit` so the agent toolkit gets the four+ ``Schedule*`` tools.+ background_task_manager (`BackgroundTaskManager`):+ Tracks offloaded long-running tool tasks. Also provides+ the :class:`TaskStop` tool through+ :func:`get_toolkit`.+ message_bus (`MessageBus`):+ Application-wide message bus. Provides session-level+ distributed locking (via :meth:`session_run`), event+ replay + live fan-out (via :meth:`session_publish_event`),+ and inbox delivery (via :class:`InboxMiddleware`).extra_agent_middlewares (`AgentMiddlewareFactory | None`, \optional):Async factory invoked at every chat turn to produce@@ -67,13 +91,14 @@ optional):user/session-specific tools to register in the toolkit."""self._storage = storage- self._session_manager = session_manager- self._background_task_manager = background_task_managerself._workspace_manager = workspace_manager+ self._scheduler_manager = scheduler_manager+ self._background_task_manager = background_task_manager+ self._message_bus = message_busself._extra_agent_middlewares = extra_agent_middlewaresself._extra_agent_tools = extra_agent_tools- async def stream_chat(+ async def run(self,user_id: str,session_id: str,@@ -83,13 +108,21 @@ optional):| UserConfirmResultEvent| ExternalExecutionResultEvent| None = None,- ) -> AsyncGenerator[AgentEvent, None]:- """Run the agent and yield events.+ ) -> None:+ """Drive a chat run to completion.- Persists input messages (Case A) or the incoming continuation event- applied to the existing reply (Case B), streams the agent's reply- while building an ``AssistantMsg`` from the event flow, and- persists the reply and updated agent state when finished.+ Persists input messages (Case A) or the incoming continuation+ event applied to the existing reply (Case B), runs the agent+ while publishing every produced event to the message bus, and+ persists the rebuilt reply ``Msg`` + updated agent state when+ finished.++ Session serialisation is handled by the bus's distributed lock+ (:meth:`MessageBus.session_run`); events are simultaneously+ persisted to the replay log and fanned out on the live channel+ via :meth:`MessageBus.session_publish_event`. Exceptions are+ logged and swallowed so a single failed fire does not tear+ down its trigger (HTTP request task, wakeup dispatcher, …).Args:user_id (`str`):@@ -100,64 +133,194 @@ optional):Agent to run.input_msg:One of:- - ``Msg`` / ``list[Msg]``: new user message(s) (Case A)- - ``None``: continue from current state, e.g. a retrigger- triggered by a completed background tool (Case A with- no input)- - ``UserConfirmResultEvent`` /- ``ExternalExecutionResultEvent``:- resume an awaiting tool call (Case B)- Yields:- AgentEvent: Streamed events from the agent.+ - ``Msg`` / ``list[Msg]``: new user message(s) (Case A).+ - ``None``: continue from current state — used by the+ wakeup dispatcher when there is no fresh user input+ but pending inbox content needs draining (Case A+ with no input).+ - ``UserConfirmResultEvent`` /+ ``ExternalExecutionResultEvent``: resume an awaiting+ tool call (Case B)."""+ try:+ await self._run_impl(user_id, session_id, agent_id, input_msg)+ except Exception as e:+ logger.exception(+ "ChatService.run failed for user_id=%s session_id=%s "+ "agent_id=%s, error=%s",+ user_id,+ session_id,+ agent_id,+ str(e),+ )++ async def _run_impl(+ self,+ user_id: str,+ session_id: str,+ agent_id: str,+ input_msg: Msg+ | list[Msg]+ | UserConfirmResultEvent+ | ExternalExecutionResultEvent+ | None,+ ) -> None:+ """The actual chat-run body; wrapped by :meth:`run` for error+ swallowing. Separated so the try/except doesn't bury the+ per-step logic at one extra indentation level."""# ----------------------------------------------------------------- # 1. Build middlewares+ # 1. Load records + resolve workspace ONCE here, reused below.+ # Reject missing records up front with a clear error so the+ # downstream assembly code can rely on non-None values.# ----------------------------------------------------------------- async def _retrigger(- sess_id: str,- ag_id: str,- uid: str,- ) -> None:- """Re-invoke the agent to process completed background results."""- async for _ in self.stream_chat(- user_id=uid,- session_id=sess_id,- agent_id=ag_id,- input_msg=None,- ):- pass+ agent_record = await self._storage.get_agent(user_id, agent_id)+ if agent_record is None:+ raise HTTPException(+ status_code=404,+ detail=f"Agent {agent_id!r} not found.",+ )+ session_record = await self._storage.get_session(+ user_id,+ agent_id,+ session_id,+ )+ if session_record is None:+ raise HTTPException(+ status_code=404,+ detail=(+ f"Session {session_id!r} not found for "+ f"agent {agent_id!r}."+ ),+ )+ workspace = await self._workspace_manager.get_workspace(+ user_id,+ agent_id,+ session_id,+ session_record.config.workspace_id,+ )+ # ----------------------------------------------------------------+ # 2. Toolkit (workspace tools + planning + TaskStop + schedule ++ # team + extras + skills + mcps).+ # ----------------------------------------------------------------+ toolkit = await get_toolkit(+ storage=self._storage,+ workspace=workspace,+ scheduler_manager=self._scheduler_manager,+ background_task_manager=self._background_task_manager,+ message_bus=self._message_bus,+ user_id=user_id,+ agent_record=agent_record,+ session_record=session_record,+ extra_factory=self._extra_agent_tools,+ )++ # ----------------------------------------------------------------+ # 3. Middlewares — framework-supplied first, then caller extras.+ # Background-tool completions deliver their results via+ # ``message_bus.inbox_push + enqueue_wakeup``, so the dispatcher+ # (any process) wakes an idle session — no in-process retrigger+ # plumbing is needed here.+ # ----------------------------------------------------------------middlewares: list = [+ InboxMiddleware(self._message_bus),+ StateChangeMiddleware(+ message_bus=self._message_bus,+ session_id=session_id,+ ),ToolOffloadMiddleware(- self._background_task_manager,+ bg_manager=self._background_task_manager,+ message_bus=self._message_bus,user_id=user_id,agent_id=agent_id,- session_manager=self._session_manager,- retrigger_fn=_retrigger,),]+ if self._extra_agent_middlewares is not None:+ middlewares.extend(+ await self._extra_agent_middlewares(+ user_id,+ agent_id,+ session_id,+ ),+ )# ----------------------------------------------------------------- # 2. Assemble the agent (loads session/agent/credential/model,- # restores state, builds toolkit from workspace)+ # 4. Model + fallback (resolved from session's config).# ----------------------------------------------------------------- agent = await get_agent(- storage=self._storage,- workspace_manager=self._workspace_manager,- user_id=user_id,- agent_id=agent_id,- session_id=session_id,+ model_cfg = session_record.config.chat_model_config+ if not model_cfg:+ raise HTTPException(+ status_code=404,+ detail=f"No model configuration found for agent {agent_id}",+ )+ model = await get_model(user_id, model_cfg, self._storage)++ fallback_cfg = session_record.config.fallback_chat_model_config+ fallback_model = (+ await get_model(user_id, fallback_cfg, self._storage)+ if fallback_cfg is not None+ else None+ )++ # ----------------------------------------------------------------+ # 5. Assemble the Agent.+ # ----------------------------------------------------------------+ agent_state = session_record.state+ agent_state.session_id = session_id+ agent = Agent(+ name=agent_record.data.name,+ system_prompt=agent_record.data.system_prompt,+ model=model,+ toolkit=toolkit,+ model_config=ModelConfig(fallback_model=fallback_model),+ context_config=agent_record.data.context_config,+ react_config=agent_record.data.react_config,+ state=agent_state,middlewares=middlewares,- extra_agent_middlewares=self._extra_agent_middlewares,- extra_agent_tools=self._extra_agent_tools,+ offloader=workspace,)# ----------------------------------------------------------------- # 3. Run the agent inside the session manager context+ # 6. Guard: skip wake-up driven runs when the agent is parked on+ # an awaiting tool call.+ #+ # Wake-ups deliver pending inbox content (team messages, etc.) by+ # poking the dispatcher to run the session with ``input_msg=None``.+ # If the agent is currently parked on an ``ASKING`` or+ # ``SUBMITTED`` tool call (waiting for user confirmation or+ # external-execution results), kicking off another ``None`` run+ # would hit :meth:`Agent._check_incoming_event`, which rightly+ # rejects ``None`` when there is something to confirm — and fail+ # the run noisily. The inbox content is safe to leave queued:+ # whenever the user does confirm (or the external result lands),+ # the resuming run's next reasoning step lets+ # :class:`InboxMiddleware` drain the queue naturally.# ----------------------------------------------------------------- async with self._session_manager.run(session_id) as run:+ if input_msg is None and agent.state.context:+ last_msg = agent.state.context[-1]+ if last_msg.role == "assistant" and last_msg.name == agent.name:+ awaiting = [+ tc+ for tc in last_msg.get_content_blocks("tool_call")+ if tc.state+ in (ToolCallState.ASKING, ToolCallState.SUBMITTED)+ ]+ if awaiting:+ logger.info(+ "Skipping wake-up for session %s: agent is parked "+ "on %d awaiting tool call(s); inbox messages will "+ "be drained when the agent resumes.",+ session_id,+ len(awaiting),+ )+ return++ # ----------------------------------------------------------------+ # 7. Run the agent inside the bus's distributed session lock+ # ----------------------------------------------------------------+ async with self._message_bus.session_run(session_id):reply_msg: Msg | None = Noneif input_msg is None or isinstance(input_msg, (Msg, list)):@@ -177,8 +340,10 @@ optional):)async for event in agent.reply_stream(inputs=input_msg):- await run.publish(event)- yield event+ await self._message_bus.session_publish_event(+ session_id,+ event.model_dump(mode="json"),+ )if isinstance(event, ReplyStartEvent):reply_msg = AssistantMsg(id=event.reply_id,@@ -205,21 +370,18 @@ optional):session_id,)elif input_msg:- # Apply the incoming event so the persisted message- # reflects updated tool-call states before streaming- # resumes (e.g. ASKING→ALLOWED/FINISHED for- # UserConfirmResultEvent, or appended ToolResultBlocks- # for ExternalExecutionResultEvent).reply_msg.append_event(input_msg)async for event in agent.reply_stream(inputs=input_msg):- await run.publish(event)- yield event+ await self._message_bus.session_publish_event(+ session_id,+ event.model_dump(mode="json"),+ )if reply_msg is not None:reply_msg.append_event(event)# Persist the reply Msg (upsert: overwrite if same id, append- # if new)+ # if new).if reply_msg is not None:await self._storage.upsert_message(user_id,@@ -227,12 +389,16 @@ optional):reply_msg,)- # ----------------------------------------------------------------- # 4. Persist agent state- # ----------------------------------------------------------------- await self._storage.update_session_state(- user_id=user_id,- agent_id=agent_id,- session_id=session_id,- state=agent.state,- )+ # Persist the updated agent state. MUST happen inside the+ # session lock: if we released the lock first, another+ # process could acquire it and load a stale state from+ # storage before this write lands.+ await self._storage.update_session_state(+ user_id=user_id,+ agent_id=agent_id,+ session_id=session_id,+ state=agent.state,+ )++ # ``session_run.__aexit__`` trims the replay log before+ # releasing the lock — see :meth:`MessageBus.session_run`.diff --git a/src/agentscope/app/_service/_session.py b/src/agentscope/app/_service/_session.pynew file mode 100644index 000000000..b344c0f4e--- /dev/null+++ b/src/agentscope/app/_service/_session.py@@ -0,0 +1,383 @@+# -*- coding: utf-8 -*-+"""Cross-resource session lifecycle service.++Owns the "stop in-flight runs + delete records + drop bus state"+cascades that ``DELETE /sessions/{sid}``, ``DELETE /agents/{aid}``,+``DELETE /schedules/{sid}`` and the agent-facing+:class:`~agentscope.app._tools.TeamDelete` /+:class:`~agentscope.app._manager._scheduler._tools.ScheduleDelete`+tools all share.++Layering+========++Methods deliberately delegate down the cascade so the bus-touching+logic lives in exactly one place — :meth:`delete_session`. Higher-level+methods only orchestrate which sessions to delete, then ask storage+to clean its own non-session scope (records, indexes, back-refs).++::++ delete_session ← atomic: cancel run, storage.delete_session,+ bus.session_purge+ │+ delete_team → service.delete_agent per worker+ → storage.delete_team (record + leader detach)+ │+ delete_agent → service.delete_session per session+ → service.delete_schedule per owned schedule+ → storage.delete_agent (agent record + team back-refs)+ │+ delete_schedule → service.delete_session per spawned session+ → storage.delete_schedule (schedule record + indexes)++Storage's own internal cascades (e.g.+``storage.delete_agent`` re-iterating sessions) become idempotent+no-ops because the records are already gone — they still execute, but+do no work and never touch the bus, so the storage layer stays+unaware of the message bus.++Separation of concerns+======================++Storage and message bus are treated as distinct backends — they may+live in different databases in the future. The service is the **only**+component that touches both in the same call. Storage code never+imports the bus; bus code never imports storage.+"""+import asyncio++from ..message_bus import MessageBus+from ..storage import StorageBase+from ..._logging import logger+++class SessionService:+ """Cancel in-flight chat runs and cascade-delete related records.++ The cancel side broadcasts via+ :meth:`MessageBus.session_publish_cancel`, then polls+ :meth:`MessageBus.session_is_running` until the run-lock clears or+ a timeout expires — so the implementation is multi-process and+ multi-node by construction.++ Args:+ storage (`StorageBase`):+ Persistent storage backend. Owns durable records and their+ cascades among themselves.+ message_bus (`MessageBus`):+ Live message bus. Owns transient per-session state (events+ log, inbox, run-lock, cancel channel).+ """++ _CANCEL_POLL_INTERVAL_SECS: float = 0.1+ """Interval between :meth:`MessageBus.session_is_running` polls+ while waiting for a cancelled run to release its distributed+ run-lock."""++ def __init__(+ self,+ storage: StorageBase,+ message_bus: MessageBus,+ ) -> None:+ """Bind dependencies.++ Args:+ storage (`StorageBase`): Persistent storage backend.+ message_bus (`MessageBus`): Live message bus.+ """+ self._storage = storage+ self._bus = message_bus++ # ------------------------------------------------------------------+ # Cancel+ # ------------------------------------------------------------------++ async def cancel_session_run(+ self,+ session_id: str,+ *,+ timeout: float = 10.0,+ ) -> bool:+ """Broadcast a session cancel and wait for the chat-run lock to+ clear.++ Publishes one cancel payload on the bus's shared cancel channel,+ unconditionally. Every process's+ :class:`~agentscope.app._manager.CancelDispatcher` reacts to the+ broadcast by cancelling whatever it locally holds for the+ session — the chat-run asyncio task **and** any background+ tasks owned by that session. The publisher does not need to+ know which worker holds which piece.++ After publishing, polls+ :meth:`MessageBus.session_is_running` until the distributed+ chat-run lock clears. Only the chat run holds a distributed+ lock; BG tasks do not, so this poll only waits for the chat+ run. Returns immediately when no chat run was active.++ Idempotent: calling on an idle session just sends a no-op+ broadcast and observes a clear lock.++ Args:+ session_id (`str`):+ The session whose chat run + BG tasks should be+ cancelled.+ timeout (`float`, defaults to ``10.0``):+ Maximum seconds to wait for the chat-run lock to+ release. On timeout the method returns ``False`` so+ callers can proceed (e.g. with cascade delete) instead+ of hanging on a process that may have died.++ Returns:+ `bool`:+ ``True`` if the chat-run lock was confirmed released+ within ``timeout`` seconds (or was never held).+ ``False`` if the lock was still held when the timeout+ expired.+ """+ await self._bus.session_publish_cancel(session_id)++ deadline = asyncio.get_event_loop().time() + timeout+ while True:+ if not await self._bus.session_is_running(session_id):+ return True+ if asyncio.get_event_loop().time() >= deadline:+ logger.warning(+ "Session %s did not release its run-lock within "+ "%.1fs after cancel; proceeding anyway.",+ session_id,+ timeout,+ )+ return False+ await asyncio.sleep(self._CANCEL_POLL_INTERVAL_SECS)++ # ------------------------------------------------------------------+ # Delete cascades — every higher-level method delegates to+ # ``delete_session`` so the cancel + bus-purge logic exists in+ # exactly one place.+ # ------------------------------------------------------------------++ async def delete_session(+ self,+ user_id: str,+ agent_id: str,+ session_id: str,+ ) -> bool:+ """Cancel, delete and bus-purge a single session.++ This is the atomic primitive — every other cascade delegates+ here for per-session work.++ Steps:++ 1. Cancel any in-flight run for ``session_id`` (cross-process+ via the bus cancel channel).+ 2. Delete the session record (and its storage-side cascade:+ message log, schedule-session index, team dissolution when+ this session leads one — recursive into worker agents).+ 3. Purge transient bus state for ``session_id`` (events log,+ inbox).++ Worker sessions that storage cascades through are picked up+ here too: when this session is a team leader,+ ``storage.delete_session`` calls ``storage.delete_team`` →+ ``storage.delete_agent`` → ``storage.delete_session`` for each+ worker, and we mirror that on the bus side by purging worker+ sessions identified up front via+ :meth:`_team_worker_session_ids`.++ Args:+ user_id (`str`): The owner user id.+ agent_id (`str`): The agent that owns the session.+ session_id (`str`): The session to delete.++ Returns:+ `bool`:+ ``True`` if the session record existed and was deleted,+ ``False`` otherwise. Mirrors+ :meth:`StorageBase.delete_session`.+ """+ # Identify all bus-purge targets before storage mutates anything.+ worker_sids = await self._team_worker_session_ids(+ user_id,+ agent_id,+ session_id,+ )+ all_sids = [session_id, *worker_sids]++ await self._cancel_runs(all_sids)+ deleted = await self._storage.delete_session(+ user_id,+ agent_id,+ session_id,+ )+ await self._purge_bus(all_sids)+ return deleted++ async def delete_team(self, user_id: str, team_id: str) -> bool:+ """Cancel, delete and bus-purge a team.++ Delegates worker dissolution to :meth:`delete_agent` (one call+ per ``member_id``) so the per-session cancel + bus purge runs+ for each worker. The leader's own session is **not** deleted —+ teams dissolve, leaders survive (and have their ``team_id``+ cleared by ``storage.delete_team``).++ Args:+ user_id (`str`): The owner user id.+ team_id (`str`): The team to dissolve.++ Returns:+ `bool`:+ ``True`` if the team record existed and was deleted.+ """+ team = await self._storage.get_team(user_id, team_id)+ if team is None:+ # Still call storage.delete_team so it can clean any index+ # residue, but the return value will be False.+ return await self._storage.delete_team(user_id, team_id)++ for member_id in team.data.member_ids:+ await self.delete_agent(user_id, member_id)++ # storage.delete_team will iterate member_ids again to delete+ # each worker agent — those calls are now no-ops because the+ # agents are already gone, leaving only the leader-detach and+ # team-record cleanup work.+ return await self._storage.delete_team(user_id, team_id)++ async def delete_agent(self, user_id: str, agent_id: str) -> bool:+ """Cancel, delete and bus-purge every session and schedule+ owned by an agent, then drop the agent record.++ Delegates per-session work to :meth:`delete_session` and+ per-schedule work to :meth:`delete_schedule`, then asks+ storage to clean the remaining agent-scoped state (the agent+ record, the agent index entry, and any team back-references).++ Args:+ user_id (`str`): The owner user id.+ agent_id (`str`): The agent to delete.++ Returns:+ `bool`:+ ``True`` if the agent record existed and was deleted.+ """+ for session in await self._storage.list_sessions(user_id, agent_id):+ await self.delete_session(user_id, agent_id, session.id)++ for schedule in await self._storage.list_schedules(user_id):+ if schedule.agent_id == agent_id:+ await self.delete_schedule(user_id, schedule.id)++ # storage.delete_agent re-iterates sessions and schedules —+ # those re-runs are idempotent no-ops because the records were+ # already removed above. What remains is the agent record,+ # the agent index entry, and team back-reference scrubbing.+ return await self._storage.delete_agent(user_id, agent_id)++ async def delete_schedule(+ self,+ user_id: str,+ schedule_id: str,+ ) -> bool:+ """Cancel, delete and bus-purge every session spawned by a+ schedule, then drop the schedule record.++ Args:+ user_id (`str`): The owner user id.+ schedule_id (`str`): The schedule to delete.++ Returns:+ `bool`:+ ``True`` if the schedule record existed and was deleted.+ """+ for session in await self._storage.list_sessions_by_schedule(+ user_id,+ schedule_id,+ ):+ await self.delete_session(+ user_id,+ session.agent_id,+ session.id,+ )++ # storage.delete_schedule re-iterates the same sessions —+ # idempotent no-ops; only schedule record + indexes remain.+ return await self._storage.delete_schedule(user_id, schedule_id)++ # ------------------------------------------------------------------+ # Internals+ # ------------------------------------------------------------------++ async def _team_worker_session_ids(+ self,+ user_id: str,+ agent_id: str,+ session_id: str,+ ) -> list[str]:+ """Return the session ids of every worker in the team that+ ``session_id`` leads, or ``[]`` when the session does not lead+ a team.++ Mirrors :meth:`StorageBase.delete_session`'s own team-leader+ cascade so the bus side can purge the same sessions.++ Args:+ user_id (`str`): The owner user id.+ agent_id (`str`):+ The agent that owns ``session_id``. May be empty when+ unknown; team-leader lookup does not depend on it.+ session_id (`str`):+ The candidate leader session.++ Returns:+ `list[str]`:+ Worker session ids, empty when this session is not a+ team leader.+ """+ session = await self._storage.get_session(+ user_id,+ agent_id,+ session_id,+ )+ if session is None or not session.team_id:+ return []+ team = await self._storage.get_team(user_id, session.team_id)+ if team is None or team.session_id != session_id:+ return []+ sids: list[str] = []+ for member_id in team.data.member_ids:+ worker_sessions = await self._storage.list_sessions(+ user_id,+ member_id,+ )+ sids.extend(s.id for s in worker_sessions)+ return sids++ async def _cancel_runs(self, session_ids: list[str]) -> None:+ """Cancel every in-flight run in ``session_ids`` concurrently.++ Args:+ session_ids (`list[str]`):+ Sessions whose runs should be cancelled.+ """+ if not session_ids:+ return+ await asyncio.gather(+ *(self.cancel_session_run(sid) for sid in session_ids),+ )++ async def _purge_bus(self, session_ids: list[str]) -> None:+ """Drop bus state (events log + inbox) for each id concurrently.++ Args:+ session_ids (`list[str]`):+ Sessions whose bus state should be purged.+ """+ if not session_ids:+ return+ await asyncio.gather(+ *(self._bus.session_purge(sid) for sid in session_ids),+ )diff --git a/src/agentscope/app/_service/_toolkit.py b/src/agentscope/app/_service/_toolkit.pynew file mode 100644index 000000000..57166859a--- /dev/null+++ b/src/agentscope/app/_service/_toolkit.py@@ -0,0 +1,171 @@+# -*- coding: utf-8 -*-+"""Toolkit assembly for an (agent, session) pair.++The single entry point :func:`get_toolkit` gathers every tool source —+workspace builtins, MCPs, skills, planning tools (Task*), background-task+control (TaskStop), schedule control (Schedule*), team participation+tools, and caller-supplied extras — into one :class:`Toolkit`.+"""+from typing import Any++from .._manager import BackgroundTaskManager, SchedulerManager+from ..message_bus import MessageBus+from .._tools import AgentCreate, TeamCreate, TeamDelete, TeamSay+from .._types import AgentToolFactory+from ..storage import AgentRecord, SessionRecord, StorageBase+from ...tool import (+ TaskCreate,+ TaskGet,+ TaskList,+ TaskUpdate,+ Toolkit,+ ToolGroup,+)+from ...workspace import WorkspaceBase+++async def get_toolkit(+ *,+ storage: StorageBase,+ workspace: WorkspaceBase,+ scheduler_manager: SchedulerManager,+ background_task_manager: BackgroundTaskManager,+ message_bus: MessageBus,+ user_id: str,+ agent_record: AgentRecord,+ session_record: SessionRecord,+ extra_factory: AgentToolFactory | None = None,+) -> Toolkit:+ """Assemble the complete :class:`Toolkit` for one chat turn.++ Tool sources (in attachment order):++ 1. Workspace builtins (Bash / Read / Write / Grep / …)+ 2. Planning tools (:class:`TaskCreate` / :class:`TaskList` /+ :class:`TaskGet` / :class:`TaskUpdate`)+ 3. Background-task control (:class:`TaskStop`, from+ :meth:`BackgroundTaskManager.list_tools`)+ 4. Schedule control (:class:`ScheduleCreate` / :class:`ScheduleView`+ / :class:`ScheduleDelete` / :class:`ScheduleList`, from+ :meth:`SchedulerManager.list_tools`). Only attached when the+ session has a model configured (Schedule tools need a model to+ fire new chats with).+ 5. Team tools — selected inline by ``agent_record.source``:+ worker (``"team"``) gets only ``TeamSay``; everyone else gets+ the full leader-side toolset+ (``TeamCreate / AgentCreate / TeamSay / TeamDelete``)+ 6. Caller-supplied extras (``extra_factory``)++ Plus the workspace's skills and MCPs, which become the toolkit's+ ``skills_or_loaders`` and ``mcps`` parameters.++ Args:+ storage (`StorageBase`):+ Application storage backend; needed by team tools to read+ fresh team / session state at call time, and by schedule+ tools.+ workspace (`WorkspaceBase`):+ Pre-resolved per-session workspace (caller resolves it+ via :meth:`WorkspaceManagerBase.get_workspace`). Used here+ for tool / skill / MCP discovery.+ scheduler_manager (`SchedulerManager`):+ Application scheduler. Provides the four schedule tools and+ persists schedules through it.+ background_task_manager (`BackgroundTaskManager`):+ Application background-task registry. Provides the+ :class:`TaskStop` tool bound to its live task dict.+ message_bus (`MessageBus`):+ Application message bus; passed to team tools so they can+ push HintBlocks + wakeups when delivering inter-session+ messages.+ user_id (`str`):+ Caller user id.+ agent_record (`AgentRecord`):+ Pre-loaded agent record (loaded once by the caller). Its+ ``source`` field determines which team tools are attached.+ session_record (`SessionRecord`):+ Pre-loaded session record (loaded once by the caller).+ Used for the schedule-tool model configuration.+ extra_factory (`AgentToolFactory | None`, optional):+ Async factory invoked once per assembly to produce+ user/session-specific extra tools.++ Returns:+ `Toolkit`: Fully populated toolkit (tools + skills + MCPs).+ """++ tool_groups = []++ # The general tools running in the workspace+ tools = await workspace.list_tools()++ # Planning tools — always on.+ tools += [TaskCreate(), TaskList(), TaskGet(), TaskUpdate()]++ # Background-task control.+ tools += await background_task_manager.list_tools()++ # Schedule control. Requires a model config on this session because+ # ``ScheduleCreate`` records it into new ``ScheduleRecord`` instances.+ if session_record.config.chat_model_config is not None:+ # Add schedule tools as a tool group+ tool_groups.append(+ ToolGroup(+ name="schedule_tools",+ description=(+ """Tools for managing cron schedules. A cron schedule is \+a recurring task that fires at a specified time — at that point, a new \+session is created and an agent will be invoked to complete the given task \+autonomously.++## When to Use This Tool Group+- When you need to create a new cron schedule that triggers at a specific \+time or interval"+- When you're asked to list, inspect, stop, or delete existing cron schedules+"""+ ),+ tools=await scheduler_manager.list_tools(+ user_id=user_id,+ agent_id=agent_record.id,+ chat_model_config=session_record.config.chat_model_config,+ ),+ ),+ )++ # Team tools — variant based on ``agent_record.source``. A worker+ # only gets TeamSay (to report back); a user-owned agent always+ # gets the full leader-side toolset. Each tool checks its own+ # preconditions (am I in a team? am I the leader?) at call time+ # against fresh storage, which is why the full set can be attached+ # unconditionally without needing a stale snapshot of team_id.+ team_tool_kwargs: dict[str, Any] = {+ "storage": storage,+ "message_bus": message_bus,+ "user_id": user_id,+ "session_id": session_record.id,+ "agent_id": agent_record.id,+ }+ if agent_record.source == "team":+ tools.append(TeamSay(**team_tool_kwargs, role="worker"))+ else:+ tools += [+ TeamCreate(**team_tool_kwargs),+ AgentCreate(**team_tool_kwargs),+ TeamSay(**team_tool_kwargs, role="leader"),+ TeamDelete(**team_tool_kwargs),+ ]++ # Caller-supplied extras.+ if extra_factory is not None:+ tools += await extra_factory(+ user_id,+ agent_record.id,+ session_record.id,+ )++ return Toolkit(+ tools=tools,+ skills_or_loaders=await workspace.list_skills(),+ mcps=await workspace.list_mcps(),+ tool_groups=tool_groups,+ )diff --git a/src/agentscope/app/_tools/__init__.py b/src/agentscope/app/_tools/__init__.pynew file mode 100644index 000000000..6c65309f5--- /dev/null+++ b/src/agentscope/app/_tools/__init__.py@@ -0,0 +1,37 @@+# -*- coding: utf-8 -*-+"""Framework-builtin tools wired into team-participating agents.++These tools differ from the workspace-provided builtins (Bash, Read,+Task series, …) in two ways:++1. **Construction depends on app-level resources** — they bind a+ :class:`StorageBase` + :class:`MessageBus` reference plus the+ request-scoped ``user_id`` / ``session_id`` / ``agent_id`` at agent+ assembly time, and call storage / bus directly in their+ ``__call__`` (no intermediate service layer).+2. **Visibility depends only on the agent's source field** —+ ``source='user'`` agents always see the full leader-side toolset+ (``TeamCreate / AgentCreate / TeamSay / TeamDelete``) regardless of+ whether they currently lead a team. Each tool checks the storage+ state at ``__call__`` time and fails clearly if its precondition+ is not met. ``source='team'`` workers only see ``TeamSay``.++ The benefit is that a single chat run can ``TeamCreate`` and then+ ``AgentCreate`` immediately afterward — there is no toolkit+ refresh point because the toolkit never changed; only the+ underlying storage state did, which the next tool reads fresh.++Selection of the right subset by ``agent.source`` happens inline in+:func:`get_toolkit`; there is no separate "team tool factory" helper.+"""+from ._agent_create import AgentCreate+from ._team_create import TeamCreate+from ._team_delete import TeamDelete+from ._team_say import TeamSay++__all__ = [+ "AgentCreate",+ "TeamCreate",+ "TeamDelete",+ "TeamSay",+]diff --git a/src/agentscope/app/_tools/_agent_create.py b/src/agentscope/app/_tools/_agent_create.pynew file mode 100644index 000000000..b75d3edcd--- /dev/null+++ b/src/agentscope/app/_tools/_agent_create.py@@ -0,0 +1,388 @@+# -*- coding: utf-8 -*-+"""The AgentCreate tool — spawns a worker into the current team."""+import json+from typing import Literal++from pydantic import Field++from ._team_tool_base import _TeamToolBase+from ..storage import AgentData, AgentRecord, SessionConfig+from ...agent import ContextConfig, ReActConfig+from ...message import HintBlock, TextBlock, ToolResultState+from ...permission import PermissionContext, PermissionMode+from ...state import AgentState+from ...tool import ToolChunk, ParamsBase+++_PERMISSION_MODE_BY_VALUE: dict[str, PermissionMode] = {+ mode.value: mode for mode in PermissionMode+}+++def _build_worker_system_prompt(+ team_name: str,+ team_description: str,+ member_name: str,+ member_description: str,+) -> str:+ """Compose the system prompt for a freshly spawned worker."""+ sections = [f"You are {member_name}, a member of team {team_name!r}."]+ if team_description:+ sections.append(f"Team purpose: {team_description}")+ if member_description:+ sections.append(f"Your role: {member_description}")+ sections.append(+ "You communicate with the team leader and other members "+ "through the TeamSay tool. Other tool calls execute in your "+ "own session. Speak on the team only when you have something "+ "external to share — your private reasoning stays private.",+ )+ return "\n\n".join(sections)+++class _AgentCreateParams(ParamsBase):+ """Parameters for :class:`AgentCreate`."""++ name: str = Field(+ description=(+ 'Short identifier for the new member, e.g. ``"researcher"`` '+ 'or ``"coder-1"``. Other members address it via '+ "``TeamSay(to=<this name>)``, so it MUST be unique within "+ "the team."+ ),+ )+ description: str = Field(+ description=(+ "One-sentence summary of the member's role — e.g. "+ '``"Researches background information on the target topic"``. '+ "Becomes part of the member's system prompt so it understands "+ "its place in the team."+ ),+ )+ prompt: str = Field(+ description=(+ "The first task delivered to the member as a user message. "+ "The member begins executing immediately upon creation, so "+ "make this concrete and self-contained — do not just say "+ '``"wait for instructions"`` (use TeamSay later instead). '+ "Include any context, constraints, deliverables, and "+ "deadlines the member needs."+ ),+ )+ permission_mode: Literal[+ "default",+ "accept_edits",+ "explore",+ "bypass",+ "dont_ask",+ ] = Field(+ default="default",+ description=(+ "Permission mode controlling how the member handles tool "+ "calls that would otherwise require user confirmation.\n\n"+ "Choose based on the member's responsibilities:\n\n"+ '- ``"default"`` — Each tool call that touches the system '+ "(file writes, shell commands, etc.) requires confirmation. "+ "Pick this when the member's work has real-world side effects "+ "you want the user to review.\n"+ '- ``"accept_edits"`` — Auto-approve file edits and '+ "filesystem-shaping commands inside the working directory; "+ "still confirm other risky calls. Pick this for a member "+ "doing rapid iteration on code under your supervision.\n"+ '- ``"explore"`` — Read-only mode: allow Read/Grep/Glob, '+ "deny anything that mutates state. Pick this for research / "+ "audit / planning members that should never modify anything.\n"+ '- ``"bypass"`` — Skip every permission check. Pick this '+ "ONLY for fully sandboxed members where any operation is "+ "guaranteed safe (e.g. a containerised worker on disposable "+ "data).\n"+ '- ``"dont_ask"`` — Convert every ASK decision to DENY. '+ "Pick this for unattended/background members where the user "+ 'isn\'t around to answer prompts; safer than ``"bypass"`` '+ "because risky calls fail-closed instead of executing.\n\n"+ 'When unsure, start with ``"default"``.'+ ),+ )+++class AgentCreate(_TeamToolBase):+ """Spawn a new worker member into the team you lead."""++ name: str = "AgentCreate"++ description: str = """Add a new member to the team you lead.++## When to Use This Tool+After ``TeamCreate``, call this for each member you want on the team. \+Each call:+- Creates a worker agent dedicated to this team.+- Delivers ``prompt`` as the worker's first user message — **the worker \+starts executing it immediately**. (So DONT use ``TeamSay`` right after \+creating one agent).++## When NOT to Use This Tool+- You're not currently leading a team. Call ``TeamCreate`` first.+- The new member would duplicate an existing member's role; reuse the \+existing member via ``TeamSay`` instead.++## Effects+- Use the ``name`` you chose as ``to=<name>`` in ``TeamSay`` to direct \+messages to this member specifically. Names must be unique within the \+team (including against the leader's name); duplicates are rejected.+- Members spawned this way live only as long as the team — they are \+deleted when ``TeamDelete`` is called.++## Important+- You are responsible for organising the team, assigning tasks, collecting \+every member's report, and producing the final answer — all members report \+directly to you. Therefore, **DO NOT** encourage members to communicate with \+each other, and **AVOID** creating "integrator"-style members; both make the \+overall communication topology unnecessarily complex.+"""++ input_schema: dict = _AgentCreateParams.model_json_schema()++ async def __call__(+ self,+ name: str,+ description: str,+ prompt: str,+ permission_mode: str = "default",+ ) -> ToolChunk:+ """Spawn the worker agent + session directly via storage.++ Reads the current session + team records from storage to+ enforce two preconditions: the calling session must be in a+ team, and it must be that team's leader.++ Args:+ name (`str`):+ Short identifier for the worker.+ description (`str`):+ One-sentence summary of the worker's role.+ prompt (`str`):+ First task delivered as a user message to the worker.+ permission_mode (`str`, defaults to ``"default"``):+ Permission mode the worker operates under.++ Returns:+ `ToolChunk`:+ A success message containing the new member id, or an+ error chunk on failure.+ """+ try:+ session = await self._storage.get_session(+ self._user_id,+ self._agent_id,+ self._session_id,+ )+ if session is None or session.team_id is None:+ return ToolChunk(+ content=[+ TextBlock(+ text=(+ "AgentCreate: this session is not in "+ "any team — call TeamCreate first."+ ),+ ),+ ],+ state=ToolResultState.ERROR,+ )+ team = await self._storage.get_team(+ self._user_id,+ session.team_id,+ )+ if team is None:+ return ToolChunk(+ content=[+ TextBlock(+ text=(+ "AgentCreate: team "+ f"{session.team_id} no longer exists."+ ),+ ),+ ],+ state=ToolResultState.ERROR,+ )+ if team.session_id != self._session_id:+ return ToolChunk(+ content=[+ TextBlock(+ text=(+ "AgentCreate: only the team leader "+ "can add members; this session is a "+ "worker."+ ),+ ),+ ],+ state=ToolResultState.ERROR,+ )++ # Look up leader session for chat-model inheritance + name.+ leader_session = await self._storage.get_session(+ self._user_id,+ "", # agent_id unused at storage level+ team.session_id,+ )+ if leader_session is None:+ return ToolChunk(+ content=[+ TextBlock(+ text=(+ f"AgentCreate: leader session "+ f"{team.session_id} for team {team.id} is "+ f"missing — team is in an inconsistent "+ f"state."+ ),+ ),+ ],+ state=ToolResultState.ERROR,+ )++ if permission_mode not in _PERMISSION_MODE_BY_VALUE:+ return ToolChunk(+ content=[+ TextBlock(+ text=(+ f"AgentCreate: unknown permission_mode "+ f"{permission_mode!r}; expected one of "+ f"{list(_PERMISSION_MODE_BY_VALUE)}."+ ),+ ),+ ],+ state=ToolResultState.ERROR,+ )+ mode_enum = _PERMISSION_MODE_BY_VALUE[permission_mode]++ # Enforce team-scoped name uniqueness. TeamSay routes by+ # ``name`` (not agent_id), so duplicates would be ambiguous+ # and unaddressable. The leader's name participates too —+ # workers must not collide with it.+ leader_agent_record = await self._storage.get_agent(+ self._user_id,+ leader_session.agent_id,+ )+ existing_names: set[str] = set()+ if leader_agent_record is not None:+ existing_names.add(leader_agent_record.data.name)+ for member_id in team.data.member_ids:+ member_record = await self._storage.get_agent(+ self._user_id,+ member_id,+ )+ if member_record is not None:+ existing_names.add(member_record.data.name)+ if name in existing_names:+ return ToolChunk(+ content=[+ TextBlock(+ text=(+ f"AgentCreate: a team member named "+ f"{name!r} already exists. Member names "+ f"must be unique within the team "+ f"(including the leader's name); pick "+ f"another."+ ),+ ),+ ],+ state=ToolResultState.ERROR,+ )++ # 1. Build worker AgentRecord (source="team" so it's hidden+ # from the global agent list).+ system_prompt = _build_worker_system_prompt(+ team_name=team.data.name,+ team_description=team.data.description,+ member_name=name,+ member_description=description,+ )+ worker_agent = AgentRecord(+ user_id=self._user_id,+ source="team",+ data=AgentData(+ name=name,+ system_prompt=system_prompt,+ context_config=ContextConfig(),+ react_config=ReActConfig(),+ ),+ )+ await self._storage.upsert_agent(self._user_id, worker_agent)++ # 2. Build worker SessionRecord, inheriting leader's model+ # config.+ worker_state = AgentState(+ permission_context=PermissionContext(mode=mode_enum),+ )+ worker_session = await self._storage.upsert_session(+ user_id=self._user_id,+ agent_id=worker_agent.id,+ config=SessionConfig(+ workspace_id=leader_session.config.workspace_id,+ name=f"team:{team.id}/{name}",+ chat_model_config=(+ leader_session.config.chat_model_config+ ),+ fallback_chat_model_config=(+ leader_session.config.fallback_chat_model_config+ ),+ ),+ state=worker_state,+ )+ await self._storage.set_session_team_id(+ self._user_id,+ worker_session.id,+ team.id,+ )++ # 3. Append worker to team.member_ids.+ team.data.member_ids = [+ *team.data.member_ids,+ worker_agent.id,+ ]+ await self._storage.upsert_team(self._user_id, team)++ # 4. Deliver the initial task to the worker's inbox + wakeup.+ leader_name = (+ leader_agent_record.data.name+ if leader_agent_record is not None+ else leader_session.agent_id+ )+ hint = HintBlock(+ hint=(+ f'<team-message from="{leader_name}">\n'+ f"{prompt}\n"+ f"</team-message>"+ ),+ source=json.dumps(+ {+ "label": "team_message",+ "sublabel": leader_name,+ },+ ensure_ascii=False,+ ),+ )+ await self._message_bus.inbox_push(+ worker_session.id,+ hint.model_dump(mode="json"),+ )+ await self._message_bus.enqueue_wakeup(+ user_id=self._user_id,+ session_id=worker_session.id,+ agent_id=worker_agent.id,+ )++ return ToolChunk(+ content=[+ TextBlock(+ text=(+ f"Member {name!r} added to team "+ f"{team.data.name!r}."+ ),+ ),+ ],+ )+ except Exception as e: # pylint: disable=broad-except+ return ToolChunk(+ content=[TextBlock(text=f"AgentCreate failed: {e}")],+ state=ToolResultState.ERROR,+ )diff --git a/src/agentscope/app/_tools/_team_create.py b/src/agentscope/app/_tools/_team_create.pynew file mode 100644index 000000000..d2c2c4782--- /dev/null+++ b/src/agentscope/app/_tools/_team_create.py@@ -0,0 +1,145 @@+# -*- coding: utf-8 -*-+"""The TeamCreate tool — establishes a new team led by the current session."""+from pydantic import Field++from ._team_tool_base import _TeamToolBase+from ..storage import TeamData, TeamRecord+from ...message import TextBlock, ToolResultState+from ...tool import ToolChunk, ParamsBase+++class _TeamCreateParams(ParamsBase):+ """Parameters for :class:`TeamCreate`."""++ name: str = Field(+ description=(+ "Display name of the team. Used by the user to identify the "+ "team and shown in the team UI."+ ),+ )+ description: str = Field(+ description=(+ "What the team is for — its overall goal or shared context. "+ "This becomes the team's charter and is wired into every "+ "member's system prompt so all members share the same "+ "high-level understanding of why the team exists."+ ),+ )+++class TeamCreate(_TeamToolBase):+ """Create a new team and become its leader."""++ name: str = "TeamCreate"++ description: str = """Create a new team led by your current session and \+return its team id.++## When to Use This Tool+Use this tool when the task you've been given is best decomposed into \+parallel sub-tasks executed by multiple specialised agents (members) \+under your coordination. After creating the team, use ``AgentCreate`` to \+spawn each member with its own role, prompt, and permission mode. NOTE: \+the ``prompt`` you pass to ``AgentCreate`` is delivered to that member \+automatically, so do **NOT** call ``TeamSay`` right after ``AgentCreate`` — \+just wait for the members to report back.++## When NOT to Use This Tool+- The task is small enough to handle yourself.+- You already lead a team in this session — a session can only lead \+one team at a time.+"""++ input_schema: dict = _TeamCreateParams.model_json_schema()++ async def __call__(+ self,+ name: str,+ description: str,+ ) -> ToolChunk:+ """Create the team directly via storage.++ Reads the current session record from storage to enforce the+ precondition: a session can only lead one team at a time.+ This makes the tool safe to attach unconditionally to+ ``source='user'`` agents — calling it when the session+ already leads a team returns a clear error rather than+ silently corrupting state.++ Args:+ name (`str`):+ Display name of the team.+ description (`str`):+ Description / charter of the team.++ Returns:+ `ToolChunk`:+ A success message containing the team id, or an error+ chunk if a precondition fails or creation failed.+ """+ try:+ session = await self._storage.get_session(+ self._user_id,+ self._agent_id,+ self._session_id,+ )+ if session is None:+ return ToolChunk(+ content=[+ TextBlock(+ text=(+ "TeamCreate: session "+ f"{self._session_id} not found."+ ),+ ),+ ],+ state=ToolResultState.ERROR,+ )+ if session.team_id is not None:+ return ToolChunk(+ content=[+ TextBlock(+ text=(+ "TeamCreate: this session is already "+ f"part of team {session.team_id}. A "+ "session can only lead one team at a "+ "time — dissolve the current one with "+ "TeamDelete first."+ ),+ ),+ ],+ state=ToolResultState.ERROR,+ )++ team = TeamRecord(+ user_id=self._user_id,+ session_id=self._session_id,+ data=TeamData(+ name=name,+ description=description,+ member_ids=[],+ ),+ )+ await self._storage.upsert_team(self._user_id, team)+ await self._storage.set_session_team_id(+ self._user_id,+ self._session_id,+ team.id,+ )++ return ToolChunk(+ content=[+ TextBlock(+ text=(+ f"Team {team.id} ({team.data.name}) created. "+ f"You are the leader. Use AgentCreate to add "+ f"members, then TeamSay to coordinate them."+ ),+ ),+ ],+ )+ except Exception as e: # pylint: disable=broad-except+ return ToolChunk(+ content=[TextBlock(text=f"TeamCreate failed: {e}")],+ state=ToolResultState.ERROR,+ )diff --git a/src/agentscope/app/_tools/_team_delete.py b/src/agentscope/app/_tools/_team_delete.pynew file mode 100644index 000000000..ea34bfe3c--- /dev/null+++ b/src/agentscope/app/_tools/_team_delete.py@@ -0,0 +1,130 @@+# -*- coding: utf-8 -*-+"""The TeamDelete tool — dissolves the team led by the current session."""+from ._team_tool_base import _TeamToolBase+from ...message import TextBlock, ToolResultState+from ...tool import ToolChunk, ParamsBase+++class _TeamDeleteParams(ParamsBase):+ """Parameters for :class:`TeamDelete` — none."""+++class TeamDelete(_TeamToolBase):+ """Dissolve the team you currently lead and clean up all members."""++ name: str = "TeamDelete"++ description: str = """Dissolve the team you currently lead.++## When to Use This Tool+- The team has finished its work and you want to clean up.+- The team is unrecoverably stuck and you want to start over.+- You have collected the deliverables you need from each member.++## When NOT to Use This Tool+- Members are still producing useful output and you may want their \+follow-up; dissolving deletes them and they cannot be revived.+- You want to remove only one specific member — there is no "remove \+single member" tool in v1, only whole-team dissolution.++## Effects+- Every member agent + its session is deleted.+- The team record is deleted.+- Your own session continues to exist but is no longer associated with \+any team — the team-related tools become unavailable on subsequent \+reasoning steps.++This is irreversible.+"""++ input_schema: dict = _TeamDeleteParams.model_json_schema()++ async def __call__(self) -> ToolChunk:+ """Dissolve the bound session's team via :class:`SessionService`.++ Reads the current session + team records from storage to+ enforce: caller must be in a team AND must be its leader.+ Then delegates the actual cancel + delete + bus-purge cascade+ to :meth:`SessionService.delete_team`, which routes every+ member through the shared session-level primitive — so worker+ chat runs are cancelled cross-process and their bus state is+ cleaned up the same way ``DELETE /agents`` would.++ Returns:+ `ToolChunk`:+ A confirmation message, or an error chunk if a+ precondition fails.+ """+ try:+ session = await self._storage.get_session(+ self._user_id,+ self._agent_id,+ self._session_id,+ )+ if session is None or session.team_id is None:+ return ToolChunk(+ content=[+ TextBlock(+ text=(+ "TeamDelete: this session is not in "+ "any team."+ ),+ ),+ ],+ state=ToolResultState.ERROR,+ )+ team = await self._storage.get_team(+ self._user_id,+ session.team_id,+ )+ if team is None:+ return ToolChunk(+ content=[+ TextBlock(+ text=(+ "TeamDelete: team "+ f"{session.team_id} no longer exists."+ ),+ ),+ ],+ state=ToolResultState.ERROR,+ )+ if team.session_id != self._session_id:+ return ToolChunk(+ content=[+ TextBlock(+ text=(+ "TeamDelete: only the team leader "+ "can dissolve the team; this session "+ "is a worker."+ ),+ ),+ ],+ state=ToolResultState.ERROR,+ )++ # Local import to avoid a circular dependency between+ # ``_tools`` and ``_service`` at module load.+ from .._service import SessionService # noqa: PLC0415++ session_service = SessionService(+ storage=self._storage,+ message_bus=self._message_bus,+ )+ await session_service.delete_team(self._user_id, team.id)+ return ToolChunk(+ content=[+ TextBlock(+ text=(+ f"Team {team.id} dissolved. All members "+ f"deleted; your session is no longer "+ f"leading any team."+ ),+ ),+ ],+ )+ except Exception as e: # pylint: disable=broad-except+ return ToolChunk(+ content=[TextBlock(text=f"TeamDelete failed: {e}")],+ state=ToolResultState.ERROR,+ )diff --git a/src/agentscope/app/_tools/_team_say.py b/src/agentscope/app/_tools/_team_say.pynew file mode 100644index 000000000..87af8cf4d--- /dev/null+++ b/src/agentscope/app/_tools/_team_say.py@@ -0,0 +1,329 @@+# -*- coding: utf-8 -*-+"""The TeamSay tool — sends a message to one or all team members."""+from typing import Any++from pydantic import Field++from ._team_tool_base import _TeamToolBase+from ...message import HintBlock, TextBlock, ToolResultState+from ...tool import ToolChunk, ParamsBase+++class _TeamSayParams(ParamsBase):+ """Parameters for :class:`TeamSay`."""++ content: str = Field(+ description=(+ "The message text. Plain natural-language; the recipient "+ "sees it as a user message in its context."+ ),+ )+ to: str | None = Field(+ default=None,+ description=(+ "Recipient member name. Pass ``null`` (the default) to "+ "broadcast to every other member of the team. To address "+ "a specific peer use that member's name."+ ),+ )+++_LEADER_DESCRIPTION = """Send a message to a specific team member or \+broadcast to all members.++## When to Use This Tool+- Pass **new** requirements or context from the user to a specific member.+- Broadcast an update or coordination message to all members.+- Ask a member a follow-up question when you need clarification.++## When NOT to Use This Tool+- DO NOT repeatedly call this to check on a member's progress — members \+will automatically notify you via ``TeamSay`` when they finish their task. \+Wait for their message instead of polling.+- DO NOT call this right after creating a member by ``AgentCreate``, the \+member will receive its initial task from the ``prompt`` of the \+``AgentCreate`` call and report back when done — just wait for their message. \+- The session is not in a team yet (call ``TeamCreate`` first).+- You want to talk to yourself — use your own reasoning.++## Important+- Each member starts working immediately when created via AgentCreate. \+When a member finishes its task, it will call ``TeamSay`` to report results \+back to you. You do NOT need to prompt them — just wait for their reply.+- **DO NOT** reply to a member's report message unless you have further \+questions or requirements. ``TeamSay`` is for coordination, not chit-chat — \+your top priority is to complete the overall task.+"""++_WORKER_DESCRIPTION = """Send a message to the team leader or broadcast to \+all team members.++## When to Use This Tool+- **IMPORTANT**: When you finish your assigned task, you MUST call this \+tool to report your results back to the leader. The leader is waiting \+for your report — do not end your turn without sending it.+- Share intermediate findings or ask the leader for clarification.+- Broadcast information that other members might need.++## When NOT to Use This Tool+- You want to talk to yourself — use your own reasoning.+- The message is a transient internal thought with no value to others.+"""+++class TeamSay(_TeamToolBase):+ """Send a message to a teammate (or broadcast to all teammates).++ Resolves the team membership at ``__call__`` time from storage,+ so a member added moments earlier in the same chat run is+ addressable immediately.++ The ``description`` shown to the agent differs by role: leaders+ are reminded not to poll members, workers are reminded to report+ results when done. The role is passed at construction time via+ the ``role`` parameter.+ """++ name: str = "TeamSay"+ description: str++ is_concurrency_safe: bool = True+ is_read_only: bool = True++ input_schema: dict = _TeamSayParams.model_json_schema()++ def __init__(+ self,+ *args: Any,+ role: str = "leader",+ **kwargs: Any,+ ) -> None:+ """Initialise with role-specific description.++ Args:+ role (`str`, defaults to ``"leader"``):+ Either ``"leader"`` or ``"worker"``. Determines which+ description the agent sees for this tool.+ *args:+ Forwarded to :class:`_TeamToolBase.__init__`.+ **kwargs:+ Forwarded to :class:`_TeamToolBase.__init__`.+ """+ super().__init__(*args, **kwargs)+ self.description = (+ _LEADER_DESCRIPTION if role == "leader" else _WORKER_DESCRIPTION+ )++ async def __call__(+ self,+ content: str,+ to: str | None = None,+ ) -> ToolChunk:+ """Deliver the message directly via storage + message bus.++ Reads the current session record from storage to resolve the+ team_id (the agent's team membership may have changed since+ agent assembly), builds the team's (agent_id, session_id)+ directory, and pushes a HintBlock + wakeup to each recipient.++ Args:+ content (`str`):+ Message body.+ to (`str | None`, defaults to ``None``):+ Specific member agent id to target, or ``None`` for+ broadcast.++ Returns:+ `ToolChunk`:+ A confirmation containing the recipient count, or an+ error chunk on failure.+ """+ try:+ session = await self._storage.get_session(+ self._user_id,+ self._agent_id,+ self._session_id,+ )+ if session is None or session.team_id is None:+ return ToolChunk(+ content=[+ TextBlock(+ text=(+ "TeamSay: this session is not in any "+ "team — call TeamCreate first if you "+ "want to start one."+ ),+ ),+ ],+ state=ToolResultState.ERROR,+ )++ team = await self._storage.get_team(+ self._user_id,+ session.team_id,+ )+ if team is None:+ return ToolChunk(+ content=[+ TextBlock(+ text=(+ f"TeamSay: team {session.team_id} no longer "+ f"exists."+ ),+ ),+ ],+ state=ToolResultState.ERROR,+ )++ leader_session = await self._storage.get_session(+ self._user_id,+ "",+ team.session_id,+ )+ if leader_session is None:+ return ToolChunk(+ content=[+ TextBlock(+ text=(+ f"TeamSay: leader session "+ f"{team.session_id} missing for team "+ f"{team.id}."+ ),+ ),+ ],+ state=ToolResultState.ERROR,+ )++ # Build a (name -> (session_id, agent_id)) directory in one+ # pass over the team. Routing is by **name** rather than+ # agent_id so workers can address the leader (they receive+ # the leader's name in the <team-message from="..."> hint+ # but never see the leader's agent_id). Uniqueness of names+ # within the team is enforced at AgentCreate time.+ leader_agent = await self._storage.get_agent(+ self._user_id,+ leader_session.agent_id,+ )+ leader_name = (+ leader_agent.data.name+ if leader_agent is not None+ else leader_session.agent_id+ )+ directory: dict[str, tuple[str, str]] = {+ leader_name: (leader_session.id, leader_session.agent_id),+ }+ for worker_agent_id in team.data.member_ids:+ worker_agent = await self._storage.get_agent(+ self._user_id,+ worker_agent_id,+ )+ if worker_agent is None:+ continue+ sessions = await self._storage.list_sessions(+ self._user_id,+ worker_agent_id,+ )+ if sessions:+ directory[worker_agent.data.name] = (+ sessions[0].id,+ worker_agent_id,+ )++ own_session_ids = {sid for sid, _aid in directory.values()}+ if self._session_id not in own_session_ids:+ return ToolChunk(+ content=[+ TextBlock(+ text=(+ f"TeamSay: this session "+ f"({self._session_id}) is not part of "+ f"team {team.id}."+ ),+ ),+ ],+ state=ToolResultState.ERROR,+ )++ if to is None:+ recipients: list[tuple[str, str]] = [+ (sid, aid)+ for sid, aid in directory.values()+ if sid != self._session_id+ ]+ else:+ resolved = directory.get(to)+ if resolved is None:+ known = sorted(directory.keys())+ return ToolChunk(+ content=[+ TextBlock(+ text=(+ f"TeamSay: no team member is named "+ f"{to!r}. Known members: {known}."+ ),+ ),+ ],+ state=ToolResultState.ERROR,+ )+ target_session_id, target_agent_id = resolved+ if target_session_id == self._session_id:+ return ToolChunk(+ content=[+ TextBlock(+ text=(+ "TeamSay: cannot send a message to "+ "yourself; talk to yourself in your "+ "own reasoning instead."+ ),+ ),+ ],+ state=ToolResultState.ERROR,+ )+ recipients = [(target_session_id, target_agent_id)]++ # Resolve sender display name once.+ sender_agent = await self._storage.get_agent(+ self._user_id,+ self._agent_id,+ )+ sender_name = (+ sender_agent.data.name+ if sender_agent is not None+ else self._agent_id+ )++ hint = HintBlock(+ hint=(+ f'<team-message from="{sender_name}">\n'+ f"{content}\n"+ f"</team-message>"+ ),+ source=sender_name,+ )+ payload = hint.model_dump(mode="json")++ for sid, aid in recipients:+ await self._message_bus.inbox_push(sid, payload)+ await self._message_bus.enqueue_wakeup(+ user_id=self._user_id,+ session_id=sid,+ agent_id=aid,+ )++ count = len(recipients)+ target = "broadcast" if to is None else f"member {to!r}"+ return ToolChunk(+ content=[+ TextBlock(+ text=(+ f"Delivered to {count} recipient(s) "+ f"({target})."+ ),+ ),+ ],+ )+ except Exception as e: # pylint: disable=broad-except+ return ToolChunk(+ content=[TextBlock(text=f"TeamSay failed: {e}")],+ state=ToolResultState.ERROR,+ )diff --git a/src/agentscope/app/_tools/_team_tool_base.py b/src/agentscope/app/_tools/_team_tool_base.pynew file mode 100644index 000000000..734e74e5f--- /dev/null+++ b/src/agentscope/app/_tools/_team_tool_base.py@@ -0,0 +1,99 @@+# -*- coding: utf-8 -*-+"""Base class shared by the team tools."""+from typing import Any, TYPE_CHECKING++from ...permission import (+ PermissionBehavior,+ PermissionContext,+ PermissionDecision,+)+from ...tool import ToolBase++if TYPE_CHECKING:+ from ..message_bus import MessageBus+ from ..storage import StorageBase+++class _TeamToolBase(ToolBase):+ """Shared base for the team tools.++ All team tools are constructed at agent assembly time (in+ :func:`get_toolkit`) with the request-scoped ``user_id``,+ ``session_id``, and ``agent_id`` plus ``storage`` + ``message_bus``+ references. Each tool's ``__call__`` does its work directly via+ those two dependencies — there is no intermediate service layer.++ Permissions: all team tools allow themselves unconditionally — the+ agent's authority to call them is already gated by the+ role/source-aware logic inside :func:`get_toolkit` that decides+ which team tools to attach in the first place.+ """++ name: str+ description: str+ input_schema: dict[str, Any]+ is_concurrency_safe: bool = False+ is_read_only: bool = True+ is_state_injected: bool = False+ is_external_tool: bool = False+ is_mcp: bool = False+ mcp_name: str | None = None++ def __init__(+ self,+ storage: "StorageBase",+ message_bus: "MessageBus",+ user_id: str,+ session_id: str,+ agent_id: str,+ ) -> None:+ """Bind request-scoped identifiers and shared dependencies.++ Args:+ storage (`StorageBase`):+ Application storage. Each tool reads the current+ session / team records at ``__call__`` time to do+ runtime precondition checks (am I in a team? am I the+ leader?) — this is what lets all four team tools be+ attached unconditionally to ``source='user'`` agents+ without depending on a stale snapshot of ``team_id``+ taken at agent assembly time.+ message_bus (`MessageBus`):+ Application message bus. Tools that deliver+ inter-session messages (``AgentCreate``, ``TeamSay``)+ push HintBlocks + wakeups through it.+ user_id (`str`):+ The owner user id of the calling agent.+ session_id (`str`):+ The current session id of the calling agent.+ agent_id (`str`):+ The id of the agent invoking the tool.+ """+ self._storage = storage+ self._message_bus = message_bus+ self._user_id = user_id+ self._session_id = session_id+ self._agent_id = agent_id++ async def check_permissions(+ self,+ tool_input: dict[str, Any],+ context: PermissionContext,+ ) -> PermissionDecision:+ """Always allow — gating is done by tool-attachment logic.++ Args:+ tool_input (`dict[str, Any]`):+ The arguments the agent passed; ignored here.+ context (`PermissionContext`):+ The active permission context; ignored here.++ Returns:+ `PermissionDecision`:+ An ``ALLOW`` decision with a brief explanation.+ """+ return PermissionDecision(+ behavior=PermissionBehavior.ALLOW,+ message=f"{self.name} is always allowed when attached to the "+ f"agent.",+ )diff --git a/src/agentscope/app/_deps.py b/src/agentscope/app/deps.pysimilarity index 67%rename from src/agentscope/app/_deps.pyrename to src/agentscope/app/deps.pyindex 75ad39206..ed2a2dd97 100644--- a/src/agentscope/app/_deps.py+++ b/src/agentscope/app/deps.py@@ -2,13 +2,15 @@"""Shared FastAPI dependencies for the agentscope app."""from fastapi import Header, HTTPException, Request, status+from .workspace_manager import WorkspaceManagerBasefrom ._manager import (BackgroundTaskManager,- SessionManager,- WorkspaceManagerBase,+ ChatRunRegistry,SchedulerManager,)+from ._service import ChatService, SessionServicefrom ._types import AgentMiddlewareFactory, AgentToolFactory+from .message_bus import MessageBusfrom .storage import StorageBase@@ -20,10 +22,6 @@ async def get_current_user_id() -> str:"""Return the caller's user ID from the ``X-User-ID`` request header.- This is a placeholder dependency. Once an auth middleware is in place,- replace the header extraction with a JWT / session-token lookup and remove- the ``X-User-ID`` header entirely.-Args:x_user_id (`str`): Value of the ``X-User-ID`` header.@@ -53,49 +51,65 @@ async def get_storage(request: Request) -> StorageBase:return request.app.state.storage-async def get_session_manager(request: Request) -> SessionManager:- """Return the application-wide session manager.+async def get_message_bus(request: Request) -> MessageBus:+ """Return the application-wide message bus.Args:request (`Request`): The incoming FastAPI request.Returns:- `SessionManager`: The session manager stored in ``app.state``.+ `MessageBus`: The message bus instance stored in ``app.state``."""- return request.app.state.session_manager+ return request.app.state.message_bus-async def get_scheduler_manager(request: Request) -> SchedulerManager:- """Return the application-wide scheduler manager.+async def get_chat_service(request: Request) -> ChatService:+ """Return the application-wide chat service.Args:request (`Request`): The incoming FastAPI request.Returns:- `SchedulerManager`: The scheduler manager stored in ``app.state``.+ `ChatService`: The chat service instance stored in ``app.state``."""- return request.app.state.scheduler_manager+ return request.app.state.chat_service-async def get_workspace_manager(request: Request) -> WorkspaceManagerBase:- """Return the application-wide workspace manager.+async def get_session_service(request: Request) -> SessionService:+ """Return the application-wide session service.Args:request (`Request`): The incoming FastAPI request.Returns:- `WorkspaceManagerBase`: The workspace manager stored in ``app.state``.+ `SessionService`: The session service instance stored in+ ``app.state``.+ """+ return request.app.state.session_service- Raises:- `HTTPException`: 503 if no workspace manager is configured.++async def get_chat_run_registry(request: Request) -> ChatRunRegistry:+ """Return the per-process chat-run registry.++ Args:+ request (`Request`): The incoming FastAPI request.++ Returns:+ `ChatRunRegistry`: The registry stored in ``app.state``."""- manager = request.app.state.workspace_manager- if manager is None:- raise HTTPException(- status_code=status.HTTP_503_SERVICE_UNAVAILABLE,- detail="Workspace manager is not configured.",- )- return manager+ return request.app.state.chat_run_registry+++async def get_scheduler_manager(request: Request) -> SchedulerManager:+ """Return the application-wide scheduler manager.++ Args:+ request (`Request`): The incoming FastAPI request.++ Returns:+ `SchedulerManager`: The scheduler manager stored in ``app.state``.+ """+ return request.app.state.scheduler_managerasync def get_background_task_manager(@@ -107,11 +121,24 @@ async def get_background_task_manager(request (`Request`): The incoming FastAPI request.Returns:- `BackgroundTaskManager`: The manager stored in ``app.state``.+ `BackgroundTaskManager`: The background task manager stored in+ ``app.state``."""return request.app.state.background_task_manager+async def get_workspace_manager(request: Request) -> WorkspaceManagerBase:+ """Return the application-wide workspace manager.++ Args:+ request (`Request`): The incoming FastAPI request.++ Returns:+ `WorkspaceManagerBase`: The workspace manager stored in ``app.state``.+ """+ return request.app.state.workspace_manager++async def get_extra_agent_middlewares(request: Request,) -> AgentMiddlewareFactory | None:diff --git a/src/agentscope/app/message_bus/__init__.py b/src/agentscope/app/message_bus/__init__.pynew file mode 100644index 000000000..147ec9dc5--- /dev/null+++ b/src/agentscope/app/message_bus/__init__.py@@ -0,0 +1,10 @@+# -*- coding: utf-8 -*-+"""The message bus module — live transport for cross-session messages."""++from ._base import MessageBus+from ._redis_message_bus import RedisMessageBus++__all__ = [+ "MessageBus",+ "RedisMessageBus",+]diff --git a/src/agentscope/app/message_bus/_base.py b/src/agentscope/app/message_bus/_base.pynew file mode 100644index 000000000..59985bff3--- /dev/null+++ b/src/agentscope/app/message_bus/_base.py@@ -0,0 +1,747 @@+# -*- coding: utf-8 -*-+"""The message bus abstract base class.++The message bus is the *live* transport layer used to coordinate work+across sessions and processes. It is intentionally separate from+:class:`StorageBase`, which owns *persistent* records: storage may live+on a relational database while the bus stays on a push-capable backend+(Redis, NATS, …) where waking idle consumers and fanning out events is+cheap.++The interface is grouped by **consumption semantics** — i.e. how a+payload's lifetime ends — rather than by business use case. Callers map+their own concepts (agent inbox, session SSE replay, idle wake-up, …)+onto the right mode plus a key naming convention they own.++Three orthogonal modes are exposed:++============================ ===========================================+Mode A — drain queue Mode C — replay log+``queue_push`` / ``log_append`` /+``queue_drain`` ``log_read`` / ``log_trim``++Single-consumer, ack-on-read. Multi-consumer, externally bounded.+Each entry returned at most Each reader tracks its own cursor;+once; storage drops it the entries persist until trimmed,+moment it is read. TTL bounds ``max_len`` truncates from the head,+orphaned data when the consumer or TTL expires the whole key.+disappears.+============================ ===========================================++Mode D — transient broadcast: ``publish`` / ``subscribe``. Fire-and-forget+pub/sub; only currently-subscribed listeners receive a payload, no+history. Use for wake-up signals where missed-while-offline is fine.++Counted broadcast (one entry consumed by N distinct readers) is+intentionally not exposed as a primitive: in practice it requires+consumer-group coordination (Redis Streams' XREADGROUP/XACK semantics)+and adds substantial state. Producers wanting "fan out to N members"+should fan out at write time — push one entry per recipient inbox using+Mode A. The bus stays simple; deduplication is the producer's+responsibility.+"""+from abc import ABC, abstractmethod+from collections.abc import AsyncGenerator+from contextlib import asynccontextmanager+from typing import Any, Callable, Self+++class MessageBus(ABC): # pylint: disable=too-many-public-methods+ """Abstract base class for live message transport.++ Implementations expose three consumption modes (drain queue, replay+ log, transient broadcast) over arbitrary string keys and JSON-style+ dict payloads. Callers own key naming and payload schemas.+ """++ async def __aenter__(self) -> Self:+ """Open underlying transport resources (connection pools, …).++ Returns:+ `Self`:+ The bus instance, for use as an async context manager.+ """+ return self++ async def __aexit__(+ self,+ exc_type: type[BaseException] | None,+ exc_value: BaseException | None,+ traceback: Any,+ ) -> None:+ """Release transport resources on context exit.++ Args:+ exc_type (`type[BaseException] | None`):+ The exception class raised inside the context, if any.+ exc_value (`BaseException | None`):+ The exception instance raised inside the context, if any.+ traceback (`Any`):+ The traceback associated with the exception, if any.+ """+ await self.aclose()++ async def aclose(self) -> None:+ """Release underlying transport resources. Default is a no-op."""++ # ------------------------------------------------------------------+ # Mode A — drain queue (single consumer, ack-on-read)+ # ------------------------------------------------------------------++ @abstractmethod+ async def queue_push(+ self,+ key: str,+ payload: dict,+ *,+ ttl_secs: int | None = None,+ ) -> str:+ """Append ``payload`` to the drain queue at ``key``.++ Drain queues are single-consumer, ack-on-read: a subsequent+ :meth:`queue_drain` returns each entry exactly once and then+ deletes it. ``ttl_secs`` bounds the queue's lifetime so a key+ whose consumer disappears does not accumulate entries forever.++ Args:+ key (`str`):+ Queue identifier. Caller-defined naming convention; the+ bus treats it as opaque.+ payload (`dict`):+ JSON-serializable dict to enqueue. Schema is the+ caller's responsibility.+ ttl_secs (`int | None`, optional):+ If set, refresh the queue key's expiry to this many+ seconds on every push (sliding TTL). When ``None``, the+ key never expires and must be drained or deleted+ explicitly.++ Returns:+ `str`:+ Transport-level entry id (e.g. the Redis Stream entry+ id). Useful for tracing; not required for normal+ consumption.+ """++ @abstractmethod+ async def queue_drain(+ self,+ key: str,+ max_count: int = 100,+ ) -> list[tuple[str, dict]]:+ """Drain up to ``max_count`` entries from the queue at ``key``.++ Returned entries are removed from the queue in the same+ operation, so a subsequent call returns only entries that+ arrived after this one. Safe under the single-consumer-per-key+ invariant.++ Args:+ key (`str`):+ Queue identifier.+ max_count (`int`, defaults to ``100``):+ Maximum number of entries to return in one call.+ Older entries are returned first; remaining entries+ stay in the queue for the next call.++ Returns:+ `list[tuple[str, dict]]`:+ ``(entry_id, payload)`` pairs in arrival order. Empty+ list when the queue is empty.+ """++ @abstractmethod+ async def queue_delete(self, key: str) -> None:+ """Delete the drain queue at ``key`` and all of its entries.++ Idempotent: a no-op when the key does not exist. Used by+ :meth:`session_purge` to drop a session's inbox during+ cascade-delete.++ Args:+ key (`str`):+ Queue identifier.+ """++ # ------------------------------------------------------------------+ # Mode C — replay log (multi-consumer, externally bounded)+ # ------------------------------------------------------------------++ @abstractmethod+ async def log_append(+ self,+ key: str,+ payload: dict,+ *,+ ttl_secs: int | None = None,+ max_len: int | None = None,+ ) -> str:+ """Append ``payload`` to the replay log at ``key``.++ Replay logs are append-only; readers track their own cursor and+ may join at any time. Lifetime is bounded externally: by+ ``ttl_secs`` (whole key expires), by ``max_len`` (oldest+ entries trimmed once the log exceeds the cap), or by explicit+ :meth:`log_trim`.++ Args:+ key (`str`):+ Log identifier.+ payload (`dict`):+ JSON-serializable dict to append.+ ttl_secs (`int | None`, optional):+ If set, refresh the key's expiry to this many seconds+ on every append (sliding TTL). ``None`` means no TTL.+ max_len (`int | None`, optional):+ If set, cap the log at approximately this many entries+ — older entries are trimmed when the cap is exceeded.+ The cap is approximate so the operation can use the+ backend's efficient near-trim mode (e.g. ``XADD MAXLEN+ ~N``). ``None`` means no cap.++ Returns:+ `str`:+ Transport-level entry id, useful as a cursor for+ subsequent :meth:`log_read` calls.+ """++ @abstractmethod+ async def log_read(+ self,+ key: str,+ since: str | None = None,+ max_count: int = 100,+ ) -> list[tuple[str, dict]]:+ """Read up to ``max_count`` entries from the replay log at+ ``key``, starting after ``since``.++ Reads are non-destructive: the same entries can be returned to+ any number of readers, or to the same reader on retry. Each+ reader is responsible for tracking its own cursor.++ Args:+ key (`str`):+ Log identifier.+ since (`str | None`, optional):+ Cursor — return entries strictly newer than this id.+ Pass the last ``entry_id`` from the previous read.+ ``None`` reads from the beginning of the log.+ max_count (`int`, defaults to ``100``):+ Maximum number of entries to return.++ Returns:+ `list[tuple[str, dict]]`:+ ``(entry_id, payload)`` pairs in append order. Empty+ list when no entries are newer than ``since``.+ """++ @abstractmethod+ async def log_trim(+ self,+ key: str,+ before_id: str | None = None,+ ) -> None:+ """Trim the replay log at ``key``.++ Args:+ key (`str`):+ Log identifier.+ before_id (`str | None`, optional):+ Drop all entries with id strictly older than this.+ ``None`` drops the entire log (i.e. deletes the key).+ """++ # ------------------------------------------------------------------+ # Mode D — transient broadcast (fire-and-forget)+ # ------------------------------------------------------------------++ @abstractmethod+ async def publish(+ self,+ key: str,+ payload: dict,+ ) -> None:+ """Publish ``payload`` on the broadcast channel ``key``.++ Only subscribers connected at the moment of publish receive the+ payload — no history is retained. Use for wake-up signals or+ short-lived notifications where missed-while-offline is+ acceptable.++ Args:+ key (`str`):+ Channel identifier.+ payload (`dict`):+ JSON-serializable dict delivered as-is to subscribers.+ """++ @abstractmethod+ async def subscribe(+ self,+ key: str,+ *,+ on_ready: Callable[[], None] | None = None,+ ) -> AsyncGenerator[dict, None]:+ """Yield broadcast payloads for ``key`` until the consumer+ closes the generator.++ Subscriptions are best-effort: only payloads published *after*+ the subscription is established are delivered. Callers own the+ generator's lifetime — closing it releases the underlying+ subscription.++ Args:+ key (`str`):+ Channel identifier.+ on_ready (`Callable[[], None] | None`, optional):+ If supplied, invoked exactly once after the underlying+ subscription is established and before any payload is+ yielded. Used by callers that need to block a+ bootstrapping step (e.g.+ ``SessionTriggerListenerManager.start``) until the+ subscription is live, so a publish-immediately-after+ race is impossible.++ Yields:+ `dict`:+ Each payload originally passed to :meth:`publish`.+ """+ # The empty `yield` makes Python treat this as an async generator+ # function (return type AsyncGenerator) rather than a coroutine+ # returning an AsyncGenerator. Subclasses override it; this body+ # never runs.+ if False: # pylint: disable=using-constant-test+ yield # pylint: disable=unreachable++ # ------------------------------------------------------------------+ # Mode E — distributed lock (cluster-wide mutex)+ # ------------------------------------------------------------------++ @abstractmethod+ @asynccontextmanager+ async def acquire_lock(+ self,+ key: str,+ *,+ ttl_secs: int = 600,+ ) -> AsyncGenerator[None, None]:+ """Acquire a distributed mutex on ``key``.++ Blocks until the lock is acquired, then yields. The+ implementation maintains the lock across long-running+ bodies (typically with a heartbeat task that renews the+ TTL) so the lease only expires if the holding process+ actually crashes — at which point another acquirer may+ take over after at most ``ttl_secs``.++ Args:+ key (`str`):+ Lock identifier.+ ttl_secs (`int`, defaults to ``600``):+ Lease duration in seconds. The implementation+ should renew this periodically while the body+ runs; callers do not need to.++ Yields:+ `None`: while the lock is held.+ """+ # The decorator-based abstract method requires a body for+ # @asynccontextmanager to work; subclasses override it.+ if False: # pylint: disable=using-constant-test+ yield # pylint: disable=unreachable++ @abstractmethod+ async def is_locked(self, key: str) -> bool:+ """Return whether ``key`` currently holds a lock.++ Args:+ key (`str`):+ Lock identifier (same key passed to+ :meth:`acquire_lock`).++ Returns:+ `bool`:+ ``True`` if some process holds the lock right now.+ """++ # ==================================================================+ # Domain helpers — concrete on the base class so all backends+ # share the same key conventions and serialisation rules.+ # ==================================================================++ # Session run coordination -----------------------------------------++ _SESSION_LOCK_KEY = "agentscope:session:lock:{sid}"+ """Per-session distributed-lock key template."""++ _SESSION_EVENTS_KEY = "agentscope:session:events:{sid}"+ """Per-session replay log + live pub/sub channel key template."""++ _SESSION_CANCEL_KEY = "agentscope:session:cancel"+ """Global cancel-broadcast channel. Used by+ :meth:`session_publish_cancel` to ask whichever process is currently+ running a given session to abort its run; the payload carries the+ target ``session_id`` and only the worker actually holding that+ session's task reacts."""++ _SESSION_RUN_TTL_SECS = 600+ """Default lock lease for a chat run (10 minutes)."""++ _SESSION_REPLAY_MAX_LEN = 1000+ """Replay log length cap; older events are trimmed on append."""++ @asynccontextmanager+ async def session_run(self, session_id: str) -> AsyncGenerator[None, None]:+ """Block until exclusive control of ``session_id`` is held.++ Two processes calling this for the same session_id queue up;+ the second only enters after the first releases (or its+ lease expires after a crash).++ On exit, the session's replay log is trimmed *before* the+ lock is released. This guarantees that any process which+ acquires the lock next sees a clean log (and any SSE+ subscriber that connects between this run and the next sees+ a clean slate, not stale events from this run).++ Args:+ session_id (`str`):+ The session to lock.++ Yields:+ `None`: while the session lock is held.+ """+ async with self.acquire_lock(+ self._SESSION_LOCK_KEY.format(sid=session_id),+ ttl_secs=self._SESSION_RUN_TTL_SECS,+ ):+ try:+ yield+ finally:+ # Replay log was the in-flight buffer for this run;+ # the chat run is responsible for persisting the+ # complete Msg to storage before releasing the lock,+ # so the log is no longer needed by any subscriber.+ await self.log_trim(+ self._SESSION_EVENTS_KEY.format(sid=session_id),+ )++ async def session_is_running(self, session_id: str) -> bool:+ """Return whether some process is currently running this session.++ Args:+ session_id (`str`):+ The session to check.++ Returns:+ `bool`:+ ``True`` if a chat run holds the session lock right now.+ """+ return await self.is_locked(+ self._SESSION_LOCK_KEY.format(sid=session_id),+ )++ async def session_publish_event(+ self,+ session_id: str,+ event: dict,+ ) -> str:+ """Append a session event to the replay log + fan it out live.++ The single event is persisted to a Redis Stream (so late-joining+ subscribers can replay it) and simultaneously+ published on a Pub/Sub channel of the same key (so already-connected+ subscribers see it immediately). The persisted+ log entry id is included in the live payload as+ ``_entry_id`` so subscribers can deduplicate replay vs live+ delivery.++ Args:+ session_id (`str`):+ The session this event belongs to.+ event (`dict`):+ JSON-serializable event payload (typically+ ``AgentEvent.model_dump(mode='json')``).++ Returns:+ `str`:+ The replay-log entry id assigned by the backend.+ """+ key = self._SESSION_EVENTS_KEY.format(sid=session_id)+ entry_id = await self.log_append(+ key,+ event,+ max_len=self._SESSION_REPLAY_MAX_LEN,+ )+ await self.publish(key, {**event, "_entry_id": entry_id})+ return entry_id++ async def session_read_events(+ self,+ session_id: str,+ since: str | None = None,+ max_count: int = 1000,+ ) -> list[tuple[str, dict]]:+ """Read events from the session's replay log.++ Args:+ session_id (`str`):+ The session whose events to read.+ since (`str | None`, optional):+ Cursor — return entries strictly newer than this+ replay-log id. ``None`` reads from the beginning.+ max_count (`int`, defaults to ``1000``):+ Maximum events to return.++ Returns:+ `list[tuple[str, dict]]`:+ ``(entry_id, event_payload)`` pairs in append order.+ """+ return await self.log_read(+ self._SESSION_EVENTS_KEY.format(sid=session_id),+ since=since,+ max_count=max_count,+ )++ async def session_subscribe_events(+ self,+ session_id: str,+ *,+ on_ready: Callable[[], None] | None = None,+ ) -> AsyncGenerator[dict, None]:+ """Live-subscribe to a session's published events.++ Yields only payloads delivered after the subscription is+ established. To replay history first, call+ :meth:`session_read_events` separately.++ Args:+ session_id (`str`):+ The session to subscribe to.+ on_ready (`Callable[[], None] | None`, optional):+ Forwarded to the underlying :meth:`subscribe`.++ Yields:+ `dict`:+ Event payloads, with the internal ``_entry_id``+ field stripped (callers don't need to see it).+ """+ key = self._SESSION_EVENTS_KEY.format(sid=session_id)+ async for payload in self.subscribe(key, on_ready=on_ready):+ yield {k: v for k, v in payload.items() if k != "_entry_id"}++ # Cross-process cancel ---------------------------------------------++ async def session_publish_cancel(self, session_id: str) -> None:+ """Broadcast a cancel request for ``session_id``.++ Sent on a transient pub/sub channel: only processes that have+ an active :meth:`session_subscribe_cancel` subscription at+ publish time will see it. The process actually running the+ session is expected to be such a subscriber (its+ :class:`~agentscope.app._manager.CancelDispatcher` subscribes+ for the lifetime of the app). Other processes ignore the+ message because they hold no asyncio task for that session.++ Args:+ session_id (`str`):+ The session whose run should be cancelled.+ """+ await self.publish(+ self._SESSION_CANCEL_KEY,+ {"session_id": session_id},+ )++ async def session_subscribe_cancel(+ self,+ *,+ on_ready: Callable[[], None] | None = None,+ ) -> AsyncGenerator[str, None]:+ """Subscribe to the cancel-broadcast channel.++ Yields session ids as cancel requests arrive. A single+ subscriber per process is enough — the+ :class:`~agentscope.app._manager.CancelDispatcher` filters+ locally by checking whether the incoming ``session_id`` is in+ its own :class:`ChatRunRegistry`.++ Args:+ on_ready (`Callable[[], None] | None`, optional):+ Forwarded to the underlying :meth:`subscribe`.++ Yields:+ `str`:+ The session id from each incoming cancel payload.+ """+ async for payload in self.subscribe(+ self._SESSION_CANCEL_KEY,+ on_ready=on_ready,+ ):+ sid = payload.get("session_id")+ if isinstance(sid, str):+ yield sid++ # Purge -------------------------------------------------------------++ async def session_purge(self, session_id: str) -> None:+ """Delete all per-session bus state.++ Drops the events log and the inbox queue. The distributed+ run-lock is intentionally not touched: callers must ensure no+ run is in flight (e.g. by publishing cancel via+ :meth:`session_publish_cancel` and polling+ :meth:`is_locked` until it clears) before calling this.+ Any residual lock key expires on its own after at most+ :attr:`_SESSION_RUN_TTL_SECS`.++ Idempotent: a no-op when the keys are already absent.++ Args:+ session_id (`str`):+ The session whose bus state should be removed.+ """+ await self.log_trim(self._SESSION_EVENTS_KEY.format(sid=session_id))+ await self.queue_delete(self._INBOX_KEY.format(sid=session_id))++ # Inbox -----------------------------------------------------------++ _INBOX_KEY = "agentscope:inbox:{sid}"+ """Per-session inbox queue key template."""++ async def inbox_push(+ self,+ session_id: str,+ msg: dict,+ *,+ ttl_secs: int | None = None,+ ) -> str:+ """Append an inbound message to a session's inbox.++ Args:+ session_id (`str`):+ The recipient session id.+ msg (`dict`):+ JSON-serializable :class:`Msg` payload (use+ ``Msg.model_dump(mode='json')``).+ ttl_secs (`int | None`, optional):+ Inbox key lifetime; ``None`` means no expiry.++ Returns:+ `str`:+ The transport-level entry id from+ :meth:`queue_push`.+ """+ return await self.queue_push(+ self._INBOX_KEY.format(sid=session_id),+ msg,+ ttl_secs=ttl_secs,+ )++ async def inbox_drain(+ self,+ session_id: str,+ max_count: int = 100,+ ) -> list[tuple[str, dict]]:+ """Drain pending inbox messages for a session.++ Args:+ session_id (`str`):+ The session whose inbox to drain.+ max_count (`int`, defaults to ``100``):+ Maximum entries to drain in one call.++ Returns:+ `list[tuple[str, dict]]`:+ ``(entry_id, msg_payload)`` pairs in arrival order.+ """+ return await self.queue_drain(+ self._INBOX_KEY.format(sid=session_id),+ max_count=max_count,+ )++ # Wakeup ----------------------------------------------------------++ _WAKEUP_QUEUE_KEY = "agentscope:wakeups"+ """Shared wake-up queue (durable Redis Stream)."""++ _WAKEUP_SIGNAL_KEY = "agentscope:wakeup_signal"+ """Shared Pub/Sub channel that nudges dispatchers to drain the+ wake-up queue."""++ async def enqueue_wakeup(+ self,+ user_id: str,+ session_id: str,+ agent_id: str,+ ) -> None:+ """Enqueue a wake-up request and signal dispatchers.++ Producers (e.g. ``TeamSay``, ``AgentCreate``, the scheduler+ trigger, or the BG-tool completion watcher) call this after+ depositing a message in the recipient's inbox. The shared+ :class:`WakeupDispatcher` (one per process) drains the queue+ on each signal and starts a chat run for any session that+ is not currently active.++ Args:+ user_id (`str`):+ The owning user id.+ session_id (`str`):+ The session to wake.+ agent_id (`str`):+ The agent id that owns the session.+ """+ await self.queue_push(+ self._WAKEUP_QUEUE_KEY,+ {+ "user_id": user_id,+ "session_id": session_id,+ "agent_id": agent_id,+ },+ )+ await self.publish(self._WAKEUP_SIGNAL_KEY, {})++ async def dequeue_wakeups(+ self,+ max_count: int = 64,+ ) -> list[dict]:+ """Drain pending wake-up entries.++ Args:+ max_count (`int`, defaults to ``64``):+ Maximum entries to drain per call.++ Returns:+ `list[dict]`:+ Entries shaped ``{"user_id", "session_id",+ "agent_id"}`` in enqueue order.+ """+ entries = await self.queue_drain(+ self._WAKEUP_QUEUE_KEY,+ max_count=max_count,+ )+ return [payload for _entry_id, payload in entries]++ async def subscribe_wakeup_signal(+ self,+ *,+ on_ready: Callable[[], None] | None = None,+ ) -> AsyncGenerator[dict, None]:+ """Subscribe to the shared wake-up signal channel.++ Each yielded item indicates "drain the queue now"; the+ payload itself carries no business data.++ Args:+ on_ready (`Callable[[], None] | None`, optional):+ Forwarded to the underlying :meth:`subscribe`.++ Yields:+ `dict`:+ The empty / opaque signal payload.+ """+ async for payload in self.subscribe(+ self._WAKEUP_SIGNAL_KEY,+ on_ready=on_ready,+ ):+ yield payloaddiff --git a/src/agentscope/app/message_bus/_redis_message_bus.py b/src/agentscope/app/message_bus/_redis_message_bus.pynew file mode 100644index 000000000..bc850062f--- /dev/null+++ b/src/agentscope/app/message_bus/_redis_message_bus.py@@ -0,0 +1,536 @@+# -*- coding: utf-8 -*-+"""The Redis-backed message bus implementation."""+import asyncio+import json+import uuid+from collections.abc import AsyncGenerator+from contextlib import asynccontextmanager+from typing import Any, Callable, Self, TYPE_CHECKING++from ._base import MessageBus++if TYPE_CHECKING:+ from redis.asyncio import ConnectionPool, Redis+else:+ ConnectionPool = Any+ Redis = Any+++class RedisMessageBus(MessageBus):+ """Redis-backed implementation of :class:`MessageBus`.++ Mapping of bus modes to Redis primitives:++ - **Mode A (drain queue)** uses a Redis Stream per key. ``XADD``+ appends a payload whose single field ``payload`` carries the+ JSON-serialised dict. ``queue_drain`` performs ``XRANGE`` followed+ by per-id ``XDEL`` so the read is destructive and idempotent+ under the single-consumer-per-key invariant. ``ttl_secs`` is+ enforced via ``EXPIRE`` after each push (sliding TTL).+ - **Mode C (replay log)** also uses a Redis Stream, but never+ ``XDEL``s on read. Trimming happens via ``XADD … MAXLEN ~N``+ (approximate, for performance) on append, via the ``ttl_secs``+ ``EXPIRE`` on the whole key, or explicitly via+ :meth:`log_trim`. ``log_read`` uses ``XRANGE`` with an exclusive+ start id derived from ``since``.+ - **Mode D (transient broadcast)** rides Redis Pub/Sub. Wake-ups+ are best-effort: payloads published before a subscription exists+ are not delivered.++ The bus owns its own connection pool by default; an external pool+ may be supplied for tests or for sharing a pool across services.+ """++ def __init__(+ self,+ host: str = "localhost",+ port: int = 6379,+ db: int = 0,+ password: str | None = None,+ connection_pool: ConnectionPool | None = None,+ **kwargs: Any,+ ) -> None:+ """Store connection parameters; the actual pool is created in+ :meth:`__aenter__`.++ Args:+ host (`str`, defaults to ``"localhost"``):+ Redis server host.+ port (`int`, defaults to ``6379``):+ Redis server port.+ db (`int`, defaults to ``0``):+ Redis logical database index.+ password (`str | None`, optional):+ Redis password if required by the server.+ connection_pool (`ConnectionPool | None`, optional):+ An externally managed connection pool. When provided+ the pool is used as-is and **not** closed by+ :meth:`aclose` — the caller retains ownership of its+ lifecycle. When omitted a pool is created from+ *host*/*port*/*db*/*password* on :meth:`__aenter__`+ and closed on :meth:`aclose`.+ **kwargs (`Any`):+ Extra keyword arguments forwarded to+ ``redis.asyncio.ConnectionPool`` when the pool is+ created internally (e.g. ``max_connections=20``,+ ``socket_timeout=5``).+ """+ self._host = host+ self._port = port+ self._db = db+ self._password = password+ self._external_pool: ConnectionPool | None = connection_pool+ self._kwargs = kwargs++ # Populated in __aenter__; None until the context is entered.+ self._client: Redis | None = None+ self._owned_pool: ConnectionPool | None = None++ async def __aenter__(self) -> Self:+ """Create the connection pool and Redis client.++ If an external pool was supplied at construction time it is+ used directly and its lifecycle remains the caller's+ responsibility. Otherwise, an internal pool is created from the+ stored host/port/db parameters and will be closed by+ :meth:`aclose`.++ Returns:+ `Self`:+ The bus, ready for use as an async context manager.+ """+ try:+ import redis.asyncio as aioredis+ except ImportError as e:+ raise ImportError(+ "The 'redis' package is required for RedisMessageBus. "+ "Install it with: pip install redis[async]",+ ) from e++ if self._external_pool is not None:+ pool = self._external_pool+ else:+ self._owned_pool = aioredis.ConnectionPool(+ host=self._host,+ port=self._port,+ db=self._db,+ password=self._password,+ decode_responses=True,+ **self._kwargs,+ )+ pool = self._owned_pool++ self._client = aioredis.Redis(connection_pool=pool)+ return self++ async def aclose(self) -> None:+ """Close the connection pool if it was created internally.++ Externally supplied pools are left open — the caller owns them.+ """+ if self._owned_pool is not None:+ await self._owned_pool.aclose()+ self._owned_pool = None+ self._client = None++ async def __aexit__(+ self,+ exc_type: type[BaseException] | None,+ exc_value: BaseException | None,+ traceback: Any,+ ) -> None:+ """Exit the async context manager and release resources.++ Args:+ exc_type (`type[BaseException] | None`):+ Exception class raised inside the context, if any.+ exc_value (`BaseException | None`):+ Exception instance raised inside the context, if any.+ traceback (`Any`):+ Traceback associated with the exception, if any.+ """+ await self.aclose()++ def get_client(self) -> Redis:+ """Return the underlying Redis client.++ Only valid inside the async context (between :meth:`__aenter__`+ and :meth:`aclose`).++ Returns:+ `Redis`:+ The asyncio Redis client instance.+ """+ return self._client++ # ------------------------------------------------------------------+ # Helpers+ # ------------------------------------------------------------------++ @staticmethod+ def _exclusive_start(since: str | None) -> str:+ """Compute the exclusive start id for ``XRANGE`` given a cursor.++ Redis Streams 6.2+ support the ``(`` prefix for exclusive+ ranges, so the simplest portable encoding of "after ``since``"+ is ``f"({since}"``. ``None`` resolves to ``"-"`` (the absolute+ minimum id).++ Args:+ since (`str | None`):+ The previous cursor returned by :meth:`log_read`, or+ ``None`` to read from the beginning.++ Returns:+ `str`:+ The start argument for ``XRANGE``.+ """+ if since is None:+ return "-"+ return f"({since}"++ # ------------------------------------------------------------------+ # Mode A — drain queue+ # ------------------------------------------------------------------++ async def queue_push(+ self,+ key: str,+ payload: dict,+ *,+ ttl_secs: int | None = None,+ ) -> str:+ """Append ``payload`` to the drain queue at ``key``.++ Args:+ key (`str`):+ Stream key for this drain queue.+ payload (`dict`):+ JSON-serializable dict; encoded into the ``payload``+ field of a Redis Stream entry.+ ttl_secs (`int | None`, optional):+ If set, refresh the key's expiry on every push+ (sliding TTL). ``None`` means no TTL — the queue+ persists until drained or deleted explicitly.++ Returns:+ `str`:+ The Redis Stream entry id assigned by ``XADD``.+ """+ entry_id = await self._client.xadd(+ key,+ {"payload": json.dumps(payload)},+ )+ if ttl_secs is not None:+ await self._client.expire(key, ttl_secs)+ return entry_id++ async def queue_drain(+ self,+ key: str,+ max_count: int = 100,+ ) -> list[tuple[str, dict]]:+ """Drain up to ``max_count`` entries from the queue at ``key``.++ Implementation: ``XRANGE`` followed by ``XDEL`` of the+ returned ids, so the operation is destructive in a single+ round-trip pair. Entries that arrive between ``XRANGE`` and+ ``XDEL`` are not affected.++ Args:+ key (`str`):+ Stream key for the drain queue.+ max_count (`int`, defaults to ``100``):+ Maximum entries to return in one call.++ Returns:+ `list[tuple[str, dict]]`:+ ``(entry_id, payload)`` pairs in arrival order. Empty+ list when the queue is empty or absent.+ """+ entries = await self._client.xrange(key, count=max_count)+ if not entries:+ return []++ results: list[tuple[str, dict]] = []+ ids_to_delete: list[str] = []+ for entry_id, fields in entries:+ ids_to_delete.append(entry_id)+ raw = fields.get("payload")+ if raw is None:+ continue+ results.append((entry_id, json.loads(raw)))++ if ids_to_delete:+ await self._client.xdel(key, *ids_to_delete)++ return results++ async def queue_delete(self, key: str) -> None:+ """Delete the drain queue at ``key``.++ Args:+ key (`str`):+ Stream key for the drain queue. ``DEL`` is a no-op+ when the key does not exist.+ """+ await self._client.delete(key)++ # ------------------------------------------------------------------+ # Mode C — replay log+ # ------------------------------------------------------------------++ async def log_append(+ self,+ key: str,+ payload: dict,+ *,+ ttl_secs: int | None = None,+ max_len: int | None = None,+ ) -> str:+ """Append ``payload`` to the replay log at ``key``.++ Args:+ key (`str`):+ Stream key for this replay log.+ payload (`dict`):+ JSON-serializable dict; encoded into the ``payload``+ field of a Redis Stream entry.+ ttl_secs (`int | None`, optional):+ If set, refresh the key's expiry on every append+ (sliding TTL). ``None`` means no TTL.+ max_len (`int | None`, optional):+ If set, cap the log at approximately this many entries+ using ``XADD MAXLEN ~N``. The cap is approximate so+ Redis can use its O(1) trim-by-radix-tree-node mode.+ ``None`` means no cap.++ Returns:+ `str`:+ The Redis Stream entry id, suitable as a cursor for+ later :meth:`log_read` calls.+ """+ kwargs: dict[str, Any] = {}+ if max_len is not None:+ kwargs["maxlen"] = max_len+ kwargs["approximate"] = True+ entry_id = await self._client.xadd(+ key,+ {"payload": json.dumps(payload)},+ **kwargs,+ )+ if ttl_secs is not None:+ await self._client.expire(key, ttl_secs)+ return entry_id++ async def log_read(+ self,+ key: str,+ since: str | None = None,+ max_count: int = 100,+ ) -> list[tuple[str, dict]]:+ """Read up to ``max_count`` entries newer than ``since``.++ Args:+ key (`str`):+ Stream key for the replay log.+ since (`str | None`, optional):+ Exclusive cursor — return entries strictly newer than+ this id (typically the last id from a previous read).+ ``None`` reads from the beginning.+ max_count (`int`, defaults to ``100``):+ Maximum entries to return.++ Returns:+ `list[tuple[str, dict]]`:+ ``(entry_id, payload)`` pairs in append order.+ """+ start = self._exclusive_start(since)+ entries = await self._client.xrange(+ key,+ min=start,+ count=max_count,+ )+ results: list[tuple[str, dict]] = []+ for entry_id, fields in entries:+ raw = fields.get("payload")+ if raw is None:+ continue+ results.append((entry_id, json.loads(raw)))+ return results++ async def log_trim(+ self,+ key: str,+ before_id: str | None = None,+ ) -> None:+ """Trim the replay log at ``key``.++ Args:+ key (`str`):+ Stream key for the replay log.+ before_id (`str | None`, optional):+ Drop all entries with id strictly older than this.+ ``None`` deletes the entire key.+ """+ if before_id is None:+ await self._client.delete(key)+ return+ # XTRIM MINID drops entries with id < before_id.+ await self._client.xtrim(key, minid=before_id)++ # ------------------------------------------------------------------+ # Mode D — transient broadcast+ # ------------------------------------------------------------------++ async def publish(+ self,+ key: str,+ payload: dict,+ ) -> None:+ """Publish ``payload`` on the broadcast channel ``key``.++ Args:+ key (`str`):+ Pub/Sub channel name.+ payload (`dict`):+ JSON-serializable dict; encoded as the channel+ message body.+ """+ await self._client.publish(key, json.dumps(payload))++ async def subscribe(+ self,+ key: str,+ *,+ on_ready: Callable[[], None] | None = None,+ ) -> AsyncGenerator[dict, None]:+ """Yield broadcast payloads on ``key`` until the consumer+ closes the generator.++ Args:+ key (`str`):+ Pub/Sub channel name.+ on_ready (`Callable[[], None] | None`, optional):+ Called once after ``SUBSCRIBE`` has been issued (and+ before any payload is yielded). Lets callers block on+ a "subscription is live" event so they can publish+ immediately after starting a subscriber without losing+ the first message to a SUBSCRIBE/PUBLISH race.++ Yields:+ `dict`:+ Each payload originally passed to :meth:`publish`.+ """+ pubsub = self._client.pubsub()+ try:+ await pubsub.subscribe(key)+ if on_ready is not None:+ on_ready()+ async for message in pubsub.listen():+ if message.get("type") != "message":+ # Skip ``subscribe`` ack and similar control frames.+ continue+ data = message.get("data")+ if data is None:+ continue+ yield json.loads(data)+ finally:+ await pubsub.unsubscribe(key)+ await pubsub.aclose()++ # ------------------------------------------------------------------+ # Mode E — distributed lock+ # ------------------------------------------------------------------++ # Poll interval while waiting for a contested lock.+ _LOCK_RETRY_DELAY_SECS = 0.1++ @asynccontextmanager+ async def acquire_lock(+ self,+ key: str,+ *,+ ttl_secs: int = 600,+ ) -> AsyncGenerator[None, None]:+ """Acquire ``key`` as a distributed mutex.++ Implementation:++ - ``SET key <random-token> NX EX ttl_secs`` to claim the+ lock atomically. Retries every+ ``_LOCK_RETRY_DELAY_SECS`` until acquired.+ - A heartbeat task renews the TTL every ``ttl_secs / 2``+ seconds while the body runs, so a long-running holder+ does not lose the lease.+ - On exit, the heartbeat is cancelled and the lock is+ released by GET-then-DEL guarded on the random token —+ we never delete a key whose value isn't ours, so a+ process whose lease has already expired (and been re-+ acquired by someone else) cannot accidentally release+ the new holder's lock. The non-atomic GET+DEL race+ window opens only after the heartbeat is cancelled, in+ a sub-millisecond span; the ``ttl_secs`` lease still has+ plenty of time left so the race effectively never+ materialises.++ Args:+ key (`str`):+ Lock identifier.+ ttl_secs (`int`, defaults to ``600``):+ Lease duration; auto-renewed via heartbeat.++ Yields:+ `None`: while the lock is held.+ """+ token = uuid.uuid4().hex+ # Acquire (poll until success).+ while True:+ ok = await self._client.set(key, token, nx=True, ex=ttl_secs)+ if ok:+ break+ await asyncio.sleep(self._LOCK_RETRY_DELAY_SECS)++ # Heartbeat: renew TTL every ttl/2 seconds.+ async def _heartbeat() -> None:+ while True:+ await asyncio.sleep(max(1.0, ttl_secs / 2))+ await self._client.expire(key, ttl_secs)++ hb_task = asyncio.create_task(+ _heartbeat(),+ name=f"lock-heartbeat:{key}",+ )++ try:+ yield+ finally:+ hb_task.cancel()+ try:+ await hb_task+ except asyncio.CancelledError:+ pass+ # Release: only delete if the value still matches our+ # token. Failures are swallowed (the lease may have+ # expired naturally, in which case there is nothing to+ # do).+ try:+ current = await self._client.get(key)+ if current == token:+ await self._client.delete(key)+ except Exception: # pylint: disable=broad-except+ pass++ async def is_locked(self, key: str) -> bool:+ """Return whether ``key`` currently holds a lock.++ Args:+ key (`str`):+ Lock identifier.++ Returns:+ `bool`:+ ``True`` if Redis has a value at this key.+ """+ result = await self._client.exists(key)+ return bool(result)diff --git a/src/agentscope/app/_middleware/__init__.py b/src/agentscope/app/middleware/__init__.pysimilarity index 64%rename from src/agentscope/app/_middleware/__init__.pyrename to src/agentscope/app/middleware/__init__.pyindex c34b4aa20..640d8a8b7 100644--- a/src/agentscope/app/_middleware/__init__.py+++ b/src/agentscope/app/middleware/__init__.py@@ -1,12 +1,16 @@# -*- coding: utf-8 -*-"""The middlewares module."""+from ._inbox_middleware import InboxMiddlewarefrom ._protocol import ProtocolMiddlewareBase, AGUIProtocolMiddleware+from ._state_change_middleware import StateChangeMiddlewarefrom ._tool_offload_middleware import ToolOffloadMiddleware__all__ = [+ "InboxMiddleware","ProtocolMiddlewareBase","AGUIProtocolMiddleware",+ "StateChangeMiddleware","ToolOffloadMiddleware",]diff --git a/src/agentscope/app/middleware/_inbox_middleware.py b/src/agentscope/app/middleware/_inbox_middleware.pynew file mode 100644index 000000000..bbf76840d--- /dev/null+++ b/src/agentscope/app/middleware/_inbox_middleware.py@@ -0,0 +1,136 @@+# -*- coding: utf-8 -*-+"""Generic middleware that drains the message bus inbox before reasoning.++Producers push :class:`~agentscope.message.HintBlock` payloads into+the per-session inbox via :class:`~agentscope.app._message_bus.MessageBus`.+This middleware drains the inbox at the start of each reasoning step+and injects the HintBlocks into ``agent.state.context`` — appended to+the last assistant message's content list (same pattern as+:class:`ToolOffloadMiddleware`).++Each injected HintBlock also yields a one-shot ``HintBlockEvent``+so the front-end SSE stream can render it in real time.+"""+from typing import Any, AsyncGenerator, Callable++from ..message_bus import MessageBus+from ..._logging import logger+from ...agent import Agent+from ...event import HintBlockEvent+from ...message import AssistantMsg, HintBlock+from ...middleware import MiddlewareBase+++class InboxMiddleware(MiddlewareBase): # pylint: disable=abstract-method+ """Drain the session's inbox and inject HintBlocks before each+ reasoning step.++ Each entry in the inbox is a serialised+ :class:`~agentscope.message.HintBlock`. The middleware+ deserializes them, appends to the last assistant message in+ ``agent.state.context``, and yields a one-shot ``HintBlockEvent``+ for each so the front-end sees them.++ Args:+ message_bus (`MessageBus`):+ The application message bus to read from.+ max_count (`int`, defaults to ``100``):+ Maximum number of entries drained per reasoning step.+ """++ def __init__(+ self,+ message_bus: MessageBus,+ max_count: int = 100,+ ) -> None:+ """Initialise the middleware.++ Args:+ message_bus (`MessageBus`):+ The application-level message bus.+ max_count (`int`, defaults to ``100``):+ Maximum entries drained per reasoning step.+ """+ self._bus = message_bus+ self._max_count = max_count++ async def on_reasoning( # type: ignore[override]+ self,+ agent: Agent,+ input_kwargs: dict,+ next_handler: Callable[..., AsyncGenerator],+ ) -> AsyncGenerator[Any, None]:+ """Drain the inbox, inject HintBlocks into context, yield+ events, then continue with downstream reasoning.++ Args:+ agent (`Agent`):+ The executing agent. ``agent.state.session_id`` selects+ the inbox to drain.+ input_kwargs (`dict`):+ Reasoning input kwargs (contains ``tool_choice``);+ forwarded unchanged to ``next_handler``.+ next_handler (`Callable[..., AsyncGenerator]`):+ The downstream middleware or core reasoning logic.++ Yields:+ `Any`:+ One ``HintBlockEvent`` per drained inbox entry,+ followed by events from downstream.+ """+ entries = await self._bus.inbox_drain(+ agent.state.session_id,+ max_count=self._max_count,+ )++ if entries:+ hint_blocks = [+ HintBlock.model_validate(payload)+ for _entry_id, payload in entries+ ]++ logger.info(+ "InboxMiddleware: injecting %d HintBlock(s) into context "+ "for session %s",+ len(hint_blocks),+ agent.state.session_id,+ )++ # Inject into agent context (same pattern as+ # ToolOffloadMiddleware).+ if len(agent.state.context) > 0:+ last_msg = agent.state.context[-1]+ if (+ last_msg.role == "assistant"+ and last_msg.name == agent.name+ ):+ last_msg.content.extend(hint_blocks)+ else:+ agent.state.context.append(+ AssistantMsg(+ id=agent.state.reply_id,+ name=agent.name,+ content=list(hint_blocks),+ ),+ )+ else:+ agent.state.context.append(+ AssistantMsg(+ id=agent.state.reply_id,+ name=agent.name,+ content=list(hint_blocks),+ ),+ )++ # Yield one-shot events so the front-end SSE stream sees+ # each HintBlock.+ for hint in hint_blocks:+ yield HintBlockEvent(+ reply_id=agent.state.reply_id,+ block_id=hint.id,+ source=hint.source,+ hint=hint.hint,+ )++ async for evt in next_handler(**input_kwargs):+ yield evtdiff --git a/src/agentscope/app/_middleware/_protocol/__init__.py b/src/agentscope/app/middleware/_protocol/__init__.pysimilarity index 100%rename from src/agentscope/app/_middleware/_protocol/__init__.pyrename to src/agentscope/app/middleware/_protocol/__init__.pydiff --git a/src/agentscope/app/_middleware/_protocol/_agui.py b/src/agentscope/app/middleware/_protocol/_agui.pysimilarity index 100%rename from src/agentscope/app/_middleware/_protocol/_agui.pyrename to src/agentscope/app/middleware/_protocol/_agui.pydiff --git a/src/agentscope/app/_middleware/_protocol/_base.py b/src/agentscope/app/middleware/_protocol/_base.pysimilarity index 100%rename from src/agentscope/app/_middleware/_protocol/_base.pyrename to src/agentscope/app/middleware/_protocol/_base.pydiff --git a/src/agentscope/app/middleware/_state_change_middleware.py b/src/agentscope/app/middleware/_state_change_middleware.pynew file mode 100644index 000000000..7ed174bbf--- /dev/null+++ b/src/agentscope/app/middleware/_state_change_middleware.py@@ -0,0 +1,141 @@+# -*- coding: utf-8 -*-+"""Middleware that detects agent state / team changes after each tool+call and pushes a :class:`CustomEvent` notification to the session's+event stream.++Two kinds of change are detected:++- **State change** — ``tasks_context`` or ``permission_context``+ modified during the tool call (detected via hash comparison).+ Pushes ``CustomEvent(name="state_updated", value={...})``.+- **Team change** — the tool that just ran is one of the team tools+ (``TeamCreate``, ``AgentCreate``, ``TeamDelete``). These tools+ directly mutate storage (``TeamRecord``, ``SessionRecord.team_id``),+ so we don't need to check storage; the fact that the tool ran is+ the trigger. Pushes ``CustomEvent(name="team_updated", value={})``.++Both events are published directly to the bus (via+``session_publish_event``) instead of being yielded through the agent's+event chain, because ``on_acting`` yields ``ToolChunk | ToolResponse``+— not ``AgentEvent``. The SSE ``/stream`` endpoint picks them up from+the bus like any other session event.+"""+import hashlib+from typing import Any, AsyncGenerator, Callable++from ..message_bus import MessageBus+from ...event import CustomEvent+from ...middleware import MiddlewareBase++_TEAM_TOOL_NAMES = frozenset({"TeamCreate", "AgentCreate", "TeamDelete"})+# Tool names whose execution implies a team membership change.+++class StateChangeMiddleware(MiddlewareBase): # pylint: disable=abstract-method+ """Detect state / team changes after each tool call and push+ notifications to the session event stream.++ Args:+ message_bus (`MessageBus`):+ Used to publish ``CustomEvent`` to the session's event+ stream via :meth:`MessageBus.session_publish_event`.+ session_id (`str`):+ The session whose event stream to publish to.+ """++ def __init__(+ self,+ message_bus: MessageBus,+ session_id: str,+ ) -> None:+ """Initialise the middleware.++ Args:+ message_bus (`MessageBus`):+ Application message bus.+ session_id (`str`):+ The session id to publish events for.+ """+ self._bus = message_bus+ self._session_id = session_id++ @staticmethod+ def _state_hash(agent: Any) -> str:+ """Compute a fast hash of the state fields we track.++ Only ``tasks_context`` and ``permission_context`` are included;+ ``context`` (the message history) is intentionally excluded+ because it changes on every reasoning step and is not what+ this middleware cares about.++ Args:+ agent: The agent instance.++ Returns:+ `str`: A hex digest that changes when the tracked fields+ change.+ """+ raw = (+ agent.state.tasks_context.model_dump_json()+ + agent.state.permission_context.model_dump_json()+ )+ return hashlib.md5(raw.encode()).hexdigest()++ async def on_acting(+ self,+ agent: Any,+ input_kwargs: dict,+ next_handler: Callable[..., AsyncGenerator],+ ) -> AsyncGenerator:+ """Wrap tool execution: snapshot state hash before, compare+ after, and push notifications if anything changed.++ Args:+ agent: The executing agent.+ input_kwargs (`dict`):+ Contains ``tool_call`` (``ToolCallBlock``).+ next_handler (`Callable[..., AsyncGenerator]`):+ The downstream middleware or core acting logic.++ Yields:+ ``ToolChunk | ToolResponse`` — unchanged from downstream.+ """+ tool_call = input_kwargs.get("tool_call")+ tool_name = tool_call.name if tool_call else ""++ hash_before = self._state_hash(agent)++ async for item in next_handler(**input_kwargs):+ yield item++ # Check 1: state fields changed?+ hash_after = self._state_hash(agent)+ if hash_before != hash_after:+ event = CustomEvent(+ name="state_updated",+ value={+ "tasks_context": agent.state.tasks_context.model_dump(+ mode="json",+ ),+ "permission_context": (+ agent.state.permission_context.model_dump(+ mode="json",+ )+ ),+ },+ )+ await self._bus.session_publish_event(+ self._session_id,+ event.model_dump(mode="json"),+ )++ # Check 2: team tool ran?+ if tool_name in _TEAM_TOOL_NAMES:+ event = CustomEvent(+ name="team_updated",+ value={},+ )+ await self._bus.session_publish_event(+ self._session_id,+ event.model_dump(mode="json"),+ )diff --git a/src/agentscope/app/_middleware/_tool_offload_middleware.py b/src/agentscope/app/middleware/_tool_offload_middleware.pysimilarity index 51%rename from src/agentscope/app/_middleware/_tool_offload_middleware.pyrename to src/agentscope/app/middleware/_tool_offload_middleware.pyindex a37c412ee..044cc8604 100644--- a/src/agentscope/app/_middleware/_tool_offload_middleware.py+++ b/src/agentscope/app/middleware/_tool_offload_middleware.py@@ -1,16 +1,40 @@# -*- coding: utf-8 -*--"""Middleware that offloads long-running tool calls to background tasks and-injects their results back into the agent context before the next reasoning-step.+"""Middleware that offloads long-running tool calls to background tasks.++When a tool times out, this middleware:++- Lets the underlying asyncio task keep running via+ :class:`BackgroundTaskManager` (the task is **never cancelled**).+- Yields a synthetic placeholder :class:`ToolResponse` so the agent+ loop unblocks immediately.+- On task completion, pushes the real result as a+ :class:`HintBlock` to the session's inbox via the message bus and+ enqueues a wakeup. From there the result follows the same path as a+ team message: :class:`InboxMiddleware` drains it into context on+ the next reasoning step (same run or a fresh wakeup-driven run),+ and :class:`WakeupDispatcher` ensures an idle session is started by+ some process.++The middleware no longer keeps its own pending-result store or+retrigger callback — both responsibilities now live in the+bus/wakeup infrastructure, which works correctly across processes."""import asyncio-from typing import Any, AsyncGenerator, Callable+import json+from copy import deepcopy+from typing import AsyncGenerator, Callable+from .._manager import BackgroundTaskManagerfrom ...middleware import MiddlewareBasefrom ...tool import ToolChunk, ToolResponse-from ...message import AssistantMsg, HintBlock, TextBlock, ToolResultState+from ...message import (+ DataBlock,+ HintBlock,+ TextBlock,+ ToolResultState,+)from ...agent import Agent-from .._manager import BackgroundTaskManager+from ..message_bus import MessageBusfrom ..._logging import logger@@ -21,148 +45,62 @@ _QUEUE_SENTINEL = object()class ToolOffloadMiddleware(MiddlewareBase): # pylint: disable=abstract-method"""Middleware that offloads timed-out tool calls to background tasks.- When a tool execution exceeds ``timeout_secs`` this middleware:-- 1. Lets the underlying :mod:`asyncio` task keep running in the- background via :class:`~agentscope.app.BackgroundTaskManager`.- The task is **never cancelled**.- 2. Returns a synthetic :class:`~agentscope.tool.ToolResponse` to the- agent immediately so the ReAct loop can continue without blocking.- 3. When the background task finishes the real tool result is pushed- into :class:`~agentscope.app.BackgroundTaskManager` result storage.- 4. Before the next :meth:`on_reasoning` call the pending results are- pulled from the manager and injected into ``agent.state.context``- so the model is informed of the completed background result.-.. note::Tools with ``is_state_injected=True`` receive the live- ``agent.state`` object. Offloading such tools to a background- task may cause concurrent state mutations and is therefore- **blocked** — they are always executed synchronously.-- .. code-block:: python-- from agentscope.app import BackgroundTaskManager, ToolOffloadMiddleware-- bg_manager = BackgroundTaskManager()- middleware = ToolOffloadMiddleware(- bg_manager=bg_manager,- timeout_secs=15.0- )-- agent = Agent(- ...,- middlewares=[middleware],- )+ ``agent.state`` object. Offloading them could race on shared+ state, so they are always executed synchronously instead.Args:bg_manager (`BackgroundTaskManager`):- The application-level background task manager shared across- all agents and services. Used only for task registration and- cancellation via :class:`~agentscope.app.TaskStop`.- timeout_secs (`float`, optional):- Maximum seconds to wait for a tool execution before offloading- it to the background. Defaults to ``15.0``.+ Application-level background task manager. Used to register+ the running asyncio task so :class:`TaskStop` can target it.+ message_bus (`MessageBus`):+ Application message bus. The completion callback uses it to+ push the result HintBlock to the session's inbox and to+ enqueue a wakeup so an idle session is woken on any process.+ user_id (`str`):+ User id of the current request — included in the wakeup+ payload so the dispatcher can re-invoke ``ChatService.run``.+ agent_id (`str`):+ Agent record id (not the display name) — same purpose as+ ``user_id``.+ timeout_secs (`float`, defaults to ``10.0``):+ Maximum seconds to wait for a tool execution before+ offloading it to the background."""def __init__(self,- bg_manager: "BackgroundTaskManager",+ bg_manager: BackgroundTaskManager,+ message_bus: MessageBus,+ user_id: str,+ agent_id: str,timeout_secs: float = 10.0,- user_id: str = "",- agent_id: str = "",- session_manager: Any = None,- retrigger_fn: Callable[..., Any] | None = None,) -> None:- """Initialise the middleware.+ """Bind dependencies.Args:bg_manager (`BackgroundTaskManager`):- The application-level background task manager.- timeout_secs (`float`, optional):- Timeout in seconds before a tool call is offloaded.- Defaults to ``10.0``.- user_id (`str`, optional):- The user id for the current request.- agent_id (`str`, optional):- The agent record ID (not the display name).- session_manager:- The session manager, used to check if a session is active.- retrigger_fn:- Async callable ``(session_id, agent_id, user_id) -> None``- that triggers a new agent reply when the session is idle.+ Application background task manager.+ message_bus (`MessageBus`):+ Application message bus.+ user_id (`str`):+ User id of the current request.+ agent_id (`str`):+ Agent record id (not the display name).+ timeout_secs (`float`, defaults to ``10.0``):+ Tool execution timeout before offloading to background."""self._bg_manager = bg_manager- self._timeout_secs = timeout_secs+ self._message_bus = message_busself._user_id = user_idself._agent_id = agent_id- self._session_manager = session_manager- self._retrigger_fn = retrigger_fn+ self._timeout_secs = timeout_secs# ------------------------------------------------------------------# Middleware hooks# ------------------------------------------------------------------- async def on_reasoning( # type:ignore[override]- self,- agent: "Agent",- input_kwargs: dict,- next_handler: Callable[..., AsyncGenerator],- ) -> AsyncGenerator:- """Inject pending background results before reasoning.-- Pops :class:`~agentscope.message.HintBlock` objects pushed by- completed background tasks and appends them to the last assistant- message in ``agent.state.context`` (or creates a new one with- ``state.reply_id`` if the last message is not from the agent).-- Args:- agent (`Agent`):- The executing agent.- input_kwargs (`dict`):- Reasoning input kwargs (contains ``tool_choice``).- next_handler (`Callable[..., AsyncGenerator]`):- The downstream middleware or core reasoning logic.-- Yields:- Events produced by the reasoning process.- """- hint_blocks = self._bg_manager.pop_results(agent.state.session_id)- if hint_blocks:- logger.info(- "Injecting %d pending background result(s) into context: "- "session_id=%s, agent_id=%s",- len(hint_blocks),- agent.state.session_id,- agent.name,- )- if len(agent.state.context) > 0:- last_msg = agent.state.context[-1]- if (- last_msg.role == "assistant"- and last_msg.name == agent.name- ):- last_msg.content.extend(hint_blocks)- else:- agent.state.context.append(- AssistantMsg(- id=agent.state.reply_id,- name=agent.name,- content=list(hint_blocks),- ),- )- else:- agent.state.context.append(- AssistantMsg(- id=agent.state.reply_id,- name=agent.name,- content=list(hint_blocks),- ),- )-- async for evt in next_handler(**input_kwargs):- yield evt-async def on_acting( # type:ignore[override]self,agent: Agent,@@ -177,11 +115,11 @@ class ToolOffloadMiddleware(MiddlewareBase): # pylint: disable=abstract-methoddeadline. If the deadline fires before the tool finishes:- The running task is **not** cancelled.- - It is registered with :attr:`_bg_manager` via- :meth:`~BackgroundTaskManager.register_task`.- - An ``on_complete`` callback (owned by this middleware) drains the- queue, builds a ``<system-notification>`` message, and stores it- in :attr:`_pending_messages`.+ - It is registered with :attr:`_bg_manager` so that+ :class:`TaskStop` can target it and shutdown can cancel it.+ - A separate watcher coroutine is spawned to await the task's+ completion and then push the result as a+ :class:`HintBlock` to the session inbox + enqueue a wakeup.- A synthetic :class:`~agentscope.tool.ToolResponse` notifyingthe agent of the background task id is yielded instead.@@ -282,7 +220,7 @@ class ToolOffloadMiddleware(MiddlewareBase): # pylint: disable=abstract-methodreturn# ----------------------------------------------------------------- # Timeout path: build on_complete callback, register, yield synthetic+ # Timeout path: spawn deliverer, register drain_task, yield synthetic# ----------------------------------------------------------------session_id = agent.state.session_idtool_name = tool_call.name@@ -297,8 +235,34 @@ class ToolOffloadMiddleware(MiddlewareBase): # pylint: disable=abstract-methodagent.name,)- async def _on_complete() -> None:- """Drain remaining queue items and push notification message."""+ async def _deliver_when_done() -> None:+ """Wait for the offloaded tool to finish, then push its+ result to the session inbox + enqueue a wakeup.++ On cancellation (e.g. ``TaskStop``) or unhandled exception+ no result is delivered — the agent is left without a+ completion notification in those edge cases.+ """+ try:+ await drain_task+ except asyncio.CancelledError:+ logger.info(+ "Background tool '%s' cancelled, skipping delivery: "+ "session_id=%s",+ tool_name,+ session_id,+ )+ return+ except Exception: # pylint: disable=broad-except+ logger.warning(+ "Background tool '%s' failed, skipping delivery: "+ "session_id=%s",+ tool_name,+ session_id,+ exc_info=True,+ )+ return+remaining_items: list = []while not queue.empty():try:@@ -315,65 +279,87 @@ class ToolOffloadMiddleware(MiddlewareBase): # pylint: disable=abstract-methodNone,)- if response is not None:- texts = [- b.text- for b in response.content- if isinstance(b, TextBlock)- ]- result_text = "\n".join(texts)- hint_text = (- f"<system-notification>\n"- f"Background task for tool '{tool_name}' has completed.\n"- f"Result:\n{result_text}\n"- f"</system-notification>"+ tool_call_id = tool_call.id++ hint_source = json.dumps(+ {+ "label": "tool_output",+ "sublabel": f"{tool_name} · {tool_call_id}",+ },+ ensure_ascii=False,+ )++ if response is None or len(response.content) == 0:+ hint = HintBlock(+ hint=(+ f"<system-notification>"+ f"Tool '{tool_name}' running in background "+ f"(id={tool_call_id}) has completed with no output."+ f"</system-notification>"+ ),+ source=hint_source,)+else:- hint_text = (- f"<system-notification>\n"- f"Background task for tool '{tool_name}' has completed "- f"with no result.\n"- f"</system-notification>"+ # Preserve all content blocks (text + multimodal) from+ # the tool response so nothing is lost.+ content_blocks: list[TextBlock | DataBlock] = deepcopy(+ response.content,+ )++ prefix = (+ f"<system-notification>"+ f"Tool '{tool_name}' running in background "+ f"(id={tool_call_id}) has completed.\n\n"+ f"Result:\n\n")+ if isinstance(content_blocks[0], TextBlock):+ content_blocks[0].text = prefix + content_blocks[0].text++ else:+ content_blocks.insert(0, TextBlock(text=prefix))++ suffix = "</system-notification>"++ if isinstance(content_blocks[-1], TextBlock):+ content_blocks[-1].text += suffix+ else:+ content_blocks.append(+ TextBlock(text=suffix),+ )++ hint = HintBlock(+ hint=content_blocks,+ source=hint_source,+ )++ # Deliver via inbox + wakeup — same path as a team message.+ # InboxMiddleware drains the inbox into context on the next+ # reasoning step, and WakeupDispatcher kicks an idle session+ # on whichever process picks up the wakeup.logger.info(- "Background tool '%s' completed, pushing result to pending "- "hints: session_id=%s",+ "Background tool '%s' completed, pushing result to inbox "+ "and enqueueing wakeup: session_id=%s",tool_name,session_id,)- self._bg_manager.push_result(+ await self._message_bus.inbox_push(session_id,- HintBlock(hint=hint_text),+ hint.model_dump(mode="json"),+ )+ await self._message_bus.enqueue_wakeup(+ user_id=self._user_id,+ session_id=session_id,+ agent_id=self._agent_id,)- # Re-trigger the agent if the session is idle- if (- self._session_manager is not None- and self._retrigger_fn is not None- and not self._session_manager.is_running(session_id)- ):- logger.info(- "Session idle after background tool '%s' completed, "- "triggering re-invocation: session_id=%s, agent_id=%s",- tool_name,- session_id,- self._agent_id,- )- asyncio.create_task(- self._retrigger_fn(- session_id,- self._agent_id,- self._user_id,- ),- )-+ asyncio.create_task(_deliver_when_done())task_id = await self._bg_manager.register_task(asyncio_task=drain_task,session_id=session_id,agent_id=self._agent_id,user_id=self._user_id,- on_complete=_on_complete,)logger.info(@@ -385,14 +371,16 @@ class ToolOffloadMiddleware(MiddlewareBase): # pylint: disable=abstract-methodagent.name,)- placeholder_text = (- f"<system-reminder>Tool '{tool_name}' is taking "- f"longer than expected and has been moved to the "- f"background (task_id={task_id}). "- f"You may continue with other tasks. "- f"The result will be injected into the context "- f"automatically when finished.</system-reminder>"- )+ placeholder_text = f"""<system-reminder>Tool '{tool_name}' is \+running in background (id={task_id}) for over {self._timeout_secs}s. \+You will be notified automatically when it finishes, so **DO NOT** poll, \+query, or wait for the result yourself. **DO NOT** call any waiting tool \+such as `bash sleep`. You have exactly two valid options:+1. Continue with other independent tasks and ignore this tool for now; or+2. If there is nothing else to do, simply give a text reply without calling \+any tool, which ends the current reasoning loop — just do nothing and end \+this run.+</system-reminder>"""yield ToolChunk(content=[TextBlock(text=placeholder_text)],diff --git a/src/agentscope/app/storage/__init__.py b/src/agentscope/app/storage/__init__.pyindex 1aeee4883..3038ff139 100644--- a/src/agentscope/app/storage/__init__.py+++ b/src/agentscope/app/storage/__init__.py@@ -2,7 +2,7 @@"""The storage module in agentscope."""from ._base import StorageBase-from ._redis_storage import RedisStorage, RedisKeyConfig+from ._redis_storage import RedisStoragefrom ._model import (AgentData,AgentRecord,@@ -14,13 +14,15 @@ from ._model import (SessionRecord,SessionSource,ChatModelConfig,+ TeamData,+ TeamRecord,UserRecord,)__all__ = ["StorageBase",- "RedisKeyConfig","RedisStorage",+ # The ORM models"AgentData","AgentRecord","CredentialRecord",@@ -28,6 +30,8 @@ __all__ = ["SessionRecord","SessionSource","ChatModelConfig",+ "TeamData",+ "TeamRecord","UserRecord","ScheduleData","ScheduleRecord",diff --git a/src/agentscope/app/storage/_base.py b/src/agentscope/app/storage/_base.pyindex dc4efbce4..6f446b7f1 100644--- a/src/agentscope/app/storage/_base.py+++ b/src/agentscope/app/storage/_base.py@@ -12,6 +12,7 @@ from ._model import (SessionRecord,SessionConfig,SessionSource,+ TeamRecord,)from ...credential import CredentialBasefrom ...message import Msg@@ -201,6 +202,31 @@ class StorageBase(ABC):`SessionRecord`: The created or updated record."""+ @abstractmethod+ async def set_session_team_id(+ self,+ user_id: str,+ session_id: str,+ team_id: str | None,+ ) -> None:+ """Set or clear ``team_id`` on an existing session record.++ Bypasses :meth:`upsert_session` because that method does not+ write ``team_id``. Used by team operations (create/dissolve/+ leave) to keep the leader/worker → team relationship consistent.+ Idempotent: a no-op if the session does not exist or already+ holds the given value.++ Args:+ user_id (`str`):+ The owner user id.+ session_id (`str`):+ The session whose ``team_id`` should be updated.+ team_id (`str | None`):+ The new value. ``None`` detaches the session from any+ team.+ """+@abstractmethodasync def update_session_state(self,@@ -423,3 +449,79 @@ class StorageBase(ABC):Returns:`list[Msg]`: Messages in chronological order."""++ # ------------------------------------------------------------------+ # Team persistence+ # ------------------------------------------------------------------++ @abstractmethod+ async def upsert_team(+ self,+ user_id: str,+ record: TeamRecord,+ ) -> TeamRecord:+ """Create or update a team record.++ Args:+ user_id (`str`): The owner user id.+ record (`TeamRecord`): The team record to persist. The record's+ ``id`` is used as the primary key; if a record with the same+ id already exists it is overwritten.++ Returns:+ `TeamRecord`: The stored record (with ``updated_at`` refreshed).+ """++ @abstractmethod+ async def get_team(+ self,+ user_id: str,+ team_id: str,+ ) -> TeamRecord | None:+ """Fetch a single team record by id.++ Args:+ user_id (`str`): The owner user id.+ team_id (`str`): The team id.++ Returns:+ `TeamRecord | None`: The record, or ``None`` if not found.+ """++ @abstractmethod+ async def list_teams(self, user_id: str) -> list[TeamRecord]:+ """List all teams owned by a given user.++ Args:+ user_id (`str`): The user id.++ Returns:+ `list[TeamRecord]`: All team records belonging to the user.+ """++ @abstractmethod+ async def delete_team(self, user_id: str, team_id: str) -> bool:+ """Delete a team record and cascade-delete all of its workers.++ The cascade mirrors SQL's ``ON DELETE CASCADE`` semantics:++ 1. For each ``member_id`` in :attr:`TeamData.member_ids`, call+ :meth:`delete_agent` (which cascades that worker's session).+ 2. Clear ``team_id`` on the leader session referenced by+ :attr:`TeamRecord.session_id` (``ON DELETE SET NULL`` for the+ leader's back-reference to the team). Idempotent if the+ session has already been deleted.+ 3. Delete the :class:`TeamRecord` key and the per-user team+ index entry.++ Args:+ user_id (`str`):+ The owner user id.+ team_id (`str`):+ The id of the team to delete.++ Returns:+ `bool`:+ ``True`` if the team record existed and was deleted,+ ``False`` if not found.+ """diff --git a/src/agentscope/app/storage/_model/__init__.py b/src/agentscope/app/storage/_model/__init__.pyindex e58c5acc1..e376acbec 100644--- a/src/agentscope/app/storage/_model/__init__.py+++ b/src/agentscope/app/storage/_model/__init__.py@@ -10,6 +10,7 @@ from ._session import (ChatModelConfig,SessionSource,)+from ._team import TeamRecord, TeamDatafrom ._user import UserRecord__all__ = [@@ -23,5 +24,7 @@ __all__ = ["SessionRecord","SessionSource","ChatModelConfig",+ "TeamData",+ "TeamRecord","UserRecord",]diff --git a/src/agentscope/app/storage/_model/_agent.py b/src/agentscope/app/storage/_model/_agent.pyindex 2a2b1cb5c..709397631 100644--- a/src/agentscope/app/storage/_model/_agent.py+++ b/src/agentscope/app/storage/_model/_agent.py@@ -1,6 +1,7 @@# -*- coding: utf-8 -*-"""The agent storage class."""import uuid+from typing import Literalfrom pydantic import Field, BaseModel@@ -48,5 +49,16 @@ class AgentRecord(_RecordBase):user_id: str"""The user id"""+ source: Literal["user", "team"] = "user"+ """How this agent was created.++ - ``"user"``: created directly by the user (default). Can have multiple+ sessions and is listed in the user's regular agent list.+ - ``"team"``: spawned as a team worker by another agent's+ ``create_team`` / ``team_add_member`` tool. Has exactly one session.+ Team membership itself is session-level and stored on+ :class:`SessionRecord.team_id`.+ """+data: AgentData"""The agent data"""diff --git a/src/agentscope/app/storage/_model/_schedule.py b/src/agentscope/app/storage/_model/_schedule.pyindex 9a2b22261..523b5c1ce 100644--- a/src/agentscope/app/storage/_model/_schedule.py+++ b/src/agentscope/app/storage/_model/_schedule.py@@ -22,6 +22,21 @@ class ScheduleSource(str, Enum):AGENT = "AGENT"+def _get_local_timezone() -> str:+ """Get the local timezone.++ Returns:+ `str`:+ The local timezone.+ """+ try:+ from tzlocal import get_localzone++ return str(get_localzone())+ except Exception:+ return "UTC"++class ScheduleData(BaseModel):"""The schedule configuration data."""@@ -40,7 +55,7 @@ class ScheduleData(BaseModel):)timezone: str = Field(- default="UTC",+ default=_get_local_timezone(),description="IANA timezone name used to evaluate the cron expression, ""e.g. 'America/New_York' or 'Asia/Shanghai'.",)@@ -51,6 +66,7 @@ class ScheduleData(BaseModel):started_at: datetime = Field(description="The date and time the schedule was started.",+ default_factory=datetime.now,)ended_at: datetime | None = Field(diff --git a/src/agentscope/app/storage/_model/_session.py b/src/agentscope/app/storage/_model/_session.pyindex 6881bcd50..0c1e1c79f 100644--- a/src/agentscope/app/storage/_model/_session.py+++ b/src/agentscope/app/storage/_model/_session.py@@ -67,6 +67,14 @@ class SessionRecord(_RecordBase):source_schedule_id: str | None = None"""The source schedule Id."""+ team_id: str | None = None+ """The team this session participates in, if any.++ Team membership is session-level: a user agent can lead multiple teams+ across different sessions, and each worker session belongs to exactly+ one team. ``None`` means the session is not part of any team.+ """+config: SessionConfig"""Session configuration (workspace, name, model)."""diff --git a/src/agentscope/app/storage/_model/_team.py b/src/agentscope/app/storage/_model/_team.pynew file mode 100644index 000000000..af1b39c1e--- /dev/null+++ b/src/agentscope/app/storage/_model/_team.py@@ -0,0 +1,55 @@+# -*- coding: utf-8 -*-+"""The team storage class."""+from pydantic import BaseModel, Field++from ._base import _RecordBase+++class TeamData(BaseModel):+ """The team data model."""++ name: str = Field(+ description="Display name of the team.",+ title="Name",+ )++ description: str = Field(+ default="",+ description=(+ "What the team is for — its overall goal or shared context. "+ "Wired into every member's system prompt so all members share "+ "the same high-level understanding of why the team exists."+ ),+ title="Description",+ )++ member_ids: list[str] = Field(+ default_factory=list,+ description=(+ "Worker agent ids that belong to this team. Each worker has "+ "``source='team'`` and exactly one session, so the agent id "+ "uniquely identifies the member; the session can be looked up "+ "via :meth:`StorageBase.list_sessions`."+ ),+ title="Member Ids",+ )+++class TeamRecord(_RecordBase):+ """The team ORM model.++ Team membership is session-level: the leader is identified by its+ ``session_id`` (since a user agent can lead multiple teams across+ different sessions). Workers are identified by their agent id in+ :attr:`TeamData.member_ids` (since workers have a 1:1 mapping between+ agent and session).+ """++ user_id: str+ """The user id."""++ session_id: str+ """The leader session id — the session that called ``create_team``."""++ data: TeamData+ """The team data."""diff --git a/src/agentscope/app/storage/_redis_storage.py b/src/agentscope/app/storage/_redis_storage.pyindex 969f794ba..c45e4f924 100644--- a/src/agentscope/app/storage/_redis_storage.py+++ b/src/agentscope/app/storage/_redis_storage.py@@ -15,6 +15,7 @@ from ._model import (SessionRecord,SessionConfig,SessionSource,+ TeamRecord,)from ._utils import _dump_with_secretsfrom ...credential import CredentialBase@@ -28,35 +29,50 @@ else:Redis = Any-class RedisKeyConfig(BaseModel):- """Key templates for all Redis keys used by RedisStorage."""+class RedisStorage(StorageBase):+ """The Redis storage implementation."""- # Record keys- credential: str = "agentscope:user:{user_id}:credential:{credential_id}"- agent: str = "agentscope:user:{user_id}:agent:{agent_id}"- session: str = "agentscope:user:{user_id}:session:{session_id}"+ class KeyConfig(BaseModel):+ """Key templates for all Redis keys used by :class:`RedisStorage`.- # Index keys (Redis Sets — store all IDs for a given scope)- credential_index: str = "agentscope:user:{user_id}:credentials"- agent_index: str = "agentscope:user:{user_id}:agents"- session_index: str = "agentscope:user:{user_id}:agent:{agent_id}:sessions"+ Nested on :class:`RedisStorage` because customising key prefixes+ is meaningful only for this backend; users tweak them via+ ``RedisStorage(key_config=RedisStorage.KeyConfig(...))``.+ """- # Lookup key: maps (user_id, agent_id) → session_id- session_lookup: str = "agentscope:user:{user_id}:agent:{agent_id}:session"+ # Record keys+ credential: str = (+ "agentscope:user:{user_id}:credential:{credential_id}"+ )+ agent: str = "agentscope:user:{user_id}:agent:{agent_id}"+ session: str = "agentscope:user:{user_id}:session:{session_id}"++ # Index keys (Redis Sets — store all IDs for a given scope)+ credential_index: str = "agentscope:user:{user_id}:credentials"+ agent_index: str = "agentscope:user:{user_id}:agents"+ session_index: str = (+ "agentscope:user:{user_id}:agent:{agent_id}:sessions"+ )- # Message list key (Redis List — ordered message history per session)- messages: str = "agentscope:user:{user_id}:session:{session_id}:messages"+ # Lookup key: maps (user_id, agent_id) → session_id+ session_lookup: str = (+ "agentscope:user:{user_id}:agent:{agent_id}:session"+ )- schedule: str = "agentscope:user:{user_id}:schedule:{schedule_id}"- schedule_index: str = "agentscope:user:{user_id}:schedules"- schedule_global_index: str = "agentscope:schedules"- schedule_session_index: str = (- "agentscope:user:{user_id}:schedule:{schedule_id}:sessions"- )+ # Message list key (Redis List — ordered message history per session)+ messages: str = (+ "agentscope:user:{user_id}:session:{session_id}:messages"+ )+ schedule: str = "agentscope:user:{user_id}:schedule:{schedule_id}"+ schedule_index: str = "agentscope:user:{user_id}:schedules"+ schedule_global_index: str = "agentscope:schedules"+ schedule_session_index: str = (+ "agentscope:user:{user_id}:schedule:{schedule_id}:sessions"+ )-class RedisStorage(StorageBase):- """The Redis storage implementation."""+ team: str = "agentscope:user:{user_id}:team:{team_id}"+ team_index: str = "agentscope:user:{user_id}:teams"def __init__(self,@@ -66,7 +82,7 @@ class RedisStorage(StorageBase):password: str | None = None,connection_pool: ConnectionPool | None = None,key_ttl: int | None = None,- key_config: RedisKeyConfig | None = None,+ key_config: "RedisStorage.KeyConfig | None" = None,**kwargs: Any,) -> None:"""Store connection parameters; the actual pool is created in@@ -88,8 +104,9 @@ class RedisStorage(StorageBase):key_ttl (`int | None`, optional):Expire time in seconds for record keys. Refreshed on everywrite (sliding TTL). If `None`, keys do not expire.- key_config (`RedisKeyConfig | None`, optional):- Key template configuration. Defaults to `RedisKeyConfig()`.+ key_config (`RedisStorage.KeyConfig | None`, optional):+ Key template configuration. Defaults to+ ``RedisStorage.KeyConfig()``.**kwargs (`Any`):Extra keyword arguments forwarded to``redis.asyncio.ConnectionPool`` when the pool is created@@ -102,7 +119,7 @@ class RedisStorage(StorageBase):self._external_pool: ConnectionPool | None = connection_poolself._kwargs = kwargsself.key_ttl = key_ttl- self.key_config = key_config or RedisKeyConfig()+ self.key_config = key_config or RedisStorage.KeyConfig()# Populated in __aenter__; None until the context is entered.self._client: Redis | None = None@@ -381,17 +398,23 @@ class RedisStorage(StorageBase):return agent_record.idasync def list_agents(self, user_id: str) -> list[AgentRecord]:- """Return all agent records belonging to the given user.+ """Return user-facing agent records (``source='user'``).- Reads the per-user agent index Set to obtain all ids, then fetches- each record individually. Records whose keys have expired or been- deleted externally are silently skipped.+ Reads the per-user agent index Set to obtain all ids, fetches+ each record individually, and **filters out team-spawned+ workers** (``source='team'``) — those are scoped to a team+ and only addressable via team detail / direct id lookup, not+ enumerated as part of the user's regular agent list.++ Records whose keys have expired or been deleted externally+ are silently skipped.Args:user_id (`str`): The owner user id.Returns:- `list[AgentRecord]`: All agent records for the user.+ `list[AgentRecord]`:+ All ``source='user'`` agent records for the user."""index_key = self._key(self.key_config.agent_index, user_id=user_id)ids = await self._client.smembers(index_key)@@ -405,7 +428,9 @@ class RedisStorage(StorageBase):),)if raw:- records.append(AgentRecord.model_validate_json(raw))+ record = AgentRecord.model_validate_json(raw)+ if record.source == "user":+ records.append(record)return recordsasync def get_agent(@@ -423,21 +448,38 @@ class RedisStorage(StorageBase):return AgentRecord.model_validate_json(raw) if raw else Noneasync def delete_agent(self, user_id: str, agent_id: str) -> bool:- """Delete an agent record and cascade-delete its sessions and- schedules.-- Removes all session records (and their lookup / index keys) that belong- to this agent, then removes all schedule records whose- ``data.agent_id`` matches. Finally, the agent record itself and its- entry in the per-user agent index are deleted.+ """Delete an agent record and cascade-delete its sessions,+ schedules, and any team back-references.++ Cascade order:++ 1. **Sessions** — every session belonging to this agent is+ deleted via :meth:`delete_session` (which itself cascades+ message log, schedule-session index, and — if a session leads+ a team — the team).+ 2. **Schedules** — every schedule whose ``data.agent_id`` matches+ is deleted via :meth:`delete_schedule`.+ 3. **Team back-references (defensive)** — if the agent is a team+ worker (``source='team'``) but the caller chose to delete it+ directly instead of going through :meth:`delete_team`, scan+ the user's teams and remove the agent id from every+ :attr:`TeamData.member_ids` list it appears in. The normal+ path (``delete_team`` iterates ``member_ids`` and calls+ ``delete_agent`` for each) does not need this scan, but it+ keeps the team record consistent if a caller bypasses it.+ 4. **Agent record + index** — finally delete the agent key and+ remove from the per-user agent index.Args:- user_id (`str`): The owner user id.- agent_id (`str`): The id of the agent to delete.+ user_id (`str`):+ The owner user id.+ agent_id (`str`):+ The id of the agent to delete.Returns:- `bool`: ``True`` if the agent record existed and was deleted,- ``False`` if it did not exist.+ `bool`:+ ``True`` if the agent record existed and was deleted,+ ``False`` if it did not exist."""# Cascade: sessionssessions = await self.list_sessions(user_id, agent_id)@@ -447,9 +489,21 @@ class RedisStorage(StorageBase):# Cascade: schedules owned by this agentschedules = await self.list_schedules(user_id)for schedule in schedules:- if schedule.data.agent_id == agent_id:+ if schedule.agent_id == agent_id:await self.delete_schedule(user_id, schedule.id)+ # Defensive: scrub agent_id from any team's member_ids list.+ # The common path (delete_team -> delete_agent) is unaffected+ # because the team is being torn down anyway and removed from+ # the index in step 4 of delete_team.+ teams = await self.list_teams(user_id)+ for team in teams:+ if agent_id in team.data.member_ids:+ team.data.member_ids = [+ mid for mid in team.data.member_ids if mid != agent_id+ ]+ await self.upsert_team(user_id, team)+key = self._key(self.key_config.agent,user_id=user_id,@@ -491,6 +545,10 @@ class RedisStorage(StorageBase):await self._set_with_ttl(key, record.model_dump_json())return record+ # Use the caller-provided ``session_id`` when given so a+ # "create-if-missing under this id" call (e.g. scheduler's+ # stateful-mode session) lands at the expected key.+ new_id_kwargs = {"id": session_id} if session_id else {}record = SessionRecord(user_id=user_id,agent_id=agent_id,@@ -498,6 +556,7 @@ class RedisStorage(StorageBase):source=source,source_schedule_id=source_schedule_id,state=state if state is not None else AgentState(),+ **new_id_kwargs,)key = self._key(self.key_config.session,@@ -609,7 +668,41 @@ class RedisStorage(StorageBase):agent_id: str,session_id: str,) -> bool:- """Delete a session record and clean up all associated keys."""+ """Delete a session record and cascade clean-up.++ Cascades:++ - Existing: per-session message log, schedule-session index entry.+ - **NEW**: if this session is the leader of a team (``team_id``+ set AND a :class:`TeamRecord` exists with+ ``session_id == this session_id``), call :meth:`delete_team`+ first. ``delete_team`` will recursively cascade workers and+ clear ``team_id`` on this session — that clear is idempotent+ and the session itself is deleted right after, so the order is+ safe.++ Worker sessions (``team_id`` set, but the team's+ ``leader_session_id`` is **not** this session) are deleted+ without dissolving the team — the team and the surviving leader+ keep their member_ids list pointing to the now-orphaned worker+ agent. This intentional asymmetry mirrors SQL: there is no FK+ from :class:`SessionRecord` back to the agent that owns it, so+ deleting a session doesn't automatically delete the agent.++ Args:+ user_id (`str`):+ The owner user id.+ agent_id (`str`):+ The id of the agent that owns the session (used to+ clean up the per-agent session index).+ session_id (`str`):+ The id of the session to delete.++ Returns:+ `bool`:+ ``True`` if the session existed and was deleted,+ ``False`` if no record was found.+ """key = self._key(self.key_config.session,user_id=user_id,@@ -621,6 +714,12 @@ class RedisStorage(StorageBase):record = SessionRecord.model_validate_json(raw)+ # Cascade: if this session leads a team, dissolve it first.+ if record.team_id:+ team = await self.get_team(user_id, record.team_id)+ if team is not None and team.session_id == session_id:+ await self.delete_team(user_id, record.team_id)+index_key = self._key(self.key_config.session_index,user_id=user_id,@@ -854,3 +953,195 @@ class RedisStorage(StorageBase):key = self._message_key(user_id, session_id)raw_list = await self._client.lrange(key, offset, offset + limit - 1)return [Msg.model_validate_json(raw) for raw in raw_list]++ # ------------------------------------------------------------------+ # Team persistence+ # ------------------------------------------------------------------++ async def upsert_team(+ self,+ user_id: str,+ record: TeamRecord,+ ) -> TeamRecord:+ """Persist a team record and register it in the user's team index.++ Args:+ user_id (`str`):+ The owner user id. Used to scope both the record key and+ the per-user team index.+ record (`TeamRecord`):+ The team record to persist. Its ``id`` is used as the+ primary key; an existing record with the same id is+ overwritten. ``updated_at`` is refreshed to ``datetime.now()``+ before writing.++ Returns:+ `TeamRecord`:+ The stored record (with refreshed ``updated_at``).+ """+ record.updated_at = datetime.now()+ key = self._key(+ self.key_config.team,+ user_id=user_id,+ team_id=record.id,+ )+ index_key = self._key(self.key_config.team_index, user_id=user_id)+ await self._set_with_ttl(key, record.model_dump_json())+ await self._client.sadd(index_key, record.id)+ return record++ async def get_team(+ self,+ user_id: str,+ team_id: str,+ ) -> TeamRecord | None:+ """Fetch a single team record by id.++ Args:+ user_id (`str`):+ The owner user id.+ team_id (`str`):+ The team id to look up.++ Returns:+ `TeamRecord | None`:+ The record, or ``None`` if no record exists at the+ ``(user_id, team_id)`` key (e.g. expired or never created).+ """+ key = self._key(+ self.key_config.team,+ user_id=user_id,+ team_id=team_id,+ )+ raw = await self._client.get(key)+ if not raw:+ return None+ return TeamRecord.model_validate_json(raw)++ async def list_teams(self, user_id: str) -> list[TeamRecord]:+ """Return all team records belonging to the given user.++ Reads the per-user team index (a Redis Set of team ids) and fetches+ each record individually. Records whose keys have expired or been+ deleted externally are silently skipped.++ Args:+ user_id (`str`):+ The owner user id whose teams to list.++ Returns:+ `list[TeamRecord]`:+ All team records for the user, in arbitrary order (the+ index is a Set).+ """+ index_key = self._key(self.key_config.team_index, user_id=user_id)+ ids = await self._client.smembers(index_key)+ records: list[TeamRecord] = []+ for team_id in ids:+ raw = await self._client.get(+ self._key(+ self.key_config.team,+ user_id=user_id,+ team_id=team_id,+ ),+ )+ if raw:+ records.append(TeamRecord.model_validate_json(raw))+ return records++ async def set_session_team_id(+ self,+ user_id: str,+ session_id: str,+ team_id: str | None,+ ) -> None:+ """Set or clear ``team_id`` on an existing session record.++ Bypasses :meth:`upsert_session` because that method does not+ allow writing ``team_id`` (which is a relation column the+ application normally only mutates via team operations).+ Idempotent: a no-op if the session does not exist or already+ holds the given value.++ Args:+ user_id (`str`):+ The owner user id.+ session_id (`str`):+ The session whose ``team_id`` should be updated.+ team_id (`str | None`):+ The new value. ``None`` detaches the session from any+ team (used by :meth:`delete_team` and by the team+ service when a session leaves a team).+ """+ key = self._key(+ self.key_config.session,+ user_id=user_id,+ session_id=session_id,+ )+ raw = await self._client.get(key)+ if not raw:+ return+ record = SessionRecord.model_validate_json(raw)+ if record.team_id == team_id:+ return+ record.team_id = team_id+ record.updated_at = datetime.now()+ await self._set_with_ttl(key, record.model_dump_json())++ async def delete_team(self, user_id: str, team_id: str) -> bool:+ """Delete a team record and cascade-delete all of its workers.++ Cascade order (mirrors what SQL's ``ON DELETE CASCADE`` would do+ for the same set of foreign keys):++ 1. For each ``member_id`` in :attr:`TeamData.member_ids`, call+ :meth:`delete_agent`. Each call cascades the worker's single+ session via the existing agent-cascade logic.+ 2. Clear ``team_id`` on the leader session (referenced by+ :attr:`TeamRecord.session_id`) — semantically equivalent to+ ``ON DELETE SET NULL`` for that direction of the relationship.+ Idempotent if the session has already been deleted (no-op).+ 3. Delete the :class:`TeamRecord` key and remove it from the+ per-user team index.++ The cascade is best-effort: Redis has no cross-key transaction,+ so a process crash mid-cascade may leave residue. Each step is+ idempotent so retries are safe.++ Args:+ user_id (`str`):+ The owner user id.+ team_id (`str`):+ The id of the team to delete.++ Returns:+ `bool`:+ ``True`` if the team record existed and was deleted,+ ``False`` if no record was found at the+ ``(user_id, team_id)`` key.+ """+ team = await self.get_team(user_id, team_id)+ if team is None:+ # Make sure the index is also clean if the record vanished+ # for any reason.+ index_key = self._key(self.key_config.team_index, user_id=user_id)+ await self._client.srem(index_key, team_id)+ return False++ # Cascade: delete each worker agent (which cascades its session)+ for member_id in team.data.member_ids:+ await self.delete_agent(user_id, member_id)++ # Clear team_id on the leader session (idempotent)+ await self.set_session_team_id(user_id, team.session_id, None)++ # Delete the TeamRecord key + index entry+ key = self._key(+ self.key_config.team,+ user_id=user_id,+ team_id=team_id,+ )+ existed = await self._client.delete(key)+ index_key = self._key(self.key_config.team_index, user_id=user_id)+ await self._client.srem(index_key, team_id)+ return bool(existed)diff --git a/src/agentscope/app/workspace_manager/__init__.py b/src/agentscope/app/workspace_manager/__init__.pynew file mode 100644index 000000000..d60a97472--- /dev/null+++ b/src/agentscope/app/workspace_manager/__init__.py@@ -0,0 +1,15 @@+# -*- coding: utf-8 -*-+"""The workspace manager classes, responsible for managing the resources+and their lifecycles, and filesystem isolation."""++from ._base import WorkspaceManagerBase+from ._local_workspace_manager import LocalWorkspaceManager+from ._docker_workspace_manager import DockerWorkspaceManager+from ._e2b_workspace_manager import E2BWorkspaceManager++__all__ = [+ "WorkspaceManagerBase",+ "LocalWorkspaceManager",+ "DockerWorkspaceManager",+ "E2BWorkspaceManager",+]diff --git a/src/agentscope/app/workspace_manager/_base.py b/src/agentscope/app/workspace_manager/_base.pynew file mode 100644index 000000000..dc6a933b5--- /dev/null+++ b/src/agentscope/app/workspace_manager/_base.py@@ -0,0 +1,73 @@+# -*- coding: utf-8 -*-+"""Workspace manager implementations."""++from abc import ABC, abstractmethod+from typing import Self++from ...workspace import WorkspaceBase+++class WorkspaceManagerBase(ABC):+ """Abstract base for workspace managers.++ Subclasses are expected to be used as async context managers — entering+ the context activates any background machinery the subclass needs (e.g.+ a TTL sweeper task) and exiting it tears that machinery down and closes+ every cached workspace via :meth:`close_all`.++ The default ``__aenter__`` / ``__aexit__`` cover the common case where a+ subclass has no background machinery: enter is a no-op, exit just calls+ :meth:`close_all`. Subclasses that own background tasks should override+ both.+ """++ @abstractmethod+ async def get_workspace(+ self,+ user_id: str,+ agent_id: str,+ session_id: str,+ workspace_id: str,+ ) -> WorkspaceBase:+ """Return an initialized workspace.++ Args:+ user_id (`str`):+ The user id.+ agent_id (`str`):+ The agent id.+ session_id (`str`):+ The session id.+ workspace_id (`str`):+ The workspace id (reconnection credential).+ """++ @abstractmethod+ async def create_workspace(+ self,+ user_id: str,+ agent_id: str,+ session_id: str,+ ) -> WorkspaceBase:+ """Create a new workspace and return it."""++ @abstractmethod+ async def close(self, workspace_id: str) -> None:+ """Close and evict a single workspace from the cache."""++ @abstractmethod+ async def close_all(self) -> None:+ """Close every cached workspace.++ Pure "close all currently tracked workspaces" semantics — does not+ imply the manager itself is being torn down. Use ``async with`` (or+ :meth:`__aexit__` directly) for full manager shutdown.+ """++ async def __aenter__(self) -> Self:+ """Enter the manager's lifetime. Default is a no-op."""+ return self++ async def __aexit__(self, *exc: object) -> None:+ """Exit the manager's lifetime — closes all cached workspaces."""+ await self.close_all()diff --git a/src/agentscope/app/_manager/_docker_workspace_manager.py b/src/agentscope/app/workspace_manager/_docker_workspace_manager.pysimilarity index 97%rename from src/agentscope/app/_manager/_docker_workspace_manager.pyrename to src/agentscope/app/workspace_manager/_docker_workspace_manager.pyindex 4a34ade4c..63ac56301 100644--- a/src/agentscope/app/_manager/_docker_workspace_manager.py+++ b/src/agentscope/app/workspace_manager/_docker_workspace_manager.py@@ -3,7 +3,7 @@Mirrors :class:`LocalWorkspaceManager` 1:1 in its public surface(``get_workspace`` / ``create_workspace`` / ``close`` / ``close_all``)-so that callers — notably :func:`agentscope.app._service.get_agent` —+so that callers — notably :class:`agentscope.app._service.ChatService` —do not branch on backend.Differences from the local manager (allowed to surface only via the@@ -30,14 +30,14 @@ import osimport timefrom typing import Self-from ..._logging import logger-from ...mcp import MCPClient-from ...workspace._docker import DockerWorkspace-from ...workspace._docker._make_dockerfile import (+from agentscope._logging import logger+from agentscope.mcp import MCPClient+from agentscope.workspace._docker import DockerWorkspace+from agentscope.workspace._docker._make_dockerfile import (DEFAULT_BASE_IMAGE,DEFAULT_GATEWAY_PORT,)-from ._workspace_manager import WorkspaceManagerBase+from ._base import WorkspaceManagerBaseDEFAULT_SWEEP_INTERVAL = 300.0diff --git a/src/agentscope/app/_manager/_e2b_workspace_manager.py b/src/agentscope/app/workspace_manager/_e2b_workspace_manager.pysimilarity index 98%rename from src/agentscope/app/_manager/_e2b_workspace_manager.pyrename to src/agentscope/app/workspace_manager/_e2b_workspace_manager.pyindex c16b208d1..ca0b9778e 100644--- a/src/agentscope/app/_manager/_e2b_workspace_manager.py+++ b/src/agentscope/app/workspace_manager/_e2b_workspace_manager.py@@ -3,7 +3,7 @@Mirrors :class:`DockerWorkspaceManager` 1:1 in its public surface(``get_workspace`` / ``create_workspace`` / ``close`` / ``close_all``)-so callers — notably :func:`agentscope.app._service.get_agent` —+so callers — notably :class:`agentscope.app._service.ChatService` —do not branch on backend.Differences from the Docker manager:@@ -36,15 +36,15 @@ import asyncioimport timefrom typing import Self-from ..._logging import logger-from ...mcp import MCPClient-from ...workspace import E2BWorkspace-from ...workspace._e2b._bootstrap import (+from agentscope._logging import logger+from agentscope.mcp import MCPClient+from agentscope.workspace import E2BWorkspace+from agentscope.workspace._e2b._bootstrap import (DEFAULT_GATEWAY_PORT,DEFAULT_TEMPLATE,DEFAULT_TIMEOUT,)-from ._workspace_manager import WorkspaceManagerBase+from ._base import WorkspaceManagerBaseDEFAULT_SWEEP_INTERVAL = 300.0diff --git a/src/agentscope/app/_manager/_workspace_manager.py b/src/agentscope/app/workspace_manager/_local_workspace_manager.pysimilarity index 74%rename from src/agentscope/app/_manager/_workspace_manager.pyrename to src/agentscope/app/workspace_manager/_local_workspace_manager.pyindex b4f921a56..7985c27f9 100644--- a/src/agentscope/app/_manager/_workspace_manager.py+++ b/src/agentscope/app/workspace_manager/_local_workspace_manager.py@@ -1,79 +1,13 @@# -*- coding: utf-8 -*--"""Workspace manager implementations."""+"""The local workspace manager."""+import asyncioimport osimport time-from abc import ABC, abstractmethod-from typing import Selffrom ..._logging import logger-from ...workspace import WorkspaceBase, LocalWorkspace---class WorkspaceManagerBase(ABC):- """Abstract base for workspace managers.-- Subclasses are expected to be used as async context managers — entering- the context activates any background machinery the subclass needs (e.g.- a TTL sweeper task) and exiting it tears that machinery down and closes- every cached workspace via :meth:`close_all`.-- The default ``__aenter__`` / ``__aexit__`` cover the common case where a- subclass has no background machinery: enter is a no-op, exit just calls- :meth:`close_all`. Subclasses that own background tasks should override- both.- """-- @abstractmethod- async def get_workspace(- self,- user_id: str,- agent_id: str,- session_id: str,- workspace_id: str,- ) -> WorkspaceBase:- """Return an initialized workspace.-- Args:- user_id (`str`):- The user id.- agent_id (`str`):- The agent id.- session_id (`str`):- The session id.- workspace_id (`str`):- The workspace id (reconnection credential).- """-- @abstractmethod- async def create_workspace(- self,- user_id: str,- agent_id: str,- session_id: str,- ) -> WorkspaceBase:- """Create a new workspace and return it."""-- @abstractmethod- async def close(self, workspace_id: str) -> None:- """Close and evict a single workspace from the cache."""-- @abstractmethod- async def close_all(self) -> None:- """Close every cached workspace.-- Pure "close all currently tracked workspaces" semantics — does not- imply the manager itself is being torn down. Use ``async with`` (or- :meth:`__aexit__` directly) for full manager shutdown.- """-- async def __aenter__(self) -> Self:- """Enter the manager's lifetime. Default is a no-op."""- return self-- async def __aexit__(self, *exc: object) -> None:- """Exit the manager's lifetime — closes all cached workspaces."""- await self.close_all()+from ...workspace import LocalWorkspace+from ._base import WorkspaceManagerBaseclass LocalWorkspaceManager(WorkspaceManagerBase):diff --git a/src/agentscope/event/__init__.py b/src/agentscope/event/__init__.pyindex b0f0f6dca..d03d7278a 100644--- a/src/agentscope/event/__init__.py+++ b/src/agentscope/event/__init__.py@@ -17,6 +17,7 @@ from ._event import (ThinkingBlockStartEvent,ThinkingBlockDeltaEvent,ThinkingBlockEndEvent,+ HintBlockEvent,ToolCallStartEvent,ToolCallDeltaEvent,ToolCallEndEvent,@@ -29,6 +30,7 @@ from ._event import (RequireExternalExecutionEvent,UserConfirmResultEvent,ExternalExecutionResultEvent,+ CustomEvent,AgentEvent,ConfirmResult,)@@ -50,6 +52,7 @@ __all__ = ["ThinkingBlockStartEvent","ThinkingBlockDeltaEvent","ThinkingBlockEndEvent",+ "HintBlockEvent","ToolCallStartEvent","ToolCallDeltaEvent","ToolCallEndEvent",@@ -62,6 +65,7 @@ __all__ = ["RequireExternalExecutionEvent","UserConfirmResultEvent","ExternalExecutionResultEvent",+ "CustomEvent","AgentEvent","ConfirmResult",]diff --git a/src/agentscope/event/_event.py b/src/agentscope/event/_event.pyindex 8b491052d..ae40b96d9 100644--- a/src/agentscope/event/_event.py+++ b/src/agentscope/event/_event.py@@ -7,7 +7,13 @@ from typing import Literal, List, TypeAliasfrom pydantic import BaseModel, Field, ConfigDict-from ..message import ToolCallBlock, ToolResultBlock, ToolResultState+from ..message import (+ DataBlock,+ TextBlock,+ ToolCallBlock,+ ToolResultBlock,+ ToolResultState,+)from ..permission import PermissionRule@@ -32,6 +38,8 @@ class EventType(StrEnum):THINKING_BLOCK_DELTA = "THINKING_BLOCK_DELTA"THINKING_BLOCK_END = "THINKING_BLOCK_END"+ HINT_BLOCK = "HINT_BLOCK"+TOOL_CALL_START = "TOOL_CALL_START"TOOL_CALL_DELTA = "TOOL_CALL_DELTA"TOOL_CALL_END = "TOOL_CALL_END"@@ -49,6 +57,8 @@ class EventType(StrEnum):USER_CONFIRM_RESULT = "USER_CONFIRM_RESULT"EXTERNAL_EXECUTION_RESULT = "EXTERNAL_EXECUTION_RESULT"+ CUSTOM = "CUSTOM"+class EventBase(BaseModel):"""Base event class."""@@ -224,6 +234,31 @@ class ThinkingBlockEndEvent(EventBase):"""Unique identifier of the thinking block."""+class HintBlockEvent(EventBase):+ """One-shot hint block event.++ Unlike text/thinking blocks, hint blocks are not streamed — the+ full content is available at creation time (team messages,+ background tool results, user interruptions, …). A single event+ carries the complete :class:`~agentscope.message.HintBlock`.++ The ``hint`` field mirrors :attr:`HintBlock.hint` and may be a+ plain string or a list of :class:`TextBlock` / :class:`DataBlock`+ for multimodal content.+ """++ type: Literal[EventType.HINT_BLOCK] = EventType.HINT_BLOCK+ """Event type."""+ reply_id: str+ """ID of the reply message this block belongs to."""+ block_id: str+ """Unique identifier of the hint block."""+ source: str | None = None+ """Sender or origin of this hint (e.g. ``"alice"``, ``"system"``)."""+ hint: str | List[TextBlock | DataBlock]+ """Complete hint content — ``str`` or ``list[TextBlock | DataBlock]``."""++class ToolCallStartEvent(EventBase):"""Tool call start event."""@@ -402,6 +437,40 @@ class ExternalExecutionResultEvent(EventBase):"""Results returned by the external executor."""+class CustomEvent(EventBase):+ """Generic extensible event for signals that don't fit a specific+ ``AgentEvent`` subtype.++ Used by service-layer middleware to notify front-end subscribers+ about state changes (task progress, team membership, permission+ updates, …) without polluting the core agent event enum with+ application-specific types.++ Front-end implementations should handle unknown ``name`` values+ gracefully — skip with no error.++ Attributes:+ name (`str`):+ Identifies the kind of notification. Well-known values:++ - ``"state_updated"`` — agent state (tasks / permission)+ changed during a tool call.+ - ``"team_updated"`` — team membership changed (member+ added / team created or dissolved).++ value (`dict`):+ Arbitrary JSON-serializable payload whose schema depends+ on ``name``. May be empty.+ """++ type: Literal[EventType.CUSTOM] = EventType.CUSTOM+ """Event type discriminator."""+ name: str+ """Kind of notification — see class docstring for well-known values."""+ value: dict = Field(default_factory=dict)+ """Arbitrary payload."""++AgentEvent: TypeAlias = (ReplyStartEvent| ReplyEndEvent@@ -419,6 +488,7 @@ AgentEvent: TypeAlias = (| ThinkingBlockStartEvent| ThinkingBlockDeltaEvent| ThinkingBlockEndEvent+ | HintBlockEvent| ToolCallStartEvent| ToolCallDeltaEvent| ToolCallEndEvent@@ -428,4 +498,5 @@ AgentEvent: TypeAlias = (| ToolResultEndEvent| UserConfirmResultEvent| ExternalExecutionResultEvent+ | CustomEvent)diff --git a/src/agentscope/formatter/_anthropic_formatter.py b/src/agentscope/formatter/_anthropic_formatter.pyindex 35eebac4c..51983137a 100644--- a/src/agentscope/formatter/_anthropic_formatter.py+++ b/src/agentscope/formatter/_anthropic_formatter.py@@ -28,6 +28,7 @@ class _AnthropicFormatterBase(FormatterBase, ABC):"""Mixin for formatting Anthropic formatters to avoid duplication betweenAnthropicChatFormatter and AnthropicMultiAgentFormatter."""+ # pylint: disable=too-many-branchesasync def _format_messages(self,msgs: list[Msg],@@ -105,14 +106,32 @@ class _AnthropicFormatterBase(FormatterBase, ABC):content_blocks = []has_tool_result = False- messages.append(- {- "role": "user",- "content": [- {"type": "text", "text": block.hint},- ],- },- )+ if isinstance(block.hint, str):+ messages.append(+ {+ "role": "user",+ "content": [+ {"type": "text", "text": block.hint},+ ],+ },+ )+ else:+ hint_parts: list[dict] = []+ for sub in block.hint:+ if isinstance(sub, TextBlock):+ hint_parts.append(+ {"type": "text", "text": sub.text},+ )+ elif isinstance(sub, DataBlock):+ formatted_sub = (+ self._format_anthropic_data_block(sub)+ )+ if formatted_sub:+ hint_parts.append(formatted_sub)+ if hint_parts:+ messages.append(+ {"role": "user", "content": hint_parts},+ )elif isinstance(block, DataBlock):formatted_block = self._format_anthropic_data_block(block)diff --git a/src/agentscope/formatter/_dashscope_formatter.py b/src/agentscope/formatter/_dashscope_formatter.pyindex 73959045c..bfe431623 100644--- a/src/agentscope/formatter/_dashscope_formatter.py+++ b/src/agentscope/formatter/_dashscope_formatter.py@@ -231,6 +231,7 @@ class DashScopeChatFormatter(_DashScopeFormatterBase):thinking (``reasoning_content``)."""+ # pylint: disable=too-many-branchesasync def format(self,msgs: list[Msg],@@ -284,14 +285,35 @@ class DashScopeChatFormatter(_DashScopeFormatterBase):tool_calls = []thinking_parts = []- formatted_msgs.append(- {- "role": "user",- "content": [- {"type": "text", "text": block.hint},- ],- },- )+ if isinstance(block.hint, str):+ formatted_msgs.append(+ {+ "role": "user",+ "content": [+ {"type": "text", "text": block.hint},+ ],+ },+ )+ else:+ hint_parts: list[dict] = []+ for sub in block.hint:+ if isinstance(sub, TextBlock):+ hint_parts.append(+ {"type": "text", "text": sub.text},+ )+ elif isinstance(sub, DataBlock):+ formatted_sub = (+ self._format_dashscope_data_block(+ sub,+ role="user",+ )+ )+ if formatted_sub:+ hint_parts.append(formatted_sub)+ if hint_parts:+ formatted_msgs.append(+ {"role": "user", "content": hint_parts},+ )elif isinstance(block, ToolCallBlock):tool_calls.append(diff --git a/src/agentscope/formatter/_deepseek_formatter.py b/src/agentscope/formatter/_deepseek_formatter.pyindex 3b26741b1..fba0eb0a0 100644--- a/src/agentscope/formatter/_deepseek_formatter.py+++ b/src/agentscope/formatter/_deepseek_formatter.py@@ -9,6 +9,7 @@ from .._logging import loggerfrom ..message import (Msg,TextBlock,+ DataBlock,ThinkingBlock,HintBlock,ToolCallBlock,@@ -86,9 +87,27 @@ class DeepSeekChatFormatter(FormatterBase):reasoning_content_blocks = []tool_calls = []- messages.append(- {"role": "user", "content": block.hint},- )+ if isinstance(block.hint, str):+ messages.append(+ {"role": "user", "content": block.hint},+ )+ else:+ hint_text_parts: list[str] = []+ for sub in block.hint:+ if isinstance(sub, TextBlock):+ hint_text_parts.append(sub.text)+ elif isinstance(sub, DataBlock):+ hint_text_parts.append(+ f"[{sub.source.media_type} attached, "+ "not supported by this provider]",+ )+ if hint_text_parts:+ messages.append(+ {+ "role": "user",+ "content": "\n".join(hint_text_parts),+ },+ )elif isinstance(block, ToolCallBlock):tool_calls.append(diff --git a/src/agentscope/formatter/_gemini_formatter.py b/src/agentscope/formatter/_gemini_formatter.pyindex 1854b9323..6bb2f92f6 100644--- a/src/agentscope/formatter/_gemini_formatter.py+++ b/src/agentscope/formatter/_gemini_formatter.py@@ -165,12 +165,28 @@ class GeminiChatFormatter(_GeminiFormatterBase):messages.append({"role": role, "parts": parts})parts = []- messages.append(- {- "role": "user",- "parts": [{"text": block.hint}],- },- )+ if isinstance(block.hint, str):+ messages.append(+ {+ "role": "user",+ "parts": [{"text": block.hint}],+ },+ )+ else:+ hint_parts: list[dict] = []+ for sub in block.hint:+ if isinstance(sub, TextBlock):+ hint_parts.append({"text": sub.text})+ elif isinstance(sub, DataBlock):+ formatted_sub = self._format_gemini_data_block(+ sub,+ )+ if formatted_sub:+ hint_parts.append(formatted_sub)+ if hint_parts:+ messages.append(+ {"role": "user", "parts": hint_parts},+ )elif isinstance(block, DataBlock):formatted = self._format_gemini_data_block(block)diff --git a/src/agentscope/formatter/_moonshot_formatter.py b/src/agentscope/formatter/_moonshot_formatter.pyindex 7fdf59ba6..075c012c4 100644--- a/src/agentscope/formatter/_moonshot_formatter.py+++ b/src/agentscope/formatter/_moonshot_formatter.py@@ -80,6 +80,7 @@ class MoonshotChatFormatter(_OpenAIFormatterBase):) -> dict[str, Any]:return _moonshot_format_image_source(source)+ # pylint: disable=too-many-branchesasync def format(self,msgs: list[Msg],@@ -145,14 +146,33 @@ class MoonshotChatFormatter(_OpenAIFormatterBase):reasoning_parts = []tool_calls = []- messages.append(- {- "role": "user",- "content": [- {"type": "text", "text": block.hint},- ],- },- )+ if isinstance(block.hint, str):+ messages.append(+ {+ "role": "user",+ "content": [+ {"type": "text", "text": block.hint},+ ],+ },+ )+ else:+ hint_parts: list[dict] = []+ for sub in block.hint:+ if isinstance(sub, TextBlock):+ hint_parts.append(+ {"type": "text", "text": sub.text},+ )+ elif isinstance(sub, DataBlock):+ formatted_sub = self._format_openai_data_block(+ sub,+ role="user",+ )+ if formatted_sub is not None:+ hint_parts.append(formatted_sub)+ if hint_parts:+ messages.append(+ {"role": "user", "content": hint_parts},+ )elif isinstance(block, ToolCallBlock):tool_calls.append(diff --git a/src/agentscope/formatter/_ollama_formatter.py b/src/agentscope/formatter/_ollama_formatter.pyindex 88e9b0231..c239e869e 100644--- a/src/agentscope/formatter/_ollama_formatter.py+++ b/src/agentscope/formatter/_ollama_formatter.py@@ -150,9 +150,30 @@ class OllamaChatFormatter(_OllamaFormatterBase):content_parts = []images = []- messages.append(- {"role": "user", "content": block.hint},- )+ if isinstance(block.hint, str):+ messages.append(+ {"role": "user", "content": block.hint},+ )+ else:+ hint_text_parts: list[str] = []+ hint_images: list[str] = []+ for sub in block.hint:+ if isinstance(sub, TextBlock):+ hint_text_parts.append(sub.text)+ elif isinstance(sub, DataBlock):+ formatted_sub = self._format_ollama_data_block(+ sub,+ )+ if formatted_sub:+ hint_images.append(formatted_sub)+ if hint_text_parts or hint_images:+ hint_msg: dict[str, Any] = {+ "role": "user",+ "content": "\n".join(hint_text_parts),+ }+ if hint_images:+ hint_msg["images"] = hint_images+ messages.append(hint_msg)elif isinstance(block, DataBlock):formatted_image = self._format_ollama_data_block(block)diff --git a/src/agentscope/formatter/_openai_formatter.py b/src/agentscope/formatter/_openai_formatter.pyindex ec4354b73..0e842b9ab 100644--- a/src/agentscope/formatter/_openai_formatter.py+++ b/src/agentscope/formatter/_openai_formatter.py@@ -258,14 +258,33 @@ class OpenAIChatFormatter(_OpenAIFormatterBase):content_blocks = []tool_calls = []- messages.append(- {- "role": "user",- "content": [- {"type": "text", "text": block.hint},- ],- },- )+ if isinstance(block.hint, str):+ messages.append(+ {+ "role": "user",+ "content": [+ {"type": "text", "text": block.hint},+ ],+ },+ )+ else:+ hint_parts: list[dict] = []+ for sub in block.hint:+ if isinstance(sub, TextBlock):+ hint_parts.append(+ {"type": "text", "text": sub.text},+ )+ elif isinstance(sub, DataBlock):+ formatted_sub = self._format_openai_data_block(+ sub,+ role="user",+ )+ if formatted_sub is not None:+ hint_parts.append(formatted_sub)+ if hint_parts:+ messages.append(+ {"role": "user", "content": hint_parts},+ )elif isinstance(block, ToolCallBlock):tool_calls.append(diff --git a/src/agentscope/formatter/_openai_response_formatter.py b/src/agentscope/formatter/_openai_response_formatter.pyindex 82aa82d81..283f1188c 100644--- a/src/agentscope/formatter/_openai_response_formatter.py+++ b/src/agentscope/formatter/_openai_response_formatter.py@@ -103,6 +103,7 @@ class OpenAIResponseFormatter(_OpenAIResponseFormatterBase):echoed back verbatim as required by reasoning models (e.g. ``o1``)."""+ # pylint: disable=too-many-branchesasync def format(self,msgs: list[Msg],@@ -161,17 +162,41 @@ class OpenAIResponseFormatter(_OpenAIResponseFormatterBase):)content_parts = []- items.append(- {- "role": "user",- "content": [- {- "type": "input_text",- "text": block.hint,- },- ],- },- )+ if isinstance(block.hint, str):+ items.append(+ {+ "role": "user",+ "content": [+ {+ "type": "input_text",+ "text": block.hint,+ },+ ],+ },+ )+ else:+ hint_parts: list[dict] = []+ for sub in block.hint:+ if isinstance(sub, TextBlock):+ hint_parts.append(+ {+ "type": "input_text",+ "text": sub.text,+ },+ )+ elif isinstance(sub, DataBlock):+ formatted_sub = (+ self._format_response_data_block(+ sub,+ role="user",+ )+ )+ if formatted_sub is not None:+ hint_parts.append(formatted_sub)+ if hint_parts:+ items.append(+ {"role": "user", "content": hint_parts},+ )elif isinstance(block, ThinkingBlock):# When reasoning_item_id is present the block originateddiff --git a/src/agentscope/formatter/_xai_formatter.py b/src/agentscope/formatter/_xai_formatter.pyindex cd89f280a..7f557382e 100644--- a/src/agentscope/formatter/_xai_formatter.py+++ b/src/agentscope/formatter/_xai_formatter.py@@ -97,7 +97,15 @@ class XAIChatFormatter(FormatterBase):if content_args:xai_messages.append(user(*content_args))content_args = []- xai_messages.append(user(block.hint))+ if isinstance(block.hint, str):+ xai_messages.append(user(block.hint))+ else:+ hint_args = self._xai_user_args_from_blocks(+ block.hint,+ image,+ )+ if hint_args:+ xai_messages.append(user(*hint_args))elif isinstance(block, TextBlock):content_args.append(block.text)elif isinstance(block, DataBlock):@@ -229,7 +237,15 @@ class XAIChatFormatter(FormatterBase):if text:xai_messages.append(assistant(text))pending_text = []- xai_messages.append(user(block.hint))+ if isinstance(block.hint, str):+ xai_messages.append(user(block.hint))+ else:+ hint_args = self._xai_user_args_from_blocks(+ block.hint,+ image,+ )+ if hint_args:+ xai_messages.append(user(*hint_args))if pending_tool_calls:# Assistant turn that triggered tool calls (history).@@ -264,6 +280,68 @@ class XAIChatFormatter(FormatterBase):return xai_messages+ def _xai_user_args_from_blocks(+ self,+ blocks: list,+ image: Any,+ ) -> list:+ """Convert a list of ``TextBlock | DataBlock`` into the positional+ args expected by ``xai_sdk.chat.user(*args)``.++ DataBlocks that are not images (or use an unsupported media type)+ are dropped with a warning, matching the existing user-role+ DataBlock handling above.++ Args:+ blocks (`list`):+ The ``hint`` list from a :class:`HintBlock`.+ image (`Any`):+ The ``xai_sdk.chat.image`` constructor, passed in to keep+ the local import contract identical to ``format``.++ Returns:+ `list`:+ Positional args for ``user(*args)``; empty if nothing+ survived.+ """+ args: list = []+ for sub in blocks:+ if isinstance(sub, TextBlock):+ args.append(sub.text)+ elif isinstance(sub, DataBlock):+ if not sub.source.media_type.startswith("image/"):+ logger.warning(+ "Unsupported media type %s for xAI API. "+ "Only image/jpeg and image/png are supported. "+ "This hint sub-block will be skipped.",+ sub.source.media_type,+ )+ continue+ if isinstance(sub.source, URLSource):+ url_str = str(sub.source.url)+ if url_str.startswith("file://"):+ local_path = url_str.removeprefix("file://")+ with open(local_path, "rb") as f:+ encoded = base64.b64encode(f.read()).decode(+ "utf-8",+ )+ args.append(+ image(+ f"data:{sub.source.media_type};"+ f"base64,{encoded}",+ ),+ )+ else:+ args.append(image(url_str))+ elif isinstance(sub.source, Base64Source):+ args.append(+ image(+ f"data:{sub.source.media_type};"+ f"base64,{sub.source.data}",+ ),+ )+ return args+def _extract_result_text(self, output: Any) -> str:"""Extract a plain-text string from a ``ToolResultBlock`` output.diff --git a/src/agentscope/message/_base.py b/src/agentscope/message/_base.pyindex c68bb6ab7..6ef60edc6 100644--- a/src/agentscope/message/_base.py+++ b/src/agentscope/message/_base.py@@ -306,6 +306,18 @@ class Msg(BaseModel):case EventType.THINKING_BLOCK_END:pass+ case EventType.HINT_BLOCK:+ # One-shot event — the full HintBlock content arrives in+ # a single event, so just append it to ``content`` for+ # persistence and replay.+ self.content.append(+ HintBlock(+ id=event.block_id,+ source=event.source,+ hint=event.hint,+ ),+ )+case EventType.TOOL_CALL_START:self.content.append(ToolCallBlock(@@ -392,6 +404,14 @@ class Msg(BaseModel):else:assert isinstance(block, ToolResultBlock)block.state = event.state+ # The paired ToolCallBlock's lifecycle ends with its+ # result — flip it to FINISHED here so the SSE-rebuilt+ # reply_msg matches ``agent.state.context``, which+ # ``_update_tool_call_state`` mutates directly.+ call_block = self._find_block("tool_call", event.tool_call_id)+ if call_block is not None:+ assert isinstance(call_block, ToolCallBlock)+ call_block.state = ToolCallState.FINISHEDcase EventType.REQUIRE_USER_CONFIRM:for tool_call in event.tool_calls:diff --git a/src/agentscope/message/_block.py b/src/agentscope/message/_block.pyindex bd71ef0a3..5755c0bae 100644--- a/src/agentscope/message/_block.py+++ b/src/agentscope/message/_block.py@@ -5,7 +5,7 @@ from enum import StrEnumfrom typing import Literal, List, TypeAliasfrom pydantic import BaseModel, Field, AnyUrl, field_serializer, ConfigDict-from agentscope.permission import PermissionRule+from ..permission import PermissionRuleclass TextBlock(BaseModel):@@ -37,20 +37,6 @@ class ThinkingBlock(BaseModel):"""The unique identifier of the block."""-class HintBlock(BaseModel):- """A block used to provide instructions or hints to the LLM during the- reasoning-acting loop. When passed to the LLM API, the hint block is- converted into a user message.- """-- type: Literal["hint"] = "hint"- """The type of the hint block, which is always 'hint'."""- hint: str- """The hint content of the block."""- id: str = Field(default_factory=lambda: uuid.uuid4().hex)- """The unique identifier of the block."""--class Base64Source(BaseModel):"""The base64 source."""@@ -92,6 +78,29 @@ class DataBlock(BaseModel):"""The name of the data block, which is optional."""+class HintBlock(BaseModel):+ """A block used to provide instructions or hints to the LLM during the+ reasoning-acting loop. When passed to the LLM API, the hint block is+ converted into a user message.++ The ``hint`` field can be a plain string (text-only) or a list of+ :class:`TextBlock` / :class:`DataBlock` for multimodal content+ (e.g. a background tool result containing both text and an image).+ """++ type: Literal["hint"] = "hint"+ """The type of the hint block, which is always 'hint'."""+ hint: str | list[TextBlock | DataBlock]+ """The hint content — plain text or a list of content blocks for+ multimodal data."""+ id: str = Field(default_factory=lambda: uuid.uuid4().hex)+ """The unique identifier of the block."""+ source: str | None = None+ """The sender or origin of this hint. For team messages this is the+ sender's display name (e.g. ``"alice"``); for system notifications+ it may be ``"system"`` or ``None``."""++class ToolCallState(StrEnum):"""The state of the tool call."""diff --git a/src/agentscope/model/_base.py b/src/agentscope/model/_base.pyindex f41caf678..07ef0cd93 100644--- a/src/agentscope/model/_base.py+++ b/src/agentscope/model/_base.py@@ -26,6 +26,7 @@ from ..message import (DataBlock,URLSource,Base64Source,+ HintBlock,)from ..tool import ToolChoice@@ -330,6 +331,20 @@ class ChatModelBase:elif isinstance(block, ThinkingBlock):acc_texts.append(block.thinking)+ elif isinstance(block, HintBlock):+ # ``hint`` may be a plain string or a list of+ # ``TextBlock`` / ``DataBlock`` for multimodal+ # content; mirror the ``ToolResultBlock.output``+ # branching above.+ if isinstance(block.hint, str):+ acc_texts.append(block.hint)+ else:+ for item in block.hint:+ if isinstance(item, TextBlock):+ acc_texts.append(item.text)+ elif isinstance(item, DataBlock):+ data_blocks.append(item)+elif isinstance(block, ToolCallBlock):acc_texts.append(block.input)diff --git a/src/agentscope/tool/__init__.py b/src/agentscope/tool/__init__.pyindex 1782942d6..feac7fedb 100644--- a/src/agentscope/tool/__init__.py+++ b/src/agentscope/tool/__init__.py@@ -4,7 +4,7 @@from ._types import ToolChoice, Function, RegisteredToolfrom ._response import ToolResponse, ToolChunkfrom ._toolkit import Toolkit-from ._base import ToolBase+from ._base import ToolBase, ParamsBasefrom ._adapters import MCPTool, FunctionToolfrom ._builtin import (ResetTools,@@ -28,6 +28,7 @@ __all__ = ["ToolChoice","Function","ToolBase",+ "ParamsBase","MCPTool","FunctionTool","ToolGroup",diff --git a/src/agentscope/tool/_base.py b/src/agentscope/tool/_base.pyindex 60e30e655..e7e44ce2e 100644--- a/src/agentscope/tool/_base.py+++ b/src/agentscope/tool/_base.py@@ -19,7 +19,7 @@ from ._response import ToolChunkfrom ._utils import _remove_title_field-class _ParamsBase(BaseModel):+class ParamsBase(BaseModel):"""A base class for tool parameters that remove the title field from theexported JSON schema."""diff --git a/src/agentscope/tool/_builtin/_grep.py b/src/agentscope/tool/_builtin/_grep.pyindex 83a589bfe..48172a90c 100644--- a/src/agentscope/tool/_builtin/_grep.py+++ b/src/agentscope/tool/_builtin/_grep.py@@ -14,8 +14,7 @@ from ...permission import (PermissionRule,)from .._response import ToolChunk-from ...message import TextBlock-+from ...message import TextBlock, ToolResultState# Version control system directories to exclude from searchesVCS_DIRECTORIES_TO_EXCLUDE = [@@ -345,7 +344,7 @@ class Grep(ToolBase):"Windows: choco install ripgrep",),],- state="error",+ state=ToolResultState.ERROR,is_last=True,)@@ -364,7 +363,7 @@ class Grep(ToolBase):if multiline:args.extend(["-U", "--multiline-dotall"])- # Case insensitive (support both i and case_insensitive+ # Case-insensitive (support both i and case_insensitive# for compatibility)if i or case_insensitive:args.append("-i")@@ -422,13 +421,13 @@ class Grep(ToolBase):except RipgrepTimeoutError as e:return ToolChunk(content=[TextBlock(text=str(e))],- state="error",+ state=ToolResultState.ERROR,is_last=True,)except RuntimeError as e:return ToolChunk(content=[TextBlock(text=str(e))],- state="error",+ state=ToolResultState.ERROR,is_last=True,)@@ -437,7 +436,7 @@ class Grep(ToolBase):content=[TextBlock(text=f"No matches found for pattern: {pattern}"),],- state="running",+ state=ToolResultState.SUCCESS,is_last=True,)@@ -459,6 +458,6 @@ class Grep(ToolBase):return ToolChunk(content=[TextBlock(text="\n".join(limited) + suffix)],- state="running",+ state=ToolResultState.SUCCESS,is_last=True,)diff --git a/src/agentscope/tool/_task/_create_task.py b/src/agentscope/tool/_task/_create_task.pyindex 177d48520..7531e23f1 100644--- a/src/agentscope/tool/_task/_create_task.py+++ b/src/agentscope/tool/_task/_create_task.py@@ -27,22 +27,30 @@ class TaskCreate(_TaskToolBase):name: str = "TaskCreate"- # pylint: disable=line-too-long- description: str = """Use this tool to create a structured task list for your current coding session. This helps you track progress, organize complex tasks, and demonstrate thoroughness to the user.-It also helps the user understand the progress of the task and overall progress of their requests.+ description: str = """Use this tool to create a structured task list for \+your current session. This helps you track progress, organize complex tasks, \+and demonstrate thoroughness to the user.+It also helps the user understand the progress of the task and overall \+progress of their requests.## When to Use This Tool-Use this tool proactively in these scenarios:-- Complex multi-step tasks - When a task requires 3 or more distinct steps or actions-- Non-trivial and complex tasks - Tasks that require careful planning or multiple operations+- Complex multi-step tasks - When a task requires 3 or more distinct steps \+or actions+- Non-trivial and complex tasks - Tasks that require careful planning or \+multiple operations- Plan mode - When using plan mode, create a task list to track the work-- User explicitly requests todo list - When the user directly asks you to use the todo list-- User provides multiple tasks - When users provide a list of things to be done (numbered or comma-separated)-- After receiving new instructions - Immediately capture user requirements as tasks-- When you start working on a task - Mark it as in_progress BEFORE beginning work-- After completing a task - Mark it as completed and add any new follow-up tasks discovered during implementation+- User explicitly requests todo list - When the user directly asks you to \+use the todo list+- User provides multiple tasks - When users provide a list of things to be \+done (numbered or comma-separated)+- After receiving new instructions - Immediately capture user requirements \+as tasks+- When you start working on a task - Mark it as in_progress BEFORE \+beginning work+- After completing a task - Mark it as completed and add any new follow-up \+tasks discovered during implementation## When NOT to Use This Tool@@ -52,11 +60,13 @@ Skip using this tool when:- The task can be completed in less than 3 trivial steps- The task is purely conversational or informational-NOTE that you should not use this tool if there is only one trivial task to do. In this case you are better off just doing the task directly.+NOTE that you should not use this tool if there is only one trivial task to \+do. In this case you are better off just doing the task directly.## Task Fields-- **subject**: A brief, actionable title in imperative form (e.g., "Fix authentication bug in login flow")+- **subject**: A brief, actionable title in imperative form (e.g., \+"Fix authentication bug in login flow")- **description**: What needs to be doneAll tasks are created with status `pending`.@@ -64,8 +74,9 @@ All tasks are created with status `pending`.## Tips- Create tasks with clear, specific subjects that describe the outcome-- After creating tasks, use TaskUpdate to set up dependencies (blocks/blockedBy) if needed-- Check TaskList first to avoid creating duplicate tasks""" # noqa: E501+- After creating tasks, use TaskUpdate to set up dependencies \+(blocks/blockedBy) if needed+- Check TaskList first to avoid creating duplicate tasks"""input_schema: dict = _TaskCreateParams.model_json_schema()@@ -85,7 +96,19 @@ All tasks are created with status `pending`.)try:+ # Derive the next sequential id from existing tasks.+ # Existing ids that look numeric are considered; any+ # non-numeric ids (e.g. legacy UUIDs) are ignored.+ max_numeric = 0+ for t in _agent_state.tasks_context.tasks:+ try:+ max_numeric = max(max_numeric, int(t.id))+ except (ValueError, TypeError):+ pass+ next_id = str(max_numeric + 1)+task = Task(+ id=next_id,subject=subject,description=description,metadata=metadata or {},@@ -95,7 +118,7 @@ All tasks are created with status `pending`.return ToolChunk(content=[TextBlock(- text=f"Task {task.id} created successfully: "+ text=f"Task (id={next_id}) created successfully: "f"{task.subject}",),],diff --git a/src/agentscope/tool/_task/_get_task.py b/src/agentscope/tool/_task/_get_task.pyindex 7d6ab3e29..978a16d69 100644--- a/src/agentscope/tool/_task/_get_task.py+++ b/src/agentscope/tool/_task/_get_task.py@@ -74,7 +74,7 @@ Returns full task details:# Build the responselines = [- f"Task #{task.id}: {task.subject}",+ f"Task (id={task.id}): {task.subject}",f"Status: {task.state}",f"Description: {task.description}",]diff --git a/src/agentscope/tool/_task/_list_task.py b/src/agentscope/tool/_task/_list_task.pyindex 7e409f91f..c1164fd3b 100644--- a/src/agentscope/tool/_task/_list_task.py+++ b/src/agentscope/tool/_task/_list_task.py@@ -3,13 +3,13 @@from ._task_tool_base import _TaskToolBasefrom .._response import ToolChunk-from .._base import _ParamsBase+from .._base import ParamsBasefrom ...state import AgentStatefrom ...exception import DeveloperOrientedExceptionfrom ...message import TextBlock-class _TaskListParams(_ParamsBase):+class _TaskListParams(ParamsBase):"""The params of the list task params."""@@ -64,7 +64,7 @@ Use TaskGet with a specific task ID to view full details including description aelse "")tasks.append(- f"#{task.id} [{task.state}] {task.subject}{owner}{blocked}",+ f"{task.id} [{task.state}] {task.subject}{owner}{blocked}",)return ToolChunk(diff --git a/src/agentscope/tool/_task/_update_task.py b/src/agentscope/tool/_task/_update_task.pyindex bb294df6e..7f4a95b71 100644--- a/src/agentscope/tool/_task/_update_task.py+++ b/src/agentscope/tool/_task/_update_task.py@@ -163,7 +163,7 @@ Set up task dependencies:content=[TextBlock(text=f"TaskNotFoundError: "- f"The task {task_id} does not exist.",+ f"The task (id={task_id}) does not exist.",),],state=ToolResultState.ERROR,@@ -227,7 +227,9 @@ Set up task dependencies:task.blocked_by.remove(task_id)return ToolChunk(content=[- TextBlock(text=f"Task {task_id} has been deleted."),+ TextBlock(+ text=f"Task (id={task_id}) has been deleted.",+ ),],)# Update the status@@ -250,10 +252,10 @@ Set up task dependencies:_agent_state.tasks_context.tasks[index].metadata[k] = vif updated_fields:- res = f'Update task #{task_id} {", ".join(updated_fields)}.'+ res = f'Update task (id={task_id}) {", ".join(updated_fields)}.'else:res = (- f"No updates were made to the task #{task_id}. "+ f"No updates were made to the task (id={task_id}). "f"Make sure you provided at least one field to update and "f"the values are correct.")diff --git a/tests/agui_protocol_test.py b/tests/agui_protocol_test.pyindex 8497c0de9..4a1746541 100644--- a/tests/agui_protocol_test.py+++ b/tests/agui_protocol_test.py@@ -4,7 +4,7 @@from unittest.async_case import IsolatedAsyncioTestCasefrom unittest.mock import MagicMock-from agentscope.app import AGUIProtocolMiddleware+from agentscope.app.middleware import AGUIProtocolMiddlewarefrom agentscope.event import (ConfirmResult,DataBlockDeltaEvent,diff --git a/tests/builtin_grep_test.py b/tests/builtin_grep_test.pyindex dc73e01bb..a790c6c8e 100644--- a/tests/builtin_grep_test.py+++ b/tests/builtin_grep_test.py@@ -4,6 +4,7 @@ import osimport tempfilefrom unittest.async_case import IsolatedAsyncioTestCase+from agentscope.message import ToolResultStatefrom agentscope.tool import Grepfrom agentscope.permission import (PermissionContext,@@ -86,7 +87,7 @@ class GrepToolTest(IsolatedAsyncioTestCase):output_mode="files_with_matches",)- self.assertEqual(chunk.state, "running")+ self.assertEqual(chunk.state, ToolResultState.SUCCESS)content = chunk.content[0].text# Should find files containing "Hello"diff --git a/tests/event_to_message_test.py b/tests/event_to_message_test.pyindex 6c4134f66..e78786bee 100644--- a/tests/event_to_message_test.py+++ b/tests/event_to_message_test.py@@ -429,8 +429,14 @@ class EventToMessageTest(IsolatedAsyncioTestCase):tool_call_id=_TC_ALLOW,state=ToolResultState.SUCCESS,)+ # TOOL_RESULT_END flips the paired ToolCallBlock to FINISHED, so the+ # tool_call state in the prefix changes from "allowed" to "finished"+ # from this point onward.+ _s4b_done_prefix = _s4_prefix + [+ _tcb(_TC_ALLOW, "search", '{"q": "hi"}', "finished"),+ ]gt_result_end_ok = _base(- _s4b_prefix+ _s4b_done_prefix+ [_trb(_TC_ALLOW,@@ -450,7 +456,7 @@ class EventToMessageTest(IsolatedAsyncioTestCase):# ================================================================# Stage 5 – ToolCall (TC_DENY): stream → confirm → denied (finished)# ================================================================- _s5_prefix = _s4b_prefix + [+ _s5_prefix = _s4b_done_prefix + [_trb(_TC_ALLOW,"search",@@ -636,8 +642,12 @@ class EventToMessageTest(IsolatedAsyncioTestCase):tool_call_id=_TC_IMG,state=ToolResultState.ERROR,)+ # TOOL_RESULT_END flips the paired ToolCallBlock to FINISHED.+ _s7b_done_prefix = _s7_prefix + [+ _tcb(_TC_IMG, "screenshot", "", "finished"),+ ]gt_res_img_end = _base(- _s7b_prefix+ _s7b_done_prefix+ [_trb(_TC_IMG,@@ -659,7 +669,7 @@ class EventToMessageTest(IsolatedAsyncioTestCase):# Stage 8 – ModelCallEndEvent (first call: usage initialized;# second call: usage accumulated)# ================================================================- _final_content = _s7b_prefix + [+ _final_content = _s7b_done_prefix + [_trb(_TC_IMG,"screenshot",diff --git a/tests/formatter_anthropic_test.py b/tests/formatter_anthropic_test.pyindex e07202090..6035e1617 100644--- a/tests/formatter_anthropic_test.py+++ b/tests/formatter_anthropic_test.py@@ -784,3 +784,49 @@ class TestAnthropicFormatter(IsolatedAsyncioTestCase):],res,)++ async def test_chat_formatter_hint_block_multimodal(self) -> None:+ """Multimodal HintBlock becomes a single user message with text+ + image."""+ fmt = AnthropicChatFormatter()+ msgs = [+ AssistantMsg(+ name="assistant",+ content=[+ HintBlock(+ hint=[+ TextBlock(text="Inspect this screenshot:"),+ DataBlock(+ source=Base64Source(+ data=self.image_b64,+ media_type="image/png",+ ),+ ),+ ],+ ),+ ],+ ),+ ]+ res = await fmt.format(msgs)+ self.assertListEqual(+ [+ {+ "role": "user",+ "content": [+ {+ "type": "text",+ "text": "Inspect this screenshot:",+ },+ {+ "type": "image",+ "source": {+ "type": "base64",+ "media_type": "image/png",+ "data": self.image_b64,+ },+ },+ ],+ },+ ],+ res,+ )diff --git a/tests/formatter_dashscope_test.py b/tests/formatter_dashscope_test.pyindex 9e67fe866..8d64914ef 100644--- a/tests/formatter_dashscope_test.py+++ b/tests/formatter_dashscope_test.py@@ -991,3 +991,45 @@ class TestDashScopeFormatter(IsolatedAsyncioTestCase):],res,)++ async def test_chat_formatter_hint_block_multimodal(self) -> None:+ """Multimodal HintBlock becomes a single user message with text+ + image."""+ fmt = DashScopeChatFormatter()+ msgs = [+ AssistantMsg(+ name="assistant",+ content=[+ HintBlock(+ hint=[+ TextBlock(text="Inspect this screenshot:"),+ DataBlock(+ source=Base64Source(+ data=self.image_b64,+ media_type="image/png",+ ),+ ),+ ],+ ),+ ],+ ),+ ]+ res = await fmt.format(msgs)+ self.assertListEqual(+ [+ {+ "role": "user",+ "content": [+ {+ "type": "text",+ "text": "Inspect this screenshot:",+ },+ {+ "type": "image_url",+ "image_url": {"url": self.image_data_uri},+ },+ ],+ },+ ],+ res,+ )diff --git a/tests/formatter_deepseek_test.py b/tests/formatter_deepseek_test.pyindex 9a764cb35..c9b7e6c7a 100644--- a/tests/formatter_deepseek_test.py+++ b/tests/formatter_deepseek_test.py@@ -13,6 +13,8 @@ from agentscope.message import (AssistantMsg,SystemMsg,TextBlock,+ DataBlock,+ Base64Source,ToolCallBlock,ToolResultBlock,ToolResultState,@@ -492,3 +494,39 @@ class TestDeepSeekFormatter(IsolatedAsyncioTestCase):],res,)++ async def test_chat_formatter_hint_block_multimodal(self) -> None:+ """DeepSeek is text-only — DataBlock degrades to a placeholder+ string."""+ fmt = DeepSeekChatFormatter()+ msgs = [+ AssistantMsg(+ name="assistant",+ content=[+ HintBlock(+ hint=[+ TextBlock(text="Inspect this screenshot:"),+ DataBlock(+ source=Base64Source(+ data="ZmFrZSBpbWFnZSBkYXRh",+ media_type="image/png",+ ),+ ),+ ],+ ),+ ],+ ),+ ]+ res = await fmt.format(msgs)+ self.assertListEqual(+ [+ {+ "role": "user",+ "content": (+ "Inspect this screenshot:\n"+ "[image/png attached, not supported by this provider]"+ ),+ },+ ],+ res,+ )diff --git a/tests/formatter_gemini_test.py b/tests/formatter_gemini_test.pyindex 76151eb64..fc4969340 100644--- a/tests/formatter_gemini_test.py+++ b/tests/formatter_gemini_test.py@@ -675,3 +675,44 @@ class TestGeminiFormatter(IsolatedAsyncioTestCase):],res,)++ async def test_chat_formatter_hint_block_multimodal(self) -> None:+ """Multimodal HintBlock becomes a single user message with text ++ image."""+ fmt = GeminiChatFormatter()+ msgs = [+ AssistantMsg(+ name="assistant",+ content=[+ HintBlock(+ hint=[+ TextBlock(text="Inspect this screenshot:"),+ DataBlock(+ source=Base64Source(+ data=self.image_b64,+ media_type="image/png",+ ),+ ),+ ],+ ),+ ],+ ),+ ]+ res = await fmt.format(msgs)+ self.assertListEqual(+ [+ {+ "role": "user",+ "parts": [+ {"text": "Inspect this screenshot:"},+ {+ "inline_data": {+ "data": self.image_b64,+ "mime_type": "image/png",+ },+ },+ ],+ },+ ],+ res,+ )diff --git a/tests/formatter_moonshot_test.py b/tests/formatter_moonshot_test.pyindex b33682738..2e3680372 100644--- a/tests/formatter_moonshot_test.py+++ b/tests/formatter_moonshot_test.py@@ -782,3 +782,45 @@ class TestMoonshotFormatter(IsolatedAsyncioTestCase):],res,)++ async def test_chat_formatter_hint_block_multimodal(self) -> None:+ """Multimodal HintBlock becomes a single user message with text ++ image."""+ fmt = MoonshotChatFormatter()+ msgs = [+ AssistantMsg(+ name="assistant",+ content=[+ HintBlock(+ hint=[+ TextBlock(text="Inspect this screenshot:"),+ DataBlock(+ source=Base64Source(+ data=self.image_b64,+ media_type="image/png",+ ),+ ),+ ],+ ),+ ],+ ),+ ]+ res = await fmt.format(msgs)+ self.assertListEqual(+ [+ {+ "role": "user",+ "content": [+ {+ "type": "text",+ "text": "Inspect this screenshot:",+ },+ {+ "type": "image_url",+ "image_url": {"url": self.image_data_uri},+ },+ ],+ },+ ],+ res,+ )diff --git a/tests/formatter_ollama_test.py b/tests/formatter_ollama_test.pyindex 2b1e5294c..9cfd6bd12 100644--- a/tests/formatter_ollama_test.py+++ b/tests/formatter_ollama_test.py@@ -540,3 +540,37 @@ class TestOllamaFormatter(IsolatedAsyncioTestCase):],res,)++ async def test_chat_formatter_hint_block_multimodal(self) -> None:+ """Multimodal HintBlock becomes one user message with text + images+ list."""+ fmt = OllamaChatFormatter()+ msgs = [+ AssistantMsg(+ name="assistant",+ content=[+ HintBlock(+ hint=[+ TextBlock(text="Inspect this screenshot:"),+ DataBlock(+ source=Base64Source(+ data=self.image_b64,+ media_type="image/png",+ ),+ ),+ ],+ ),+ ],+ ),+ ]+ res = await fmt.format(msgs)+ self.assertListEqual(+ [+ {+ "role": "user",+ "content": "Inspect this screenshot:",+ "images": [self.image_b64],+ },+ ],+ res,+ )diff --git a/tests/formatter_openai_chat_test.py b/tests/formatter_openai_chat_test.pyindex 6b178a944..7ca7a4203 100644--- a/tests/formatter_openai_chat_test.py+++ b/tests/formatter_openai_chat_test.py@@ -728,3 +728,45 @@ class TestOpenAIFormatter(IsolatedAsyncioTestCase):],res,)++ async def test_chat_formatter_hint_block_multimodal(self) -> None:+ """Multimodal HintBlock becomes a single user message with text ++ image."""+ fmt = OpenAIChatFormatter()+ msgs = [+ AssistantMsg(+ name="assistant",+ content=[+ HintBlock(+ hint=[+ TextBlock(text="Inspect this screenshot:"),+ DataBlock(+ source=Base64Source(+ data=self.image_b64,+ media_type="image/png",+ ),+ ),+ ],+ ),+ ],+ ),+ ]+ res = await fmt.format(msgs)+ self.assertListEqual(+ [+ {+ "role": "user",+ "content": [+ {+ "type": "text",+ "text": "Inspect this screenshot:",+ },+ {+ "type": "image_url",+ "image_url": {"url": self.image_data_uri},+ },+ ],+ },+ ],+ res,+ )diff --git a/tests/formatter_openai_response_test.py b/tests/formatter_openai_response_test.pyindex be6603cb1..0ca18e39e 100644--- a/tests/formatter_openai_response_test.py+++ b/tests/formatter_openai_response_test.py@@ -735,3 +735,45 @@ class TestOpenAIResponseFormatter(IsolatedAsyncioTestCase):],res,)++ async def test_chat_formatter_hint_block_multimodal(self) -> None:+ """Multimodal HintBlock becomes a single user message with text ++ image."""+ fmt = OpenAIResponseFormatter()+ msgs = [+ AssistantMsg(+ name="assistant",+ content=[+ HintBlock(+ hint=[+ TextBlock(text="Inspect this screenshot:"),+ DataBlock(+ source=Base64Source(+ data=self.image_b64,+ media_type="image/png",+ ),+ ),+ ],+ ),+ ],+ ),+ ]+ res = await fmt.format(msgs)+ self.assertListEqual(+ [+ {+ "role": "user",+ "content": [+ {+ "type": "input_text",+ "text": "Inspect this screenshot:",+ },+ {+ "type": "input_image",+ "image_url": self.image_data_uri,+ },+ ],+ },+ ],+ res,+ )diff --git a/tests/formatter_xai_test.py b/tests/formatter_xai_test.pyindex 38082841c..1dd5da422 100644--- a/tests/formatter_xai_test.py+++ b/tests/formatter_xai_test.py@@ -19,6 +19,8 @@ from agentscope.message import (AssistantMsg,SystemMsg,TextBlock,+ DataBlock,+ Base64Source,ToolCallBlock,ToolResultBlock,ThinkingBlock,@@ -558,3 +560,37 @@ class TestXAIFormatter(IsolatedAsyncioTestCase):],res,)++ async def test_chat_formatter_hint_block_multimodal(self) -> None:+ """Multimodal HintBlock becomes one user() stub carrying text ++ image."""+ fmt = XAIChatFormatter()+ image_b64 = "ZmFrZSBpbWFnZSBkYXRh"+ msgs = [+ AssistantMsg(+ name="assistant",+ content=[+ HintBlock(+ hint=[+ TextBlock(text="Inspect this screenshot:"),+ DataBlock(+ source=Base64Source(+ data=image_b64,+ media_type="image/png",+ ),+ ),+ ],+ ),+ ],+ ),+ ]+ res = await fmt.format(msgs)+ self.assertListEqual(+ [+ user(+ "Inspect this screenshot:",+ image(f"data:image/png;base64,{image_b64}"),+ ),+ ],+ res,+ )diff --git a/tests/message_test.py b/tests/message_test.pyindex bf1c8130c..4ec2ee13d 100644--- a/tests/message_test.py+++ b/tests/message_test.py@@ -161,7 +161,12 @@ class MessageTest(IsolatedAsyncioTestCase):"name": "assistant","role": "assistant","content": [- {"type": "hint", "hint": "hint...", "id": AnyString()},+ {+ "type": "hint",+ "hint": "hint...",+ "id": AnyString(),+ "source": None,+ },],"metadata": {},"created_at": AnyString(),diff --git a/tests/service_cancel_dispatcher_test.py b/tests/service_cancel_dispatcher_test.pynew file mode 100644index 000000000..6b2f0c4a1--- /dev/null+++ b/tests/service_cancel_dispatcher_test.py@@ -0,0 +1,336 @@+# -*- coding: utf-8 -*-+# pylint: disable=protected-access+"""Tests for :class:`CancelDispatcher` — one-per-process consumer of the+shared session-cancel broadcast channel.++Verifies that on each incoming ``session_id`` the dispatcher:++- Cancels the chat-run task in :class:`ChatRunRegistry` when it owns one+ locally.+- Asks :class:`BackgroundTaskManager` to cancel local BG tasks for the+ same session.+- Silently does nothing for sessions whose state lives on other+ processes.+"""+import asyncio+from contextlib import asynccontextmanager+from typing import AsyncGenerator, Callable+from unittest import IsolatedAsyncioTestCase++from agentscope.app._manager import (+ BackgroundTaskManager,+ CancelDispatcher,+ ChatRunRegistry,+)+from agentscope.app.message_bus import MessageBus+++class _FakeBus(MessageBus):+ """In-memory bus with just enough behaviour for the dispatcher.++ Only the cancel-broadcast channel is exercised here; the other+ primitives are stubbed.+ """++ def __init__(self) -> None:+ self._channels: dict[str, asyncio.Queue] = {}+ self._locks: set[str] = set()++ def _channel(self, key: str) -> asyncio.Queue:+ return self._channels.setdefault(key, asyncio.Queue())++ # Mode A — queue (unused)+ async def queue_push(+ self,+ key: str,+ payload: dict,+ *,+ ttl_secs: int | None = None,+ ) -> str:+ return "n/a"++ async def queue_drain(+ self,+ key: str,+ max_count: int = 100,+ ) -> list[tuple[str, dict]]:+ return []++ async def queue_delete(self, key: str) -> None:+ return None++ # Mode C — log (unused)+ async def log_append(+ self,+ key: str,+ payload: dict,+ *,+ max_len: int | None = None,+ ttl_secs: int | None = None,+ ) -> str:+ return "n/a"++ async def log_read(+ self,+ key: str,+ since: str | None = None,+ max_count: int = 100,+ ) -> list[tuple[str, dict]]:+ return []++ async def log_trim(+ self,+ key: str,+ before_id: str | None = None,+ ) -> None:+ return None++ # Mode D — pub/sub+ async def publish(self, key: str, payload: dict) -> None:+ await self._channel(key).put(payload)++ async def subscribe(+ self,+ key: str,+ *,+ on_ready: Callable[[], None] | None = None,+ ) -> AsyncGenerator[dict, None]:+ if on_ready is not None:+ on_ready()+ while True:+ yield await self._channel(key).get()++ # Mode E — lock (unused)+ @asynccontextmanager+ async def acquire_lock(+ self,+ key: str,+ *,+ ttl_secs: int = 600,+ ) -> AsyncGenerator[None, None]:+ self._locks.add(key)+ try:+ yield+ finally:+ self._locks.discard(key)++ async def is_locked(self, key: str) -> bool:+ return key in self._locks+++async def _yield_a_few_times(ticks: int = 8) -> None:+ """Yield the event loop a few times so spawned tasks make progress."""+ for _ in range(ticks):+ await asyncio.sleep(0)+++class _NeverEndingCoro:+ """Helper: yields a fresh coroutine that sleeps forever."""++ @staticmethod+ async def run() -> None:+ """The fake coroutine."""+ await asyncio.Event().wait()+++class TestCancelDispatcher(IsolatedAsyncioTestCase):+ """Verifies the cross-process cancel fan-out."""++ async def test_cancel_signal_cancels_local_chat_run(self) -> None:+ """Broadcast for a session whose chat run is registered locally+ cancels the registered asyncio task."""+ bus = _FakeBus()+ registry = ChatRunRegistry()+ bg_manager = BackgroundTaskManager()++ async with bg_manager, registry, CancelDispatcher(+ message_bus=bus,+ registry=registry,+ bg_manager=bg_manager,+ ):+ chat_task = registry.spawn(+ _NeverEndingCoro.run(),+ session_id="sess-A",+ )+ await bus.session_publish_cancel("sess-A")++ # Wait until the cancel actually propagates.+ for _ in range(50):+ if chat_task.cancelled() or chat_task.done():+ break+ await asyncio.sleep(0.01)++ self.assertTrue(chat_task.cancelled() or chat_task.done())++ async def test_cancel_signal_cancels_local_bg_tasks(self) -> None:+ """Broadcast for a session with locally-registered BG tasks+ cancels each of them; tasks for other sessions are untouched."""+ bus = _FakeBus()+ registry = ChatRunRegistry()+ bg_manager = BackgroundTaskManager()++ async with bg_manager, registry, CancelDispatcher(+ message_bus=bus,+ registry=registry,+ bg_manager=bg_manager,+ ):+ bg_task_a1 = asyncio.create_task(_NeverEndingCoro.run())+ bg_task_a2 = asyncio.create_task(_NeverEndingCoro.run())+ bg_task_b = asyncio.create_task(_NeverEndingCoro.run())++ await bg_manager.register_task(+ bg_task_a1,+ session_id="sess-A",+ agent_id="agent-A",+ user_id="u",+ )+ await bg_manager.register_task(+ bg_task_a2,+ session_id="sess-A",+ agent_id="agent-A",+ user_id="u",+ )+ await bg_manager.register_task(+ bg_task_b,+ session_id="sess-B",+ agent_id="agent-B",+ user_id="u",+ )++ await bus.session_publish_cancel("sess-A")++ for _ in range(50):+ if bg_task_a1.cancelled() and bg_task_a2.cancelled():+ break+ await asyncio.sleep(0.01)++ self.assertTrue(bg_task_a1.cancelled() or bg_task_a1.done())+ self.assertTrue(bg_task_a2.cancelled() or bg_task_a2.done())+ # sess-B BG task is left running until shutdown cancels it.+ self.assertFalse(bg_task_b.cancelled())+ bg_task_b.cancel()++ async def test_cancel_signal_for_remote_session_is_noop(self) -> None:+ """Broadcast for a session held on another process is silently+ ignored — no exception, no spurious cancel."""+ bus = _FakeBus()+ registry = ChatRunRegistry()+ bg_manager = BackgroundTaskManager()++ async with bg_manager, registry, CancelDispatcher(+ message_bus=bus,+ registry=registry,+ bg_manager=bg_manager,+ ):+ # Register an unrelated chat run + unrelated BG task so we+ # can verify the unrelated work survives the broadcast.+ unrelated_chat = registry.spawn(+ _NeverEndingCoro.run(),+ session_id="other",+ )+ unrelated_bg = asyncio.create_task(_NeverEndingCoro.run())+ await bg_manager.register_task(+ unrelated_bg,+ session_id="other",+ agent_id="agent",+ user_id="u",+ )++ await bus.session_publish_cancel("not-on-this-process")+ await _yield_a_few_times()++ self.assertFalse(unrelated_chat.cancelled())+ self.assertFalse(unrelated_bg.cancelled())++ # __aexit__ of ChatRunRegistry + BackgroundTaskManager cancels+ # the unrelated tasks on shutdown.++ async def test_cancel_fans_out_to_both_chat_and_bg_in_one_signal(+ self,+ ) -> None:+ """A single cancel broadcast cancels both the local chat run+ and the local BG task(s) for the session, not just one."""+ bus = _FakeBus()+ registry = ChatRunRegistry()+ bg_manager = BackgroundTaskManager()++ async with bg_manager, registry, CancelDispatcher(+ message_bus=bus,+ registry=registry,+ bg_manager=bg_manager,+ ):+ chat_task = registry.spawn(+ _NeverEndingCoro.run(),+ session_id="sess-X",+ )+ bg_task = asyncio.create_task(_NeverEndingCoro.run())+ await bg_manager.register_task(+ bg_task,+ session_id="sess-X",+ agent_id="agent-X",+ user_id="u",+ )++ await bus.session_publish_cancel("sess-X")++ for _ in range(50):+ if chat_task.cancelled() and bg_task.cancelled():+ break+ await asyncio.sleep(0.01)++ self.assertTrue(chat_task.cancelled() or chat_task.done())+ self.assertTrue(bg_task.cancelled() or bg_task.done())+++class TestBackgroundTaskManagerCancelSessionTasks(IsolatedAsyncioTestCase):+ """Verifies :meth:`BackgroundTaskManager.cancel_session_tasks`."""++ async def test_cancels_only_matching_session(self) -> None:+ """Only tasks whose ``session_id`` matches are cancelled; the+ return value reports the local count."""+ bg_manager = BackgroundTaskManager()+ async with bg_manager:+ task_a = asyncio.create_task(_NeverEndingCoro.run())+ task_b = asyncio.create_task(_NeverEndingCoro.run())+ await bg_manager.register_task(+ task_a,+ session_id="match",+ agent_id="a",+ user_id="u",+ )+ await bg_manager.register_task(+ task_b,+ session_id="other",+ agent_id="b",+ user_id="u",+ )++ count = bg_manager.cancel_session_tasks("match")+ self.assertEqual(count, 1)++ for _ in range(50):+ if task_a.cancelled():+ break+ await asyncio.sleep(0.01)++ self.assertTrue(task_a.cancelled())+ self.assertFalse(task_b.cancelled())++ async def test_no_matches_returns_zero(self) -> None:+ """A session with no locally-registered tasks returns 0 and+ does no work."""+ bg_manager = BackgroundTaskManager()+ async with bg_manager:+ task = asyncio.create_task(_NeverEndingCoro.run())+ await bg_manager.register_task(+ task,+ session_id="other",+ agent_id="a",+ user_id="u",+ )++ self.assertEqual(+ bg_manager.cancel_session_tasks("ghost"),+ 0,+ )+ self.assertFalse(task.cancelled())diff --git a/tests/service_inbox_middleware_test.py b/tests/service_inbox_middleware_test.pynew file mode 100644index 000000000..731ffbc8d--- /dev/null+++ b/tests/service_inbox_middleware_test.py@@ -0,0 +1,450 @@+# -*- coding: utf-8 -*-+# pylint: disable=abstract-method,protected-access+"""Tests for :class:`InboxMiddleware`.++Every cross-session message delivery in the framework (team messages+via ``TeamSay`` / ``AgentCreate``, background-tool completion results,+scheduler fires) goes through this middleware on the consumer side, so+the four branches below cover the whole inbox→context pipeline:++- empty inbox → no injection, no event yield, downstream unchanged;+- last context msg already an assistant msg from this agent → hints are+ *extended* into its ``content``;+- last context msg is something else (system / different agent) → a+ fresh ``AssistantMsg`` is appended;+- empty context → a fresh ``AssistantMsg`` is appended.++Each non-empty drain must also yield one ``HintBlockEvent`` per hint so+the SSE stream renders them.+"""+import uuid+from contextlib import asynccontextmanager+from types import SimpleNamespace+from typing import Any, AsyncGenerator, Callable+from unittest import IsolatedAsyncioTestCase++from utils import AnyString++from agentscope.app.message_bus import MessageBus+from agentscope.app.middleware import InboxMiddleware+from agentscope.message import (+ AssistantMsg,+ HintBlock,+ SystemMsg,+ TextBlock,+)+++class _FakeBus(MessageBus):+ """In-memory bus that only implements the inbox API needed by+ :class:`InboxMiddleware`. All other primitives raise ``NotImplemented``+ to make accidental dependencies obvious."""++ def __init__(self) -> None:+ self._queues: dict[str, list[tuple[str, dict]]] = {}+ self._next_id = 0++ def _alloc_id(self) -> str:+ """Allocate a monotonically increasing entry id."""+ self._next_id += 1+ return f"id-{self._next_id}"++ # Mode A — drain queue+ async def queue_push(+ self,+ key: str,+ payload: dict,+ *,+ ttl_secs: int | None = None,+ ) -> str:+ entry_id = self._alloc_id()+ self._queues.setdefault(key, []).append((entry_id, payload))+ return entry_id++ async def queue_drain(+ self,+ key: str,+ *,+ max_count: int,+ ) -> list[tuple[str, dict]]:+ entries = self._queues.get(key, [])[:max_count]+ self._queues[key] = self._queues.get(key, [])[max_count:]+ return entries++ async def queue_delete(self, key: str) -> None:+ self._queues.pop(key, None)++ # Mode C — log (unused)+ async def log_append(+ self,+ key: str,+ payload: dict,+ *,+ max_len: int | None = None,+ ttl_secs: int | None = None,+ ) -> str:+ raise NotImplementedError++ async def log_read(+ self,+ key: str,+ since: str | None = None,+ max_count: int = 100,+ ) -> list[tuple[str, dict]]:+ raise NotImplementedError++ async def log_trim(+ self,+ key: str,+ before_id: str | None = None,+ ) -> None:+ raise NotImplementedError++ # Mode D — pub/sub (unused)+ async def publish(self, key: str, payload: dict) -> None:+ raise NotImplementedError++ async def subscribe(+ self,+ key: str,+ *,+ on_ready: Callable[[], None] | None = None,+ ) -> AsyncGenerator[dict, None]:+ raise NotImplementedError+ yield # pragma: no cover # pylint: disable=unreachable++ # Mode E — lock (unused)+ @asynccontextmanager+ async def acquire_lock(+ self,+ key: str,+ *,+ ttl_secs: int = 600,+ ) -> AsyncGenerator[None, None]:+ raise NotImplementedError+ yield # pragma: no cover # pylint: disable=unreachable++ async def is_locked(self, key: str) -> bool:+ raise NotImplementedError+++def _make_agent(+ *,+ name: str,+ session_id: str,+ reply_id: str,+ context: list,+) -> Any:+ """Build the smallest object that satisfies what+ :class:`InboxMiddleware.on_reasoning` reads off ``agent``.++ Args:+ name: Agent display name.+ session_id: Identifier for the inbox key.+ reply_id: Reply id stamped onto freshly-appended AssistantMsg.+ context: Mutable list of messages — the middleware mutates this+ in place to inject hints.++ Returns:+ A ``SimpleNamespace`` shaped like the real :class:`Agent` for+ the fields the middleware touches.+ """+ return SimpleNamespace(+ name=name,+ state=SimpleNamespace(+ session_id=session_id,+ reply_id=reply_id,+ context=context,+ ),+ )+++async def _noop_next_handler(**_kwargs: Any) -> AsyncGenerator:+ """Stand-in for the downstream reasoning chain. Yields nothing —+ InboxMiddleware should run its inbox-drain step first, then exit+ the iteration cleanly."""+ return+ yield # pragma: no cover # pylint: disable=unreachable+++async def _drain(gen: AsyncGenerator) -> list:+ """Collect every value yielded by an async generator."""+ out: list = []+ async for item in gen:+ out.append(item)+ return out+++def _push_hint(+ bus: _FakeBus,+ sid: str,+ hint: HintBlock,+) -> None:+ """Push a :class:`HintBlock` into the per-session inbox key the+ middleware will drain."""+ key = MessageBus._INBOX_KEY.format(sid=sid)+ # asyncio.run on the bus would be overkill — `_queues` is a plain+ # dict, mutate it directly.+ bus._queues.setdefault(key, []).append(+ (bus._alloc_id(), hint.model_dump(mode="json")),+ )+++class TestInboxMiddlewareEmptyInbox(IsolatedAsyncioTestCase):+ """When the inbox is empty, ``on_reasoning`` injects nothing, yields+ nothing, and delegates straight to ``next_handler``."""++ async def test_empty_inbox_is_noop(self) -> None:+ """An empty inbox produces no events and leaves context untouched."""+ bus = _FakeBus()+ agent = _make_agent(+ name="A",+ session_id="s",+ reply_id=uuid.uuid4().hex,+ context=[],+ )+ mw = InboxMiddleware(bus)++ out = await _drain(+ mw.on_reasoning(agent, {}, _noop_next_handler),+ )++ self.assertEqual(out, [])+ self.assertEqual(agent.state.context, [])+++class TestInboxMiddlewareInjection(IsolatedAsyncioTestCase):+ """Branch coverage for the three injection cases."""++ async def test_extends_into_last_assistant_msg_from_same_agent(+ self,+ ) -> None:+ """When the last context msg is already an assistant msg from+ this agent, hints are extended into its ``content`` and a new+ msg is NOT appended."""+ bus = _FakeBus()+ existing = AssistantMsg(+ name="A",+ content=[TextBlock(text="hello")],+ )+ agent = _make_agent(+ name="A",+ session_id="s",+ reply_id=uuid.uuid4().hex,+ context=[existing],+ )+ hint = HintBlock(hint="poke", source="tester")+ _push_hint(bus, "s", hint)+ mw = InboxMiddleware(bus)++ events = await _drain(+ mw.on_reasoning(agent, {}, _noop_next_handler),+ )++ # No new message appended; hint extended into existing assistant msg.+ self.assertEqual(len(agent.state.context), 1)+ self.assertIs(agent.state.context[0], existing)+ self.assertDictEqual(+ existing.model_dump(),+ {+ "id": AnyString(),+ "name": "A",+ "role": "assistant",+ "content": [+ {"type": "text", "text": "hello", "id": AnyString()},+ {+ "type": "hint",+ "hint": "poke",+ "id": hint.id,+ "source": "tester",+ },+ ],+ "metadata": {},+ "created_at": AnyString(),+ "finished_at": None,+ "usage": None,+ },+ )+ # One HintBlockEvent yielded.+ self.assertEqual(+ [e.model_dump(mode="json") for e in events],+ [+ {+ "type": "HINT_BLOCK",+ "id": AnyString(),+ "created_at": AnyString(),+ "reply_id": agent.state.reply_id,+ "block_id": hint.id,+ "source": "tester",+ "hint": "poke",+ },+ ],+ )++ async def test_appends_new_msg_when_last_is_different_agent(+ self,+ ) -> None:+ """When the last context msg is from a different agent (or a+ system msg), a fresh :class:`AssistantMsg` is appended with the+ hints as its content."""+ bus = _FakeBus()+ system_msg = SystemMsg(name="system", content="boot")+ agent = _make_agent(+ name="A",+ session_id="s",+ reply_id="rid-1",+ context=[system_msg],+ )+ hint = HintBlock(hint="hi", source="x")+ _push_hint(bus, "s", hint)+ mw = InboxMiddleware(bus)++ await _drain(mw.on_reasoning(agent, {}, _noop_next_handler))++ self.assertEqual(len(agent.state.context), 2)+ self.assertDictEqual(+ agent.state.context[-1].model_dump(),+ {+ "id": "rid-1",+ "name": "A",+ "role": "assistant",+ "content": [+ {+ "type": "hint",+ "hint": "hi",+ "id": hint.id,+ "source": "x",+ },+ ],+ "metadata": {},+ "created_at": AnyString(),+ "finished_at": None,+ "usage": None,+ },+ )++ async def test_appends_new_msg_when_context_empty(self) -> None:+ """When ``agent.state.context`` is empty, a fresh+ :class:`AssistantMsg` containing the hints is the first entry."""+ bus = _FakeBus()+ agent = _make_agent(+ name="A",+ session_id="s",+ reply_id="rid-empty",+ context=[],+ )+ hint = HintBlock(hint="hi", source="x")+ _push_hint(bus, "s", hint)+ mw = InboxMiddleware(bus)++ await _drain(mw.on_reasoning(agent, {}, _noop_next_handler))++ self.assertEqual(len(agent.state.context), 1)+ self.assertDictEqual(+ agent.state.context[0].model_dump(),+ {+ "id": "rid-empty",+ "name": "A",+ "role": "assistant",+ "content": [+ {+ "type": "hint",+ "hint": "hi",+ "id": hint.id,+ "source": "x",+ },+ ],+ "metadata": {},+ "created_at": AnyString(),+ "finished_at": None,+ "usage": None,+ },+ )+++class TestInboxMiddlewareYieldsHintBlockEvents(IsolatedAsyncioTestCase):+ """One ``HintBlockEvent`` is yielded per injected hint, in order,+ each carrying the hint's own block_id / source / content."""++ async def test_event_count_and_payload(self) -> None:+ """One HintBlockEvent is yielded per inbox hint, in arrival order."""+ bus = _FakeBus()+ agent = _make_agent(+ name="A",+ session_id="s",+ reply_id="rid-evt",+ context=[],+ )+ h1 = HintBlock(hint="a", source="alice")+ h2 = HintBlock(hint="b", source="bob")+ _push_hint(bus, "s", h1)+ _push_hint(bus, "s", h2)+ mw = InboxMiddleware(bus)++ events = await _drain(+ mw.on_reasoning(agent, {}, _noop_next_handler),+ )++ self.assertEqual(+ [e.model_dump(mode="json") for e in events],+ [+ {+ "type": "HINT_BLOCK",+ "id": AnyString(),+ "created_at": AnyString(),+ "reply_id": "rid-evt",+ "block_id": h1.id,+ "source": "alice",+ "hint": "a",+ },+ {+ "type": "HINT_BLOCK",+ "id": AnyString(),+ "created_at": AnyString(),+ "reply_id": "rid-evt",+ "block_id": h2.id,+ "source": "bob",+ "hint": "b",+ },+ ],+ )+++class TestInboxMiddlewareDelegatesDownstream(IsolatedAsyncioTestCase):+ """After the inbox is drained, events from ``next_handler`` come+ out of the middleware in order."""++ async def test_downstream_events_pass_through(self) -> None:+ """Downstream events appear after any HintBlockEvents."""+ bus = _FakeBus()+ agent = _make_agent(+ name="A",+ session_id="s",+ reply_id="rid",+ context=[],+ )+ hint = HintBlock(hint="hi", source="x")+ _push_hint(bus, "s", hint)+ mw = InboxMiddleware(bus)++ async def downstream(**_k: Any) -> AsyncGenerator[str, None]:+ yield "ds-1"+ yield "ds-2"++ out = await _drain(mw.on_reasoning(agent, {}, downstream))++ # 1 HintBlockEvent followed by 2 downstream items.+ self.assertEqual(len(out), 3)+ self.assertDictEqual(+ out[0].model_dump(mode="json"),+ {+ "type": "HINT_BLOCK",+ "id": AnyString(),+ "created_at": AnyString(),+ "reply_id": "rid",+ "block_id": hint.id,+ "source": "x",+ "hint": "hi",+ },+ )+ self.assertEqual(out[1:], ["ds-1", "ds-2"])diff --git a/tests/service_message_bus_test.py b/tests/service_message_bus_test.pynew file mode 100644index 000000000..5bcdd2be3--- /dev/null+++ b/tests/service_message_bus_test.py@@ -0,0 +1,375 @@+# -*- coding: utf-8 -*-+# pylint: disable=protected-access+"""Tests for :class:`RedisMessageBus` and the domain helpers on the base+:class:`MessageBus` class.++The Redis backend is exercised against ``fakeredis`` so tests cover both+the abstract surface (queue / log / pubsub / lock) and the domain helpers+(``session_run`` / ``session_publish_event`` / ``inbox_*`` / ``wakeup_*``)+that are layered on top.+"""+import asyncio+from contextlib import AsyncExitStack+from unittest import IsolatedAsyncioTestCase++import fakeredis.aioredis++from agentscope.app.message_bus import MessageBus, RedisMessageBus+++def _make_bus(+ fake_redis: fakeredis.aioredis.FakeRedis,+) -> RedisMessageBus:+ """Construct a :class:`RedisMessageBus` that uses *fake_redis*.++ The bus subclass overrides ``__aenter__`` so it talks to fakeredis+ instead of opening a real connection pool.++ Args:+ fake_redis (`fakeredis.aioredis.FakeRedis`):+ A fakeredis client whose pubsub / streams APIs are async.++ Returns:+ `RedisMessageBus`:+ A bus instance ready to be used as an async context manager.+ """++ class _FakeBus(RedisMessageBus):+ """Bus subclass that returns the supplied fakeredis client on+ context entry instead of building a real one."""++ async def __aenter__(self) -> "RedisMessageBus":+ self._client = fake_redis+ return self++ async def aclose(self) -> None:+ # The fakeredis client is owned by the test, not the bus.+ self._client = None++ return _FakeBus()+++class TestQueuePrimitive(IsolatedAsyncioTestCase):+ """Mode A — ``queue_push`` + ``queue_drain`` semantics."""++ async def asyncSetUp(self) -> None:+ self.fr = fakeredis.aioredis.FakeRedis(decode_responses=True)+ self._stack = AsyncExitStack()+ self.bus = await self._stack.enter_async_context(_make_bus(self.fr))++ async def asyncTearDown(self) -> None:+ await self._stack.aclose()+ await self.fr.aclose()++ async def test_push_drain_returns_payloads_in_order(self) -> None:+ """Entries pushed in order come back out in order, once each."""+ await self.bus.queue_push("k", {"i": 1})+ await self.bus.queue_push("k", {"i": 2})+ entries = await self.bus.queue_drain("k", max_count=10)+ self.assertEqual([p for _id, p in entries], [{"i": 1}, {"i": 2}])++ async def test_drain_is_destructive(self) -> None:+ """A drained entry is gone; a second drain yields nothing."""+ await self.bus.queue_push("k", {"x": 1})+ await self.bus.queue_drain("k", max_count=10)+ self.assertEqual(await self.bus.queue_drain("k", max_count=10), [])++ async def test_drain_respects_max_count(self) -> None:+ """``max_count`` caps the batch size; remaining entries persist."""+ for i in range(5):+ await self.bus.queue_push("k", {"i": i})+ first = await self.bus.queue_drain("k", max_count=3)+ rest = await self.bus.queue_drain("k", max_count=10)+ self.assertEqual([p["i"] for _id, p in first], [0, 1, 2])+ self.assertEqual([p["i"] for _id, p in rest], [3, 4])+++class TestLogPrimitive(IsolatedAsyncioTestCase):+ """Mode C — replay log: append / read with cursor / trim."""++ async def asyncSetUp(self) -> None:+ self.fr = fakeredis.aioredis.FakeRedis(decode_responses=True)+ self._stack = AsyncExitStack()+ self.bus = await self._stack.enter_async_context(_make_bus(self.fr))++ async def asyncTearDown(self) -> None:+ await self._stack.aclose()+ await self.fr.aclose()++ async def test_read_returns_everything_when_no_cursor(self) -> None:+ """Without a ``since`` cursor, the whole log comes back."""+ await self.bus.log_append("k", {"i": 1})+ await self.bus.log_append("k", {"i": 2})+ entries = await self.bus.log_read("k")+ self.assertEqual([p["i"] for _id, p in entries], [1, 2])++ async def test_read_with_cursor_is_exclusive(self) -> None:+ """``since=last_id`` skips that id and returns only newer entries."""+ await self.bus.log_append("k", {"i": 1})+ await self.bus.log_append("k", {"i": 2})+ await self.bus.log_append("k", {"i": 3})+ all_entries = await self.bus.log_read("k")+ cursor = all_entries[1][0] # id of entry 2+ rest = await self.bus.log_read("k", since=cursor)+ self.assertEqual([p["i"] for _id, p in rest], [3])++ async def test_trim_without_before_drops_entire_log(self) -> None:+ """``log_trim(key)`` empties the log; subsequent read is empty."""+ await self.bus.log_append("k", {"i": 1})+ await self.bus.log_append("k", {"i": 2})+ await self.bus.log_trim("k")+ self.assertEqual(await self.bus.log_read("k"), [])+++class TestPubSubPrimitive(IsolatedAsyncioTestCase):+ """Mode D — transient broadcast: publish / subscribe."""++ async def asyncSetUp(self) -> None:+ self.fr = fakeredis.aioredis.FakeRedis(decode_responses=True)+ self._stack = AsyncExitStack()+ self.bus = await self._stack.enter_async_context(_make_bus(self.fr))++ async def asyncTearDown(self) -> None:+ await self._stack.aclose()+ await self.fr.aclose()++ async def test_subscribe_receives_messages_published_after_ready(+ self,+ ) -> None:+ """Subscribers receive payloads published after the subscription+ is established. The ``on_ready`` hook fires once before any+ payload is yielded."""+ ready = asyncio.Event()+ received: list[dict] = []++ async def _consumer() -> None:+ async for payload in self.bus.subscribe(+ "ch",+ on_ready=ready.set,+ ):+ received.append(payload)+ if len(received) == 2:+ break++ task = asyncio.create_task(_consumer())+ await asyncio.wait_for(ready.wait(), timeout=2.0)++ await self.bus.publish("ch", {"i": 1})+ await self.bus.publish("ch", {"i": 2})+ await asyncio.wait_for(task, timeout=2.0)+ self.assertEqual([p["i"] for p in received], [1, 2])+++class TestLockPrimitive(IsolatedAsyncioTestCase):+ """Mode E — distributed mutex semantics."""++ async def asyncSetUp(self) -> None:+ self.fr = fakeredis.aioredis.FakeRedis(decode_responses=True)+ self._stack = AsyncExitStack()+ self.bus = await self._stack.enter_async_context(_make_bus(self.fr))++ async def asyncTearDown(self) -> None:+ await self._stack.aclose()+ await self.fr.aclose()++ async def test_is_locked_reflects_acquire_release(self) -> None:+ """``is_locked`` flips to True while the body runs and back to+ False once the context exits."""+ self.assertFalse(await self.bus.is_locked("k"))+ async with self.bus.acquire_lock("k", ttl_secs=10):+ self.assertTrue(await self.bus.is_locked("k"))+ self.assertFalse(await self.bus.is_locked("k"))++ async def test_second_acquirer_waits_until_release(self) -> None:+ """A second ``acquire_lock`` on the same key blocks until the+ first releases."""+ order: list[str] = []++ async def _holder() -> None:+ async with self.bus.acquire_lock("k", ttl_secs=10):+ order.append("first-in")+ await asyncio.sleep(0.05)+ order.append("first-out")++ async def _challenger() -> None:+ # Tiny delay so the holder grabs the lock first.+ await asyncio.sleep(0.005)+ async with self.bus.acquire_lock("k", ttl_secs=10):+ order.append("second-in")++ await asyncio.gather(_holder(), _challenger())+ self.assertEqual(+ order,+ ["first-in", "first-out", "second-in"],+ )+++class TestSessionRunAutoTrimsLog(IsolatedAsyncioTestCase):+ """``session_run.__aexit__`` must trim the session's replay log+ *before* releasing the distributed lock, so any subscriber that+ connects between two runs sees a clean slate."""++ async def asyncSetUp(self) -> None:+ self.fr = fakeredis.aioredis.FakeRedis(decode_responses=True)+ self._stack = AsyncExitStack()+ self.bus = await self._stack.enter_async_context(_make_bus(self.fr))++ async def asyncTearDown(self) -> None:+ await self._stack.aclose()+ await self.fr.aclose()++ async def test_log_trim_happens_on_session_run_exit(self) -> None:+ """Events published inside a ``session_run`` block are trimmed+ once the block exits — a fresh ``session_read_events`` returns+ an empty list."""+ sid = "s-trim"+ async with self.bus.session_run(sid):+ await self.bus.session_publish_event(sid, {"i": 1})+ await self.bus.session_publish_event(sid, {"i": 2})+ mid = await self.bus.session_read_events(sid)+ self.assertEqual([p["i"] for _id, p in mid], [1, 2])+ self.assertEqual(await self.bus.session_read_events(sid), [])++ async def test_log_trim_runs_even_when_body_raises(self) -> None:+ """If the body raises, the log is still trimmed before the lock+ releases — the next run starts clean."""+ sid = "s-raise"++ class _Boom(RuntimeError):+ """Marker exception raised inside the run body."""++ with self.assertRaises(_Boom):+ async with self.bus.session_run(sid):+ await self.bus.session_publish_event(sid, {"i": 1})+ raise _Boom()++ self.assertEqual(await self.bus.session_read_events(sid), [])+++class TestSessionDomainHelpers(IsolatedAsyncioTestCase):+ """``session_publish_event`` + ``session_subscribe_events`` ++ ``session_is_running`` round-trip behaviour."""++ async def asyncSetUp(self) -> None:+ self.fr = fakeredis.aioredis.FakeRedis(decode_responses=True)+ self._stack = AsyncExitStack()+ self.bus = await self._stack.enter_async_context(_make_bus(self.fr))++ async def asyncTearDown(self) -> None:+ await self._stack.aclose()+ await self.fr.aclose()++ async def test_publish_event_writes_to_log_and_pubsub(self) -> None:+ """``session_publish_event`` writes one entry to the replay log+ AND fans it out on the live channel; subscribers receive the+ payload with the ``_entry_id`` field stripped."""+ sid = "s-pub"+ ready = asyncio.Event()+ received: list[dict] = []++ async def _consumer() -> None:+ async for payload in self.bus.session_subscribe_events(+ sid,+ on_ready=ready.set,+ ):+ received.append(payload)+ break++ task = asyncio.create_task(_consumer())+ await asyncio.wait_for(ready.wait(), timeout=2.0)++ await self.bus.session_publish_event(sid, {"hello": "world"})+ await asyncio.wait_for(task, timeout=2.0)++ # Replay log captured the entry too.+ log_entries = await self.bus.session_read_events(sid)+ self.assertEqual(len(log_entries), 1)+ self.assertEqual(log_entries[0][1], {"hello": "world"})++ # Live subscriber saw it without the internal _entry_id key.+ self.assertEqual(received, [{"hello": "world"}])++ async def test_session_is_running_reflects_session_run(self) -> None:+ """``session_is_running`` returns True while inside+ ``session_run`` and False after."""+ sid = "s-isrun"+ self.assertFalse(await self.bus.session_is_running(sid))+ async with self.bus.session_run(sid):+ self.assertTrue(await self.bus.session_is_running(sid))+ self.assertFalse(await self.bus.session_is_running(sid))+++class TestInboxAndWakeupHelpers(IsolatedAsyncioTestCase):+ """Inbox + wakeup domain helpers used by team / tool-offload /+ scheduler to deliver work to idle sessions."""++ async def asyncSetUp(self) -> None:+ self.fr = fakeredis.aioredis.FakeRedis(decode_responses=True)+ self._stack = AsyncExitStack()+ self.bus = await self._stack.enter_async_context(_make_bus(self.fr))++ async def asyncTearDown(self) -> None:+ await self._stack.aclose()+ await self.fr.aclose()++ async def test_inbox_push_drain_round_trip(self) -> None:+ """``inbox_push`` payloads are returned by ``inbox_drain`` in+ push order, exactly once."""+ sid = "s-inbox"+ await self.bus.inbox_push(sid, {"hint": "a"})+ await self.bus.inbox_push(sid, {"hint": "b"})+ entries = await self.bus.inbox_drain(sid, max_count=10)+ self.assertEqual(+ [p["hint"] for _id, p in entries],+ ["a", "b"],+ )+ self.assertEqual(+ await self.bus.inbox_drain(sid, max_count=10),+ [],+ )++ async def test_enqueue_wakeup_signals_and_queues(self) -> None:+ """``enqueue_wakeup`` puts the payload on the durable queue and+ fires the signal channel; a subscriber and a ``dequeue_wakeups``+ call both see it."""+ ready = asyncio.Event()+ received: list[dict] = []++ async def _signal_consumer() -> None:+ async for payload in self.bus.subscribe_wakeup_signal(+ on_ready=ready.set,+ ):+ received.append(payload)+ break++ task = asyncio.create_task(_signal_consumer())+ await asyncio.wait_for(ready.wait(), timeout=2.0)++ await self.bus.enqueue_wakeup(+ user_id="u",+ session_id="s",+ agent_id="a",+ )+ await asyncio.wait_for(task, timeout=2.0)++ # Signal fired.+ self.assertEqual(len(received), 1)++ # Queue holds the structured entry.+ entries = await self.bus.dequeue_wakeups(max_count=10)+ self.assertEqual(len(entries), 1)+ self.assertEqual(+ entries[0],+ {"user_id": "u", "session_id": "s", "agent_id": "a"},+ )+++class TestBaseClassIsAbstract(IsolatedAsyncioTestCase):+ """``MessageBus`` itself cannot be instantiated."""++ def test_instantiating_base_class_raises(self) -> None:+ """The abstract methods are not implemented on the base — direct+ instantiation must fail."""+ with self.assertRaises(TypeError):+ # pylint: disable=abstract-class-instantiated+ MessageBus() # type: ignore[abstract]diff --git a/tests/service_scheduler_test.py b/tests/service_scheduler_test.pynew file mode 100644index 000000000..f2e0d9c97--- /dev/null+++ b/tests/service_scheduler_test.py@@ -0,0 +1,261 @@+# -*- coding: utf-8 -*-+# pylint: disable=protected-access+"""Tests for :meth:`SchedulerManager._build_trigger`.++We don't drive APScheduler here — we ask the manager to build a trigger+coroutine for a record and invoke it directly. The trigger's contract is:++- when ``ScheduleData.enabled`` is False → no side effects;+- when enabled → resolve / create a target session, push a+ ``<scheduled-task>``-wrapped :class:`HintBlock` to the session inbox,+ and enqueue one wakeup pointing at that session.++In stateful mode the session id is deterministic (``{record_id}_stateful``)+and reused across fires; in non-stateful mode a fresh session id is+created every fire.+"""+import json+from contextlib import AsyncExitStack+from datetime import datetime+from unittest import IsolatedAsyncioTestCase++import fakeredis.aioredis++from utils import AnyString++from agentscope.app._manager import SchedulerManager+from agentscope.app.message_bus import RedisMessageBus+from agentscope.app.storage import (+ ChatModelConfig,+ RedisStorage,+ ScheduleData,+ ScheduleRecord,+ SessionSource,+)+from agentscope.permission import PermissionMode+++def _make_storage(+ fr: fakeredis.aioredis.FakeRedis,+) -> RedisStorage:+ """Construct a :class:`RedisStorage` bound to *fr*."""++ class _S(RedisStorage):+ async def __aenter__(self) -> "RedisStorage": # type: ignore[override]+ self._client = fr+ return self++ async def aclose(self) -> None:+ self._client = None++ return _S()+++def _make_bus(+ fr: fakeredis.aioredis.FakeRedis,+) -> RedisMessageBus:+ """Construct a :class:`RedisMessageBus` bound to *fr*."""++ class _B(RedisMessageBus):+ async def __aenter__( # type: ignore[override]+ self,+ ) -> "RedisMessageBus":+ self._client = fr+ return self++ async def aclose(self) -> None:+ self._client = None++ return _B()+++def _make_record(+ *,+ user_id: str = "u",+ agent_id: str = "a",+ enabled: bool = True,+ stateful: bool = False,+ description: str = "run nightly summary",+) -> ScheduleRecord:+ """Build a minimal :class:`ScheduleRecord` for the trigger test."""+ return ScheduleRecord(+ user_id=user_id,+ agent_id=agent_id,+ data=ScheduleData(+ name="sched-a",+ description=description,+ enabled=enabled,+ cron_expression="0 0 * * *",+ started_at=datetime(2025, 1, 1),+ chat_model_config=ChatModelConfig(+ type="dashscope_credential",+ credential_id="c",+ model="m",+ parameters={},+ ),+ stateful=stateful,+ permission_mode=PermissionMode.DONT_ASK,+ ),+ )+++class _SchedulerFireTestBase(IsolatedAsyncioTestCase):+ """Shared fakeredis + storage + bus + manager fixture."""++ async def asyncSetUp(self) -> None:+ self.fr = fakeredis.aioredis.FakeRedis(decode_responses=True)+ self._stack = AsyncExitStack()+ self.storage = await self._stack.enter_async_context(+ _make_storage(self.fr),+ )+ self.bus = await self._stack.enter_async_context(_make_bus(self.fr))+ # Do NOT enter the SchedulerManager context — that would start+ # APScheduler. We only need ``_build_trigger`` from the+ # un-started manager.+ self.manager = SchedulerManager(+ storage=self.storage,+ message_bus=self.bus,+ )++ async def asyncTearDown(self) -> None:+ await self._stack.aclose()+ await self.fr.aclose()+++class TestSchedulerFireDelivery(_SchedulerFireTestBase):+ """A fire delivers the prompt as a HintBlock + wakeup."""++ async def test_fire_pushes_hint_and_wakeup(self) -> None:+ """A fire creates a session, pushes the wrapped HintBlock to its+ inbox, and enqueues one wakeup pointing at that session."""+ record = _make_record(description="please summarise the news")+ trigger = self.manager._build_trigger(record)+ await trigger()++ # A session was created.+ sessions = await self.storage.list_sessions(+ record.user_id,+ record.agent_id,+ )+ self.assertEqual(len(sessions), 1)+ session = sessions[0]+ self.assertEqual(+ {+ "source": session.source,+ "source_schedule_id": session.source_schedule_id,+ },+ {+ "source": SessionSource.SCHEDULE,+ "source_schedule_id": record.id,+ },+ )++ # Inbox has the wrapped HintBlock.+ inbox = await self.bus.inbox_drain(session.id, max_count=10)+ self.assertEqual(len(inbox), 1)+ hint = inbox[0][1]+ self.assertDictEqual(+ hint,+ {+ "type": "hint",+ "id": AnyString(),+ "hint": AnyString(),+ "source": json.dumps(+ {"label": "schedule", "sublabel": record.data.name},+ ),+ },+ )+ self.assertIn("<scheduled-task>", hint["hint"])+ self.assertIn("please summarise the news", hint["hint"])++ # A wakeup is enqueued for that session.+ wakeups = await self.bus.dequeue_wakeups(max_count=10)+ self.assertEqual(len(wakeups), 1)+ self.assertEqual(+ wakeups[0],+ {+ "session_id": session.id,+ "agent_id": record.agent_id,+ "user_id": record.user_id,+ },+ )+++class TestSchedulerFireDisabled(_SchedulerFireTestBase):+ """Disabled schedules are a no-op."""++ async def test_disabled_fire_does_nothing(self) -> None:+ """A fire on a disabled schedule creates no session and no wakeup."""+ record = _make_record(enabled=False)+ trigger = self.manager._build_trigger(record)+ await trigger()++ # No session created, no wakeup enqueued.+ sessions = await self.storage.list_sessions(+ record.user_id,+ record.agent_id,+ )+ self.assertEqual(sessions, [])+ wakeups = await self.bus.dequeue_wakeups(max_count=10)+ self.assertEqual(wakeups, [])+++class TestSchedulerFireStatefulMode(_SchedulerFireTestBase):+ """Stateful schedules reuse the same session id across fires."""++ async def test_stateful_fires_share_one_session(self) -> None:+ """Two fires of a stateful schedule reuse the same session id."""+ record = _make_record(stateful=True)+ trigger = self.manager._build_trigger(record)+ await trigger()+ await trigger()++ sessions = await self.storage.list_sessions(+ record.user_id,+ record.agent_id,+ )+ # Exactly ONE session reused.+ self.assertEqual(len(sessions), 1)+ self.assertEqual([s.id for s in sessions], [f"{record.id}_stateful"])++ # That single session has two HintBlocks in its inbox.+ inbox = await self.bus.inbox_drain(sessions[0].id, max_count=10)+ self.assertEqual(len(inbox), 2)++ # Two wakeups, both pointing at the same session.+ wakeups = await self.bus.dequeue_wakeups(max_count=10)+ self.assertEqual(+ wakeups,+ [+ {+ "session_id": sessions[0].id,+ "agent_id": record.agent_id,+ "user_id": record.user_id,+ },+ {+ "session_id": sessions[0].id,+ "agent_id": record.agent_id,+ "user_id": record.user_id,+ },+ ],+ )+++class TestSchedulerFireNonStatefulMode(_SchedulerFireTestBase):+ """Non-stateful schedules create a fresh session every fire."""++ async def test_non_stateful_fires_create_distinct_sessions(+ self,+ ) -> None:+ """Two fires of a non-stateful schedule create distinct sessions."""+ record = _make_record(stateful=False)+ trigger = self.manager._build_trigger(record)+ await trigger()+ await trigger()++ sessions = await self.storage.list_sessions(+ record.user_id,+ record.agent_id,+ )+ self.assertEqual(len(sessions), 2)+ self.assertNotEqual(sessions[0].id, sessions[1].id)diff --git a/tests/service_team_tools_test.py b/tests/service_team_tools_test.pynew file mode 100644index 000000000..025ea897c--- /dev/null+++ b/tests/service_team_tools_test.py@@ -0,0 +1,781 @@+# -*- coding: utf-8 -*-+# pylint: disable=protected-access+"""Tests for the four framework-builtin team tools — :class:`TeamCreate`,+:class:`AgentCreate`, :class:`TeamSay`, :class:`TeamDelete`.++Each tool's business logic now lives inline in its ``__call__`` (the+old ``TeamService`` orchestration layer is gone), so unit tests run the+tools directly against a real :class:`RedisStorage` + :class:`RedisMessageBus`+backed by ``fakeredis``. They assert:++- the success path: storage rows updated, inbox + wakeup pushed where+ expected;+- the failure paths: each precondition (not in a team / not the leader /+ recipient missing / etc.) returns an ``ERROR`` ``ToolChunk`` instead+ of raising.+"""+from contextlib import AsyncExitStack+from unittest import IsolatedAsyncioTestCase++import fakeredis.aioredis++from utils import AnyString++from agentscope.agent import ContextConfig, ReActConfig+from agentscope.app._tools import (+ AgentCreate,+ TeamCreate,+ TeamDelete,+ TeamSay,+)+from agentscope.app.message_bus import RedisMessageBus+from agentscope.app.storage import (+ AgentData,+ AgentRecord,+ RedisStorage,+ SessionConfig,+)+++def _make_storage(+ fr: fakeredis.aioredis.FakeRedis,+) -> RedisStorage:+ """Construct a :class:`RedisStorage` that talks to *fr*."""++ class _S(RedisStorage):+ async def __aenter__(self) -> "RedisStorage": # type: ignore[override]+ self._client = fr+ return self++ async def aclose(self) -> None:+ self._client = None++ return _S()+++def _make_bus(+ fr: fakeredis.aioredis.FakeRedis,+) -> RedisMessageBus:+ """Construct a :class:`RedisMessageBus` that talks to *fr*."""++ class _B(RedisMessageBus):+ async def __aenter__( # type: ignore[override]+ self,+ ) -> "RedisMessageBus":+ self._client = fr+ return self++ async def aclose(self) -> None:+ self._client = None++ return _B()+++def _make_agent_record(+ user_id: str,+ name: str,+ source: str = "user",+) -> AgentRecord:+ """Build a minimal :class:`AgentRecord`."""+ return AgentRecord(+ user_id=user_id,+ source=source,+ data=AgentData(+ name=name,+ system_prompt=f"You are {name}.",+ context_config=ContextConfig(),+ react_config=ReActConfig(),+ ),+ )+++class _TeamToolsTestBase(IsolatedAsyncioTestCase):+ """Shared fixture: a fakeredis-backed storage + bus, a leader+ agent record, and a leader session.++ Sub-classes set up their own teams / workers on top.+ """++ user_id = "u"++ async def asyncSetUp(self) -> None:+ self.fr = fakeredis.aioredis.FakeRedis(decode_responses=True)+ self._stack = AsyncExitStack()+ self.storage = await self._stack.enter_async_context(+ _make_storage(self.fr),+ )+ self.bus = await self._stack.enter_async_context(_make_bus(self.fr))++ # Leader agent + its session.+ self.leader_agent = _make_agent_record(self.user_id, "leader")+ await self.storage.upsert_agent(self.user_id, self.leader_agent)+ self.leader_session = await self.storage.upsert_session(+ user_id=self.user_id,+ agent_id=self.leader_agent.id,+ config=SessionConfig(workspace_id="ws"),+ )++ async def asyncTearDown(self) -> None:+ await self._stack.aclose()+ await self.fr.aclose()+++class TestTeamCreate(_TeamToolsTestBase):+ """``TeamCreate`` creates a TeamRecord and stamps ``team_id`` on+ the calling session."""++ async def test_creates_team_and_stamps_session(self) -> None:+ """A successful ``TeamCreate`` writes a TeamRecord and stamps the+ leader's session with the new ``team_id``."""+ tool = TeamCreate(+ storage=self.storage,+ message_bus=self.bus,+ user_id=self.user_id,+ session_id=self.leader_session.id,+ agent_id=self.leader_agent.id,+ )+ chunk = await tool(name="alpha", description="t-desc")++ self.assertDictEqual(+ chunk.model_dump(),+ {+ "content": [+ {"type": "text", "text": AnyString(), "id": AnyString()},+ ],+ "state": "running",+ "is_last": True,+ "metadata": {},+ "id": AnyString(),+ },+ )+ # A team exists and the leader's session now points at it.+ sess = await self.storage.get_session(+ self.user_id,+ self.leader_agent.id,+ self.leader_session.id,+ )+ self.assertIsNotNone(sess.team_id)+ team = await self.storage.get_team(self.user_id, sess.team_id)+ self.assertIsNotNone(team)+ self.assertDictEqual(+ {+ "name": team.data.name,+ "session_id": team.session_id,+ "member_ids": team.data.member_ids,+ },+ {+ "name": "alpha",+ "session_id": self.leader_session.id,+ "member_ids": [],+ },+ )++ async def test_rejects_when_session_already_in_team(self) -> None:+ """A session can lead at most one team."""+ tool = TeamCreate(+ storage=self.storage,+ message_bus=self.bus,+ user_id=self.user_id,+ session_id=self.leader_session.id,+ agent_id=self.leader_agent.id,+ )+ await tool(name="first", description="d")+ chunk = await tool(name="second", description="d")+ self.assertDictEqual(+ chunk.model_dump(),+ {+ "content": [+ {"type": "text", "text": AnyString(), "id": AnyString()},+ ],+ "state": "error",+ "is_last": True,+ "metadata": {},+ "id": AnyString(),+ },+ )+++class TestAgentCreate(_TeamToolsTestBase):+ """``AgentCreate`` spawns a worker agent + session, appends it to+ the team, and delivers the initial prompt via inbox + wakeup."""++ async def asyncSetUp(self) -> None:+ await super().asyncSetUp()+ # Pre-create a team so the leader has one to add to.+ await TeamCreate(+ storage=self.storage,+ message_bus=self.bus,+ user_id=self.user_id,+ session_id=self.leader_session.id,+ agent_id=self.leader_agent.id,+ )(name="team", description="team desc")++ async def test_spawns_worker_and_delivers_initial_prompt(+ self,+ ) -> None:+ """A successful ``AgentCreate`` adds the worker agent + session to+ the team and delivers the initial prompt via inbox + wakeup."""+ tool = AgentCreate(+ storage=self.storage,+ message_bus=self.bus,+ user_id=self.user_id,+ session_id=self.leader_session.id,+ agent_id=self.leader_agent.id,+ )+ chunk = await tool(+ name="worker",+ description="does research",+ prompt="please look up X",+ permission_mode="default",+ )+ self.assertDictEqual(+ chunk.model_dump(),+ {+ "content": [+ {"type": "text", "text": AnyString(), "id": AnyString()},+ ],+ "state": "running",+ "is_last": True,+ "metadata": {},+ "id": AnyString(),+ },+ )++ # Team has one member.+ sess = await self.storage.get_session(+ self.user_id,+ self.leader_agent.id,+ self.leader_session.id,+ )+ team = await self.storage.get_team(self.user_id, sess.team_id)+ self.assertEqual(len(team.data.member_ids), 1)+ worker_agent_id = team.data.member_ids[0]++ # Worker agent exists with source=team.+ worker_agent = await self.storage.get_agent(+ self.user_id,+ worker_agent_id,+ )+ self.assertEqual(+ {"source": worker_agent.source, "name": worker_agent.data.name},+ {"source": "team", "name": "worker"},+ )++ # Worker has exactly one session, marked with team_id.+ worker_sessions = await self.storage.list_sessions(+ self.user_id,+ worker_agent_id,+ )+ self.assertEqual(len(worker_sessions), 1)+ self.assertEqual(worker_sessions[0].team_id, sess.team_id)++ # The initial prompt is in the worker's inbox as a HintBlock+ # wrapped in a <team-message> tag.+ inbox = await self.bus.inbox_drain(+ worker_sessions[0].id,+ max_count=10,+ )+ self.assertEqual(len(inbox), 1)+ hint_payload = inbox[0][1]+ self.assertDictEqual(+ hint_payload,+ {+ "type": "hint",+ "id": AnyString(),+ "hint": AnyString(),+ "source": '{"label": "team_message", "sublabel": "leader"}',+ },+ )+ self.assertIn("please look up X", hint_payload["hint"])+ self.assertIn("<team-message", hint_payload["hint"])++ # A wakeup was enqueued for the worker.+ wakeups = await self.bus.dequeue_wakeups(max_count=10)+ self.assertEqual(len(wakeups), 1)+ self.assertEqual(+ wakeups[0],+ {+ "session_id": worker_sessions[0].id,+ "agent_id": worker_agent_id,+ "user_id": self.user_id,+ },+ )++ async def test_rejects_when_not_in_team(self) -> None:+ """Calling ``AgentCreate`` from a session that hasn't run+ ``TeamCreate`` yet returns an error chunk."""+ # Build a second leader session that is NOT in any team.+ loner_session = await self.storage.upsert_session(+ user_id=self.user_id,+ agent_id=self.leader_agent.id,+ config=SessionConfig(workspace_id="ws2"),+ )+ tool = AgentCreate(+ storage=self.storage,+ message_bus=self.bus,+ user_id=self.user_id,+ session_id=loner_session.id,+ agent_id=self.leader_agent.id,+ )+ chunk = await tool(+ name="worker",+ description="d",+ prompt="p",+ permission_mode="default",+ )+ self.assertDictEqual(+ chunk.model_dump(),+ {+ "content": [+ {"type": "text", "text": AnyString(), "id": AnyString()},+ ],+ "state": "error",+ "is_last": True,+ "metadata": {},+ "id": AnyString(),+ },+ )++ async def test_rejects_unknown_permission_mode(self) -> None:+ """An unrecognised ``permission_mode`` returns an error chunk."""+ tool = AgentCreate(+ storage=self.storage,+ message_bus=self.bus,+ user_id=self.user_id,+ session_id=self.leader_session.id,+ agent_id=self.leader_agent.id,+ )+ chunk = await tool(+ name="w",+ description="d",+ prompt="p",+ permission_mode="not-a-mode", # type: ignore[arg-type]+ )+ self.assertDictEqual(+ chunk.model_dump(),+ {+ "content": [+ {"type": "text", "text": AnyString(), "id": AnyString()},+ ],+ "state": "error",+ "is_last": True,+ "metadata": {},+ "id": AnyString(),+ },+ )++ async def test_rejects_duplicate_member_name(self) -> None:+ """Two ``AgentCreate`` calls with the same ``name`` is rejected:+ TeamSay routes by name, so duplicates would be ambiguous."""+ tool = AgentCreate(+ storage=self.storage,+ message_bus=self.bus,+ user_id=self.user_id,+ session_id=self.leader_session.id,+ agent_id=self.leader_agent.id,+ )+ first = await tool(+ name="worker",+ description="d",+ prompt="p",+ permission_mode="default",+ )+ self.assertEqual(first.state.value, "running")++ second = await tool(+ name="worker",+ description="d",+ prompt="p",+ permission_mode="default",+ )+ self.assertEqual(second.state.value, "error")++ # The team still only has one member — the second call did not+ # persist anything.+ sess = await self.storage.get_session(+ self.user_id,+ self.leader_agent.id,+ self.leader_session.id,+ )+ team = await self.storage.get_team(self.user_id, sess.team_id)+ self.assertEqual(len(team.data.member_ids), 1)++ async def test_rejects_member_name_colliding_with_leader(self) -> None:+ """A worker name that matches the leader's name is rejected —+ ``TeamSay(to=<leader name>)`` must remain unambiguous."""+ tool = AgentCreate(+ storage=self.storage,+ message_bus=self.bus,+ user_id=self.user_id,+ session_id=self.leader_session.id,+ agent_id=self.leader_agent.id,+ )+ chunk = await tool(+ name=self.leader_agent.data.name, # "leader"+ description="d",+ prompt="p",+ permission_mode="default",+ )+ self.assertEqual(chunk.state.value, "error")++ # No worker was added.+ sess = await self.storage.get_session(+ self.user_id,+ self.leader_agent.id,+ self.leader_session.id,+ )+ team = await self.storage.get_team(self.user_id, sess.team_id)+ self.assertEqual(team.data.member_ids, [])+++class TestTeamSay(_TeamToolsTestBase):+ """``TeamSay`` delivers a HintBlock + wakeup to each addressed+ teammate."""++ async def asyncSetUp(self) -> None:+ await super().asyncSetUp()+ await TeamCreate(+ storage=self.storage,+ message_bus=self.bus,+ user_id=self.user_id,+ session_id=self.leader_session.id,+ agent_id=self.leader_agent.id,+ )(name="team", description="team desc")+ # Add 2 workers.+ agent_create = AgentCreate(+ storage=self.storage,+ message_bus=self.bus,+ user_id=self.user_id,+ session_id=self.leader_session.id,+ agent_id=self.leader_agent.id,+ )+ await agent_create(+ name="w1",+ description="d",+ prompt="p1",+ permission_mode="default",+ )+ await agent_create(+ name="w2",+ description="d",+ prompt="p2",+ permission_mode="default",+ )+ # Drain the pre-existing wakeups so subsequent assertions only+ # see what TeamSay enqueues.+ await self.bus.dequeue_wakeups(max_count=100)+ # Resolve worker IDs.+ sess = await self.storage.get_session(+ self.user_id,+ self.leader_agent.id,+ self.leader_session.id,+ )+ team = await self.storage.get_team(self.user_id, sess.team_id)+ self.worker_ids = team.data.member_ids+ self.worker_sessions = {}+ for aid in self.worker_ids:+ ss = await self.storage.list_sessions(self.user_id, aid)+ self.worker_sessions[aid] = ss[0].id+ # Drain initial-prompt hints too.+ await self.bus.inbox_drain(ss[0].id, max_count=100)++ async def test_targeted_message_delivers_to_one(self) -> None:+ """``to=<member name>`` delivers a HintBlock + wakeup to that worker+ only; other team members see nothing."""+ tool = TeamSay(+ storage=self.storage,+ message_bus=self.bus,+ user_id=self.user_id,+ session_id=self.leader_session.id,+ agent_id=self.leader_agent.id,+ role="leader",+ )+ target_aid = self.worker_ids[0]+ target_agent = await self.storage.get_agent(+ self.user_id,+ target_aid,+ )+ chunk = await tool(content="hi w1", to=target_agent.data.name)+ self.assertDictEqual(+ chunk.model_dump(),+ {+ "content": [+ {"type": "text", "text": AnyString(), "id": AnyString()},+ ],+ "state": "running",+ "is_last": True,+ "metadata": {},+ "id": AnyString(),+ },+ )++ # Inbox of target has the hint; the other worker's inbox stays+ # empty.+ target_sid = self.worker_sessions[target_aid]+ other_sid = self.worker_sessions[self.worker_ids[1]]+ target_inbox = await self.bus.inbox_drain(target_sid, max_count=10)+ other_inbox = await self.bus.inbox_drain(other_sid, max_count=10)+ self.assertEqual(len(target_inbox), 1)+ self.assertEqual(len(other_inbox), 0)+ self.assertDictEqual(+ target_inbox[0][1],+ {+ "type": "hint",+ "id": AnyString(),+ "hint": AnyString(),+ "source": AnyString(),+ },+ )+ self.assertIn("hi w1", target_inbox[0][1]["hint"])++ # Wakeup for the target only.+ wakeups = await self.bus.dequeue_wakeups(max_count=10)+ self.assertEqual(+ wakeups,+ [+ {+ "session_id": target_sid,+ "agent_id": target_aid,+ "user_id": self.user_id,+ },+ ],+ )++ async def test_broadcast_delivers_to_all_others(self) -> None:+ """``to=None`` broadcasts to everyone in the team except the+ sender."""+ tool = TeamSay(+ storage=self.storage,+ message_bus=self.bus,+ user_id=self.user_id,+ session_id=self.leader_session.id,+ agent_id=self.leader_agent.id,+ role="leader",+ )+ chunk = await tool(content="all hands", to=None)+ self.assertDictEqual(+ chunk.model_dump(),+ {+ "content": [+ {"type": "text", "text": AnyString(), "id": AnyString()},+ ],+ "state": "running",+ "is_last": True,+ "metadata": {},+ "id": AnyString(),+ },+ )++ # Both workers receive; leader doesn't loopback to itself.+ for aid, sid in self.worker_sessions.items():+ inbox = await self.bus.inbox_drain(sid, max_count=10)+ self.assertEqual(+ len(inbox),+ 1,+ f"worker {aid} missed broadcast",+ )+ leader_inbox = await self.bus.inbox_drain(+ self.leader_session.id,+ max_count=10,+ )+ self.assertEqual(leader_inbox, [])++ wakeups = await self.bus.dequeue_wakeups(max_count=10)+ self.assertEqual(len(wakeups), 2)++ async def test_rejects_when_session_not_in_team(self) -> None:+ """A session without a team can't TeamSay."""+ loner_session = await self.storage.upsert_session(+ user_id=self.user_id,+ agent_id=self.leader_agent.id,+ config=SessionConfig(workspace_id="ws-lone"),+ )+ tool = TeamSay(+ storage=self.storage,+ message_bus=self.bus,+ user_id=self.user_id,+ session_id=loner_session.id,+ agent_id=self.leader_agent.id,+ role="leader",+ )+ chunk = await tool(content="hi", to=None)+ self.assertDictEqual(+ chunk.model_dump(),+ {+ "content": [+ {"type": "text", "text": AnyString(), "id": AnyString()},+ ],+ "state": "error",+ "is_last": True,+ "metadata": {},+ "id": AnyString(),+ },+ )++ async def test_rejects_unknown_recipient(self) -> None:+ """A ``to=`` that doesn't resolve to a team member name returns+ an error chunk."""+ tool = TeamSay(+ storage=self.storage,+ message_bus=self.bus,+ user_id=self.user_id,+ session_id=self.leader_session.id,+ agent_id=self.leader_agent.id,+ role="leader",+ )+ chunk = await tool(content="hi", to="ghost-name-not-in-team")+ self.assertDictEqual(+ chunk.model_dump(),+ {+ "content": [+ {"type": "text", "text": AnyString(), "id": AnyString()},+ ],+ "state": "error",+ "is_last": True,+ "metadata": {},+ "id": AnyString(),+ },+ )++ async def test_rejects_self_target(self) -> None:+ """``to=<own name>`` is rejected — talk to yourself in+ reasoning, not via TeamSay."""+ tool = TeamSay(+ storage=self.storage,+ message_bus=self.bus,+ user_id=self.user_id,+ session_id=self.leader_session.id,+ agent_id=self.leader_agent.id,+ role="leader",+ )+ chunk = await tool(content="hi", to=self.leader_agent.data.name)+ self.assertDictEqual(+ chunk.model_dump(),+ {+ "content": [+ {"type": "text", "text": AnyString(), "id": AnyString()},+ ],+ "state": "error",+ "is_last": True,+ "metadata": {},+ "id": AnyString(),+ },+ )++ async def test_worker_can_address_leader_by_name(self) -> None:+ """A worker constructed with ``role="worker"`` can address the+ leader using the leader's name — the only identifier a worker+ ever has for the leader (received via the ``from=`` attribute+ of the initial ``<team-message>`` hint)."""+ worker_aid = self.worker_ids[0]+ worker_sid = self.worker_sessions[worker_aid]++ tool = TeamSay(+ storage=self.storage,+ message_bus=self.bus,+ user_id=self.user_id,+ session_id=worker_sid,+ agent_id=worker_aid,+ role="worker",+ )+ chunk = await tool(+ content="task done",+ to=self.leader_agent.data.name,+ )+ self.assertEqual(chunk.state.value, "running")++ # Leader's inbox received the worker's reply.+ leader_inbox = await self.bus.inbox_drain(+ self.leader_session.id,+ max_count=10,+ )+ self.assertEqual(len(leader_inbox), 1)+ self.assertIn("task done", leader_inbox[0][1]["hint"])++ # Wakeup was enqueued for the leader.+ wakeups = await self.bus.dequeue_wakeups(max_count=10)+ self.assertEqual(+ wakeups,+ [+ {+ "session_id": self.leader_session.id,+ "agent_id": self.leader_agent.id,+ "user_id": self.user_id,+ },+ ],+ )+++class TestTeamDelete(_TeamToolsTestBase):+ """``TeamDelete`` dissolves the team and clears the leader's+ ``team_id``."""++ async def asyncSetUp(self) -> None:+ await super().asyncSetUp()+ await TeamCreate(+ storage=self.storage,+ message_bus=self.bus,+ user_id=self.user_id,+ session_id=self.leader_session.id,+ agent_id=self.leader_agent.id,+ )(name="team", description="d")++ async def test_dissolves_team_from_leader(self) -> None:+ """``TeamDelete`` removes the team and clears the leader's+ ``team_id``."""+ tool = TeamDelete(+ storage=self.storage,+ message_bus=self.bus,+ user_id=self.user_id,+ session_id=self.leader_session.id,+ agent_id=self.leader_agent.id,+ )+ chunk = await tool()+ self.assertDictEqual(+ chunk.model_dump(),+ {+ "content": [+ {"type": "text", "text": AnyString(), "id": AnyString()},+ ],+ "state": "running",+ "is_last": True,+ "metadata": {},+ "id": AnyString(),+ },+ )++ sess = await self.storage.get_session(+ self.user_id,+ self.leader_agent.id,+ self.leader_session.id,+ )+ self.assertIsNone(sess.team_id)++ async def test_rejects_when_not_in_team(self) -> None:+ """Calling ``TeamDelete`` from a session that isn't in any team+ returns an error chunk."""+ loner_session = await self.storage.upsert_session(+ user_id=self.user_id,+ agent_id=self.leader_agent.id,+ config=SessionConfig(workspace_id="ws-lone"),+ )+ tool = TeamDelete(+ storage=self.storage,+ message_bus=self.bus,+ user_id=self.user_id,+ session_id=loner_session.id,+ agent_id=self.leader_agent.id,+ )+ chunk = await tool()+ self.assertDictEqual(+ chunk.model_dump(),+ {+ "content": [+ {"type": "text", "text": AnyString(), "id": AnyString()},+ ],+ "state": "error",+ "is_last": True,+ "metadata": {},+ "id": AnyString(),+ },+ )diff --git a/tests/service_toolkit_test.py b/tests/service_toolkit_test.pynew file mode 100644index 000000000..c132d164d--- /dev/null+++ b/tests/service_toolkit_test.py@@ -0,0 +1,319 @@+# -*- coding: utf-8 -*-+# pylint: disable=protected-access+"""Tests for :func:`get_toolkit` — the single entry point that assembles+the per-chat-turn :class:`Toolkit` from every tool source the framework+manages.++Verifies the assembly rules:++- workspace builtins are always included;+- the four ``Task*`` planning tools are always included;+- :class:`TaskStop` (from ``BackgroundTaskManager``) is always included;+- the four ``Schedule*`` tools only when ``session.config.chat_model_config``+ is set (they need a model to fire new runs with);+- team tools are role-gated by ``agent_record.source``: ``"team"`` →+ one ``TeamSay`` (worker variant); anything else → the full+ leader-side toolset of four;+- caller-supplied ``extra_factory`` results land at the end.+"""+from typing import Any+from unittest import IsolatedAsyncioTestCase++from agentscope.agent import ContextConfig, ReActConfig+from agentscope.app._manager import (+ BackgroundTaskManager,+ SchedulerManager,+)+from agentscope.app._service import get_toolkit+from agentscope.app.storage import (+ AgentData,+ AgentRecord,+ ChatModelConfig,+ SessionConfig,+ SessionRecord,+)+from agentscope.tool import ToolBase+++class _FakeWorkspace:+ """Stand-in for a resolved :class:`WorkspaceBase` — only the three+ methods :func:`get_toolkit` calls are implemented."""++ def __init__(+ self,+ tools: list[ToolBase] | None = None,+ skills: list | None = None,+ mcps: list | None = None,+ ) -> None:+ self._tools = tools or []+ self._skills = skills or []+ self._mcps = mcps or []++ async def list_tools(self) -> list[ToolBase]:+ """Return the configured workspace tools."""+ return list(self._tools)++ async def list_skills(self) -> list:+ """Return the configured workspace skills."""+ return list(self._skills)++ async def list_mcps(self) -> list:+ """Return the configured workspace MCP descriptors."""+ return list(self._mcps)+++class _NullBus:+ """``MessageBus`` placeholder. Team tools only carry the reference;+ nothing in :func:`get_toolkit` actually awaits it."""+++def _make_agent(*, source: str = "user", name: str = "A") -> AgentRecord:+ """Build a minimal :class:`AgentRecord`."""+ return AgentRecord(+ user_id="u",+ source=source,+ data=AgentData(+ name=name,+ system_prompt=f"You are {name}.",+ context_config=ContextConfig(),+ react_config=ReActConfig(),+ ),+ )+++def _make_session(+ *,+ user_id: str,+ agent_id: str,+ with_model: bool,+) -> SessionRecord:+ """Build a minimal :class:`SessionRecord`, optionally with a chat+ model config."""+ cfg = SessionConfig(+ workspace_id="ws",+ chat_model_config=(+ ChatModelConfig(+ type="dashscope_credential",+ credential_id="c",+ model="m",+ parameters={},+ )+ if with_model+ else None+ ),+ )+ return SessionRecord(user_id=user_id, agent_id=agent_id, config=cfg)+++class _NoOpStorage:+ """Storage placeholder. ``get_toolkit`` itself does not call any+ storage method — the team tools bind a reference for later use."""+++def _tool_names(toolkit: Any) -> list[str]:+ """Extract every registered tool name from a :class:`Toolkit`,+ walking its tool groups."""+ return [t.name for group in toolkit.tool_groups for t in group.tools]+++class _StubTool(ToolBase):+ """Minimal :class:`ToolBase` subclass that satisfies the abstract+ methods so :func:`get_toolkit` can register the instance.++ Sub-classes override ``name`` and ``description``; nothing in the+ tests actually calls the tool, so the implementations are no-ops.+ """++ name: str = "stub"+ description: str = "stub tool"+ input_schema: dict = {}+ is_concurrency_safe: bool = True+ is_read_only: bool = False+ is_state_injected: bool = False+ is_external_tool: bool = False+ is_mcp: bool = False+ mcp_name: str | None = None++ async def check_permissions(self, *args: Any, **kwargs: Any) -> None:+ """No-op permission check — the tests do not exercise it."""++ async def __call__(self, *args: Any, **kwargs: Any) -> None:+ """No-op invocation — the tests never execute the tool."""+++class TestGetToolkitBaseAssembly(IsolatedAsyncioTestCase):+ """User-owned agent (``source="user"``) gets the full set."""++ async def test_user_agent_gets_all_sources(self) -> None:+ """A user-owned agent receives workspace, planning, scheduling,+ TaskStop, and the four leader-side team tools."""+ agent = _make_agent(source="user")+ session = _make_session(+ user_id="u",+ agent_id=agent.id,+ with_model=True,+ )++ class _WsTool(_StubTool):+ """Stub workspace tool registered through ``_FakeWorkspace``."""++ name: str = "ws-bash"+ description: str = "stub workspace tool"++ ws_tool = _WsTool()+ workspace = _FakeWorkspace(tools=[ws_tool])++ toolkit = await get_toolkit(+ storage=_NoOpStorage(), # type: ignore[arg-type]+ workspace=workspace, # type: ignore[arg-type]+ scheduler_manager=SchedulerManager(+ storage=_NoOpStorage(), # type: ignore[arg-type]+ message_bus=_NullBus(), # type: ignore[arg-type]+ ),+ background_task_manager=BackgroundTaskManager(),+ message_bus=_NullBus(), # type: ignore[arg-type]+ user_id="u",+ agent_record=agent,+ session_record=session,+ extra_factory=None,+ )++ names = set(_tool_names(toolkit))+ # Workspace tool present.+ self.assertIn("ws-bash", names)+ # Planning tools present.+ self.assertTrue(+ {"TaskCreate", "TaskList", "TaskGet", "TaskUpdate"} <= names,+ )+ # Background task control present.+ self.assertIn("TaskStop", names)+ # Schedule control present (model_config is set).+ self.assertTrue(+ {+ "ScheduleCreate",+ "ScheduleView",+ "ScheduleDelete",+ "ScheduleList",+ }+ <= names,+ )+ # Leader-side team tools (4 of them).+ self.assertTrue(+ {"TeamCreate", "AgentCreate", "TeamSay", "TeamDelete"} <= names,+ )+++class TestGetToolkitWorkerVariant(IsolatedAsyncioTestCase):+ """Worker agent (``source="team"``) only gets ``TeamSay``."""++ async def test_worker_only_gets_team_say(self) -> None:+ """A worker agent (``source="team"``) receives only ``TeamSay``+ from the team toolset."""+ agent = _make_agent(source="team", name="worker")+ session = _make_session(+ user_id="u",+ agent_id=agent.id,+ with_model=True,+ )+ toolkit = await get_toolkit(+ storage=_NoOpStorage(), # type: ignore[arg-type]+ workspace=_FakeWorkspace(), # type: ignore[arg-type]+ scheduler_manager=SchedulerManager(+ storage=_NoOpStorage(), # type: ignore[arg-type]+ message_bus=_NullBus(), # type: ignore[arg-type]+ ),+ background_task_manager=BackgroundTaskManager(),+ message_bus=_NullBus(), # type: ignore[arg-type]+ user_id="u",+ agent_record=agent,+ session_record=session,+ extra_factory=None,+ )+ names = set(_tool_names(toolkit))+ # Only TeamSay from the team toolset.+ self.assertIn("TeamSay", names)+ for missing in ("TeamCreate", "AgentCreate", "TeamDelete"):+ self.assertNotIn(missing, names)+++class TestGetToolkitSchedulingGuard(IsolatedAsyncioTestCase):+ """``Schedule*`` tools are only attached when the session has a+ model configured."""++ async def test_no_schedule_tools_without_model_config(self) -> None:+ """Without a ``chat_model_config`` on the session, the four+ ``Schedule*`` tools are omitted from the toolkit."""+ agent = _make_agent(source="user")+ session = _make_session(+ user_id="u",+ agent_id=agent.id,+ with_model=False,+ )+ toolkit = await get_toolkit(+ storage=_NoOpStorage(), # type: ignore[arg-type]+ workspace=_FakeWorkspace(), # type: ignore[arg-type]+ scheduler_manager=SchedulerManager(+ storage=_NoOpStorage(), # type: ignore[arg-type]+ message_bus=_NullBus(), # type: ignore[arg-type]+ ),+ background_task_manager=BackgroundTaskManager(),+ message_bus=_NullBus(), # type: ignore[arg-type]+ user_id="u",+ agent_record=agent,+ session_record=session,+ extra_factory=None,+ )+ names = set(_tool_names(toolkit))+ for missing in (+ "ScheduleCreate",+ "ScheduleView",+ "ScheduleDelete",+ "ScheduleList",+ ):+ self.assertNotIn(missing, names)+++class TestGetToolkitExtraFactory(IsolatedAsyncioTestCase):+ """Tools returned by ``extra_factory`` end up in the final toolkit."""++ async def test_extra_factory_tools_are_attached(self) -> None:+ """Tools returned by ``extra_factory`` end up in the final+ toolkit alongside the framework-builtin ones."""++ class _ExtraTool(_StubTool):+ """Stub tool emitted by the ``extra_factory`` callback."""++ name: str = "my-extra"+ description: str = "stub extra tool"++ extra_tool = _ExtraTool()++ async def factory(+ _user_id: str,+ _agent_id: str,+ _session_id: str,+ ) -> list[ToolBase]:+ """Stub extra-factory that always returns ``extra_tool``."""+ return [extra_tool]++ agent = _make_agent()+ session = _make_session(+ user_id="u",+ agent_id=agent.id,+ with_model=True,+ )+ toolkit = await get_toolkit(+ storage=_NoOpStorage(), # type: ignore[arg-type]+ workspace=_FakeWorkspace(), # type: ignore[arg-type]+ scheduler_manager=SchedulerManager(+ storage=_NoOpStorage(), # type: ignore[arg-type]+ message_bus=_NullBus(), # type: ignore[arg-type]+ ),+ background_task_manager=BackgroundTaskManager(),+ message_bus=_NullBus(), # type: ignore[arg-type]+ user_id="u",+ agent_record=agent,+ session_record=session,+ extra_factory=factory,+ )+ self.assertIn("my-extra", _tool_names(toolkit))diff --git a/tests/service_wakeup_dispatcher_test.py b/tests/service_wakeup_dispatcher_test.pynew file mode 100644index 000000000..f262c8ffb--- /dev/null+++ b/tests/service_wakeup_dispatcher_test.py@@ -0,0 +1,368 @@+# -*- coding: utf-8 -*-+# pylint: disable=protected-access+"""Tests for :class:`WakeupDispatcher` — one-per-process consumer of the+shared wake-up queue + signal channel.++Verifies the four behaviours that callers rely on:++- Lifecycle is purely ACM: ``__aenter__`` starts the loop and performs+ an initial drain; ``__aexit__`` cancels the loop cleanly.+- A wake-up signal triggers a queue drain; each entry is dispatched as+ a fire-and-forget ``ChatService.run`` call.+- Entries left on the queue from before startup are picked up on+ ``__aenter__`` without waiting for a fresh signal.+- Sessions that are already running are skipped (no duplicate run).+- Malformed entries are logged and skipped, not raised.+"""+import asyncio+from contextlib import asynccontextmanager+from typing import Any, AsyncGenerator, Callable+from unittest import IsolatedAsyncioTestCase++from agentscope.app._manager import ChatRunRegistry, WakeupDispatcher+from agentscope.app.message_bus import MessageBus+++class _FakeStorage:+ """Minimal storage stand-in for the dispatcher's orphan-guard check.++ ``get_session`` returns a truthy sentinel for every session id by+ default; tests that exercise the orphan path mutate+ ``missing_session_ids``.+ """++ def __init__(self) -> None:+ self.missing_session_ids: set[str] = set()++ async def get_session(+ self,+ _user_id: str,+ _agent_id: str,+ session_id: str,+ ) -> object | None:+ """Get a session id from the orphan guard."""+ if session_id in self.missing_session_ids:+ return None+ return object()+++class _FakeBus(MessageBus):+ """In-memory bus with just enough behaviour for the dispatcher.++ Implements the four primitives the dispatcher uses+ (``queue_push`` / ``dequeue_wakeups`` indirectly via the parent's+ domain helper / ``subscribe_wakeup_signal`` / ``is_locked`` /+ ``publish``) and stubs the others.+ """++ def __init__(self) -> None:+ self.queues: dict[str, list[tuple[str, dict]]] = {}+ self._channels: dict[str, asyncio.Queue] = {}+ self._next = 0+ self._locks: set[str] = set()++ def _channel(self, key: str) -> asyncio.Queue:+ return self._channels.setdefault(key, asyncio.Queue())++ # Mode A — queue+ async def queue_push(+ self,+ key: str,+ payload: dict,+ *,+ ttl_secs: int | None = None,+ ) -> str:+ self._next += 1+ entry_id = str(self._next)+ self.queues.setdefault(key, []).append((entry_id, payload))+ return entry_id++ async def queue_drain(+ self,+ key: str,+ *,+ max_count: int,+ ) -> list[tuple[str, dict]]:+ entries = self.queues.get(key, [])[:max_count]+ self.queues[key] = self.queues.get(key, [])[max_count:]+ return entries++ async def queue_delete(self, key: str) -> None:+ self.queues.pop(key, None)++ # Mode C — log (unused here)+ async def log_append(+ self,+ key: str,+ payload: dict,+ *,+ max_len: int | None = None,+ ttl_secs: int | None = None,+ ) -> str:+ return "n/a"++ async def log_read(+ self,+ key: str,+ since: str | None = None,+ max_count: int = 100,+ ) -> list[tuple[str, dict]]:+ return []++ async def log_trim(+ self,+ key: str,+ before_id: str | None = None,+ ) -> None:+ return None++ # Mode D — pub/sub+ async def publish(self, key: str, payload: dict) -> None:+ await self._channel(key).put(payload)++ async def subscribe(+ self,+ key: str,+ *,+ on_ready: Callable[[], None] | None = None,+ ) -> AsyncGenerator[dict, None]:+ if on_ready is not None:+ on_ready()+ while True:+ yield await self._channel(key).get()++ # Mode E — lock+ @asynccontextmanager+ async def acquire_lock(+ self,+ key: str,+ *,+ ttl_secs: int = 600,+ ) -> AsyncGenerator[None, None]:+ self._locks.add(key)+ try:+ yield+ finally:+ self._locks.discard(key)++ async def is_locked(self, key: str) -> bool:+ return key in self._locks+++class _FakeChatService:+ """Records calls to :meth:`run` so tests can assert dispatch."""++ def __init__(self) -> None:+ self.calls: list[dict] = []+ self.notify = asyncio.Event()++ async def run(+ self,+ user_id: str,+ session_id: str,+ agent_id: str,+ input_msg: Any = None,+ ) -> None:+ """Record the call and signal a waiter."""+ self.calls.append(+ {+ "user_id": user_id,+ "session_id": session_id,+ "agent_id": agent_id,+ "input_msg": input_msg,+ },+ )+ self.notify.set()+++async def _yield_a_few_times(ticks: int = 8) -> None:+ """Yield the event loop a few times so spawned tasks make progress."""+ for _ in range(ticks):+ await asyncio.sleep(0)+++class TestWakeupDispatcherDispatch(IsolatedAsyncioTestCase):+ """Verifies the signal-driven dispatch path."""++ async def test_signal_drives_dispatch(self) -> None:+ """A wake-up signal causes the queue to be drained and each+ entry dispatched as a chat run."""+ bus = _FakeBus()+ chat = _FakeChatService()+ async with WakeupDispatcher(+ message_bus=bus,+ storage=_FakeStorage(),+ chat_service=chat,+ chat_run_registry=ChatRunRegistry(),+ ):+ await bus.queue_push(+ MessageBus._WAKEUP_QUEUE_KEY,+ {"user_id": "u", "session_id": "s1", "agent_id": "a1"},+ )+ await bus.publish(MessageBus._WAKEUP_SIGNAL_KEY, {})++ await asyncio.wait_for(chat.notify.wait(), timeout=2.0)++ self.assertEqual(+ chat.calls,+ [+ {+ "user_id": "u",+ "session_id": "s1",+ "agent_id": "a1",+ "input_msg": None,+ },+ ],+ )++ async def test_initial_drain_picks_up_pending_entries(self) -> None:+ """Entries on the queue from before ``__aenter__`` are picked up+ without waiting for a fresh signal."""+ bus = _FakeBus()+ chat = _FakeChatService()+ await bus.queue_push(+ MessageBus._WAKEUP_QUEUE_KEY,+ {"user_id": "u", "session_id": "pre", "agent_id": "a"},+ )++ async with WakeupDispatcher(+ message_bus=bus,+ storage=_FakeStorage(),+ chat_service=chat,+ chat_run_registry=ChatRunRegistry(),+ ):+ await _yield_a_few_times()++ self.assertEqual(+ chat.calls,+ [+ {+ "user_id": "u",+ "session_id": "pre",+ "agent_id": "a",+ "input_msg": None,+ },+ ],+ )++ async def test_active_session_skipped(self) -> None:+ """If the target session is already running, no chat run is+ spawned for it."""+ bus = _FakeBus()+ chat = _FakeChatService()+ bus._locks.add(MessageBus._SESSION_LOCK_KEY.format(sid="busy"))++ async with WakeupDispatcher(+ message_bus=bus,+ storage=_FakeStorage(),+ chat_service=chat,+ chat_run_registry=ChatRunRegistry(),+ ):+ await bus.queue_push(+ MessageBus._WAKEUP_QUEUE_KEY,+ {"user_id": "u", "session_id": "busy", "agent_id": "a"},+ )+ await bus.publish(MessageBus._WAKEUP_SIGNAL_KEY, {})+ await asyncio.sleep(0.05)++ self.assertEqual(chat.calls, [])++ async def test_malformed_entry_skipped(self) -> None:+ """A wake-up entry missing required fields is logged and skipped,+ not raised; later valid entries still dispatch."""+ bus = _FakeBus()+ chat = _FakeChatService()++ async with WakeupDispatcher(+ message_bus=bus,+ storage=_FakeStorage(),+ chat_service=chat,+ chat_run_registry=ChatRunRegistry(),+ ):+ await bus.queue_push(+ MessageBus._WAKEUP_QUEUE_KEY,+ {"oops": True},+ )+ await bus.queue_push(+ MessageBus._WAKEUP_QUEUE_KEY,+ {"user_id": "u", "session_id": "s2", "agent_id": "a"},+ )+ await bus.publish(MessageBus._WAKEUP_SIGNAL_KEY, {})+ await asyncio.wait_for(chat.notify.wait(), timeout=2.0)++ # Only the valid entry made it through.+ self.assertEqual(+ chat.calls,+ [+ {+ "user_id": "u",+ "session_id": "s2",+ "agent_id": "a",+ "input_msg": None,+ },+ ],+ )++ async def test_deleted_session_skipped(self) -> None:+ """A wake-up whose target session no longer exists in storage+ is dropped without spawning a chat run; later wake-ups for live+ sessions still dispatch."""+ bus = _FakeBus()+ chat = _FakeChatService()+ storage = _FakeStorage()+ storage.missing_session_ids.add("ghost")++ async with WakeupDispatcher(+ message_bus=bus,+ storage=storage,+ chat_service=chat,+ chat_run_registry=ChatRunRegistry(),+ ):+ await bus.queue_push(+ MessageBus._WAKEUP_QUEUE_KEY,+ {"user_id": "u", "session_id": "ghost", "agent_id": "a"},+ )+ await bus.queue_push(+ MessageBus._WAKEUP_QUEUE_KEY,+ {"user_id": "u", "session_id": "live", "agent_id": "a"},+ )+ await bus.publish(MessageBus._WAKEUP_SIGNAL_KEY, {})+ await asyncio.wait_for(chat.notify.wait(), timeout=2.0)++ self.assertEqual(+ chat.calls,+ [+ {+ "user_id": "u",+ "session_id": "live",+ "agent_id": "a",+ "input_msg": None,+ },+ ],+ )+++class TestWakeupDispatcherLifecycle(IsolatedAsyncioTestCase):+ """Tests covering the ``__aenter__`` / ``__aexit__`` ACM behaviour."""++ async def test_exit_cancels_loop_cleanly(self) -> None:+ """``__aexit__`` cancels the dispatcher's loop task and returns+ without re-raising the cancellation."""+ bus = _FakeBus()+ chat = _FakeChatService()+ dispatcher = WakeupDispatcher(+ message_bus=bus,+ storage=_FakeStorage(),+ chat_service=chat,+ chat_run_registry=ChatRunRegistry(),+ )++ # pylint: disable=unnecessary-dunder-call+ await dispatcher.__aenter__()+ loop_task = dispatcher._task+ self.assertIsNotNone(loop_task)++ await dispatcher.__aexit__(None, None, None)++ self.assertIsNone(dispatcher._task)+ self.assertTrue(loop_task.cancelled() or loop_task.done())diff --git a/tests/storage_redis_test.py b/tests/storage_redis_test.pyindex 0aa0c1afb..f7b8b1eb3 100644--- a/tests/storage_redis_test.py+++ b/tests/storage_redis_test.py@@ -8,13 +8,15 @@ import fakeredis.aioredisfrom agentscope.app.storage import (RedisStorage,- RedisKeyConfig,AgentRecord,SessionConfig,+ SessionRecord,ChatModelConfig,ScheduleRecord,ScheduleData,SessionSource,+ TeamData,+ TeamRecord,)from agentscope.credential import OllamaCredentialfrom agentscope.app.storage import AgentData@@ -28,7 +30,7 @@ def make_storage() -> RedisStorage:# pylint: disable=protected-accessstorage._client = fakeredis.aioredis.FakeRedis(decode_responses=True)storage.key_ttl = None- storage.key_config = RedisKeyConfig()+ storage.key_config = RedisStorage.KeyConfig()return storage@@ -617,3 +619,462 @@ class TestScheduleSession(IsolatedAsyncioTestCase):schedule.id,)self.assertEqual(results, [])+++def make_team_record(+ user_id: str,+ session_id: str = "leader-session-1",+ name: str = "test-team",+ member_ids: list[str] | None = None,+) -> TeamRecord:+ """Create a test TeamRecord."""+ return TeamRecord(+ user_id=user_id,+ session_id=session_id,+ data=TeamData(+ name=name,+ member_ids=member_ids if member_ids is not None else [],+ ),+ )+++class TestAgentSource(IsolatedAsyncioTestCase):+ """Tests for the ``source`` field on AgentRecord."""++ async def asyncSetUp(self) -> None:+ """Set up test fixtures."""+ self.storage = make_storage()+ self.user_id = "user-1"++ async def test_default_source_is_user(self) -> None:+ """An AgentRecord built without ``source`` defaults to ``"user"``."""+ record = make_agent_record(self.user_id)+ self.assertEqual(record.source, "user")+ await self.storage.upsert_agent(self.user_id, record)+ loaded = await self.storage.get_agent(self.user_id, record.id)+ self.assertIsNotNone(loaded)+ self.assertEqual(loaded.source, "user")++ async def test_team_source_round_trips(self) -> None:+ """A worker AgentRecord persists ``source='team'`` through Redis."""+ record = AgentRecord(+ user_id=self.user_id,+ source="team",+ data=AgentData(+ id="worker-1",+ name="worker",+ system_prompt="You are a team worker.",+ context_config=ContextConfig(),+ react_config=ReActConfig(),+ ),+ )+ await self.storage.upsert_agent(self.user_id, record)+ loaded = await self.storage.get_agent(self.user_id, record.id)+ self.assertIsNotNone(loaded)+ self.assertEqual(loaded.source, "team")++ async def test_list_agents_filters_out_team_workers(self) -> None:+ """``storage.list_agents`` returns only ``source='user'`` agents.+ Workers (``source='team'``) are scoped to a team and addressable+ only via direct id lookup."""+ user_agent = make_agent_record(self.user_id)+ worker = AgentRecord(+ id="worker-1",+ user_id=self.user_id,+ source="team",+ data=AgentData(+ id="data-w",+ name="worker",+ system_prompt="",+ context_config=ContextConfig(),+ react_config=ReActConfig(),+ ),+ )+ await self.storage.upsert_agent(self.user_id, user_agent)+ await self.storage.upsert_agent(self.user_id, worker)++ listed = await self.storage.list_agents(self.user_id)+ listed_ids = {a.id for a in listed}+ self.assertIn(user_agent.id, listed_ids)+ self.assertNotIn(worker.id, listed_ids)++ # But direct lookup still works for the worker.+ loaded_worker = await self.storage.get_agent(+ self.user_id,+ worker.id,+ )+ self.assertIsNotNone(loaded_worker)+ self.assertEqual(loaded_worker.source, "team")++ async def test_legacy_record_without_source_deserializes(self) -> None:+ """JSON written before the ``source`` field was added still loads+ and falls back to the default ``"user"``."""+ legacy_record = make_agent_record(self.user_id)+ legacy_json = legacy_record.model_dump_json()+ # Strip the new field to simulate pre-migration data.+ import json++ payload = json.loads(legacy_json)+ payload.pop("source", None)+ # pylint: disable=protected-access+ key = self.storage._key(+ self.storage.key_config.agent,+ user_id=self.user_id,+ agent_id=legacy_record.id,+ )+ await self.storage._client.set(key, json.dumps(payload))+ await self.storage._client.sadd(+ self.storage._key(+ self.storage.key_config.agent_index,+ user_id=self.user_id,+ ),+ legacy_record.id,+ )++ loaded = await self.storage.get_agent(self.user_id, legacy_record.id)+ self.assertIsNotNone(loaded)+ self.assertEqual(loaded.source, "user")+++class TestSessionTeamId(IsolatedAsyncioTestCase):+ """Tests for the ``team_id`` field on SessionRecord."""++ async def asyncSetUp(self) -> None:+ """Set up test fixtures."""+ self.storage = make_storage()+ self.user_id = "user-1"+ self.agent_id = "agent-1"++ async def test_default_team_id_is_none(self) -> None:+ """A SessionRecord built without ``team_id`` defaults to ``None``."""+ session = await self.storage.upsert_session(+ self.user_id,+ self.agent_id,+ make_session_config(),+ )+ self.assertIsNone(session.team_id)++ loaded = await self.storage.get_session(+ self.user_id,+ self.agent_id,+ session.id,+ )+ self.assertIsNotNone(loaded)+ self.assertIsNone(loaded.team_id)++ async def test_legacy_session_without_team_id_deserializes(self) -> None:+ """JSON written before ``team_id`` existed still loads with default+ ``None``."""+ session = await self.storage.upsert_session(+ self.user_id,+ self.agent_id,+ make_session_config(),+ )++ # Strip the new field from the persisted JSON to simulate pre-migration+ # data, then write it back at the same key.+ import json++ # pylint: disable=protected-access+ key = self.storage._key(+ self.storage.key_config.session,+ user_id=self.user_id,+ session_id=session.id,+ )+ raw = await self.storage._client.get(key)+ payload = json.loads(raw)+ payload.pop("team_id", None)+ await self.storage._client.set(key, json.dumps(payload))++ loaded = await self.storage.get_session(+ self.user_id,+ self.agent_id,+ session.id,+ )+ self.assertIsNotNone(loaded)+ self.assertIsNone(loaded.team_id)+++class TestTeam(IsolatedAsyncioTestCase):+ """Tests for team CRUD."""++ async def asyncSetUp(self) -> None:+ """Set up test fixtures."""+ self.storage = make_storage()+ self.user_id = "user-1"++ async def test_create(self) -> None:+ """Create a team and verify it is retrievable via list."""+ record = make_team_record(self.user_id)+ stored = await self.storage.upsert_team(self.user_id, record)+ records = await self.storage.list_teams(self.user_id)+ self.assertEqual(len(records), 1)+ self.assertEqual(records[0].id, stored.id)+ self.assertEqual(records[0].session_id, "leader-session-1")+ self.assertEqual(records[0].data.name, "test-team")+ self.assertEqual(records[0].data.member_ids, [])++ async def test_list_empty(self) -> None:+ """Verify list returns empty when no teams exist."""+ records = await self.storage.list_teams(self.user_id)+ self.assertEqual(records, [])++ async def test_get_returns_record(self) -> None:+ """get_team returns the persisted record by id."""+ record = make_team_record(+ self.user_id,+ member_ids=["worker-a", "worker-b"],+ )+ await self.storage.upsert_team(self.user_id, record)+ loaded = await self.storage.get_team(self.user_id, record.id)+ self.assertIsNotNone(loaded)+ self.assertEqual(loaded.id, record.id)+ self.assertEqual(loaded.data.member_ids, ["worker-a", "worker-b"])++ async def test_get_nonexistent_returns_none(self) -> None:+ """get_team returns None when the id does not exist."""+ loaded = await self.storage.get_team(self.user_id, "no-such-id")+ self.assertIsNone(loaded)++ async def test_update_in_place(self) -> None:+ """Upsert with the same id overwrites the existing record."""+ record = make_team_record(self.user_id, name="original")+ await self.storage.upsert_team(self.user_id, record)++ record.data.name = "renamed"+ record.data.member_ids = ["new-worker"]+ await self.storage.upsert_team(self.user_id, record)++ records = await self.storage.list_teams(self.user_id)+ self.assertEqual(len(records), 1)+ self.assertEqual(records[0].data.name, "renamed")+ self.assertEqual(records[0].data.member_ids, ["new-worker"])++ async def test_upsert_refreshes_updated_at(self) -> None:+ """upsert_team bumps ``updated_at`` on each write."""+ record = make_team_record(self.user_id)+ first = await self.storage.upsert_team(self.user_id, record)+ first_updated = first.updated_at++ # Second write must have a strictly non-decreasing updated_at.+ second = await self.storage.upsert_team(self.user_id, record)+ self.assertGreaterEqual(second.updated_at, first_updated)++ async def test_delete(self) -> None:+ """Delete a team and verify it is gone from Redis and the index."""+ record = make_team_record(self.user_id)+ await self.storage.upsert_team(self.user_id, record)++ result = await self.storage.delete_team(self.user_id, record.id)+ self.assertTrue(result)++ loaded = await self.storage.get_team(self.user_id, record.id)+ self.assertIsNone(loaded)+ self.assertEqual(await self.storage.list_teams(self.user_id), [])++ async def test_delete_nonexistent(self) -> None:+ """delete_team returns False for an unknown id."""+ result = await self.storage.delete_team(self.user_id, "no-such-id")+ self.assertFalse(result)++ async def test_user_isolation(self) -> None:+ """Teams from one user are invisible to another."""+ await self.storage.upsert_team(+ "user-A",+ make_team_record("user-A"),+ )+ records = await self.storage.list_teams("user-B")+ self.assertEqual(records, [])+++def make_worker_agent(user_id: str, agent_id: str) -> AgentRecord:+ """Create a source='team' worker AgentRecord."""+ return AgentRecord(+ id=agent_id,+ user_id=user_id,+ source="team",+ data=AgentData(+ id=f"data-{agent_id}",+ name=f"name-{agent_id}",+ system_prompt="worker",+ context_config=ContextConfig(),+ react_config=ReActConfig(),+ ),+ )+++class TestTeamCascade(IsolatedAsyncioTestCase):+ """End-to-end cascade tests for the team relationship graph."""++ async def asyncSetUp(self) -> None:+ """Build a small team fixture: 1 leader user-agent + 2 workers."""+ self.storage = make_storage()+ self.user_id = "user-1"++ # Leader agent (user-created) and its session+ self.leader_agent = make_agent_record(self.user_id)+ await self.storage.upsert_agent(self.user_id, self.leader_agent)+ leader_session = await self.storage.upsert_session(+ self.user_id,+ self.leader_agent.id,+ make_session_config(),+ )+ self.leader_session_id = leader_session.id++ # Two worker agents and their sessions+ self.worker_a = make_worker_agent(self.user_id, "worker-a")+ self.worker_b = make_worker_agent(self.user_id, "worker-b")+ await self.storage.upsert_agent(self.user_id, self.worker_a)+ await self.storage.upsert_agent(self.user_id, self.worker_b)+ worker_a_session = await self.storage.upsert_session(+ self.user_id,+ self.worker_a.id,+ make_session_config(),+ )+ worker_b_session = await self.storage.upsert_session(+ self.user_id,+ self.worker_b.id,+ make_session_config(),+ )+ self.worker_a_session_id = worker_a_session.id+ self.worker_b_session_id = worker_b_session.id++ # The team itself + leader's team_id back-reference+ self.team = make_team_record(+ self.user_id,+ session_id=self.leader_session_id,+ member_ids=[self.worker_a.id, self.worker_b.id],+ )+ await self.storage.upsert_team(self.user_id, self.team)++ # Stamp team_id on every team-participating session+ # pylint: disable=protected-access+ for sid in [+ self.leader_session_id,+ self.worker_a_session_id,+ self.worker_b_session_id,+ ]:+ session_key = self.storage._key(+ self.storage.key_config.session,+ user_id=self.user_id,+ session_id=sid,+ )+ raw = await self.storage._client.get(session_key)+ rec = SessionRecord.model_validate_json(raw)+ rec.team_id = self.team.id+ await self.storage._client.set(session_key, rec.model_dump_json())++ async def test_delete_team_cascades_workers_and_clears_leader(+ self,+ ) -> None:+ """delete_team removes all workers + sessions + clears leader."""+ result = await self.storage.delete_team(self.user_id, self.team.id)+ self.assertTrue(result)++ # Team record gone+ self.assertIsNone(+ await self.storage.get_team(self.user_id, self.team.id),+ )+ # Worker agents gone+ self.assertIsNone(+ await self.storage.get_agent(self.user_id, self.worker_a.id),+ )+ self.assertIsNone(+ await self.storage.get_agent(self.user_id, self.worker_b.id),+ )+ # Worker sessions gone+ self.assertIsNone(+ await self.storage.get_session(+ self.user_id,+ self.worker_a.id,+ self.worker_a_session_id,+ ),+ )+ # Leader session still exists, team_id cleared+ leader = await self.storage.get_session(+ self.user_id,+ self.leader_agent.id,+ self.leader_session_id,+ )+ self.assertIsNotNone(leader)+ self.assertIsNone(leader.team_id)++ async def test_delete_leader_session_dissolves_team(self) -> None:+ """Deleting a leader session auto-dissolves its team."""+ await self.storage.delete_session(+ self.user_id,+ self.leader_agent.id,+ self.leader_session_id,+ )++ # Team gone+ self.assertIsNone(+ await self.storage.get_team(self.user_id, self.team.id),+ )+ # Workers gone+ self.assertIsNone(+ await self.storage.get_agent(self.user_id, self.worker_a.id),+ )+ # Leader agent itself still exists (only the session was deleted)+ self.assertIsNotNone(+ await self.storage.get_agent(self.user_id, self.leader_agent.id),+ )++ async def test_delete_leader_agent_dissolves_all_its_teams(self) -> None:+ """Deleting the leader agent dissolves every team it leads."""+ await self.storage.delete_agent(self.user_id, self.leader_agent.id)++ self.assertIsNone(+ await self.storage.get_team(self.user_id, self.team.id),+ )+ self.assertIsNone(+ await self.storage.get_agent(self.user_id, self.worker_a.id),+ )+ self.assertIsNone(+ await self.storage.get_agent(self.user_id, self.leader_agent.id),+ )++ async def test_direct_delete_worker_agent_scrubs_member_ids(self) -> None:+ """Bypassing delete_team still keeps team.member_ids consistent."""+ await self.storage.delete_agent(self.user_id, self.worker_a.id)++ team = await self.storage.get_team(self.user_id, self.team.id)+ self.assertIsNotNone(team)+ self.assertEqual(team.data.member_ids, [self.worker_b.id])+ # The other worker is untouched+ self.assertIsNotNone(+ await self.storage.get_agent(self.user_id, self.worker_b.id),+ )++ async def test_direct_delete_worker_session_does_not_dissolve_team(+ self,+ ) -> None:+ """Deleting a worker's session leaves the team intact (asymmetric+ with leader-session deletion — there's no FK from session to its+ owning agent)."""+ await self.storage.delete_session(+ self.user_id,+ self.worker_a.id,+ self.worker_a_session_id,+ )++ # Team and worker agent still exist+ self.assertIsNotNone(+ await self.storage.get_team(self.user_id, self.team.id),+ )+ self.assertIsNotNone(+ await self.storage.get_agent(self.user_id, self.worker_a.id),+ )+ # The session is gone though+ self.assertIsNone(+ await self.storage.get_session(+ self.user_id,+ self.worker_a.id,+ self.worker_a_session_id,+ ),+ )++ async def test_delete_team_idempotent_on_nonexistent(self) -> None:+ """delete_team on a missing team returns False without crashing."""+ result = await self.storage.delete_team(self.user_id, "no-such-id")+ self.assertFalse(result)diff --git a/tests/task_tool_test.py b/tests/task_tool_test.pyindex 7366c9e84..3c498cba1 100644--- a/tests/task_tool_test.py+++ b/tests/task_tool_test.py@@ -30,7 +30,7 @@ class TestTaskCreate(IsolatedAsyncioTestCase):expected_result = {"content": [{- "text": f"Task {task_id} created successfully: "+ "text": f"Task (id={task_id}) created successfully: "f"Test Task 1","type": "text","id": AnyString(),@@ -74,7 +74,8 @@ class TestTaskCreate(IsolatedAsyncioTestCase):expected_result1 = {"content": [{- "text": f"Task {task1_id} created successfully: Task 1",+ "text": f"Task (id={task1_id}) created successfully: "+ f"Task 1","type": "text","id": AnyString(),},@@ -96,7 +97,8 @@ class TestTaskCreate(IsolatedAsyncioTestCase):expected_result2 = {"content": [{- "text": f"Task {task2_id} created successfully: Task 2",+ "text": f"Task (id={task2_id}) created successfully: "+ f"Task 2","type": "text","id": AnyString(),},@@ -119,7 +121,8 @@ class TestTaskCreate(IsolatedAsyncioTestCase):expected_result3 = {"content": [{- "text": f"Task {task3_id} created successfully: Task 3",+ "text": f"Task (id={task3_id}) created successfully: "+ f"Task 3","type": "text","id": AnyString(),},@@ -188,7 +191,8 @@ class TestTaskCreate(IsolatedAsyncioTestCase):expected_result = {"content": [{- "text": f"Task {task_id} created successfully: Bug Fix",+ "text": f"Task (id={task_id}) created successfully: "+ f"Bug Fix","type": "text","id": AnyString(),},@@ -267,9 +271,9 @@ class TestTaskList(IsolatedAsyncioTestCase):expected_result = {"content": [{- "text": f"#{task1_id} [pending] Task 1\n"- f"#{task2_id} [pending] Task 2\n"- f"#{task3_id} [pending] Task 3",+ "text": f"{task1_id} [pending] Task 1\n"+ f"{task2_id} [pending] Task 2\n"+ f"{task3_id} [pending] Task 3","type": "text","id": AnyString(),},@@ -314,7 +318,7 @@ class TestTaskGet(IsolatedAsyncioTestCase):expected_result = {"content": [{- "text": f"Task #{task_id}: Test Task\n"+ "text": f"Task (id={task_id}): Test Task\n"f"Status: pending\n"f"Description: This is a test task with details\n"f"Metadata: {{'priority': 'high'}}",@@ -385,7 +389,7 @@ class TestTaskUpdate(IsolatedAsyncioTestCase):expected_result = {"content": [{- "text": f"Update task #{task_id} subject.",+ "text": f"Update task (id={task_id}) subject.","type": "text","id": AnyString(),},@@ -438,7 +442,7 @@ class TestTaskUpdate(IsolatedAsyncioTestCase):expected_result = {"content": [{- "text": f"Update task #{task_id} description.",+ "text": f"Update task (id={task_id}) description.","type": "text","id": AnyString(),},@@ -491,7 +495,7 @@ class TestTaskUpdate(IsolatedAsyncioTestCase):expected_result = {"content": [{- "text": f"Update task #{task_id} status.",+ "text": f"Update task (id={task_id}) status.","type": "text","id": AnyString(),},@@ -534,7 +538,7 @@ class TestTaskUpdate(IsolatedAsyncioTestCase):expected_result = {"content": [{- "text": f"Update task #{task_id} status.\n\n"+ "text": f"Update task (id={task_id}) status.\n\n"f"Task completed. "f"Call TaskList now to find your next available "f"task or see if your work unblocked others.",@@ -576,7 +580,7 @@ class TestTaskUpdate(IsolatedAsyncioTestCase):expected_result = {"content": [{- "text": f"Task {task_to_delete_id} has been deleted.",+ "text": f"Task (id={task_to_delete_id}) has been deleted.","type": "text","id": AnyString(),},@@ -614,7 +618,7 @@ class TestTaskUpdate(IsolatedAsyncioTestCase):expected_result = {"content": [{- "text": f"Update task #{task_id} owner.",+ "text": f"Update task (id={task_id}) owner.","type": "text","id": AnyString(),},@@ -668,7 +672,7 @@ class TestTaskUpdate(IsolatedAsyncioTestCase):expected_result = {"content": [{- "text": f"Update task #{task_id} metadata.",+ "text": f"Update task (id={task_id}) metadata.","type": "text","id": AnyString(),},@@ -732,7 +736,7 @@ class TestTaskUpdate(IsolatedAsyncioTestCase):expected_result = {"content": [{- "text": f"Update task #{task1_id} add_blocks.",+ "text": f"Update task (id={task1_id}) add_blocks.","type": "text","id": AnyString(),},@@ -803,7 +807,7 @@ class TestTaskUpdate(IsolatedAsyncioTestCase):expected_result = {"content": [{- "text": f"Update task #{task2_id} add_blocked_by.",+ "text": f"Update task (id={task2_id}) add_blocked_by.","type": "text","id": AnyString(),},@@ -901,7 +905,7 @@ class TestTaskUpdate(IsolatedAsyncioTestCase):expected_result = {"content": [{- "text": f"Task {task2_id} has been deleted.",+ "text": f"Task (id={task2_id}) has been deleted.","type": "text","id": AnyString(),},@@ -943,7 +947,7 @@ class TestTaskUpdate(IsolatedAsyncioTestCase):"content": [{"text": "TaskNotFoundError: "- "The task nonexistent-id does not exist.",+ "The task (id=nonexistent-id) does not exist.","type": "text","id": AnyString(),},diff --git a/tests/tool_offload_middleware_test.py b/tests/tool_offload_middleware_test.pyindex 593e7065d..1542de632 100644--- a/tests/tool_offload_middleware_test.py+++ b/tests/tool_offload_middleware_test.py@@ -5,14 +5,18 @@ import asyncioimport jsonfrom typing import Anyfrom unittest.async_case import IsolatedAsyncioTestCase+from unittest.mock import MagicMockfrom pydantic import BaseModel-from utils import MockModel+++from utils import AnyString, MockModelfrom agentscope.agent import Agent-from agentscope.app import BackgroundTaskManager, ToolOffloadMiddleware-from agentscope.message import HintBlock, TextBlock, UserMsg, ToolCallBlock-from agentscope.model import ChatResponse+from agentscope.app.message_bus import MessageBus+from agentscope.app.middleware import ToolOffloadMiddleware+from agentscope.app._manager import BackgroundTaskManager+from agentscope.message import TextBlock, ToolCallBlockfrom agentscope.permission import (PermissionContext,PermissionDecision,@@ -173,6 +177,9 @@ class ToolOffloadMiddlewareTest(IsolatedAsyncioTestCase):"""middleware = ToolOffloadMiddleware(bg_manager=self.bg_manager,+ message_bus=MagicMock(spec=MessageBus),+ user_id="u",+ agent_id="a",timeout_secs=timeout_secs,)agent = Agent(@@ -234,9 +241,24 @@ class ToolOffloadMiddlewareTest(IsolatedAsyncioTestCase):# Should yield a synthetic ToolResponse immediatelyresponses = [r for r in results if isinstance(r, ToolResponse)]self.assertEqual(len(responses), 1)+ self.assertDictEqual(+ responses[0].model_dump(),+ {+ "content": [+ {+ "type": "text",+ "text": AnyString(),+ "id": AnyString(),+ },+ ],+ "state": "success",+ "metadata": {},+ "id": "call_slow",+ },+ )text = responses[0].content[0].text # type: ignore[union-attr]self.assertIn("background", text)- self.assertIn("task_id=", text)+ self.assertIn("id=", text)# Background task should be registeredself.assertEqual(len(self.bg_manager.tasks), 1)@@ -245,10 +267,10 @@ class ToolOffloadMiddlewareTest(IsolatedAsyncioTestCase):self,) -> None:"""After the background tool finishes, the result is pushed to the- BackgroundTaskManager as a HintBlock."""+ session inbox on the message bus as a serialised HintBlock."""toolkit = Toolkit(tools=[SlowTool()])- agent, _ = self._make_agent(toolkit, timeout_secs=0.05)+ agent, middleware = self._make_agent(toolkit, timeout_secs=0.05)tool_call = ToolCallBlock(id="call_bg",@@ -264,52 +286,63 @@ class ToolOffloadMiddlewareTest(IsolatedAsyncioTestCase):# Wait long enough for the background tool (0.2s) to finishawait asyncio.sleep(0.4)- # The completed result should now be available on the manager- pending = self.bg_manager.pop_results(agent.state.session_id)- self.assertEqual(len(pending), 1)- self.assertIsInstance(pending[0], HintBlock)- hint_text = pending[0].hint+ # The completed result should now have been pushed to the message bus+ # inbox as a model-dumped HintBlock.+ mock_bus = middleware._message_bus+ mock_bus.inbox_push.assert_called_once()+ session_id_called, hint_dict = mock_bus.inbox_push.call_args.args+ self.assertEqual(session_id_called, agent.state.session_id)+ self.maxDiff = None+ self.assertDictEqual(+ hint_dict,+ {+ "type": "hint",+ "id": AnyString(),+ "source": '{"label": "tool_output", "sublabel": "slow_tool · '+ 'call_bg"}',+ "hint": [+ {+ "type": "text",+ "text": AnyString(),+ "id": AnyString(),+ },+ ],+ },+ )+ hint_text = hint_dict["hint"][0]["text"]self.assertIn("SlowTool finished", hint_text)self.assertIn("<system-notification>", hint_text)- async def test_on_reasoning_injects_pending_messages(self) -> None:- """on_reasoning hook injects pending HintBlocks into the agent- context as part of an assistant message."""- session_id = "session_test_inject"-- self.mock_model.set_responses(- [- ChatResponse(- content=[TextBlock(text="ok")],- is_last=True,- ),- ],- )+ async def test_background_task_triggers_wakeup_on_completion(+ self,+ ) -> None:+ """After a background tool finishes, a wakeup is enqueued on the+ message bus so that an idle session can be restarted automatically."""- toolkit = Toolkit()- agent, _ = self._make_agent(toolkit, timeout_secs=5.0)+ toolkit = Toolkit(tools=[SlowTool()])+ agent, middleware = self._make_agent(toolkit, timeout_secs=0.05)- # Override the agent's session_id and pre-populate a pending hint- # for that session on the manager.- agent.state.session_id = session_id- self.bg_manager.push_result(- session_id,- HintBlock(hint="Background result: done"),+ tool_call = ToolCallBlock(+ id="call_wakeup",+ name="slow_tool",+ input=json.dumps({"delay": 0.2}),)- await agent.reply(UserMsg("user", "anything"))-- # Context should contain a HintBlock (injected before reasoning) on- # an assistant message authored by this agent.- injected_hints = [- block.hint- for m in agent.state.context- if m.role == "assistant" and m.name == agent.name- for block in m.content- if isinstance(block, HintBlock)- ]- self.assertTrue(- any("Background result" in t for t in injected_hints),+ # Trigger offload+ # pylint: disable=protected-access+ async for _ in agent._acting(tool_call):+ pass++ # Wait long enough for the background tool (0.2s) to finish+ await asyncio.sleep(0.4)++ # enqueue_wakeup must be called exactly once with the correct ids so+ # WakeupDispatcher can re-invoke ChatService.run for this session.+ mock_bus = middleware._message_bus+ mock_bus.enqueue_wakeup.assert_called_once_with(+ user_id="u",+ session_id=agent.state.session_id,+ agent_id="a",)async def test_task_stop_cancels_background_task(self) -> None:diff --git a/tests/toolkit_task_test.py b/tests/toolkit_task_test.pyindex 2eb40fa3b..280e67f1f 100644--- a/tests/toolkit_task_test.py+++ b/tests/toolkit_task_test.py@@ -82,7 +82,7 @@ class TestToolkitTaskCreate(_ToolkitTaskTestBase):{"content": [{- "text": f"Task {task_id} created successfully: "+ "text": f"Task (id={task_id}) created successfully: ""Test Task 1","type": "text","id": AnyString(),@@ -127,7 +127,7 @@ class TestToolkitTaskCreate(_ToolkitTaskTestBase):{"content": [{- "text": f"Task {task_1_id} created successfully: "+ "text": f"Task (id={task_1_id}) created successfully: "f"Task 1","type": "text","id": AnyString(),@@ -153,7 +153,7 @@ class TestToolkitTaskCreate(_ToolkitTaskTestBase):{"content": [{- "text": f"Task {task_2_id} created successfully: "+ "text": f"Task (id={task_2_id}) created successfully: "f"Task 2","type": "text","id": AnyString(),@@ -180,7 +180,7 @@ class TestToolkitTaskCreate(_ToolkitTaskTestBase):{"content": [{- "text": f"Task {task_3_id} created successfully: "+ "text": f"Task (id={task_3_id}) created successfully: "f"Task 3","type": "text","id": AnyString(),@@ -252,7 +252,7 @@ class TestToolkitTaskCreate(_ToolkitTaskTestBase):{"content": [{- "text": f"Task {task_id} created successfully: "+ "text": f"Task (id={task_id}) created successfully: "f"Bug Fix","type": "text","id": AnyString(),@@ -355,9 +355,9 @@ class TestToolkitTaskList(_ToolkitTaskTestBase):{"content": [{- "text": f"#{task_1_id} [pending] Task 1\n"- f"#{task_2_id} [pending] Task 2\n"- f"#{task_3_id} [pending] Task 3",+ "text": f"{task_1_id} [pending] Task 1\n"+ f"{task_2_id} [pending] Task 2\n"+ f"{task_3_id} [pending] Task 3","type": "text","id": AnyString(),},@@ -431,11 +431,11 @@ class TestToolkitTaskGet(_ToolkitTaskTestBase):)self.assertDictEqual(- response.model_dump(),+ response.model_dump(mode="json"),{"content": [{- "text": f"Task #{task_id}: Test Task\n"+ "text": f"Task (id={task_id}): Test Task\n""Status: pending\n""Description: This is a test task with details\n""Metadata: {'priority': 'high'}",@@ -521,7 +521,7 @@ class TestToolkitTaskUpdate(_ToolkitTaskTestBase):{"content": [{- "text": f"Update task #{task_id} subject.",+ "text": f"Update task (id={task_id}) subject.","type": "text","id": AnyString(),},@@ -575,7 +575,7 @@ class TestToolkitTaskUpdate(_ToolkitTaskTestBase):{"content": [{- "text": f"Update task #{task_id} description.",+ "text": f"Update task (id={task_id}) description.","type": "text","id": AnyString(),},@@ -628,7 +628,7 @@ class TestToolkitTaskUpdate(_ToolkitTaskTestBase):{"content": [{- "text": f"Update task #{task_id} status.",+ "text": f"Update task (id={task_id}) status.","type": "text","id": AnyString(),},@@ -668,7 +668,7 @@ class TestToolkitTaskUpdate(_ToolkitTaskTestBase):{"content": [{- "text": f"Update task #{task_id} status.\n\n"+ "text": f"Update task (id={task_id}) status.\n\n""Task completed. Call TaskList now to find your ""next available task or see if your work ""unblocked others.",@@ -721,7 +721,8 @@ class TestToolkitTaskUpdate(_ToolkitTaskTestBase):{"content": [{- "text": f"Task {task_to_delete_id} has been deleted.",+ "text": f"Task (id={task_to_delete_id}) has been "+ f"deleted.","type": "text","id": AnyString(),},@@ -774,7 +775,7 @@ class TestToolkitTaskUpdate(_ToolkitTaskTestBase):{"content": [{- "text": f"Update task #{task_id} owner.",+ "text": f"Update task (id={task_id}) owner.","type": "text","id": AnyString(),},@@ -835,7 +836,7 @@ class TestToolkitTaskUpdate(_ToolkitTaskTestBase):{"content": [{- "text": f"Update task #{task_id} metadata.",+ "text": f"Update task (id={task_id}) metadata.","type": "text","id": AnyString(),},@@ -902,7 +903,7 @@ class TestToolkitTaskUpdate(_ToolkitTaskTestBase):{"content": [{- "text": f"Update task #{task_1_id} add_blocks.",+ "text": f"Update task (id={task_1_id}) add_blocks.","type": "text","id": AnyString(),},@@ -976,7 +977,8 @@ class TestToolkitTaskUpdate(_ToolkitTaskTestBase):{"content": [{- "text": f"Update task #{task_2_id} add_blocked_by.",+ "text": f"Update task (id={task_2_id}) "+ f"add_blocked_by.","type": "text","id": AnyString(),},@@ -1116,7 +1118,7 @@ class TestToolkitTaskUpdate(_ToolkitTaskTestBase):{"content": [{- "text": f"Task {task_2_id} has been deleted.",+ "text": f"Task (id={task_2_id}) has been deleted.","type": "text","id": AnyString(),},@@ -1172,7 +1174,7 @@ class TestToolkitTaskUpdate(_ToolkitTaskTestBase):"content": [{"text": "TaskNotFoundError: "- "The task nonexistent-id does not exist.",+ "The task (id=nonexistent-id) does not exist.","type": "text","id": AnyString(),},