Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions mini_agent/agent.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@
from .logger import AgentLogger
from .schema import Message
from .tools.base import Tool, ToolResult
from .utils import calculate_display_width
from .utils import calculate_display_width, display_assistant_text


# ANSI color codes
Expand Down Expand Up @@ -411,7 +411,7 @@ async def run(self, cancel_event: Optional[asyncio.Event] = None) -> str:
# Print assistant response
if response.content:
print(f"\n{Colors.BOLD}{Colors.BRIGHT_BLUE}🤖 Assistant:{Colors.RESET}")
print(f"{response.content}")
display_assistant_text(response.content)

# Check if task is complete (no tool calls)
if not response.tool_calls:
Expand Down
3 changes: 3 additions & 0 deletions mini_agent/utils/__init__.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
"""Utility modules for Mini-Agent."""

from .markdown_renderer import display_assistant_text, has_markdown
from .terminal_utils import (
calculate_display_width,
pad_to_width,
Expand All @@ -8,6 +9,8 @@

__all__ = [
"calculate_display_width",
"display_assistant_text",
"has_markdown",
"pad_to_width",
"truncate_with_ellipsis",
]
Expand Down
57 changes: 57 additions & 0 deletions mini_agent/utils/markdown_renderer.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
"""Render assistant output in the terminal.

Plain text is printed as-is; text containing Markdown elements (tables,
headings, code fences, lists, etc.) is rendered through ``rich.markdown.Markdown``
for a friendlier display — most notably for Markdown tables.
"""

import re

from rich.console import Console
from rich.markdown import Markdown

# Detection is intentionally high-precision: we would rather print Markdown
# as plain text (harmless) than render non-Markdown through rich (mangles
# content, e.g. ``__init__.py`` bolded or tables drawn where none exist).
# Only structural, unambiguous constructs are detected — no inline emphasis,
# bold or backtick spans, which are too easy to false-positive on
# (``__init__``, ``2 ** 3``, stray backticks...).

# Matches a Markdown table: a header row of |...| cells followed by a
# |---|---| separator row (leading/trailing pipes optional).
_TABLE_RE = re.compile(r"^\s*\|.*\|\s*\n\s*\|?[\s:|-]*-[\s:|-]*\|?", re.MULTILINE)
# Fenced code block (``` or ~~~)
_FENCE_RE = re.compile(r"^ {0,3}(```|~~~)", re.MULTILINE)
# ATX heading (# Title), indented at most 3 spaces like real Markdown —
# deeper indentation is an indented code block or a comment, not a heading
_HEADING_RE = re.compile(r"^ {0,3}#{1,6}\s+\S", re.MULTILINE)
# Unordered/ordered list item
_LIST_RE = re.compile(r"^ {0,3}(?:[-*+]|\d{1,9}[.)])\s+\S", re.MULTILINE)

_rich_console = Console()


def has_markdown(text: str) -> bool:
"""Return True if the text looks like it contains Markdown markup.

Only structural constructs are detected: tables, fenced code blocks,
headings and list items. Inline emphasis, bold and inline code are
deliberately ignored (too easy to false-positive on). Plain prose
(even with ``|`` characters scattered around) stays untouched.
"""
if not text:
return False
return bool(
_TABLE_RE.search(text)
or _FENCE_RE.search(text)
or _HEADING_RE.search(text)
or _LIST_RE.search(text)
)


def display_assistant_text(text: str) -> None:
"""Print assistant output, rendering Markdown through rich when detected."""
if has_markdown(text):
_rich_console.print(Markdown(text))
else:
print(text)
6 changes: 6 additions & 0 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ dependencies = [
"requests>=2.31.0",
"tiktoken>=0.5.0",
"prompt-toolkit>=3.0.0",
"rich>=13.0.0",
"pip>=25.3",
"pipx>=1.8.0",
"anthropic>=0.39.0",
Expand Down Expand Up @@ -62,6 +63,11 @@ disable = [
"arguments-differ", # Allow subclasses to have different parameter signatures
]

# PyPI mirror: Tsinghua TUNA — pinned here so uv.lock URLs stay consistent across all contributors
[[tool.uv.index]]
url = "https://pypi.tuna.tsinghua.edu.cn/simple"
default = true

[dependency-groups]
dev = [
"pytest-asyncio>=1.2.0",
Expand Down
88 changes: 88 additions & 0 deletions tests/test_markdown_renderer.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,88 @@
"""Tests for mini_agent.utils.markdown_renderer.

has_markdown is deliberately high-precision: it must never flag plain text
as Markdown (false positives visibly mangle content through rich rendering),
while missing some Markdown (false negatives) is acceptable — plain text is
printed as-is and still perfectly readable.
"""

import pytest

from mini_agent.utils.markdown_renderer import display_assistant_text, has_markdown


class TestHasMarkdownPositive:
"""Texts that clearly contain Markdown and should be detected."""

def test_table(self):
assert has_markdown("| a | b |\n|---|---|\n| 1 | 2 |")

def test_table_without_delimiting_pipes_missed_ok(self):
# Header row not delimited by pipes — a false negative, acceptable
# by design (plain-text printing is harmless)
assert not has_markdown("a | b\n--- | ---")

def test_fenced_code_block(self):
assert has_markdown("Example:\n\n```python\nprint('hi')\n```")

def test_tilde_fence(self):
assert has_markdown("~~~\ncode\n~~~")

def test_atx_heading(self):
assert has_markdown("## Results")

def test_unordered_list(self):
assert has_markdown("Steps:\n\n- first\n- second")

def test_ordered_list(self):
assert has_markdown("1. first\n2. second")


class TestHasMarkdownNegative:
"""Plain text that must NOT be flagged as Markdown."""

def test_empty(self):
assert not has_markdown("")

def test_plain_prose(self):
assert not has_markdown("Hello, the cost is 5 dollars and the answer is yes.")

def test_dunder_filename(self):
# __init__.py must not be read as bold markup
assert not has_markdown("Please edit mini_agent/utils/__init__.py")

def test_dunder_methods(self):
assert not has_markdown("The __init__ and __call__ methods were updated.")

def test_exponent_operator(self):
# 2 ** 3 must not be read as bold markup
assert not has_markdown("Compute 2 ** 3 ** 2 in Python.")

def test_stray_backticks(self):
assert not has_markdown("Use the ` quote character carefully.")

def test_pipes_in_prose(self):
assert not has_markdown("Either | or / separates the path parts.")

def test_hash_number_sign(self):
# "#1" has no space after the hash — not a heading
assert not has_markdown("This is the #1 choice.")

def test_indented_comment_is_not_heading(self):
# 4+ space indent is an indented code block / comment, not a heading
assert not has_markdown(" # this is a python comment")


class TestDisplayAssistantText:
def test_plain_text_printed_verbatim(self, capsys):
display_assistant_text("Plain __init__.py text")
assert capsys.readouterr().out == "Plain __init__.py text\n"

def test_markdown_rendered_without_exception(self, capsys):
display_assistant_text("| a | b |\n|---|---|\n| 1 | 2 |")
assert capsys.readouterr().out # rich produced some output


@pytest.mark.parametrize("text", ["", "| a | b |\n|---|---|"])
def test_never_raises(text):
display_assistant_text(text)
Loading