Skip to content

armgit / avibe

Public Imported from GitHub
0

Make your computer a home for your AI partner. Avibe is the local-first Agent OS: Vibey, its built-in AI partner, works out of the box, and Claude Code, Codex & OpenCode run unchanged beside it — reach them from your browser, phone, or any chat app.

fix(reply): preserve silent literals in Markdown code (#1104)

Call White829a9ad11292
diff --git a/core/message_dispatcher.py b/core/message_dispatcher.py
index 6bee7634d..037f36444 100644
--- a/core/message_dispatcher.py
+++ b/core/message_dispatcher.py
@@ -1470,7 +1470,14 @@ class ConsolidatedMessageDispatcher:
manager = getattr(self.controller, "session_turns", None)
if manager is not None:
manager.on_terminal_result(context, is_error=is_error)
- text = strip_silent_blocks(text)
+ raw_text = text
+ enhanced = None
+ if canonical_type == "result" and level != "silent":
+ quick_replies_on = getattr(self.controller.config, "reply_enhancements", True)
+ enhanced = process_reply(raw_text, include_quick_replies=quick_replies_on)
+ text = enhanced.visible_text
+ else:
+ text = strip_silent_blocks(raw_text)
# ``level="silent"`` is the explicit visibility control (orthogonal to type):
# the message already settled the dot above (for a terminal result), so here
# we release the SSE waiter and return BEFORE any delivery / persistence /
@@ -1542,11 +1549,8 @@ class ConsolidatedMessageDispatcher:
# quick-reply button block before delivery/streaming, so persisting the
# raw text would surface markup in the inbox preview / chat transcript
# that was never shown. Computed once here and reused for delivery below.
- enhanced = None
persist_text = text
if canonical_type == "result":
- quick_replies_on = getattr(self.controller.config, "reply_enhancements", True)
- enhanced = process_reply(text, include_quick_replies=quick_replies_on)
persist_text = enhanced.text if enhanced.text.strip() else text
if native_output_id and agent_message_exists(target_context, native_output_id):
@@ -1600,7 +1604,7 @@ class ConsolidatedMessageDispatcher:
result_type = "error" if is_error else "result"
if target_context.platform == "avibe":
background_enhanced = process_reply(
- text,
+ raw_text,
include_quick_replies=quick_replies_on,
keep_file_links=True,
)
@@ -1956,7 +1960,7 @@ class ConsolidatedMessageDispatcher:
# render the button group (IM channels render native buttons
# from the same ``enhanced.buttons``).
avibe_enhanced = process_reply(
- text, include_quick_replies=quick_replies_on, keep_file_links=True
+ raw_text, include_quick_replies=quick_replies_on, keep_file_links=True
)
avibe_text = self._fold_footer(avibe_enhanced.text or persist_text, folded_footer)
persisted_output = persist_agent_message(
diff --git a/core/reply_enhancer.py b/core/reply_enhancer.py
index 7aa620fae..9e97c64f9 100644
--- a/core/reply_enhancer.py
+++ b/core/reply_enhancer.py
@@ -19,11 +19,75 @@ import logging
import ntpath
import os
import re
+from bisect import bisect_left
from dataclasses import dataclass, field
from typing import List, Tuple
from urllib.parse import unquote, urlparse
+from markdown_it import MarkdownIt
+from markdown_it.common.html_re import HTML_TAG_RE
+from markdown_it.rules_inline.autolink import AUTOLINK_RE, EMAIL_RE
+from markdown_it.rules_inline.backticks import backtick as _commonmark_backtick
+from markdown_it.rules_inline.state_inline import StateInline
+
logger = logging.getLogger(__name__)
+_BLOCK_MARKDOWN = MarkdownIt("commonmark")
+_INLINE_MARKDOWN = MarkdownIt("commonmark")
+_INLINE_CODE_RANGES_KEY = "avibe_inline_code_ranges"
+_INLINE_ANGLE_RANGES_KEY = "avibe_inline_angle_ranges"
+_INLINE_SILENT_RANGES_KEY = "avibe_inline_silent_ranges"
+
+
+def _track_inline_code(state: StateInline, silent: bool) -> bool:
+ """Record source ranges accepted by the CommonMark backtick rule."""
+ start = state.pos
+ token_count = len(state.tokens)
+ matched = _commonmark_backtick(state, silent)
+ if (
+ matched
+ and not silent
+ and any(token.type == "code_inline" for token in state.tokens[token_count:])
+ ):
+ state.env.setdefault(_INLINE_CODE_RANGES_KEY, []).append(
+ (start, state.pos)
+ )
+ return matched
+
+
+def _skip_inline_angle_token(state: StateInline, silent: bool) -> bool:
+ """Skip a prevalidated raw-HTML or autolink token."""
+ token_end = state.env.get(_INLINE_ANGLE_RANGES_KEY, {}).get(state.pos)
+ if token_end is None or token_end > state.posMax:
+ return False
+ if not silent:
+ state.pending += state.src[state.pos:token_end]
+ state.pos = token_end
+ return True
+
+
+def _skip_silent_control(state: StateInline, silent: bool) -> bool:
+ """Keep real control contents from influencing inline Markdown parsing."""
+ token_end = state.env.get(_INLINE_SILENT_RANGES_KEY, {}).get(state.pos)
+ if token_end is None or token_end > state.posMax:
+ return False
+ if not silent:
+ state.pending += state.src[state.pos:token_end]
+ state.pos = token_end
+ return True
+
+
+_INLINE_MARKDOWN.inline.ruler.disable(["autolink", "html_inline"])
+_INLINE_MARKDOWN.inline.ruler.before(
+ "backticks",
+ "avibe_angle_token",
+ _skip_inline_angle_token,
+)
+_INLINE_MARKDOWN.inline.ruler.before(
+ "avibe_angle_token",
+ "avibe_silent_control",
+ _skip_silent_control,
+)
+_INLINE_MARKDOWN.inline.ruler.at("backticks", _track_inline_code)
# ---------------------------------------------------------------------------
# Data classes
@@ -64,6 +128,7 @@ class EnhancedReply:
"""Result of processing an agent reply through the enhancer."""
text: str # Cleaned message text (file links & button block removed)
+ visible_text: str = "" # Source text after silent controls are removed
files: List[FileLink] = field(default_factory=list)
buttons: List[QuickReplyButton] = field(default_factory=list)
secret_requests: List[SecretRequest] = field(default_factory=list)
@@ -113,17 +178,25 @@ _BUTTON_TOKEN_RE = re.compile(
# may itself contain.)
_PLAIN_LINKS_ONLY_RE = re.compile(r"(?:\s*\[[^\]]+\]\(" + _PLAIN_URL + r"\)\s*)+")
-# Silent output blocks are intentionally simple and model-facing. They are
-# stripped before any reply enhancement parsing so hidden text cannot create
-# file uploads or quick replies.
-_SILENT_BLOCK_RE = re.compile(r"<silent\b[^>]*>.*?</silent\s*>", re.IGNORECASE | re.DOTALL)
-_UNTERMINATED_SILENT_RE = re.compile(r"<silent\b[^>]*>.*\Z", re.IGNORECASE | re.DOTALL)
+# Silent output blocks are intentionally simple and model-facing. Once a real
+# opener is found outside code, its contents are opaque until the closing tag.
+_SILENT_OPEN_PREFIX_RE = re.compile(r"<silent\b", re.IGNORECASE)
+_SILENT_CLOSE_RE = re.compile(r"</silent\s*>", re.IGNORECASE)
+_RAW_HTML_OPEN_TAG_RE = re.compile(
+ r"""<[A-Za-z][A-Za-z0-9-]*"""
+ r"""(?:[ \t\n\f\r]+[A-Za-z_:][A-Za-z0-9_.:-]*"""
+ r"""(?:[ \t\n\f\r]*=[ \t\n\f\r]*"""
+ r"""(?:[^"'=<>`\x00-\x20]+|'[^']*'|"[^"]*"))?)*"""
+ r"""[ \t\n\f\r]*/?>"""
+)
+_RAW_HTML_CLOSE_TAG_RE = re.compile(
+ r"</[A-Za-z][A-Za-z0-9-]*[ \t\n\f\r]*>"
+)
# Dynamic secret-ask markers: ``$<openAiKey>`` (case-preserving shell name). Matched only
# outside fenced/inline code so a marker shown in an example isn't treated as a real
# request — code spans are masked first.
_SECRET_REQUEST_RE = re.compile(r"\$<([A-Za-z_][A-Za-z0-9_]*)>")
-_CODE_SPAN_RE = re.compile(r"```.*?```|~~~.*?~~~|`[^`\n]*`", re.DOTALL)
# ---------------------------------------------------------------------------
@@ -145,15 +218,29 @@ def process_reply(
for inline rendering; IM keeps the default (links stripped to plain labels and
uploaded to the platform separately).
"""
- text = strip_silent_blocks(text)
- secret_requests = _extract_secret_requests(text)
- files = _extract_file_links(text)
- text_no_files = text if keep_file_links else (_strip_file_links(text) if files else text)
+ text, markdown_mask = _strip_silent_blocks_with_mask(text)
+ visible_text = text
+ secret_requests = _extract_secret_requests(text, markdown_mask)
+ files = _extract_file_links(text, markdown_mask)
+ if keep_file_links or not files:
+ text_no_files = text
+ mask_no_files = markdown_mask
+ else:
+ text_no_files, mask_no_files = _strip_file_links_with_mask(
+ text,
+ markdown_mask,
+ )
if include_quick_replies:
- buttons, text_clean = _extract_buttons(text_no_files)
+ buttons, text_clean = _extract_buttons(text_no_files, mask_no_files)
else:
buttons, text_clean = [], text_no_files
- return EnhancedReply(text=text_clean.rstrip(), files=files, buttons=buttons, secret_requests=secret_requests)
+ return EnhancedReply(
+ text=text_clean.rstrip(),
+ visible_text=visible_text,
+ files=files,
+ buttons=buttons,
+ secret_requests=secret_requests,
+ )
def strip_file_links(text: str) -> str:
@@ -165,13 +252,26 @@ def strip_file_links(text: str) -> str:
def strip_silent_blocks(text: str) -> str:
- """Remove all ``<silent>...</silent>`` blocks from agent-visible output."""
+ """Remove silent directives outside Markdown code spans and fences."""
+ return _strip_silent_blocks_with_mask(text)[0]
+
+
+def _strip_silent_blocks_with_mask(text: str) -> Tuple[str, str]:
+ """Remove controls and retain the original Markdown eligibility mask."""
if not text:
- return text
+ return text, text
if "<silent" not in text.lower():
- return text
- stripped = _SILENT_BLOCK_RE.sub("", text)
- return _UNTERMINATED_SILENT_RE.sub("", stripped).strip()
+ return text, _mask_markdown_code(text)
+
+ candidates = _silent_control_candidates(text)
+ ranges, markdown_mask = _silent_control_ranges_and_mask(text, candidates)
+
+ if not ranges:
+ return text, markdown_mask
+
+ cleaned = _remove_ranges(text, ranges)
+ cleaned_mask = _remove_ranges(markdown_mask, ranges)
+ return _trim_blank_boundary_lines_with_mask(cleaned, cleaned_mask)
# ---------------------------------------------------------------------------
@@ -179,10 +279,14 @@ def strip_silent_blocks(text: str) -> str:
# ---------------------------------------------------------------------------
-def _extract_file_links(text: str) -> List[FileLink]:
- """Return all ``FileLink`` instances found in *text*."""
+def _extract_file_links(
+ text: str,
+ markdown_mask: str | None = None,
+) -> List[FileLink]:
+ """Return ``FileLink`` instances found outside Markdown code."""
results: List[FileLink] = []
- for bang, label, url in _FILE_LINK_RE.findall(text):
+ for match in _file_link_matches(text, markdown_mask):
+ bang, label, url = match.groups()
parsed = urlparse(url)
if parsed.scheme != "file":
continue
@@ -208,23 +312,56 @@ def _file_uri_to_local_path(parsed) -> str:
def _strip_file_links(text: str) -> str:
- """Replace ``[label](file://…)`` with just the label."""
-
- def _replacer(m: re.Match) -> str:
- label = m.group(2)
- url = m.group(3)
- if url.startswith("file://"):
- return label # keep the label text, drop the link
- return m.group(0)
-
- return _FILE_LINK_RE.sub(_replacer, text)
-
-
-def _extract_secret_requests(text: str) -> List[SecretRequest]:
+ """Replace file links outside Markdown code with their labels."""
+ return _strip_file_links_with_mask(text, _mask_markdown_code(text))[0]
+
+
+def _strip_file_links_with_mask(text: str, markdown_mask: str) -> Tuple[str, str]:
+ """Replace eligible file links while keeping text and mask aligned."""
+ matches = _file_link_matches(text, markdown_mask)
+ if not matches:
+ return text, markdown_mask
+
+ text_parts: List[str] = []
+ mask_parts: List[str] = []
+ cursor = 0
+ for match in matches:
+ text_parts.append(text[cursor : match.start()])
+ text_parts.append(match.group(2))
+ mask_parts.append(markdown_mask[cursor : match.start()])
+ mask_parts.append(match.group(2))
+ cursor = match.end()
+ text_parts.append(text[cursor:])
+ mask_parts.append(markdown_mask[cursor:])
+ return "".join(text_parts), "".join(mask_parts)
+
+
+def _file_link_matches(
+ text: str,
+ markdown_mask: str | None = None,
+) -> List[re.Match]:
+ """Find eligible link ranges using a mask, then recover original groups."""
+ matches: List[re.Match] = []
+ mask = markdown_mask if markdown_mask is not None else _mask_markdown_code(text)
+ for masked_match in _FILE_LINK_RE.finditer(mask):
+ original_match = _FILE_LINK_RE.fullmatch(
+ text,
+ masked_match.start(),
+ masked_match.end(),
+ )
+ if original_match is not None:
+ matches.append(original_match)
+ return matches
+
+
+def _extract_secret_requests(
+ text: str,
+ markdown_mask: str | None = None,
+) -> List[SecretRequest]:
"""Return ordered, de-duplicated ``$<NAME>`` markers found outside code spans."""
if not text or "$<" not in text:
return []
- masked = _CODE_SPAN_RE.sub(lambda m: " " * len(m.group(0)), text)
+ masked = markdown_mask if markdown_mask is not None else _mask_markdown_code(text)
out: List[SecretRequest] = []
seen: set[str] = set()
for match in _SECRET_REQUEST_RE.finditer(masked):
@@ -235,10 +372,550 @@ def _extract_secret_requests(text: str) -> List[SecretRequest]:
return out
-def _extract_buttons(text: str) -> Tuple[List[QuickReplyButton], str]:
+def _mask_markdown_code(text: str) -> str:
+ """Blank Markdown code regions without changing string offsets."""
+ if not any(marker in text for marker in ("`", "~~~", " ", "\t")):
+ return text
+ ranges, _ = _markdown_code_ranges(text)
+ if not ranges:
+ return text
+
+ return _mask_ranges(text, ranges)
+
+
+def _markdown_code_ranges(
+ text: str,
+) -> Tuple[List[Tuple[int, int]], List[Tuple[int, int]]]:
+ """Return code ranges and block ranges that can suppress later parsing."""
+ if not any(marker in text for marker in ("`", "~~~", " ", "\t")):
+ return [], []
+ block_ranges, inline_source_ranges, blocking_ranges = (
+ _markdown_block_ranges(text)
+ )
+ ranges = sorted(
+ [*block_ranges, *_inline_code_ranges(text, inline_source_ranges)]
+ )
+ return ranges, blocking_ranges
+
+
+def _mask_ranges(text: str, ranges: List[Tuple[int, int]]) -> str:
+ """Blank ranges while preserving newlines and every source offset."""
+
+ parts: List[str] = []
+ cursor = 0
+ for start, end in ranges:
+ if start < cursor:
+ continue
+ parts.append(text[cursor:start])
+ parts.append(re.sub(r"[^\r\n]", " ", text[start:end]))
+ cursor = end
+ parts.append(text[cursor:])
+ return "".join(parts)
+
+
+def _neutralize_ranges(text: str, ranges: List[Tuple[int, int]]) -> str:
+ """Replace ranges with plain text while preserving newlines and offsets."""
+ parts: List[str] = []
+ cursor = 0
+ for start, end in ranges:
+ if start < cursor:
+ continue
+ parts.append(text[cursor:start])
+ parts.append(re.sub(r"[^\r\n]", "x", text[start:end]))
+ cursor = end
+ parts.append(text[cursor:])
+ return "".join(parts)
+
+
+def _silent_control_candidates(text: str) -> List[Tuple[int, int]]:
+ """Return every lexical opener before applying Markdown eligibility."""
+ candidates: List[Tuple[int, int]] = []
+ cursor = 0
+ for prefix in _SILENT_OPEN_PREFIX_RE.finditer(text):
+ if prefix.start() < cursor:
+ continue
+ closing_angle = text.find(">", prefix.end())
+ if closing_angle < 0:
+ break
+ token_end = closing_angle + 1
+ candidates.append((prefix.start(), token_end))
+ cursor = token_end
+ return candidates
+
+
+def _silent_closing_candidates(text: str) -> List[Tuple[int, int]]:
+ """Return every lexical closing tag in source order."""
+ return [match.span() for match in _SILENT_CLOSE_RE.finditer(text)]
+
+
+def _silent_ranges_for_openers(
+ text: str,
+ openers: List[Tuple[int, int]],
+) -> List[Tuple[int, int]]:
+ """Pair confirmed openers while treating each real control as opaque."""
+ ranges: List[Tuple[int, int]] = []
+ closers = _silent_closing_candidates(text)
+ closer_index = 0
+ covered_until = 0
+ for start, opener_end in openers:
+ if start < covered_until:
+ continue
+ while (
+ closer_index < len(closers)
+ and closers[closer_index][0] < opener_end
+ ):
+ closer_index += 1
+ has_closing = closer_index < len(closers)
+ if has_closing:
+ end = closers[closer_index][1]
+ closer_index += 1
+ else:
+ end = len(text)
+ ranges.append((start, end))
+ covered_until = end
+ if not has_closing:
+ break
+ return ranges
+
+
+def _silent_control_ranges_and_mask(
+ text: str,
+ candidates: List[Tuple[int, int]],
+) -> Tuple[List[Tuple[int, int]], str]:
+ """Resolve controls with hidden contents opaque to block Markdown.
+
+ A real control can start an HTML block or contain a fence that suppresses
+ later code parsing. Reparse a same-length source with confirmed controls
+ hidden and uncertain tags neutralized, preserving code delimiters and source
+ offsets. A final batch refinement bounds adversarial unmatched-fence chains.
+ """
+ code_ranges, block_ranges = _markdown_code_ranges(text)
+ controls, _ = _partition_ranges_by_start(candidates, code_ranges)
+ parsed_controls: List[Tuple[int, int]] = []
+
+ for _ in range(2):
+ control_ranges = _silent_ranges_for_openers(text, controls)
+ _, invalid_blocks = _partition_ranges_by_start(
+ block_ranges,
+ control_ranges,
+ )
+ if not invalid_blocks:
+ break
+
+ stable_controls, uncertain_controls = _partition_ranges_by_start(
+ controls,
+ invalid_blocks,
+ )
+ trigger_starts = _container_starts_for_range_starts(
+ control_ranges,
+ invalid_blocks,
+ )
+ confirmed_controls = sorted(
+ [
+ *stable_controls,
+ *(
+ control
+ for control in uncertain_controls
+ if control[0] in trigger_starts
+ ),
+ ]
+ )
+ _, provisional_openers = _partition_ranges_by_start(
+ candidates,
+ invalid_blocks,
+ )
+ _, provisional_closers = _partition_ranges_by_start(
+ _silent_closing_candidates(text),
+ invalid_blocks,
+ )
+ confirmed_ranges = _silent_ranges_for_openers(
+ text,
+ confirmed_controls,
+ )
+ provisional_tags, _ = _partition_ranges_by_start(
+ sorted({*provisional_openers, *provisional_closers}),
+ confirmed_ranges,
+ )
+ opaque_source = _mask_ranges(text, confirmed_ranges)
+ opaque_source = _neutralize_ranges(opaque_source, provisional_tags)
+ code_ranges, block_ranges = _markdown_code_ranges(opaque_source)
+ parsed_controls = confirmed_controls
+ discovered, _ = _partition_ranges_by_start(candidates, code_ranges)
+ controls = sorted({*confirmed_controls, *discovered})
+
+ control_ranges = _silent_ranges_for_openers(text, controls)
+ _, invalid_blocks = _partition_ranges_by_start(
+ block_ranges,
+ control_ranges,
+ )
+ if invalid_blocks:
+ _, provisional_candidates = _partition_ranges_by_start(
+ candidates,
+ invalid_blocks,
+ )
+ provisional = sorted(
+ {
+ *controls,
+ *provisional_candidates,
+ }
+ )
+ provisional_ranges = _silent_ranges_for_openers(text, provisional)
+ opaque_source = _mask_ranges(text, provisional_ranges)
+ code_ranges, _ = _markdown_code_ranges(opaque_source)
+ parsed_controls = provisional
+ discovered, _ = _partition_ranges_by_start(candidates, code_ranges)
+ controls = sorted({*controls, *discovered})
+
+ if parsed_controls and parsed_controls != controls:
+ control_ranges = _silent_ranges_for_openers(text, controls)
+ opaque_source = _mask_ranges(text, control_ranges)
+ code_ranges, _ = _markdown_code_ranges(opaque_source)
+ return _silent_ranges_for_openers(text, controls), _mask_ranges(
+ text,
+ code_ranges,
+ )
+
+
+def _container_starts_for_range_starts(
+ containers: List[Tuple[int, int]],
+ ranges: List[Tuple[int, int]],
+) -> set[int]:
+ """Return starts of sorted containers covering any sorted range start."""
+ starts: set[int] = set()
+ container_index = 0
+ for source_range in ranges:
+ position = source_range[0]
+ while (
+ container_index < len(containers)
+ and containers[container_index][1] <= position
+ ):
+ container_index += 1
+ if (
+ container_index < len(containers)
+ and containers[container_index][0] <= position
+ and position < containers[container_index][1]
+ ):
+ starts.add(containers[container_index][0])
+ return starts
+
+
+def _partition_ranges_by_start(
+ ranges: List[Tuple[int, int]],
+ containers: List[Tuple[int, int]],
+) -> Tuple[List[Tuple[int, int]], List[Tuple[int, int]]]:
+ """Partition start-sorted ranges by start-sorted container membership."""
+ outside: List[Tuple[int, int]] = []
+ inside: List[Tuple[int, int]] = []
+ container_index = 0
+ for source_range in ranges:
+ position = source_range[0]
+ while (
+ container_index < len(containers)
+ and containers[container_index][1] <= position
+ ):
+ container_index += 1
+ if (
+ container_index < len(containers)
+ and containers[container_index][0] <= position
+ and position < containers[container_index][1]
+ ):
+ inside.append(source_range)
+ else:
+ outside.append(source_range)
+ return outside, inside
+
+
+def _remove_ranges(text: str, ranges: List[Tuple[int, int]]) -> str:
+ """Remove sorted, non-overlapping character ranges from *text*."""
+ parts: List[str] = []
+ cursor = 0
+ for start, end in ranges:
+ parts.append(text[cursor:start])
+ cursor = end
+ parts.append(text[cursor:])
+ return "".join(parts)
+
+
+def _trim_blank_boundary_lines_with_mask(text: str, mask: str) -> Tuple[str, str]:
+ """Apply text-derived boundary trimming to an aligned Markdown mask."""
+ lines = text.splitlines(keepends=True)
+ mask_lines = mask.splitlines(keepends=True)
+ start = 0
+ end = len(lines)
+ while start < end and not lines[start].strip(" \t\r\n"):
+ start += 1
+ while end > start and not lines[end - 1].strip(" \t\r\n"):
+ end -= 1
+ cleaned = "".join(lines[start:end]).rstrip("\r\n")
+ cleaned_mask = "".join(mask_lines[start:end])[: len(cleaned)]
+ return cleaned, cleaned_mask
+
+
+def _markdown_block_ranges(
+ text: str,
+) -> Tuple[
+ List[Tuple[int, int]],
+ List[Tuple[int, int, str]],
+ List[Tuple[int, int]],
+]:
+ """Return code, inline-capable, and parser-blocking source ranges."""
+ line_offsets = [0]
+ line_offsets.extend(
+ match.end() for match in re.finditer(r"\r\n|\r|\n", text)
+ )
+ code_ranges: List[Tuple[int, int]] = []
+ inline_ranges: List[Tuple[int, int, str]] = []
+ blocking_ranges: List[Tuple[int, int]] = []
+ for token in _BLOCK_MARKDOWN.parse(text):
+ if token.map is None:
+ continue
+ start_line, end_line = token.map
+ start = line_offsets[start_line]
+ end = line_offsets[end_line] if end_line < len(line_offsets) else len(text)
+ if token.type in {"fence", "code_block"}:
+ code_ranges.append((start, end))
+ blocking_ranges.append((start, end))
+ elif token.type == "html_block":
+ first_line_end = (
+ line_offsets[start_line + 1]
+ if start_line + 1 < len(line_offsets)
+ else len(text)
+ )
+ html_start = text.find("<", start, first_line_end)
+ blocking_ranges.append(
+ (html_start if html_start >= 0 else start, end)
+ )
+ elif token.type == "inline":
+ inline_ranges.append((start, end, token.content))
+ return code_ranges, inline_ranges, blocking_ranges
+
+
+def _inline_code_ranges(
+ text: str,
+ inline_source_ranges: List[Tuple[int, int, str]],
+) -> List[Tuple[int, int]]:
+ """Return inline code spans from CommonMark inline-capable blocks."""
+ ranges: List[Tuple[int, int]] = []
+ for source_start, source_end, content in inline_source_ranges:
+ ranges.extend(
+ _inline_code_ranges_in_block(
+ text,
+ source_start,
+ source_end,
+ content,
+ )
+ )
+ return ranges
+
+
+def _inline_code_ranges_in_block(
+ text: str,
+ start: int,
+ end: int,
+ content: str,
+) -> List[Tuple[int, int]]:
+ """Map CommonMark inline-code ranges back to the original source."""
+ if start >= end or not content:
+ return []
+ env: dict = {
+ _INLINE_ANGLE_RANGES_KEY: dict(_inline_angle_token_ranges(content)),
+ }
+ silent_candidates = _silent_control_candidates(content)
+ env[_INLINE_SILENT_RANGES_KEY] = {
+ start: end
+ for start, end in _silent_ranges_for_openers(
+ content,
+ silent_candidates,
+ )
+ }
+ _INLINE_MARKDOWN.inline.parse(
+ content,
+ _INLINE_MARKDOWN,
+ env,
+ [],
+ )
+ backtick_offsets = _inline_backtick_source_offsets(
+ text,
+ start,
+ end,
+ content,
+ )
+ ranges: List[Tuple[int, int]] = []
+ for range_start, range_end in env.get(_INLINE_CODE_RANGES_KEY, []):
+ source_start = backtick_offsets.get(range_start)
+ source_last = backtick_offsets.get(range_end - 1)
+ if source_start is not None and source_last is not None:
+ ranges.append((source_start, source_last + 1))
+ return ranges
+
+
+def _inline_backtick_source_offsets(
+ text: str,
+ start: int,
+ end: int,
+ content: str,
+) -> dict[int, int]:
+ """Map backticks in container-stripped inline content to source offsets."""
+ source_lines: List[Tuple[int, str]] = []
+ line_start = start
+ for match in re.finditer(r"\r\n|\r|\n", text[start:end]):
+ line_end = start + match.start()
+ source_lines.append((line_start, text[line_start:line_end]))
+ line_start = start + match.end()
+ if line_start <= end:
+ source_lines.append((line_start, text[line_start:end]))
+
+ offsets: dict[int, int] = {}
+ source_index = 0
+ content_offset = 0
+ for content_line in content.split("\n"):
+ if "`" in content_line:
+ for candidate_index in range(source_index, len(source_lines)):
+ absolute_start, source_line = source_lines[candidate_index]
+ normalized_source_line = source_line.replace("\x00", "\ufffd")
+ matched_start = normalized_source_line.find(content_line)
+ relative_start = matched_start if matched_start >= 0 else None
+ if relative_start is None:
+ first_backtick = content_line.find("`")
+ source_backtick = normalized_source_line.find("`")
+ if (
+ source_backtick >= 0
+ and normalized_source_line[source_backtick:].startswith(
+ content_line[first_backtick:]
+ )
+ ):
+ relative_start = source_backtick - first_backtick
+ if relative_start is None:
+ continue
+ for relative_offset, char in enumerate(content_line):
+ if char == "`":
+ offsets[content_offset + relative_offset] = (
+ absolute_start + relative_start + relative_offset
+ )
+ source_index = candidate_index + 1
+ break
+ elif source_index < len(source_lines):
+ source_index += 1
+ content_offset += len(content_line) + 1
+ return offsets
+
+
+def _inline_angle_token_ranges(text: str) -> List[Tuple[int, int]]:
+ """Return raw-HTML and autolink ranges without repeated suffix scans."""
+ ranges: List[Tuple[int, int]] = []
+ terminators = {
+ "-->": _substring_positions(text, "-->"),
+ "?>": _substring_positions(text, "?>"),
+ "]]>": _substring_positions(text, "]]>"),
+ ">": _substring_positions(text, ">"),
+ }
+ cursor = 0
+ while (start := text.find("<", cursor)) >= 0:
+ token_end = _autolink_end(text, start, terminators[">"])
+ if token_end is None:
+ token_end = _raw_html_end(text, start, terminators)
+ if token_end is None:
+ cursor = start + 1
+ continue
+ ranges.append((start, token_end))
+ cursor = token_end
+ return ranges
+
+
+def _substring_positions(text: str, needle: str) -> List[int]:
+ """Return delimiter positions in one forward pass."""
+ positions: List[int] = []
+ cursor = 0
+ while (position := text.find(needle, cursor)) >= 0:
+ positions.append(position)
+ cursor = position + len(needle)
+ return positions
+
+
+def _next_position(positions: List[int], minimum: int) -> int | None:
+ """Return the first indexed delimiter at or after *minimum*."""
+ index = bisect_left(positions, minimum)
+ return positions[index] if index < len(positions) else None
+
+
+def _autolink_end(
+ text: str,
+ start: int,
+ closing_angles: List[int],
+) -> int | None:
+ """Return the end of a valid CommonMark URI or email autolink."""
+ closing = _next_position(closing_angles, start + 1)
+ if closing is None or text.find("<", start + 1, closing) >= 0:
+ return None
+ value = text[start + 1:closing]
+ if AUTOLINK_RE.match(value):
+ normalized = _INLINE_MARKDOWN.normalizeLink(value)
+ elif EMAIL_RE.match(value):
+ normalized = _INLINE_MARKDOWN.normalizeLink("mailto:" + value)
+ else:
+ return None
+ return closing + 1 if _INLINE_MARKDOWN.validateLink(normalized) else None
+
+
+def _raw_html_end(
+ text: str,
+ start: int,
+ terminators: dict[str, List[int]],
+) -> int | None:
+ """Return the end of a valid CommonMark inline raw-HTML token."""
+ tag = _RAW_HTML_OPEN_TAG_RE.match(text, start)
+ closing_tag = _RAW_HTML_CLOSE_TAG_RE.match(text, start)
+ tag_ends = [
+ match.end()
+ for match in (tag, closing_tag)
+ if match is not None
+ ]
+ if tag_ends:
+ return max(tag_ends)
+
+ closer = None
+ if text.startswith("<!-->", start):
+ closer = start + 5
+ elif text.startswith("<!--->", start):
+ closer = start + 6
+ elif text.startswith("<!--", start):
+ position = _next_position(terminators["-->"], start + 4)
+ closer = position + 3 if position is not None else None
+ elif text.startswith("<?", start):
+ position = _next_position(terminators["?>"], start + 2)
+ closer = position + 2 if position is not None else None
+ elif text.startswith("<![CDATA[", start):
+ position = _next_position(terminators["]]>"], start + 9)
+ closer = position + 3 if position is not None else None
+ elif (
+ start + 2 < len(text)
+ and text.startswith("<!", start)
+ and text[start + 2].isalpha()
+ ):
+ position = _next_position(terminators[">"], start + 3)
+ closer = position + 1 if position is not None else None
+
+ if closer is None:
+ return None
+ match = HTML_TAG_RE.match(text[start:closer])
+ return closer if match is not None and match.end() == closer - start else None
+
+
+def _extract_buttons(
+ text: str,
+ markdown_mask: str | None = None,
+) -> Tuple[List[QuickReplyButton], str]:
"""Extract trailing quick-reply buttons and return ``(buttons, cleaned_text)``."""
- m = _BUTTON_BLOCK_RE.search(text)
- if not m:
+ mask = markdown_mask if markdown_mask is not None else _mask_markdown_code(text)
+ masked_match = _BUTTON_BLOCK_RE.search(mask)
+ if masked_match is None:
+ return [], text
+ m = _BUTTON_BLOCK_RE.fullmatch(
+ text,
+ masked_match.start(),
+ masked_match.end(),
+ )
+ if m is None:
return [], text
block = m.group(1)
diff --git a/modules/agents/base.py b/modules/agents/base.py
index 207a13eb7..57856be9b 100644
--- a/modules/agents/base.py
+++ b/modules/agents/base.py
@@ -536,10 +536,10 @@ class BaseAgent(ABC):
# unless there is actual result_text or suffix to deliver.
if not show_duration:
parts = []
- if visible_result and visible_result.strip():
- parts.append(visible_result)
- if visible_suffix:
- parts.append(visible_suffix)
+ if raw_result and raw_result.strip():
+ parts.append(raw_result)
+ if raw_suffix:
+ parts.append(raw_suffix)
if parts:
formatted = "\n".join(parts)
message_id = await self.controller.emit_agent_message(
@@ -583,10 +583,10 @@ class BaseAgent(ABC):
token_field=token_field,
)
parts = []
- if visible_result and visible_result.strip():
- parts.append(visible_result)
- if visible_suffix:
- parts.append(visible_suffix)
+ if raw_result and raw_result.strip():
+ parts.append(raw_result)
+ if raw_suffix:
+ parts.append(raw_suffix)
body = "\n".join(parts)
# Footer-only completion (show_duration on, no visible result/suffix):
# promote the footnote to the visible body so a duration/token-only turn
diff --git a/pyproject.toml b/pyproject.toml
index 9ae751f5d..0d403376c 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -49,6 +49,7 @@ dependencies = [
"slack-sdk>=3.26.0",
"discord.py>=2.4.0",
"aiohttp>=3.8.0",
+ "markdown-it-py>=4.2.0",
"markdown_to_mrkdwn>=0.2.0",
"typing_extensions>=4.12.2",
"PyYAML>=6.0",
diff --git a/tests/scenarios/message_delivery/catalog.yaml b/tests/scenarios/message_delivery/catalog.yaml
index 7fbbad787..335c629ca 100644
--- a/tests/scenarios/message_delivery/catalog.yaml
+++ b/tests/scenarios/message_delivery/catalog.yaml
@@ -49,6 +49,12 @@ scenarios:
kind: lifecycle
layer: contract
test: tests/test_show_git_turn_entrypoints.py::test_all_turn_entrypoints_reach_checkpoint_subscriber
+ - id: MESSAGE-DELIVERY-007
+ name: Markdown code examples survive terminal result and callback persistence
+ status: covered
+ kind: regression
+ layer: contract
+ test: tests/test_scheduled_tasks.py::test_base_agent_terminal_markdown_example_persists_complete_run_and_callback
- id: MESSAGE-DELIVERY-008
name: Run callbacks use only terminal output while directed child Runs remain independent
status: partial
diff --git a/tests/scenarios/message_delivery/observations.yaml b/tests/scenarios/message_delivery/observations.yaml
index f221dbbed..fcedc1d97 100644
--- a/tests/scenarios/message_delivery/observations.yaml
+++ b/tests/scenarios/message_delivery/observations.yaml
@@ -13,6 +13,17 @@ observations:
- keep result_text terminal-only and enqueue one terminal callback
- keep explicit child delivery independent from the parent's automatic callback
- persist harness-originated prompts with a non-user author and message type
+ - id: OBS-MESSAGE-DELIVERY-002
+ source: live_local_diagnosis
+ related_scenarios:
+ - MESSAGE-DELIVERY-007
+ summary: A terminal report containing the literal silent directive in inline Markdown code was truncated before persistence and callback delivery.
+ previous_assumption: Silent directive parsing could safely inspect raw Markdown because literal examples would only appear in non-terminal helper output.
+ observed_behavior: Run 6915939fd9e9, its persisted result message, and callback Run 8476952624d1 all stopped at the inline code opener and lost the substantial trailing report.
+ required_updates:
+ - recognize silent directives only outside Markdown inline and fenced code
+ - preserve code examples byte-for-byte while retaining real silent-block semantics
+ - prove the BaseAgent terminal path, message persistence, Run output ledger, and callback payload together
- id: OBS-MESSAGE-DELIVERY-003
source: live_local_diagnosis
related_scenarios:
diff --git a/tests/test_reply_enhancer_platform.py b/tests/test_reply_enhancer_platform.py
index 3eea453c7..21614d8e4 100644
--- a/tests/test_reply_enhancer_platform.py
+++ b/tests/test_reply_enhancer_platform.py
@@ -3,14 +3,16 @@ import sys
import unittest
from pathlib import Path
from types import SimpleNamespace
-from unittest.mock import patch
+from unittest.mock import AsyncMock, patch
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
+import core.reply_enhancer as reply_enhancer
from core.message_dispatcher import ConsolidatedMessageDispatcher
-from core.reply_enhancer import process_reply
+from core.reply_enhancer import process_reply, strip_silent_blocks
from core.system_prompt_injection import build_system_prompt_injection
from config import paths
+from modules.agents.base import AgentRequest, BaseAgent
from modules.im import MessageContext
@@ -83,6 +85,13 @@ class _StubController:
return self.settings_manager
+class _StubAgent(BaseAgent):
+ name = "stub"
+
+ async def handle_message(self, request: AgentRequest) -> None:
+ return None
+
+
class ReplyEnhancerPlatformTests(unittest.IsolatedAsyncioTestCase):
def test_prompt_can_exclude_quick_replies(self):
with patch.object(paths, "get_user_preferences_path", return_value=Path("/tmp/user_preferences.md")):
@@ -229,6 +238,906 @@ class ReplyEnhancerPlatformTests(unittest.IsolatedAsyncioTestCase):
self.assertEqual(reply.files, [])
self.assertEqual(reply.buttons, [])
+ def test_process_reply_preserves_silent_file_link_literal_inside_code(self):
+ specimens = [
+ "Example `<silent>[file](file:///tmp/secret.txt)</silent>` remains.",
+ "```markdown\n<silent>[file](file:///tmp/secret.txt)</silent>\n```",
+ "```markdown\n> <silent>[file](file:///tmp/secret.txt)</silent>\n```",
+ ]
+
+ for text in specimens:
+ with self.subTest(text=text):
+ reply = process_reply(text)
+ self.assertEqual(reply.text, text)
+ self.assertEqual(reply.files, [])
+
+ def test_process_reply_only_extracts_file_links_outside_markdown_code(self):
+ text = (
+ "Attach [report](file:///tmp/report.txt); preserve "
+ "`<silent>[example](file:///tmp/secret.txt)</silent>`."
+ )
+
+ reply = process_reply(text)
+
+ self.assertEqual(
+ reply.text,
+ "Attach report; preserve "
+ "`<silent>[example](file:///tmp/secret.txt)</silent>`.",
+ )
+ self.assertEqual([file.path for file in reply.files], ["/tmp/report.txt"])
+
+ def test_process_reply_recovers_attachment_label_from_original_text(self):
+ reply = process_reply("[see `report`](file:///tmp/report.txt)")
+
+ self.assertEqual(reply.text, "see `report`")
+ self.assertEqual([file.label for file in reply.files], ["see `report`"])
+
+ def test_process_reply_uses_shared_code_mask_for_secret_requests(self):
+ text = (
+ "````markdown\n"
+ "text ``` inner\n"
+ "<silent>$<OPENAI_KEY></silent>\n"
+ "````"
+ )
+
+ reply = process_reply(text)
+
+ self.assertEqual(reply.text, text)
+ self.assertEqual(reply.secret_requests, [])
+
+ def test_process_reply_uses_shared_code_mask_for_quick_replies(self):
+ text = (
+ "```markdown\n"
+ "<silent>literal</silent>\n"
+ "---\n"
+ "[Yes] | [No]"
+ )
+
+ reply = process_reply(text)
+
+ self.assertEqual(reply.text, text)
+ self.assertEqual(reply.buttons, [])
+
+ def test_silent_parser_preserves_inline_code_and_trailing_report_byte_for_byte(self):
+ trailing_report = "\n".join(
+ [
+ "2. Keep queue and cancellation work in their existing lanes.",
+ "3. Persist the complete terminal message and callback payload.",
+ "4. Re-run the exact-head review and CI gates.",
+ ]
+ )
+ text = (
+ "Intermediate assistant text must not leave its Session; "
+ "the literal directive is `<silent>`.\n\n"
+ f"{trailing_report}"
+ )
+
+ self.assertEqual(strip_silent_blocks(text), text)
+
+ def test_silent_parser_preserves_fenced_code_byte_for_byte(self):
+ text = (
+ "Examples:\n\n"
+ "```markdown\n"
+ "<silent>complete example</silent>\n"
+ "<silent>\n"
+ "substantial text after the unmatched literal\n"
+ "```\n\n"
+ "~~~text\n"
+ "<SILENT data-example=\"true\">\n"
+ "more literal text\n"
+ "~~~\n"
+ "Tail remains."
+ )
+
+ self.assertEqual(strip_silent_blocks(text), text)
+
+ def test_silent_parser_preserves_container_fences_byte_for_byte(self):
+ text = (
+ "- ```text\n"
+ " <silent>list literal</silent>\n"
+ " ```\n\n"
+ "> ~~~text\n"
+ "> <silent>quote literal</silent>\n"
+ "> ~~~\n\n"
+ "> - ````markdown\n"
+ "> ```nested```\n"
+ "> <silent>nested literal</silent>\n"
+ "> ````\n"
+ "Tail remains."
+ )
+
+ self.assertEqual(strip_silent_blocks(text), text)
+
+ def test_silent_parser_preserves_tab_indented_list_fence(self):
+ text = (
+ "-\t```text\n"
+ "\t<silent>tab-indented literal</silent>\n"
+ "\t```\n"
+ "Tail remains."
+ )
+
+ self.assertEqual(strip_silent_blocks(text), text)
+
+ def test_silent_parser_preserves_continuation_line_list_fence(self):
+ text = (
+ "10. Example\n"
+ " ```text\n"
+ " <silent>continuation literal</silent>\n"
+ " ```\n"
+ "Tail remains."
+ )
+
+ self.assertEqual(strip_silent_blocks(text), text)
+
+ def test_silent_parser_retains_list_state_across_lazy_continuation(self):
+ text = (
+ "- item\n"
+ "lazy continuation\n"
+ " ```text\n"
+ " <silent>lazy list literal</silent>\n"
+ " ```"
+ )
+
+ self.assertEqual(strip_silent_blocks(text), text)
+
+ def test_silent_parser_tracks_nested_list_context_across_lines(self):
+ text = (
+ "- Outer\n"
+ " 1. Inner\n"
+ " ```text\n"
+ " <silent>nested continuation literal</silent>\n"
+ " ```\n"
+ " ```text\n"
+ " > <silent>outer continuation literal</silent>\n"
+ " ```\n"
+ "Tail remains."
+ )
+
+ self.assertEqual(strip_silent_blocks(text), text)
+
+ def test_silent_parser_tracks_empty_ordered_list_item(self):
+ text = (
+ "10.\n"
+ " ```text\n"
+ " <silent>empty-item continuation literal</silent>\n"
+ " ```\n"
+ "Tail remains."
+ )
+
+ self.assertEqual(strip_silent_blocks(text), text)
+
+ def test_silent_parser_tracks_quote_nested_inside_list(self):
+ text = (
+ "- > ```text\n"
+ " > <silent>list quote literal</silent>\n"
+ " > ```\n"
+ "Tail remains."
+ )
+
+ self.assertEqual(strip_silent_blocks(text), text)
+
+ def test_silent_parser_enforces_list_indent_before_nested_quote(self):
+ text = (
+ "- > ```text\n"
+ "> <silent>remove outside code</silent>\n"
+ "> ```"
+ )
+
+ self.assertEqual(strip_silent_blocks(text), "- > ```text\n> \n> ```")
+
+ def test_silent_parser_tracks_alternating_quote_and_list_containers(self):
+ text = (
+ "> - > - ```text\n"
+ "> > <silent>alternating container literal</silent>\n"
+ "> > ```\n"
+ "Tail remains."
+ )
+
+ self.assertEqual(strip_silent_blocks(text), text)
+
+ def test_silent_parser_preserves_inline_code_after_non_one_list_text(self):
+ text = (
+ "Paragraph\n"
+ "10. Not a list interruption\n"
+ " ```text\n"
+ " <silent>paragraph code literal</silent>\n"
+ " ```\n"
+ "Tail remains."
+ )
+
+ self.assertEqual(strip_silent_blocks(text), text)
+
+ def test_silent_parser_rejects_empty_list_interrupting_paragraph(self):
+ text = (
+ "Paragraph\n"
+ "-\n"
+ " ```text\n"
+ " <silent>remove outside code</silent>\n"
+ " ```\n"
+ "Tail remains."
+ )
+ expected = (
+ "Paragraph\n"
+ "-\n"
+ " ```text\n"
+ " \n"
+ " ```\n"
+ "Tail remains."
+ )
+
+ self.assertEqual(strip_silent_blocks(text), expected)
+
+ def test_silent_parser_uses_list_relative_indented_code_threshold(self):
+ text = (
+ "- item\n"
+ "\n"
+ " <silent>remove list paragraph content</silent>\n"
+ "\n"
+ " <silent>preserve list indented code</silent>"
+ )
+ expected = (
+ "- item\n"
+ "\n"
+ " \n"
+ "\n"
+ " <silent>preserve list indented code</silent>"
+ )
+
+ self.assertEqual(strip_silent_blocks(text), expected)
+
+ def test_silent_parser_uses_nested_list_indented_code_threshold(self):
+ text = (
+ "- outer\n"
+ " - middle\n"
+ " - inner\n"
+ "\n"
+ " <silent>remove inner list content</silent>"
+ )
+
+ self.assertEqual(
+ strip_silent_blocks(text),
+ "- outer\n - middle\n - inner",
+ )
+
+ def test_silent_parser_preserves_alternating_container_indented_code(self):
+ text = "- > <silent>alternating indented literal</silent>"
+
+ self.assertEqual(strip_silent_blocks(text), text)
+
+ def test_silent_parser_resets_paragraph_state_after_heading(self):
+ text = (
+ "# Heading\n"
+ "10. item\n"
+ " ```text\n"
+ " <silent>heading list literal</silent>\n"
+ " ```\n"
+ "Tail remains."
+ )
+
+ self.assertEqual(strip_silent_blocks(text), text)
+
+ def test_silent_parser_preserves_inline_code_after_orphan_setext_marker(self):
+ text = (
+ "===\n"
+ "10. item\n"
+ " ```text\n"
+ " <silent>paragraph code literal</silent>\n"
+ " ```"
+ )
+
+ self.assertEqual(strip_silent_blocks(text), text)
+
+ def test_silent_parser_keeps_invalid_fence_line_in_paragraph_state(self):
+ text = (
+ "``` foo`bar\n"
+ "10. item\n"
+ " ```text\n"
+ " <silent>remove outside code</silent>\n"
+ " ```"
+ )
+
+ self.assertEqual(
+ strip_silent_blocks(text),
+ "``` foo`bar\n10. item\n ```text\n \n ```",
+ )
+
+ def test_silent_parser_allows_list_after_link_reference_definition(self):
+ text = (
+ "[ref]: /url\n"
+ "10. item\n"
+ " ```text\n"
+ " <silent>link definition literal</silent>\n"
+ " ```"
+ )
+
+ self.assertEqual(strip_silent_blocks(text), text)
+
+ def test_silent_parser_stops_unclosed_fence_at_container_boundary(self):
+ text = (
+ "- ```text\n"
+ " <silent>list literal</silent>\n"
+ "List ended.\n"
+ "<silent>remove after list</silent>\n\n"
+ "> ~~~text\n"
+ "> <silent>quote literal</silent>\n"
+ "Quote ended.\n"
+ "<silent>remove after quote</silent>\n"
+ "Tail remains."
+ )
+ expected = (
+ "- ```text\n"
+ " <silent>list literal</silent>\n"
+ "List ended.\n"
+ "\n\n"
+ "> ~~~text\n"
+ "> <silent>quote literal</silent>\n"
+ "Quote ended.\n"
+ "\n"
+ "Tail remains."
+ )
+
+ self.assertEqual(strip_silent_blocks(text), expected)
+
+ def test_silent_parser_removes_real_blocks_while_preserving_code_examples(self):
+ text = (
+ "Start\n"
+ "<silent>remove one</silent>\n"
+ "Inline `<silent>literal one</silent>` stays.\n"
+ "<SILENT reason=\"hidden\">remove two</silent >\n"
+ "````markdown\n"
+ "```nested fence```\n"
+ "<silent>literal two</silent>\n"
+ "````\n"
+ "End"
+ )
+ expected = (
+ "Start\n"
+ "\n"
+ "Inline `<silent>literal one</silent>` stays.\n"
+ "\n"
+ "````markdown\n"
+ "```nested fence```\n"
+ "<silent>literal two</silent>\n"
+ "````\n"
+ "End"
+ )
+
+ self.assertEqual(strip_silent_blocks(text), expected)
+
+ def test_silent_parser_handles_backtick_and_escape_edges(self):
+ protected = "Double ``literal `<silent>` marker`` remains."
+ escaped = r"Before \`<silent>remove me</silent>\` after"
+ partial_escape = "\\``<silent>literal</silent>`"
+ escaped_closer = r"`<silent>literal</silent>\`"
+
+ self.assertEqual(strip_silent_blocks(protected), protected)
+ self.assertEqual(strip_silent_blocks(escaped), r"Before \`\` after")
+ self.assertEqual(strip_silent_blocks(partial_escape), partial_escape)
+ self.assertEqual(strip_silent_blocks(escaped_closer), escaped_closer)
+
+ def test_silent_parser_preserves_multiline_inline_code_span(self):
+ text = "`foo\n<silent>multiline literal</silent>\nbar`\nTail remains."
+
+ self.assertEqual(strip_silent_blocks(text), text)
+
+ def test_silent_parser_ignores_backticks_inside_raw_html_tags(self):
+ text = '<a title="`">x</a> <silent>remove me</silent> `tail'
+
+ self.assertEqual(
+ strip_silent_blocks(text),
+ '<a title="`">x</a> `tail',
+ )
+
+ def test_silent_parser_rejects_invalid_raw_html_tag_grammar(self):
+ text = '<a? title="`"> [literal](file:///tmp/secret.txt) `'
+
+ reply = process_reply(text)
+
+ self.assertEqual(reply.text, text)
+ self.assertEqual(reply.files, [])
+
+ def test_silent_parser_honors_escape_before_raw_html_candidate(self):
+ text = r'\<a title="`"> [literal](file:///tmp/secret.txt) `'
+
+ reply = process_reply(text)
+
+ self.assertEqual(reply.text, text)
+ self.assertEqual(reply.files, [])
+
+ def test_silent_parser_rejects_unicode_space_in_raw_html_tag(self):
+ text = '<a\u00a0title="`"> [literal](file:///tmp/secret.txt) `'
+
+ reply = process_reply(text)
+
+ self.assertEqual(reply.text, text)
+ self.assertEqual(reply.files, [])
+
+ def test_silent_parser_rejects_attributes_on_raw_html_closing_tags(self):
+ text = '</a title="`"> [literal](file:///tmp/secret.txt) `'
+
+ reply = process_reply(text)
+
+ self.assertEqual(reply.text, text)
+ self.assertEqual(reply.files, [])
+
+ def test_silent_parser_parses_html_as_text_inside_open_code_span(self):
+ text = (
+ '`prefix <a title="`"> '
+ "<silent>remove outside code</silent> "
+ "`tail`"
+ )
+
+ self.assertEqual(
+ strip_silent_blocks(text),
+ '`prefix <a title="`"> `tail`',
+ )
+
+ def test_silent_parser_ignores_backticks_inside_uri_autolinks(self):
+ text = (
+ "<https://example.com/`> "
+ "<silent>remove outside code</silent> "
+ "`tail"
+ )
+
+ self.assertEqual(
+ strip_silent_blocks(text),
+ "<https://example.com/`> `tail",
+ )
+
+ def test_silent_parser_strips_quote_prefixes_before_inline_html(self):
+ text = (
+ "> text <!A\n"
+ "> `> <silent>remove outside code</silent> `tail"
+ )
+
+ self.assertEqual(
+ strip_silent_blocks(text),
+ "> text <!A\n> `> `tail",
+ )
+
+ def test_silent_parser_maps_normalized_nul_to_original_source(self):
+ text = (
+ "`before\x00"
+ "[literal](file:///tmp/secret.txt) "
+ "<silent>literal</silent>"
+ "after`"
+ )
+
+ reply = process_reply(text)
+
+ self.assertEqual(reply.text, text)
+ self.assertEqual(reply.files, [])
+
+ def test_silent_parser_maps_tab_expanded_list_continuation(self):
+ text = (
+ "- item\n"
+ "\t`<silent>[literal](file:///tmp/secret.txt)</silent>`"
+ )
+
+ reply = process_reply(text)
+
+ self.assertEqual(reply.text, text)
+ self.assertEqual(reply.files, [])
+
+ def test_silent_parser_handles_many_unmatched_backtick_runs(self):
+ unmatched_runs = " ".join("`" * length for length in range(2, 502))
+ text = f"Literal `<silent>` remains.\n{unmatched_runs}\nTail remains."
+
+ self.assertEqual(strip_silent_blocks(text), text)
+
+ def test_silent_parser_does_not_pair_inline_spans_across_lines(self):
+ text = " ```\n<silent>remove outside code</silent>\n ```\nTail remains."
+
+ self.assertEqual(
+ strip_silent_blocks(text),
+ " ```\n\n ```\nTail remains.",
+ )
+
+ def test_silent_parser_ends_quoted_fence_at_unmarked_blank_line(self):
+ text = (
+ "> ```text\n"
+ "\n"
+ "> <silent>remove outside code</silent>\n"
+ "> ```"
+ )
+
+ self.assertEqual(strip_silent_blocks(text), "> ```text\n\n> \n> ```")
+
+ def test_silent_parser_preserves_indented_code_literal(self):
+ text = "Example:\n\n <silent>indented literal</silent>\nTail remains."
+
+ self.assertEqual(strip_silent_blocks(text), text)
+
+ def test_silent_parser_preserves_quoted_indented_code_literal(self):
+ text = "> <silent>quoted indented literal</silent>"
+
+ self.assertEqual(strip_silent_blocks(text), text)
+
+ def test_silent_parser_ignores_fences_inside_raw_html_blocks(self):
+ text = (
+ "<pre>\n"
+ "```\n"
+ "<silent>remove real directive</silent>\n"
+ "```\n"
+ "</pre>\n"
+ "Tail remains."
+ )
+ expected = "<pre>\n```\n\n```\n</pre>\nTail remains."
+
+ self.assertEqual(strip_silent_blocks(text), expected)
+
+ def test_silent_parser_does_not_mask_indented_content_in_raw_html_block(self):
+ text = (
+ "<pre>\n"
+ "\n"
+ " <silent>remove real directive</silent>\n"
+ "</pre>"
+ )
+
+ self.assertEqual(strip_silent_blocks(text), "<pre>\n\n \n</pre>")
+
+ def test_silent_parser_ignores_fences_inside_html_comment_blocks(self):
+ text = (
+ "<!--\n"
+ "```\n"
+ "-->\n"
+ "<silent>remove real directive</silent>\n"
+ "```"
+ )
+
+ self.assertEqual(strip_silent_blocks(text), "<!--\n```\n-->\n\n```")
+
+ def test_silent_parser_does_not_parse_code_spans_in_unterminated_html_blocks(self):
+ for opener in ("<!--", "<?target", "<![CDATA[", "<!DOCTYPE"):
+ with self.subTest(opener=opener):
+ text = f"{opener}\n`<silent>hidden</silent>`"
+
+ self.assertEqual(strip_silent_blocks(text), f"{opener}\n``")
+
+ def test_process_reply_keeps_fence_newline_before_quick_replies(self):
+ text = "```text\nexample\n```\n---\n[Yes] | [No]"
+
+ reply = process_reply(text)
+
+ self.assertEqual(reply.text, "```text\nexample\n```")
+ self.assertEqual([button.text for button in reply.buttons], ["Yes", "No"])
+
+ def test_silent_parser_removes_many_control_blocks_in_one_pass(self):
+ blocks = "".join(
+ f"visible-{index}<silent>hidden-{index}</silent>"
+ for index in range(2_000)
+ )
+ expected = "".join(f"visible-{index}" for index in range(2_000))
+
+ self.assertEqual(strip_silent_blocks(blocks), expected)
+
+ def test_silent_parser_parses_progressively_exposed_blocks_once(self):
+ lengths = range(1, 201)
+ blocks = "".join(
+ f"<silent>{'`' * length}</silent>" for length in lengths
+ )
+ closers = " ".join("`" * length for length in lengths)
+ text = f"prefix {blocks} {closers}"
+
+ with patch.object(
+ reply_enhancer._BLOCK_MARKDOWN,
+ "parse",
+ wraps=reply_enhancer._BLOCK_MARKDOWN.parse,
+ ) as parse:
+ result = strip_silent_blocks(text)
+
+ self.assertEqual(result, f"prefix {closers}")
+ self.assertEqual(parse.call_count, 1)
+
+ def test_silent_parser_handles_many_malformed_html_prefixes_linearly(self):
+ text = "<a" * 8_000 + " `<silent>literal</silent>`"
+
+ self.assertEqual(strip_silent_blocks(text), text)
+
+ def test_silent_parser_strips_many_malformed_html_comments_linearly(self):
+ text = "<!--" * 8_000 + " `<silent>literal</silent>`"
+
+ self.assertEqual(strip_silent_blocks(text), "<!--" * 8_000 + " ``")
+
+ def test_reply_enhancer_treats_unicode_digits_as_plain_text(self):
+ text = "². item\n①. item"
+
+ self.assertEqual(process_reply(text).text, text)
+
+ def test_silent_parser_does_not_pair_inline_spans_across_cr_lines(self):
+ text = " ```\r<silent>remove outside code</silent>\r ```\rTail remains."
+
+ self.assertEqual(
+ strip_silent_blocks(text),
+ " ```\r\r ```\rTail remains.",
+ )
+
+ def test_silent_parser_closes_real_block_before_parsing_hidden_markdown(self):
+ text = "Before\n<silent>\n```\nhidden\n</silent>\nTail remains."
+
+ self.assertEqual(strip_silent_blocks(text), "Before\n\nTail remains.")
+
+ def test_silent_parser_keeps_hidden_fences_from_masking_later_blocks(self):
+ text = (
+ "Before\n"
+ "<silent>\n```\nhidden\n</silent>\n"
+ "<silent>second secret</silent>\n"
+ "Tail remains."
+ )
+
+ self.assertEqual(strip_silent_blocks(text), "Before\n\n\nTail remains.")
+
+ def test_silent_parser_restores_code_literals_after_hidden_fence(self):
+ text = (
+ "Before\n"
+ "<silent>\n````\nhidden\n</silent>\n"
+ "```text\n"
+ "<silent>literal\n```\n</silent>\n"
+ "<silent>remove two</silent>\n"
+ "Tail remains."
+ )
+ expected = (
+ "Before\n\n"
+ "```text\n"
+ "<silent>literal\n```\n</silent>\n\n"
+ "Tail remains."
+ )
+
+ self.assertEqual(strip_silent_blocks(text), expected)
+
+ def test_process_reply_reparses_after_multiline_control_html_block(self):
+ text = (
+ "<silent>\ninternal\n</silent>\n"
+ "`<silent>inline literal</silent>`\n"
+ "```text\n"
+ "<silent>[literal](file:///tmp/secret.txt)</silent>\n"
+ "```\n"
+ "Tail remains."
+ )
+ expected = (
+ "`<silent>inline literal</silent>`\n"
+ "```text\n"
+ "<silent>[literal](file:///tmp/secret.txt)</silent>\n"
+ "```\n"
+ "Tail remains."
+ )
+
+ reply = process_reply(text)
+
+ self.assertEqual(reply.text, expected)
+ self.assertEqual(reply.files, [])
+
+ def test_silent_parser_reparses_unmatched_literal_after_html_block(self):
+ tail = "\n".join(f"substantial trailing line {index}" for index in range(50))
+ text = (
+ "<silent>\ninternal\n</silent>\n"
+ "`<silent>unmatched literal opener`\n"
+ f"{tail}"
+ )
+ expected = "`<silent>unmatched literal opener`\n" + tail
+
+ self.assertEqual(strip_silent_blocks(text), expected)
+
+ def test_silent_parser_does_not_cross_pair_provisional_code_literal(self):
+ text = (
+ "<silent>\ninternal\n</silent>\n"
+ "`<silent>unmatched literal opener`\n"
+ "<silent>remove later control</silent>\n"
+ "Tail remains."
+ )
+ expected = (
+ "`<silent>unmatched literal opener`\n\n"
+ "Tail remains."
+ )
+
+ self.assertEqual(strip_silent_blocks(text), expected)
+
+ def test_silent_parser_reparses_html_block_inside_quote(self):
+ text = (
+ "> <silent>\n"
+ "> internal\n"
+ "> </silent>\n"
+ "> `<silent>literal</silent>`\n"
+ "> Tail remains."
+ )
+ expected = (
+ "> \n"
+ "> `<silent>literal</silent>`\n"
+ "> Tail remains."
+ )
+
+ self.assertEqual(strip_silent_blocks(text), expected)
+
+ def test_silent_parser_does_not_pair_code_opener_with_real_closer(self):
+ text = (
+ "```text\n"
+ "<silent>unterminated literal\n"
+ "```\n"
+ "<silent>remove real block</silent>\n"
+ "Tail remains."
+ )
+ expected = (
+ "```text\n"
+ "<silent>unterminated literal\n"
+ "```\n\n"
+ "Tail remains."
+ )
+
+ self.assertEqual(strip_silent_blocks(text), expected)
+
+ def test_silent_parser_bounds_hidden_unmatched_fence_refinement(self):
+ blocks = "".join(
+ f"<silent>\n{'`' * length}\nhidden\n</silent>\n"
+ for length in range(205, 4, -1)
+ )
+
+ with patch.object(
+ reply_enhancer._BLOCK_MARKDOWN,
+ "parse",
+ wraps=reply_enhancer._BLOCK_MARKDOWN.parse,
+ ) as parse:
+ result = strip_silent_blocks(f"Before\n{blocks}Tail remains.")
+
+ self.assertNotIn("<silent", result)
+ self.assertTrue(result.startswith("Before\n"))
+ self.assertTrue(result.endswith("Tail remains."))
+ self.assertLessEqual(parse.call_count, 4)
+
+ def test_silent_parser_partitions_sorted_ranges_in_one_pass(self):
+ class CountingPosition:
+ comparisons = 0
+
+ def __init__(self, value):
+ self.value = value
+
+ def __le__(self, other):
+ type(self).comparisons += 1
+ return self.value <= other.value
+
+ def __lt__(self, other):
+ type(self).comparisons += 1
+ return self.value < other.value
+
+ count = 8_000
+ containers = [
+ (CountingPosition(index * 4), CountingPosition(index * 4 + 1))
+ for index in range(count)
+ ]
+ ranges = [
+ source_range
+ for index in range(count)
+ for source_range in (
+ (CountingPosition(index * 4), CountingPosition(index * 4)),
+ (
+ CountingPosition(index * 4 + 2),
+ CountingPosition(index * 4 + 2),
+ ),
+ )
+ ]
+
+ outside, inside = reply_enhancer._partition_ranges_by_start(
+ ranges,
+ containers,
+ )
+
+ self.assertEqual(len(outside), count)
+ self.assertEqual(len(inside), count)
+ self.assertLess(
+ CountingPosition.comparisons,
+ 8 * (len(ranges) + len(containers)),
+ )
+
+ def test_silent_parser_scans_malformed_openers_without_unbounded_regex(self):
+ text = "<silent" * 16_000 + "\nTail remains."
+
+ with patch.object(
+ reply_enhancer,
+ "_SILENT_OPEN_RE",
+ None,
+ create=True,
+ ):
+ self.assertEqual(strip_silent_blocks(text), text)
+
+ def test_process_reply_keeps_original_enhancement_eligibility(self):
+ text = (
+ "`<silent>hidden</silent>``\n"
+ "[report](file:///tmp/report.txt)\n"
+ "$<REPORT_TOKEN>\n"
+ "---\n"
+ "[Continue] | [Stop]"
+ )
+
+ reply = process_reply(text)
+
+ self.assertEqual(reply.text, "```\nreport\n$<REPORT_TOKEN>")
+ self.assertEqual([file.path for file in reply.files], ["/tmp/report.txt"])
+ self.assertEqual(
+ [request.name for request in reply.secret_requests],
+ ["REPORT_TOKEN"],
+ )
+ self.assertEqual(
+ [button.text for button in reply.buttons],
+ ["Continue", "Stop"],
+ )
+
+ async def test_base_agent_result_keeps_attachment_eligibility_after_silent_removal(self):
+ class _DispatchingController(_StubController):
+ def __init__(self):
+ super().__init__("slack")
+ self.config.show_duration = False
+ self.dispatcher = ConsolidatedMessageDispatcher(self)
+
+ async def emit_agent_message(self, context, message_type, text, **kwargs):
+ return await self.dispatcher.emit_agent_message(
+ context,
+ message_type,
+ text,
+ **kwargs,
+ )
+
+ controller = _DispatchingController()
+ upload_file_links = AsyncMock()
+ controller.dispatcher._upload_file_links = upload_file_links
+ context = MessageContext(
+ user_id="U1",
+ channel_id="C1",
+ platform="slack",
+ )
+ source = (
+ "`<silent>hidden</silent>``\n"
+ "[report](file:///tmp/report.txt)"
+ )
+
+ await _StubAgent(controller).emit_result_message(
+ context,
+ source,
+ duration_ms=0,
+ )
+
+ uploaded_files = upload_file_links.await_args.args[2]
+ self.assertEqual(
+ [(file.label, file.path) for file in uploaded_files],
+ [("report", "/tmp/report.txt")],
+ )
+ self.assertEqual(
+ controller.im_client.sent_messages,
+ [("C1", "```\nreport", "markdown")],
+ )
+
+ def test_silent_parser_keeps_unterminated_recovery_outside_code(self):
+ text = "Visible result\n<silent>unfinished hidden diagnostic\nmust not leak"
+
+ self.assertEqual(strip_silent_blocks(text), "Visible result")
+
+ def test_silent_parser_keeps_all_silent_response_empty(self):
+ self.assertEqual(strip_silent_blocks("<silent>internal only</silent>"), "")
+
+ def test_silent_parser_preserves_boundary_indented_code(self):
+ text = (
+ "<silent>remove real directive</silent>\n\n"
+ " <silent>[literal](file:///tmp/secret.txt)</silent>"
+ )
+
+ reply = process_reply(text)
+
+ self.assertEqual(
+ reply.text,
+ " <silent>[literal](file:///tmp/secret.txt)</silent>",
+ )
+ self.assertEqual(reply.files, [])
+
+ def test_silent_parser_does_not_reparse_synthesized_openers(self):
+ text = (
+ "Visible <sil"
+ "<silent>hidden</silent>"
+ "ent>KEEP</silent> tail"
+ )
+
+ self.assertEqual(
+ strip_silent_blocks(text),
+ "Visible <silent>KEEP</silent> tail",
+ )
+
def test_process_reply_can_disable_quick_reply_button_parsing_only(self):
reply = process_reply(
"Report [file](file:///tmp/report.txt)\n\n---\n[Continue] | [Stop]",
diff --git a/tests/test_scheduled_tasks.py b/tests/test_scheduled_tasks.py
index 67ea517ff..41f8fc3a5 100644
--- a/tests/test_scheduled_tasks.py
+++ b/tests/test_scheduled_tasks.py
@@ -48,7 +48,13 @@ from core.scheduled_tasks import (
from modules.im import MessageContext
from storage.db import create_sqlite_engine
from storage.background import SQLiteBackgroundTaskStore
-from storage.models import agent_events, agent_runs, messages, run_definitions
+from storage.models import (
+ agent_events,
+ agent_runs,
+ agent_sessions,
+ messages,
+ run_definitions,
+)
from storage.pagination import PageRequest
from storage.session_activities import SQLiteSessionActivityStore
from storage.agent_session_rows import create_agent_session_row
@@ -4931,6 +4937,170 @@ def test_agent_run_keeps_output_ledger_but_callbacks_only_terminal_result(
assert callback_runs[0]["source_actor"] == request.id
+def test_base_agent_terminal_markdown_example_persists_complete_run_and_callback(
+ tmp_path: Path,
+ monkeypatch,
+) -> None:
+ """Scenario: MESSAGE-DELIVERY-007."""
+ from core.services import sessions as sessions_service
+ from modules.agents.base import BaseAgent
+ from modules.im.formatters.slack_formatter import SlackFormatter
+
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ callback_session_id = _make_avibe_session(monkeypatch, tmp_path)
+ engine = create_sqlite_engine()
+ with engine.begin() as conn:
+ callback_session = conn.execute(
+ select(agent_sessions).where(agent_sessions.c.id == callback_session_id)
+ ).mappings().one()
+ target_session = sessions_service.create_session(
+ conn,
+ scope_id=callback_session["scope_id"],
+ agent_backend="codex",
+ agent_name="codex",
+ visibility="background",
+ )
+
+ request_store = TaskExecutionStore()
+ request = request_store.enqueue_agent_run(
+ session_id=target_session["id"],
+ message="inspect the callback regression",
+ agent_name="codex",
+ callback_session_id=callback_session_id,
+ )
+ assert request_store.claim(request.id) is not None
+
+ class _IMClient:
+ formatter = SlackFormatter()
+
+ @staticmethod
+ def should_use_thread_for_reply() -> bool:
+ return False
+
+ @staticmethod
+ async def send_message(context, text, parse_mode=None, reply_to=None):
+ return "persisted-result-message"
+
+ @staticmethod
+ async def send_message_with_buttons(context, text, keyboard, parse_mode=None):
+ return "persisted-result-message"
+
+ class _SettingsManager:
+ @staticmethod
+ def _canonicalize_message_type(message_type: str) -> str:
+ return message_type
+
+ @staticmethod
+ def is_message_type_hidden(settings_key: str, message_type: str) -> bool:
+ return False
+
+ class _Controller:
+ def __init__(self) -> None:
+ self.config = SimpleNamespace(
+ platform="avibe",
+ reply_enhancements=True,
+ show_duration=False,
+ )
+ self.im_client = _IMClient()
+ self.settings_manager = _SettingsManager()
+ self.session_handler = SimpleNamespace(
+ finalize_scheduled_delivery=lambda *_args, **_kwargs: None
+ )
+ self.dispatcher = ConsolidatedMessageDispatcher(self)
+
+ @staticmethod
+ def _get_settings_key(context) -> str:
+ return context.channel_id
+
+ @staticmethod
+ def _get_session_key(context) -> str:
+ return f"avibe::{context.channel_id}"
+
+ @staticmethod
+ def get_settings_manager_for_context(context):
+ return _SettingsManager()
+
+ def get_im_client_for_context(self, context):
+ return self.im_client
+
+ async def emit_agent_message(self, context, message_type, text, **kwargs):
+ return await self.dispatcher.emit_agent_message(
+ context,
+ message_type,
+ text,
+ **kwargs,
+ )
+
+ class _CodexBaseAgent(BaseAgent):
+ name = "codex"
+
+ async def handle_message(self, request) -> None:
+ return None
+
+ specimen = (
+ "Intermediate assistant text must not leave its Session; "
+ "the literal directive is `<silent>`.\n\n"
+ "2. This substantial trailing section must survive parser cleanup.\n"
+ "3. The persisted message, output ledger, and callback must be identical.\n"
+ "4. This line proves the live 339-character truncation cannot recur."
+ )
+ context = MessageContext(
+ user_id="scheduled",
+ channel_id=target_session["id"],
+ platform="avibe",
+ platform_specific={
+ "agent_session_id": target_session["id"],
+ "task_trigger_kind": "agent_run",
+ "task_execution_id": request.id,
+ },
+ )
+
+ asyncio.run(
+ _CodexBaseAgent(_Controller()).emit_result_message(
+ context,
+ specimen,
+ duration_ms=0,
+ )
+ )
+
+ stored_run = request_store.get_run(request.id)
+ assert stored_run is not None
+ assert stored_run["status"] == "succeeded"
+ assert stored_run["result_text"] == specimen
+ assert [item["text"] for item in stored_run["result_payload"]["outputs"]] == [
+ specimen
+ ]
+ with engine.connect() as conn:
+ persisted_messages = conn.execute(
+ select(messages.c.content_text)
+ .where(messages.c.session_id == target_session["id"])
+ .where(messages.c.type == "result")
+ ).scalars().all()
+ assert persisted_messages == [specimen]
+
+ service = ScheduledTaskService(
+ controller=_avibe_controller_double(
+ gate=SimpleNamespace(
+ submit_scheduled=lambda *_args, **_kwargs: None,
+ in_flight={},
+ ),
+ handle_scheduled_message=lambda *_args, **_kwargs: None,
+ ),
+ store=ScheduledTaskStore(tmp_path / "scheduled_tasks.json"),
+ request_store=request_store,
+ )
+ asyncio.run(service._drain_callbacks())
+
+ completed_run = request_store.get_run(request.id)
+ assert completed_run is not None
+ assert completed_run["callback_status"] == "sent"
+ callback_run = request_store.get_run(completed_run["callback_run_id"])
+ assert callback_run is not None
+ assert callback_run["source_kind"] == "callback"
+ assert callback_run["parent_run_id"] == request.id
+ assert callback_run["message"] == specimen
+
+
def test_settled_deferred_run_delivers_saved_terminal_result(
tmp_path: Path,
monkeypatch,
diff --git a/uv.lock b/uv.lock
index a017e9b50..6585e1826 100644
--- a/uv.lock
+++ b/uv.lock
@@ -310,6 +310,7 @@ dependencies = [
{ name = "httpx", extra = ["socks"] },
{ name = "imagesize" },
{ name = "lark-oapi" },
+ { name = "markdown-it-py" },
{ name = "markdown-to-mrkdwn" },
{ name = "packaging" },
{ name = "prometheus-client" },
@@ -349,6 +350,7 @@ requires-dist = [
{ name = "httpx", extras = ["socks"], specifier = ">=0.27" },
{ name = "imagesize", specifier = ">=1.4.1" },
{ name = "lark-oapi", specifier = ">=1.4.0" },
+ { name = "markdown-it-py", specifier = ">=4.2.0" },
{ name = "markdown-to-mrkdwn", specifier = ">=0.2.0" },
{ name = "packaging", specifier = ">=23.0" },
{ name = "prometheus-client", specifier = ">=0.20.0" },
@@ -1071,6 +1073,18 @@ wheels = [
{ url = "https://files.pythonhosted.org/packages/bc/b1/a0ec7a5a9db730a08daef1fdfb8090435b82465abbf758a596f0ea88727e/mako-1.3.12-py3-none-any.whl", hash = "sha256:8f61569480282dbf557145ce441e4ba888be453c30989f879f0d652e39f53ea9", size = 78521, upload-time = "2026-04-28T19:01:10.393Z" },
]
+[[package]]
+name = "markdown-it-py"
+version = "4.2.0"
+source = { registry = "https://pypi.org/simple" }
+dependencies = [
+ { name = "mdurl" },
+]
+sdist = { url = "https://files.pythonhosted.org/packages/06/ff/7841249c247aa650a76b9ee4bbaeae59370dc8bfd2f6c01f3630c35eb134/markdown_it_py-4.2.0.tar.gz", hash = "sha256:04a21681d6fbb623de53f6f364d352309d4094dd4194040a10fd51833e418d49", size = 82454, upload-time = "2026-05-07T12:08:28.36Z" }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/b3/81/4da04ced5a082363ecfa159c010d200ecbd959ae410c10c0264a38cac0f5/markdown_it_py-4.2.0-py3-none-any.whl", hash = "sha256:9f7ebbcd14fe59494226453aed97c1070d83f8d24b6fc3a3bcf9a38092641c4a", size = 91687, upload-time = "2026-05-07T12:08:27.182Z" },
+]
+
[[package]]
name = "markdown-to-mrkdwn"
version = "0.3.1"
@@ -1190,6 +1204,15 @@ wheels = [
{ url = "https://files.pythonhosted.org/packages/e2/fc/6dc7659c2ae5ddf280477011f4213a74f806862856b796ef08f028e664bf/mcp-1.25.0-py3-none-any.whl", hash = "sha256:b37c38144a666add0862614cc79ec276e97d72aa8ca26d622818d4e278b9721a", size = 233076, upload-time = "2025-12-19T10:19:55.416Z" },
]
+[[package]]
+name = "mdurl"
+version = "0.1.2"
+source = { registry = "https://pypi.org/simple" }
+sdist = { url = "https://files.pythonhosted.org/packages/d6/54/cfe61301667036ec958cb99bd3efefba235e65cdeb9c84d24a8293ba1d90/mdurl-0.1.2.tar.gz", hash = "sha256:bb413d29f5eea38f31dd4754dd7377d4465116fb207585f97bf925588687c1ba", size = 8729, upload-time = "2022-08-14T12:40:10.846Z" }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/b3/38/89ba8ad64ae25be8de66a6d463314cf1eb366222074cfda9ee839c56a4b4/mdurl-0.1.2-py3-none-any.whl", hash = "sha256:84008a41e51615a49fc9966191ff91509e3c40b939176e643fd50a5c2196b8f8", size = 9979, upload-time = "2022-08-14T12:40:09.779Z" },
+]
+
[[package]]
name = "multidict"
version = "6.7.0"