Skip to content

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

feat(console): add terminal console for trying and debugging agents (#2297)

DavdGao8f24009a285f
diff --git a/README.md b/README.md
index 0d0bda538..12cea1c62 100644
--- a/README.md
+++ b/README.md
@@ -73,6 +73,7 @@ rather than constraining them with strict prompts and opinionated orchestrations
## News
<!-- BEGIN NEWS -->
+- **[2026-08] `FEAT`:** Console supported — test and debug agents in the terminal. [Example](https://github.com/agentscope-ai/agentscope/tree/main/examples/console) | [Docs](https://docs.agentscope.io/latest/en/building-blocks/console)
- **[2026-08] `INTE`:** Feishu (Lark) and Discord channels supported. [Feishu](https://docs.agentscope.io/latest/en/deploy/channel/feishu) | [Discord](https://docs.agentscope.io/latest/en/deploy/channel/discord)
- **[2026-08] `FEAT`:** Channels supported — connect agents to IM platforms in agent service. [Example](https://github.com/agentscope-ai/agentscope/tree/main/examples/agent_service) | [Docs](https://docs.agentscope.io/latest/en/deploy/channel/overview)
- **[2026-08] `INTE`:** GitHub MCP Registry and ClawHub supported as built-in hubs. [Example](https://github.com/agentscope-ai/agentscope/tree/main/examples/agent_service) | [Docs](https://docs.agentscope.io/latest/en/deploy/hub)
@@ -82,7 +83,6 @@ rather than constraining them with strict prompts and opinionated orchestrations
- **[2026-07] `INTE`:** ReMe long-term memory supported. [Example](https://github.com/agentscope-ai/agentscope/tree/main/examples/long_term_memory/reme) | [Docs](https://docs.agentscope.io/latest/en/building-blocks/long-term-memory)
- **[2026-06] `FEAT`:** Agentic Memory supported. [Example](https://github.com/agentscope-ai/agentscope/tree/main/examples/long_term_memory/agentic_memory) | [Docs](https://docs.agentscope.io/latest/en/building-blocks/long-term-memory)
- **[2026-06] `FEAT`:** Distributed & Multi-Tenancy & Multi-Session RAG service supported. [Docs](https://docs.agentscope.io/latest/en/deploy/agent-team)
-- **[2026-06] `FEAT`:** RAG supported. [Example](https://github.com/agentscope-ai/agentscope/tree/main/examples/rag) | [Docs](https://docs.agentscope.io/latest/en/building-blocks/rag)
<!-- END NEWS -->
[More news →](./docs/NEWS.md)
@@ -135,15 +135,14 @@ The SDK layer — compose an agent from a rich set of building blocks:
| [**Memory**](https://docs.agentscope.io/latest/en/building-blocks/long-term-memory) | Agentic memory with switchable backends (ReMe, Mem0) |
| [**Workspace / Sandbox**](https://docs.agentscope.io/latest/en/building-blocks/workspace/overview) | Isolated tool & code execution — local, Docker, Apple Container, Bubblewrap, E2B, OpenSandbox, Daytona, K8s |
-Start your first agent with AgentScope 2.0:
+Start your first agent with AgentScope 2.0 in console:
```python
from agentscope.agent import Agent
+from agentscope.console import launch_console
from agentscope.tool import Toolkit, Bash, Grep, Glob, Read, Write, Edit
from agentscope.credential import DashScopeCredential
from agentscope.model import DashScopeChatModel
-from agentscope.message import UserMsg
-from agentscope.event import EventType
import os, asyncio
@@ -170,21 +169,9 @@ async def main() -> None:
),
)
- async for evt in agent.reply_stream(UserMsg("Tony", "Hi, Friday!")):
- # Handle the event stream, e.g., print the message, update UI, etc.
- match evt.type:
- case EventType.REPLY_START:
- ...
- case EventType.MODEL_CALL_START:
- ...
- case EventType.TEXT_BLOCK_START:
- ...
- case EventType.TEXT_BLOCK_DELTA:
- ...
- case EventType.TEXT_BLOCK_END:
- ...
-
- # Handle other event types
+ # Chat with the agent in the terminal — streamed output, tool-call
+ # confirmation and Ctrl+C interruption are all handled for you
+ await launch_console(agent)
asyncio.run(main())
```
diff --git a/README_zh.md b/README_zh.md
index f15d9e58a..4d4cd1a40 100644
--- a/README_zh.md
+++ b/README_zh.md
@@ -72,6 +72,7 @@ AgentScope 的目标是充分发挥大模型的推理与工具调用能力,
## 新闻
<!-- BEGIN NEWS -->
+- **[2026-08] `功能`:** 支持 Console —— 在终端中测试与调试智能体。[样例](https://github.com/agentscope-ai/agentscope/tree/main/examples/console) | [文档](https://docs.agentscope.io/latest/zh/building-blocks/console)
- **[2026-08] `集成`:** 支持飞书(Lark)与 Discord 频道。[飞书](https://docs.agentscope.io/latest/zh/deploy/channel/feishu) | [Discord](https://docs.agentscope.io/latest/zh/deploy/channel/discord)
- **[2026-08] `功能`:** 支持消息频道 —— 将智能体接入即时通讯平台。[样例](https://github.com/agentscope-ai/agentscope/tree/main/examples/agent_service) | [文档](https://docs.agentscope.io/latest/zh/deploy/channel/overview)
- **[2026-08] `集成`:** 内置集成 GitHub MCP Registry 与 ClawHub。[样例](https://github.com/agentscope-ai/agentscope/tree/main/examples/agent_service) | [文档](https://docs.agentscope.io/latest/zh/deploy/hub)
@@ -81,7 +82,6 @@ AgentScope 的目标是充分发挥大模型的推理与工具调用能力,
- **[2026-07] `集成`:** 集成 ReMe 长期记忆。 [样例](https://github.com/agentscope-ai/agentscope/tree/main/examples/long_term_memory/reme) | [文档](https://docs.agentscope.io/latest/zh/building-blocks/long-term-memory)
- **[2026-06] `功能`:** 支持 Agentic Memory。 [样例](https://github.com/agentscope-ai/agentscope/tree/main/examples/long_term_memory/agentic_memory) | [文档](https://docs.agentscope.io/latest/zh/building-blocks/long-term-memory)
- **[2026-06] `功能`:** 支持分布式 & 多租户 & 多会话 RAG 服务。 [文档](https://docs.agentscope.io/latest/en/deploy/agent-team)
-- **[2026-06] `功能`:** 支持多模态 RAG。 [样例](https://github.com/agentscope-ai/agentscope/tree/main/examples/rag) | [文档](https://docs.agentscope.io/latest/en/building-blocks/rag)
<!-- END NEWS -->
[更多新闻 →](./docs/NEWS_zh.md)
@@ -135,15 +135,14 @@ SDK 层 —— 用一整套丰富的构建模块组合出你的智能体:
| [**记忆**](https://docs.agentscope.io/latest/zh/building-blocks/long-term-memory) | Agentic Memory,可切换后端(ReMe、Mem0) |
| [**工作空间 / 沙箱**](https://docs.agentscope.io/latest/zh/building-blocks/workspace/overview) | 隔离工具与代码执行 —— local、Docker、Apple Container、Bubblewrap、E2B、OpenSandbox、Daytona、K8s |
-使用 AgentScope 2.0,启动你的第一个智能体:
+使用 AgentScope 2.0,在终端中启动你的第一个智能体:
```python
from agentscope.agent import Agent
+from agentscope.console import launch_console
from agentscope.tool import Toolkit, Bash, Grep, Glob, Read, Write, Edit
from agentscope.credential import DashScopeCredential
from agentscope.model import DashScopeChatModel
-from agentscope.message import UserMsg
-from agentscope.event import EventType
import os, asyncio
@@ -170,21 +169,9 @@ async def main() -> None:
),
)
- async for evt in agent.reply_stream(UserMsg("Tony", "Hi, Friday!")):
- # 处理事件流,例如打印消息、更新 UI 等
- match evt.type:
- case EventType.REPLY_START:
- ...
- case EventType.MODEL_CALL_START:
- ...
- case EventType.TEXT_BLOCK_START:
- ...
- case EventType.TEXT_BLOCK_DELTA:
- ...
- case EventType.TEXT_BLOCK_END:
- ...
-
- # 处理其他事件类型
+ # 在终端中与智能体对话 —— 流式输出、工具调用确认、
+ # Ctrl+C 中断均已内置处理
+ await launch_console(agent)
asyncio.run(main())
```
diff --git a/docs/NEWS.md b/docs/NEWS.md
index 765456fbd..015522270 100644
--- a/docs/NEWS.md
+++ b/docs/NEWS.md
@@ -2,6 +2,7 @@
<!-- The first 10 items are automatically synced to README.md and README_zh.md via GitHub Actions. -->
<!-- To update news in READMEs, modify this file and push to trigger the workflow. -->
+- **[2026-08] `FEAT`:** Console supported — test and debug agents in the terminal. [Example](https://github.com/agentscope-ai/agentscope/tree/main/examples/console) | [Docs](https://docs.agentscope.io/latest/en/building-blocks/console)
- **[2026-08] `INTE`:** Feishu (Lark) and Discord channels supported. [Feishu](https://docs.agentscope.io/latest/en/deploy/channel/feishu) | [Discord](https://docs.agentscope.io/latest/en/deploy/channel/discord)
- **[2026-08] `FEAT`:** Channels supported — connect agents to IM platforms in agent service. [Example](https://github.com/agentscope-ai/agentscope/tree/main/examples/agent_service) | [Docs](https://docs.agentscope.io/latest/en/deploy/channel/overview)
- **[2026-08] `INTE`:** GitHub MCP Registry and ClawHub supported as built-in hubs. [Example](https://github.com/agentscope-ai/agentscope/tree/main/examples/agent_service) | [Docs](https://docs.agentscope.io/latest/en/deploy/hub)
diff --git a/docs/NEWS_zh.md b/docs/NEWS_zh.md
index b654872a3..c4078c52f 100644
--- a/docs/NEWS_zh.md
+++ b/docs/NEWS_zh.md
@@ -2,6 +2,7 @@
<!-- The first 10 items are automatically synced to README.md and README_zh.md via GitHub Actions. -->
<!-- To update news in READMEs, modify this file and push to trigger the workflow. -->
+- **[2026-08] `功能`:** 支持 Console —— 在终端中测试与调试智能体。[样例](https://github.com/agentscope-ai/agentscope/tree/main/examples/console) | [文档](https://docs.agentscope.io/latest/zh/building-blocks/console)
- **[2026-08] `集成`:** 支持飞书(Lark)与 Discord 频道。[飞书](https://docs.agentscope.io/latest/zh/deploy/channel/feishu) | [Discord](https://docs.agentscope.io/latest/zh/deploy/channel/discord)
- **[2026-08] `功能`:** 支持消息频道 —— 将智能体接入即时通讯平台。[样例](https://github.com/agentscope-ai/agentscope/tree/main/examples/agent_service) | [文档](https://docs.agentscope.io/latest/zh/deploy/channel/overview)
- **[2026-08] `集成`:** 内置集成 GitHub MCP Registry 与 ClawHub。[样例](https://github.com/agentscope-ai/agentscope/tree/main/examples/agent_service) | [文档](https://docs.agentscope.io/latest/zh/deploy/hub)
diff --git a/examples/console/README.md b/examples/console/README.md
new file mode 100644
index 000000000..f5b65e625
--- /dev/null
+++ b/examples/console/README.md
@@ -0,0 +1,61 @@
+# Terminal Console
+
+This example demonstrates the `agentscope.console` module: trying and
+debugging an agent directly in the terminal, without launching the web
+service or writing any UI code.
+
+## What the demo shows
+
+`main.py` assembles a full-featured agent and hands it to
+`launch_console`:
+
+- **Model**: `DashScopeChatModel` (default `qwen3.7-max`), streaming.
+- **Workspace**: a `LocalWorkspace` rooted at `./workspace`. The
+ builtin filesystem tools (Bash/Edit/Glob/Grep/Read/Write) and the
+ agent skills both come from the workspace, bound to its backend and
+ skill partition.
+- **Long-term memory**: `AgenticMemoryMiddleware` persists durable
+ facts as Markdown files under the workspace directory, surviving
+ across runs.
+- **Interaction** (all handled by `launch_console`):
+ - streamed rendering of text, thinking, tool calls/results, hint
+ blocks and token usage;
+ - tool-call confirmation — `y` allows once, `a` also accepts the
+ suggested permission rules so matching calls won't ask again;
+ - Ctrl+C interrupts the current reply; `exit`/`quit`/Ctrl+D leaves.
+
+## Quickstart
+
+```bash
+export DASHSCOPE_API_KEY=sk-...
+python main.py # interactive chat
+python main.py --verbosity debug # plus lifecycle events
+python main.py --verbosity quiet # only the reply text
+```
+
+Things worth trying:
+
+- `List the python files in this directory` — read-only tools run
+ without confirmation.
+- `Create a note.md summarizing our conversation` — `Write` asks for
+ confirmation; answer `a` and watch follow-up writes skip the prompt.
+- `Please remember that I prefer concise Chinese answers` — the memory
+ middleware persists it under `workspace/`; restart the demo and ask
+ `What do you remember about me?`.
+
+## Embedding the renderer in your own code
+
+For agent pipelines or scripts where you own the loop, use the passive
+`ConsoleRenderer` instead of `launch_console`:
+
+```python
+from agentscope.console import ConsoleRenderer
+
+renderer = ConsoleRenderer()
+async for event in agent.reply_stream(msg):
+ renderer.render(event)
+final_msg = renderer.last_msg
+```
+
+Inputs, tool-call confirmation and interruption are then the caller's
+responsibility — the renderer only prints.
diff --git a/examples/console/main.py b/examples/console/main.py
new file mode 100644
index 000000000..c34bafa56
--- /dev/null
+++ b/examples/console/main.py
@@ -0,0 +1,88 @@
+# -*- coding: utf-8 -*-
+"""Try a full-featured agent in the terminal via ``launch_console``.
+
+The agent is backed by ``DashScopeChatModel`` and assembled from a
+``LocalWorkspace``: the builtin filesystem tools and the agent skills
+both come from the workspace, and the filesystem-backed long-term
+memory (``AgenticMemoryMiddleware``) persists durable facts under the
+workspace directory across runs. The whole terminal interaction —
+rendering, tool-call confirmation, Ctrl+C interruption — is handled
+by ``launch_console``. Run with::
+
+ export DASHSCOPE_API_KEY=sk-...
+ python main.py [--model qwen3.7-max] [--verbosity default] \
+ [--workdir ./workspace]
+"""
+import argparse
+import asyncio
+import os
+
+from agentscope.agent import Agent
+from agentscope.console import launch_console
+from agentscope.credential import DashScopeCredential
+from agentscope.middleware import AgenticMemoryMiddleware
+from agentscope.model import DashScopeChatModel
+from agentscope.tool import Toolkit
+from agentscope.workspace import LocalWorkspace
+
+
+async def main() -> None:
+ """The main entry point of the demo."""
+ parser = argparse.ArgumentParser(description=__doc__)
+ parser.add_argument("--model", default="qwen3.7-max")
+ parser.add_argument(
+ "--verbosity",
+ choices=["quiet", "default", "debug"],
+ default="default",
+ )
+ parser.add_argument(
+ "--workdir",
+ default=os.path.join(
+ os.path.dirname(os.path.abspath(__file__)),
+ "workspace",
+ ),
+ help="The workspace root directory.",
+ )
+ args = parser.parse_args()
+
+ api_key = os.environ.get("DASHSCOPE_API_KEY")
+ if not api_key:
+ raise RuntimeError(
+ "Set the DASHSCOPE_API_KEY environment variable before "
+ "running this demo.",
+ )
+
+ async with LocalWorkspace(workdir=args.workdir) as workspace:
+ agent = Agent(
+ name="Friday",
+ system_prompt=(
+ "You are a helpful assistant named Friday. Use the "
+ "provided tools whenever they help answering the "
+ "question.\n\n" + await workspace.get_instructions()
+ ),
+ model=DashScopeChatModel(
+ credential=DashScopeCredential(api_key=api_key),
+ model=args.model,
+ stream=True,
+ ),
+ toolkit=Toolkit(
+ # Filesystem tools and skills both come from the
+ # workspace, bound to its backend and skill partition
+ tools=await workspace.list_tools(),
+ skills_or_loaders=await workspace.list_skills(),
+ ),
+ middlewares=[
+ AgenticMemoryMiddleware(
+ workdir=workspace.workdir,
+ backend=workspace.get_backend(),
+ ),
+ ],
+ # Offload compressed context and oversized tool results
+ # into the workspace
+ offloader=workspace,
+ )
+ await launch_console(agent, verbosity=args.verbosity)
+
+
+if __name__ == "__main__":
+ asyncio.run(main())
diff --git a/pyproject.toml b/pyproject.toml
index d5cdd4279..8ca629b40 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -36,6 +36,7 @@ dependencies = [
"opentelemetry-exporter-otlp>=1.39.0",
"opentelemetry-semantic-conventions>=0.60b0",
"python-socketio",
+ "rich",
"shortuuid",
"python-frontmatter",
"jinja2",
diff --git a/src/agentscope/console/__init__.py b/src/agentscope/console/__init__.py
new file mode 100644
index 000000000..517664152
--- /dev/null
+++ b/src/agentscope/console/__init__.py
@@ -0,0 +1,20 @@
+# -*- coding: utf-8 -*-
+"""The console module for viewing and trying agents in the terminal.
+
+Two public entries serve two different scenarios:
+
+- :class:`ConsoleRenderer`: a passive event renderer that turns an
+ :class:`~agentscope.event.AgentEvent` stream into line-based terminal
+ output. Embed it in your own code (scripts, agent pipelines, tests)
+ where you own the loop, the inputs and the human-in-the-loop handling.
+- :func:`launch_console`: an interactive chat loop bound to a single
+ agent — input, tool-call confirmation and Ctrl+C interruption
+ included — for trying an agent without writing any UI code.
+"""
+from ._console import launch_console
+from ._renderer import ConsoleRenderer
+
+__all__ = [
+ "ConsoleRenderer",
+ "launch_console",
+]
diff --git a/src/agentscope/console/_console.py b/src/agentscope/console/_console.py
new file mode 100644
index 000000000..da67ffc01
--- /dev/null
+++ b/src/agentscope/console/_console.py
@@ -0,0 +1,165 @@
+# -*- coding: utf-8 -*-
+"""The interactive console entry for trying an agent in the terminal."""
+import asyncio
+import signal
+
+from ._renderer import ConsoleRenderer, Verbosity
+from ..agent import Agent
+from ..event import (
+ ConfirmResult,
+ RequireUserConfirmEvent,
+ UserConfirmResultEvent,
+ UserInterruptEvent,
+)
+from ..message import Msg, UserMsg
+
+
+async def _run_reply(
+ agent: Agent,
+ renderer: ConsoleRenderer,
+ inputs: Msg | UserConfirmResultEvent | UserInterruptEvent,
+) -> RequireUserConfirmEvent | None:
+ """Consume one ``reply_stream`` call, rendering every event.
+
+ Ctrl+C during streaming cancels the reply task; the agent handles the
+ cancellation itself (closing tool calls, emitting interrupted events)
+ as long as ``react_config.interruption_raise_cancelled_error`` keeps
+ its default ``False``.
+
+ Returns:
+ `RequireUserConfirmEvent | None`:
+ The pending confirmation request if the reply parked on
+ human-in-the-loop, otherwise `None`.
+ """
+ pending: RequireUserConfirmEvent | None = None
+
+ async def consume() -> None:
+ nonlocal pending
+ async for event in agent.reply_stream(inputs):
+ renderer.render(event)
+ if isinstance(event, RequireUserConfirmEvent):
+ pending = event
+
+ task = asyncio.ensure_future(consume())
+ loop = asyncio.get_running_loop()
+ try:
+ loop.add_signal_handler(signal.SIGINT, task.cancel)
+ sigint_hooked = True
+ except (NotImplementedError, RuntimeError):
+ # e.g. Windows event loop — fall back to KeyboardInterrupt
+ sigint_hooked = False
+
+ try:
+ await task
+ except asyncio.CancelledError:
+ # Raised when the agent re-raises after the interruption
+ pass
+ finally:
+ if sigint_hooked:
+ loop.remove_signal_handler(signal.SIGINT)
+
+ return pending
+
+
+async def _confirm(
+ pending: RequireUserConfirmEvent,
+) -> UserConfirmResultEvent:
+ """Ask the user to confirm each pending tool call via stdin.
+
+ Answering ``a`` (always) also accepts the suggested permission
+ rules, so matching calls won't ask again within this process.
+ """
+ results = []
+ for tool_call in pending.tool_calls:
+ prompt = f"Allow '{tool_call.name}'? [y]es / [N]o"
+ if tool_call.suggested_rules:
+ prompt += " / [a]lways"
+ answer = (await asyncio.to_thread(input, f"{prompt} ")).strip().lower()
+ always = bool(tool_call.suggested_rules) and answer in (
+ "a",
+ "always",
+ )
+ results.append(
+ ConfirmResult(
+ confirmed=always or answer in ("y", "yes"),
+ tool_call=tool_call,
+ rules=tool_call.suggested_rules if always else None,
+ ),
+ )
+ return UserConfirmResultEvent(
+ reply_id=pending.reply_id,
+ confirm_results=results,
+ )
+
+
+async def launch_console(
+ agent: Agent,
+ user_name: str = "user",
+ verbosity: Verbosity = "default",
+ max_tool_result_lines: int | None = 20,
+) -> None:
+ """Chat with the given agent interactively in the terminal.
+
+ A lightweight try-out/debugging entry — no session management, no
+ persistence: the conversation lives in ``agent.state`` and ends with
+ the process. Reads user messages from stdin, renders every streamed
+ :class:`~agentscope.event.AgentEvent`, asks for tool-call
+ confirmation (y/n) when the agent requires it, and turns Ctrl+C into
+ an interruption of the current reply. Type ``exit``/``quit`` or
+ press Ctrl+D to leave.
+
+ .. code-block:: python
+
+ agent = Agent(name=..., model=..., toolkit=...)
+ await launch_console(agent)
+
+ Args:
+ agent (`Agent`):
+ The agent to interact with.
+ user_name (`str`, defaults to `"user"`):
+ The name attached to the user's input messages, also used
+ as the input prompt.
+ verbosity (`Verbosity`, defaults to `"default"`):
+ - `"quiet"`: only the streamed reply text and errors.
+ - `"default"`: plus thinking, tool calls/results, hint
+ blocks, token usage and human-in-the-loop notices.
+ - `"debug"`: plus lifecycle events and other events that
+ are invisible by default.
+ max_tool_result_lines (`int | None`, defaults to `20`):
+ Truncate the printed tool results to this number of lines.
+ `None` means no truncation.
+ """
+ renderer = ConsoleRenderer(
+ verbosity=verbosity,
+ max_tool_result_lines=max_tool_result_lines,
+ )
+ renderer.console.print(
+ "Chat with the agent. Type 'exit' (or Ctrl+D) to quit.",
+ style="dim",
+ )
+
+ while True:
+ try:
+ query = (
+ await asyncio.to_thread(input, f"\n{user_name}> ")
+ ).strip()
+ except (EOFError, KeyboardInterrupt):
+ break
+ if query in ("exit", "quit"):
+ break
+ if not query:
+ continue
+
+ inputs: Msg | UserConfirmResultEvent | UserInterruptEvent = UserMsg(
+ name=user_name,
+ content=query,
+ )
+ while True:
+ pending = await _run_reply(agent, renderer, inputs)
+ if pending is None:
+ break
+ try:
+ inputs = await _confirm(pending)
+ except (EOFError, KeyboardInterrupt):
+ # Abort the parked reply so the next input starts clean
+ inputs = UserInterruptEvent(reply_id=pending.reply_id)
diff --git a/src/agentscope/console/_renderer.py b/src/agentscope/console/_renderer.py
new file mode 100644
index 000000000..cc2eae1fe
--- /dev/null
+++ b/src/agentscope/console/_renderer.py
@@ -0,0 +1,425 @@
+# -*- coding: utf-8 -*-
+"""Render agent event streams as human-readable terminal output."""
+import json
+from typing import Literal
+
+from rich.console import Console
+from rich.panel import Panel
+from rich.text import Text
+
+from ..event import (
+ AgentEvent,
+ DataBlockEndEvent,
+ ExceedMaxItersEvent,
+ HintBlockEvent,
+ ModelCallEndEvent,
+ ModelCallStartEvent,
+ ReplyEndEvent,
+ ReplyStartEvent,
+ RequireExternalExecutionEvent,
+ RequireUserConfirmEvent,
+ TextBlockDeltaEvent,
+ TextBlockEndEvent,
+ ThinkingBlockDeltaEvent,
+ ThinkingBlockEndEvent,
+ ThinkingBlockStartEvent,
+ ToolCallEndEvent,
+ ToolResultEndEvent,
+)
+from ..message import (
+ AssistantMsg,
+ Base64Source,
+ DataBlock,
+ Msg,
+ TextBlock,
+ ToolCallBlock,
+ ToolResultBlock,
+)
+from ..model import FinishedReason
+from ..types import ReplyFinishedReason
+
+Verbosity = Literal["quiet", "default", "debug"]
+
+_VERBOSITY_LEVELS = {"quiet": 0, "default": 1, "debug": 2}
+
+_RESULT_STATE_STYLES = {
+ "success": ("✓", "green"),
+ "error": ("✗", "red"),
+ "denied": ("⊘", "yellow"),
+ "interrupted": ("⚠", "yellow"),
+ "running": ("…", "dim"),
+}
+
+
+def _human_size(n_bytes: int) -> str:
+ """Format a byte count as a human-readable size."""
+ size = float(n_bytes)
+ for unit in ("B", "KB", "MB"):
+ if size < 1024:
+ return f"{size:.0f}{unit}"
+ size /= 1024
+ return f"{size:.1f}GB"
+
+
+def _format_tool_input(raw: str) -> str:
+ """Pretty-print the raw JSON input of a tool call."""
+ raw = raw.strip()
+ if not raw:
+ return "{}"
+ try:
+ obj = json.loads(raw)
+ except ValueError:
+ return raw
+ compact = json.dumps(obj, ensure_ascii=False)
+ if len(compact) <= 72:
+ return compact
+ return json.dumps(obj, ensure_ascii=False, indent=2)
+
+
+class ConsoleRenderer:
+ """Render :class:`~agentscope.event.AgentEvent` streams as line-based
+ terminal output, so that consuming :meth:`Agent.reply_stream` in the
+ terminal becomes a one-liner:
+
+ .. code-block:: python
+
+ renderer = ConsoleRenderer()
+ async for event in agent.reply_stream(msg):
+ renderer.render(event)
+
+ The renderer prints text/thinking deltas as they arrive, buffers the
+ concurrently-streamed tool calls/results via
+ :meth:`~agentscope.message.Msg.append_event` and prints them as whole
+ blocks on their end events. The accumulated reply message is available
+ at :attr:`last_msg` after (or during) the reply.
+ """
+
+ def __init__(
+ self,
+ verbosity: Verbosity = "default",
+ max_tool_result_lines: int | None = 20,
+ console: Console | None = None,
+ ) -> None:
+ """Initialize the console renderer.
+
+ Args:
+ verbosity (`Verbosity`, defaults to `"default"`):
+ - `"quiet"`: only the streamed reply text and errors.
+ - `"default"`: plus thinking, tool calls/results, hint
+ blocks, token usage and human-in-the-loop notices.
+ - `"debug"`: plus lifecycle events and other events that
+ are invisible by default.
+ max_tool_result_lines (`int | None`, defaults to `20`):
+ Truncate the printed tool results to this number of lines.
+ `None` means no truncation.
+ console (`Console | None`, optional):
+ The rich console to print to. A new one on stdout is
+ created if not provided.
+ """
+ self.verbosity = verbosity
+ self.max_tool_result_lines = max_tool_result_lines
+ self.console = console or Console(highlight=False)
+
+ self._msg: Msg | None = None
+ self._mid_stream = False
+
+ @property
+ def last_msg(self) -> Msg | None:
+ """The reply message accumulated from the rendered events."""
+ return self._msg
+
+ def render(self, event: AgentEvent) -> None:
+ """Render the given agent event to the console.
+
+ Unknown event types are silently skipped (or printed as a dim line
+ under `"debug"` verbosity), so that the renderer keeps working when
+ new event types are introduced.
+
+ Args:
+ event (`AgentEvent`):
+ The event to render.
+ """
+ self._accumulate(event)
+
+ if isinstance(event, ReplyStartEvent):
+ self._render_reply_start(event)
+ elif isinstance(event, ThinkingBlockStartEvent):
+ self._render_thinking_start()
+ elif isinstance(event, ThinkingBlockDeltaEvent):
+ self._stream(event.delta, style="dim")
+ elif isinstance(event, ThinkingBlockEndEvent):
+ if self._show(1):
+ self._break_line()
+ self.console.print()
+ elif isinstance(event, TextBlockDeltaEvent):
+ self._stream(event.delta, quiet_ok=True)
+ elif isinstance(event, TextBlockEndEvent):
+ self._break_line(quiet_ok=True)
+ elif isinstance(event, ToolCallEndEvent):
+ self._render_tool_call(event)
+ elif isinstance(event, ToolResultEndEvent):
+ self._render_tool_result(event)
+ elif isinstance(event, DataBlockEndEvent):
+ self._render_data_block(event)
+ elif isinstance(event, ModelCallStartEvent):
+ self._debug_line(f"model call → {event.model_name}")
+ elif isinstance(event, ModelCallEndEvent):
+ self._render_model_call_end(event)
+ elif isinstance(event, HintBlockEvent):
+ self._render_hint(event)
+ elif isinstance(event, RequireUserConfirmEvent):
+ self._render_hitl(
+ event.tool_calls,
+ "Tool calls awaiting user confirmation:",
+ )
+ elif isinstance(event, RequireExternalExecutionEvent):
+ self._render_hitl(
+ event.tool_calls,
+ "Tool calls awaiting external execution:",
+ )
+ elif isinstance(event, ExceedMaxItersEvent):
+ if self._show(1):
+ self._break_line()
+ self.console.print(
+ "⚠ Exceeded the maximum reasoning-acting iterations.",
+ style="yellow",
+ )
+ elif isinstance(event, ReplyEndEvent):
+ self._render_reply_end(event)
+ else:
+ evt_type = str(getattr(event, "type", type(event).__name__))
+ # Delta events are noise even under debug — their content is
+ # rendered as a whole block on the corresponding end event.
+ if not evt_type.endswith("_DELTA"):
+ self._debug_line(evt_type)
+
+ # ==================================================================
+ # Internal helpers
+ # ==================================================================
+
+ def _accumulate(self, event: AgentEvent) -> None:
+ """Apply the event onto the accumulated reply message."""
+ reply_id = getattr(event, "reply_id", None)
+ if reply_id is None:
+ return
+ if isinstance(event, ReplyStartEvent):
+ self._msg = AssistantMsg(name=event.name, content=[], id=reply_id)
+ elif self._msg is None or self._msg.id != reply_id:
+ # A continuation (e.g. after HITL) without a ReplyStartEvent
+ self._msg = AssistantMsg(name="agent", content=[], id=reply_id)
+ self._msg.append_event(event)
+
+ def _show(self, level: int) -> bool:
+ """Whether the current verbosity covers the given level."""
+ return _VERBOSITY_LEVELS[self.verbosity] >= level
+
+ def _break_line(self, quiet_ok: bool = False) -> None:
+ """Terminate the current streamed line, if any."""
+ if not (quiet_ok or self._show(1)):
+ return
+ if self._mid_stream:
+ self.console.print()
+ self._mid_stream = False
+
+ def _stream(
+ self,
+ delta: str,
+ style: str | None = None,
+ quiet_ok: bool = False,
+ ) -> None:
+ """Print a streamed delta without a trailing newline."""
+ if not (quiet_ok or self._show(1)):
+ return
+ self.console.print(
+ Text(delta, style=style or ""),
+ end="",
+ soft_wrap=True,
+ )
+ self._mid_stream = True
+
+ def _debug_line(self, text: str) -> None:
+ """Print a dim single-line note under debug verbosity."""
+ if self._show(2):
+ self._break_line()
+ self.console.print(Text(f"· {text}", style="dim"))
+
+ def _find_block(self, block_type: str, block_id: str) -> object | None:
+ """Find a block in the accumulated message by type and id."""
+ if self._msg is None:
+ return None
+ for block in self._msg.content:
+ if block.type == block_type and block.id == block_id:
+ return block
+ return None
+
+ # ==================================================================
+ # Per-event renderers
+ # ==================================================================
+
+ def _render_reply_start(self, event: ReplyStartEvent) -> None:
+ if self._show(1):
+ self.console.rule(Text(event.name, style="bold"), style="dim")
+
+ def _render_thinking_start(self) -> None:
+ if self._show(1):
+ self._break_line()
+ self.console.print(Text("✻ Thinking…", style="dim italic"))
+
+ def _render_tool_call(self, event: ToolCallEndEvent) -> None:
+ if not self._show(1):
+ return
+ block = self._find_block("tool_call", event.tool_call_id)
+ if not isinstance(block, ToolCallBlock):
+ return
+ self._break_line()
+ header = Text("→ ", style="cyan")
+ header.append(block.name, style="bold cyan")
+ args = _format_tool_input(block.input)
+ if "\n" in args:
+ self.console.print(header)
+ self.console.print(
+ Text("\n".join(f" {_}" for _ in args.splitlines())),
+ )
+ else:
+ header.append(f" {args}")
+ self.console.print(header)
+
+ def _render_tool_result(self, event: ToolResultEndEvent) -> None:
+ if not self._show(1):
+ return
+ block = self._find_block("tool_result", event.tool_call_id)
+ if not isinstance(block, ToolResultBlock):
+ return
+ icon, style = _RESULT_STATE_STYLES.get(block.state, ("•", ""))
+
+ self._break_line()
+ header = Text(f"{icon} {block.name}", style=style)
+ header.append(f" · {block.state}", style="dim")
+ self.console.print(header)
+
+ text = self._format_result_output(block)
+ lines = text.splitlines() or ([""] if text else [])
+ max_lines = self.max_tool_result_lines
+ truncated = 0
+ if max_lines is not None and len(lines) > max_lines:
+ truncated = len(lines) - max_lines
+ lines = lines[:max_lines]
+ for line in lines:
+ self.console.print(Text(f" {line}", style="dim"), soft_wrap=True)
+ if truncated:
+ self.console.print(
+ Text(f" … (+{truncated} more lines)", style="dim italic"),
+ )
+ if self._show(2) and event.metadata:
+ self.console.print(
+ Text(f" metadata: {event.metadata}", style="dim"),
+ )
+ self.console.print()
+
+ def _format_result_output(self, block: ToolResultBlock) -> str:
+ """Flatten a tool result output into printable text."""
+ if isinstance(block.output, str):
+ return block.output
+ parts = []
+ for sub in block.output:
+ if isinstance(sub, TextBlock):
+ parts.append(sub.text)
+ elif isinstance(sub, DataBlock):
+ parts.append(self._data_placeholder(sub))
+ return "\n".join(parts)
+
+ @staticmethod
+ def _data_placeholder(block: DataBlock) -> str:
+ """A placeholder line for binary data instead of raw base64."""
+ source = block.source
+ if isinstance(source, Base64Source):
+ size = _human_size(len(source.data) * 3 // 4)
+ return f"[data: {source.media_type}, ~{size}]"
+ return f"[data: {source.media_type}, {source.url}]"
+
+ def _render_data_block(self, event: DataBlockEndEvent) -> None:
+ if not self._show(1):
+ return
+ block = self._find_block("data", event.block_id)
+ if isinstance(block, DataBlock):
+ self._break_line()
+ self.console.print(
+ Text(self._data_placeholder(block), style="magenta"),
+ )
+
+ def _render_model_call_end(self, event: ModelCallEndEvent) -> None:
+ if not self._show(1):
+ return
+ note = f"tokens: {event.input_tokens} in / {event.output_tokens} out"
+ if event.finished_reason != FinishedReason.COMPLETED:
+ note += f" · {event.finished_reason}"
+ self._break_line()
+ self.console.print(Text(f"· {note}", style="dim"))
+
+ def _render_hint(self, event: HintBlockEvent) -> None:
+ if not self._show(1):
+ return
+ if isinstance(event.hint, str):
+ text = event.hint
+ else:
+ text = "\n".join(
+ sub.text
+ if isinstance(sub, TextBlock)
+ else self._data_placeholder(sub)
+ for sub in event.hint
+ )
+ self._break_line()
+ source = f" from {event.source}" if event.source else ""
+ self.console.print(
+ Panel(
+ Text(text, style="dim"),
+ title=Text(f"◈ hint{source}", style="yellow"),
+ title_align="left",
+ border_style="dim yellow",
+ expand=False,
+ padding=(0, 1),
+ ),
+ )
+
+ def _render_hitl(
+ self,
+ tool_calls: list[ToolCallBlock],
+ title: str,
+ ) -> None:
+ if not self._show(1):
+ return
+ self._break_line()
+ self.console.print(Text(f"⚠ {title}", style="bold yellow"))
+ for tool_call in tool_calls:
+ line = Text(" • ", style="yellow")
+ line.append(tool_call.name, style="bold yellow")
+ line.append(f" {_format_tool_input(tool_call.input)}")
+ self.console.print(line, soft_wrap=True)
+ for rule in tool_call.suggested_rules:
+ pattern = f"({rule.rule_content})" if rule.rule_content else ""
+ self.console.print(
+ Text(
+ f" suggested rule: {rule.behavior.value} "
+ f"{rule.tool_name}{pattern}",
+ style="dim",
+ ),
+ soft_wrap=True,
+ )
+
+ def _render_reply_end(self, event: ReplyEndEvent) -> None:
+ self._break_line(quiet_ok=True)
+ if event.error is not None:
+ self.console.print(
+ Text(
+ f"✗ Error ({event.error.type}): {event.error.message}",
+ style="bold red",
+ ),
+ )
+ elif (
+ event.finished_reason == ReplyFinishedReason.INTERRUPTED
+ and self._show(1)
+ ):
+ self.console.print(
+ Text("⚠ Reply interrupted by the user.", style="yellow"),
+ )
+ self._debug_line(f"reply end · {event.finished_reason}")
diff --git a/tests/console_renderer_test.py b/tests/console_renderer_test.py
new file mode 100644
index 000000000..69bf84117
--- /dev/null
+++ b/tests/console_renderer_test.py
@@ -0,0 +1,309 @@
+# -*- coding: utf-8 -*-
+"""Console renderer test cases."""
+from io import StringIO
+from unittest import TestCase
+
+from rich.console import Console
+
+from agentscope.console import ConsoleRenderer
+from agentscope.event import (
+ HintBlockEvent,
+ ModelCallEndEvent,
+ ReplyEndEvent,
+ ReplyStartEvent,
+ RequireUserConfirmEvent,
+ TextBlockDeltaEvent,
+ TextBlockEndEvent,
+ TextBlockStartEvent,
+ ThinkingBlockDeltaEvent,
+ ThinkingBlockEndEvent,
+ ThinkingBlockStartEvent,
+ ToolCallDeltaEvent,
+ ToolCallEndEvent,
+ ToolCallStartEvent,
+ ToolResultEndEvent,
+ ToolResultStartEvent,
+ ToolResultTextDeltaEvent,
+)
+from agentscope.message import ToolCallBlock, ToolCallState, ToolResultState
+from agentscope.permission import PermissionBehavior, PermissionRule
+from agentscope.types import ReplyFinishedReason
+
+REPLY_ID = "reply-test"
+
+
+class ConsoleRendererTest(TestCase):
+ """Test cases for the console renderer."""
+
+ def setUp(self) -> None:
+ """Create a renderer that prints into a string buffer."""
+ self.buffer = StringIO()
+ self.renderer = ConsoleRenderer(
+ console=Console(file=self.buffer, width=100, highlight=False),
+ )
+
+ def output(self) -> str:
+ """The rendered terminal output so far."""
+ return self.buffer.getvalue()
+
+ def render_all(self, events: list) -> None:
+ """Render the given events in order."""
+ for event in events:
+ self.renderer.render(event)
+
+ @staticmethod
+ def text_events(text: str, block_id: str = "t1") -> list:
+ """Build start/delta/end events for a streamed text block."""
+ return [
+ TextBlockStartEvent(reply_id=REPLY_ID, block_id=block_id),
+ *[
+ TextBlockDeltaEvent(
+ reply_id=REPLY_ID,
+ block_id=block_id,
+ delta=chunk,
+ )
+ for chunk in (text[:3], text[3:])
+ ],
+ TextBlockEndEvent(reply_id=REPLY_ID, block_id=block_id),
+ ]
+
+ def test_text_streaming(self) -> None:
+ """Text deltas are printed as they arrive."""
+ self.render_all(
+ [
+ ReplyStartEvent(
+ session_id="s",
+ reply_id=REPLY_ID,
+ name="Friday",
+ ),
+ *self.text_events("hello world"),
+ ],
+ )
+ self.assertIn("Friday", self.output())
+ self.assertIn("hello world", self.output())
+
+ def test_quiet_hides_everything_but_text(self) -> None:
+ """Quiet verbosity only prints the streamed reply text."""
+ self.renderer.verbosity = "quiet"
+ self.render_all(
+ [
+ ReplyStartEvent(
+ session_id="s",
+ reply_id=REPLY_ID,
+ name="Friday",
+ ),
+ ThinkingBlockStartEvent(reply_id=REPLY_ID, block_id="th1"),
+ ThinkingBlockDeltaEvent(
+ reply_id=REPLY_ID,
+ block_id="th1",
+ delta="pondering...",
+ ),
+ ThinkingBlockEndEvent(reply_id=REPLY_ID, block_id="th1"),
+ *self.text_events("the answer"),
+ ModelCallEndEvent(
+ reply_id=REPLY_ID,
+ input_tokens=10,
+ output_tokens=5,
+ ),
+ ],
+ )
+ self.assertIn("the answer", self.output())
+ self.assertNotIn("Friday", self.output())
+ self.assertNotIn("pondering", self.output())
+ self.assertNotIn("tokens", self.output())
+
+ def test_thinking_and_usage_in_default(self) -> None:
+ """Default verbosity prints thinking and token usage."""
+ self.render_all(
+ [
+ ThinkingBlockStartEvent(reply_id=REPLY_ID, block_id="th1"),
+ ThinkingBlockDeltaEvent(
+ reply_id=REPLY_ID,
+ block_id="th1",
+ delta="pondering...",
+ ),
+ ThinkingBlockEndEvent(reply_id=REPLY_ID, block_id="th1"),
+ ModelCallEndEvent(
+ reply_id=REPLY_ID,
+ input_tokens=10,
+ output_tokens=5,
+ ),
+ ],
+ )
+ self.assertIn("Thinking", self.output())
+ self.assertIn("pondering...", self.output())
+ self.assertIn("tokens: 10 in / 5 out", self.output())
+
+ def test_tool_call_printed_whole_on_end(self) -> None:
+ """Tool call arguments are buffered and pretty-printed on end."""
+ self.render_all(
+ [
+ ToolCallStartEvent(
+ reply_id=REPLY_ID,
+ tool_call_id="c1",
+ tool_call_name="get_weather",
+ ),
+ ToolCallDeltaEvent(
+ reply_id=REPLY_ID,
+ tool_call_id="c1",
+ delta='{"city": "Hang',
+ ),
+ ToolCallDeltaEvent(
+ reply_id=REPLY_ID,
+ tool_call_id="c1",
+ delta='zhou"}',
+ ),
+ ],
+ )
+ # Nothing printed while the arguments are still streaming
+ self.assertNotIn("get_weather", self.output())
+
+ self.renderer.render(
+ ToolCallEndEvent(reply_id=REPLY_ID, tool_call_id="c1"),
+ )
+ self.assertIn('get_weather {"city": "Hangzhou"}', self.output())
+
+ def test_concurrent_tool_results_do_not_interleave(self) -> None:
+ """Interleaved result deltas are printed as whole blocks."""
+
+ def result_delta(call_id: str, delta: str) -> object:
+ return ToolResultTextDeltaEvent(
+ reply_id=REPLY_ID,
+ tool_call_id=call_id,
+ delta=delta,
+ )
+
+ self.render_all(
+ [
+ ToolResultStartEvent(
+ reply_id=REPLY_ID,
+ tool_call_id="c1",
+ tool_call_name="tool_a",
+ ),
+ ToolResultStartEvent(
+ reply_id=REPLY_ID,
+ tool_call_id="c2",
+ tool_call_name="tool_b",
+ ),
+ # Deltas of the two results interleave
+ result_delta("c1", "AAA-"),
+ result_delta("c2", "BBB-"),
+ result_delta("c1", "aaa"),
+ result_delta("c2", "bbb"),
+ ToolResultEndEvent(
+ reply_id=REPLY_ID,
+ tool_call_id="c1",
+ state=ToolResultState.SUCCESS,
+ ),
+ ToolResultEndEvent(
+ reply_id=REPLY_ID,
+ tool_call_id="c2",
+ state=ToolResultState.ERROR,
+ ),
+ ],
+ )
+ self.assertIn("AAA-aaa", self.output())
+ self.assertIn("BBB-bbb", self.output())
+ self.assertIn("✓ tool_a", self.output())
+ self.assertIn("✗ tool_b", self.output())
+
+ def test_tool_result_truncation(self) -> None:
+ """Long tool results are truncated with a hint line."""
+ self.renderer.max_tool_result_lines = 3
+ self.render_all(
+ [
+ ToolResultStartEvent(
+ reply_id=REPLY_ID,
+ tool_call_id="c1",
+ tool_call_name="Bash",
+ ),
+ ToolResultTextDeltaEvent(
+ reply_id=REPLY_ID,
+ tool_call_id="c1",
+ delta="\n".join(f"line-{i}" for i in range(10)),
+ ),
+ ToolResultEndEvent(
+ reply_id=REPLY_ID,
+ tool_call_id="c1",
+ state=ToolResultState.SUCCESS,
+ ),
+ ],
+ )
+ self.assertIn("line-2", self.output())
+ self.assertNotIn("line-3", self.output())
+ self.assertIn("(+7 more lines)", self.output())
+
+ def test_hint_block_hidden_only_in_quiet(self) -> None:
+ """Hint blocks are shown by default and hidden under quiet."""
+ hint = HintBlockEvent(
+ reply_id=REPLY_ID,
+ block_id="h1",
+ source="runtime_state_injection",
+ hint="<current-time>2026-08-12</current-time>",
+ )
+ self.renderer.verbosity = "quiet"
+ self.renderer.render(hint)
+ self.assertNotIn("current-time", self.output())
+
+ self.renderer.verbosity = "default"
+ self.renderer.render(hint)
+ self.assertIn("hint from runtime_state_injection", self.output())
+ self.assertIn("<current-time>2026-08-12</current-time>", self.output())
+
+ def test_confirm_request_shows_suggested_rules(self) -> None:
+ """The confirmation notice lists tool calls and suggested rules."""
+ self.renderer.render(
+ RequireUserConfirmEvent(
+ reply_id=REPLY_ID,
+ tool_calls=[
+ ToolCallBlock(
+ id="c1",
+ name="Bash",
+ input='{"command": "pip install requests"}',
+ state=ToolCallState.ASKING,
+ suggested_rules=[
+ PermissionRule(
+ tool_name="Bash",
+ rule_content="pip install",
+ behavior=PermissionBehavior.ALLOW,
+ source="session",
+ ),
+ ],
+ ),
+ ],
+ ),
+ )
+ self.assertIn("awaiting user confirmation", self.output())
+ self.assertIn(
+ 'Bash {"command": "pip install requests"}',
+ self.output(),
+ )
+ self.assertIn("suggested rule: allow Bash(pip install)", self.output())
+
+ def test_reply_end_interrupted_and_state_reuse(self) -> None:
+ """Interruption notice is printed and last_msg accumulates."""
+ self.render_all(
+ [
+ ReplyStartEvent(
+ session_id="s",
+ reply_id=REPLY_ID,
+ name="Friday",
+ ),
+ *self.text_events("partial answer"),
+ ReplyEndEvent(
+ session_id="s",
+ reply_id=REPLY_ID,
+ finished_reason=ReplyFinishedReason.INTERRUPTED,
+ ),
+ ],
+ )
+ self.assertIn("interrupted by the user", self.output())
+
+ msg = self.renderer.last_msg
+ assert msg is not None
+ self.assertEqual(msg.id, REPLY_ID)
+ self.assertEqual(msg.get_text_content(), "partial answer")
+ self.assertEqual(
+ msg.finished_reason,
+ ReplyFinishedReason.INTERRUPTED,
+ )