Skip to content

The agent that grows with you

fix: handle replacement transforms after CLI streaming

Ken Weinerb68a5322951d
diff --git a/cli.py b/cli.py
index 1081c8163ab..fbad8832b77 100644
--- a/cli.py
+++ b/cli.py
@@ -2982,6 +2982,25 @@ def _render_final_assistant_content(text: str, mode: str = "render"):
return Markdown(plain)
+def _post_stream_transform_output(response: str, result: dict | None) -> str:
+ """Return text that still needs display after a streamed response transform.
+
+ A transform hook is allowed to replace the final response, not merely append
+ to it. When the transformed text retains the streamed response as a prefix,
+ printing only its suffix avoids duplicating the already-rendered body. A
+ replacement has no safe suffix, so deliberately print the complete final
+ response rather than silently dropping it.
+ """
+ if not result or not result.get("response_transformed"):
+ return ""
+
+ original = result.get("pre_transform_response") or ""
+ if original and response.startswith(original):
+ return response[len(original):]
+
+ return f"\n[Response transformed after streaming]\n{response}"
+
+
_OUTPUT_HISTORY_ENABLED = True
_OUTPUT_HISTORY_REPLAYING = False
_OUTPUT_HISTORY_SUPPRESSED = False
@@ -14445,13 +14464,11 @@ class HermesCLI(CLIAgentSetupMixin, CLICommandsMixin, CLIBillingMixin):
elif already_streamed:
# Response was already streamed token-by-token with box framing;
# _flush_stream() already closed the box. Skip Rich Panel.
- # If a plugin appended content (shout, trace) after streaming,
- # print only the appended portion now.
- if result and result.get("response_transformed"):
- _pre = result.get("pre_transform_response") or ""
- _appended = response[len(_pre):]
- if _appended.strip():
- _cprint(_appended)
+ # A transform hook runs after streaming. Show a suffix for
+ # append-only changes, or the complete replacement otherwise.
+ _post_stream_text = _post_stream_transform_output(response, result)
+ if _post_stream_text.strip():
+ _cprint(_post_stream_text)
else:
_chat_console = ChatConsole()
_chat_console.print(Panel(
diff --git a/gateway/hooks.py b/gateway/hooks.py
index 1ea7faa32a1..6ecba2a435b 100644
--- a/gateway/hooks.py
+++ b/gateway/hooks.py
@@ -30,6 +30,8 @@ Context dict passed to ``agent:start`` / ``agent:end`` handlers:
``agent:end`` adds:
response -- agent response text (truncated to 500 chars)
+ model -- model name that handled the turn
+ provider -- provider that handled the turn
Handlers posting a follow-up into the same Telegram forum-topic should
include ``message_thread_id=int(thread_id)`` when ``chat_type == "forum"``
diff --git a/gateway/run.py b/gateway/run.py
index 9430d197051..647a5d11f31 100644
--- a/gateway/run.py
+++ b/gateway/run.py
@@ -18113,6 +18113,7 @@ class GatewayRunner(GatewayAuthorizationMixin, GatewayKanbanWatchersMixin, Gatew
**hook_ctx,
"response": (response or "")[:500],
"model": agent_result.get("model", "") if agent_result else "",
+ "provider": agent_result.get("provider", "") if agent_result else "",
})
# Check for pending process watchers (check_interval on background processes)
diff --git a/tests/cli/test_transformed_stream_output.py b/tests/cli/test_transformed_stream_output.py
new file mode 100644
index 00000000000..f025d458d93
--- /dev/null
+++ b/tests/cli/test_transformed_stream_output.py
@@ -0,0 +1,31 @@
+"""Regression coverage for CLI delivery after transform_llm_output streaming."""
+
+from cli import _post_stream_transform_output
+
+
+def test_streamed_transform_prints_only_appended_suffix():
+ output = _post_stream_transform_output(
+ "original answer\n\n[plugin appended this]",
+ {
+ "response_transformed": True,
+ "pre_transform_response": "original answer",
+ },
+ )
+
+ assert output == "\n\n[plugin appended this]"
+
+
+def test_streamed_transform_prints_full_replacement_instead_of_dropping_it():
+ output = _post_stream_transform_output(
+ "XYZ",
+ {
+ "response_transformed": True,
+ "pre_transform_response": "abc",
+ },
+ )
+
+ assert output == "\n[Response transformed after streaming]\nXYZ"
+
+
+def test_untransformed_stream_has_no_post_stream_output():
+ assert _post_stream_transform_output("original answer", {}) == ""
diff --git a/tests/gateway/test_gateway_silence_tokens.py b/tests/gateway/test_gateway_silence_tokens.py
index 0cd1d593677..0af7eec226c 100644
--- a/tests/gateway/test_gateway_silence_tokens.py
+++ b/tests/gateway/test_gateway_silence_tokens.py
@@ -87,3 +87,111 @@ def test_blank_and_prose_mentions_are_not_silence():
assert not is_intentional_silence_response("The reply was [SILENT], intentionally.")
+def test_failed_agent_result_never_counts_as_intentional_silence():
+ assert is_intentional_silence_agent_result({"failed": False}, "NO_REPLY")
+ assert not is_intentional_silence_agent_result({"failed": True}, "NO_REPLY")
+
+
+async def test_silence_token_suppresses_delivery_but_preserves_transcript(monkeypatch, tmp_path):
+ runner = _runner(monkeypatch, tmp_path)
+ runner._run_agent = AsyncMock(return_value={
+ "final_response": "[SILENT]",
+ "messages": [
+ {"role": "user", "content": "side chatter"},
+ {"role": "assistant", "content": "[SILENT]"},
+ ],
+ "tools": [],
+ "history_offset": 0,
+ "last_prompt_tokens": 0,
+ "api_calls": 1,
+ "failed": False,
+ })
+
+ response = await runner._handle_message_with_agent(
+ _event(), _source(), "agent:main:telegram:group:-1001:12345", 1
+ )
+
+ assert response == ""
+ appended = [call.args[1] for call in runner.session_store.append_to_transcript.call_args_list]
+ assert {"role": "assistant", "content": "[SILENT]"}.items() <= appended[-1].items()
+ assert [msg["role"] for msg in appended if msg.get("role") in {"user", "assistant"}] == ["user", "assistant"]
+
+
+async def test_empty_success_still_gets_empty_response_warning(monkeypatch, tmp_path):
+ runner = _runner(monkeypatch, tmp_path)
+ runner._run_agent = AsyncMock(return_value={
+ "final_response": "",
+ "messages": [
+ {"role": "user", "content": "question"},
+ {"role": "assistant", "content": ""},
+ ],
+ "tools": [],
+ "history_offset": 0,
+ "last_prompt_tokens": 0,
+ "api_calls": 1,
+ "failed": False,
+ })
+
+ response = await runner._handle_message_with_agent(
+ _event(), _source(), "agent:main:telegram:group:-1001:12345", 1
+ )
+
+ assert "no response was generated" in response
+
+
+async def test_prose_mentioning_silence_token_is_delivered(monkeypatch, tmp_path):
+ runner = _runner(monkeypatch, tmp_path)
+ text = "Use [SILENT] when no answer is needed."
+ runner._run_agent = AsyncMock(return_value={
+ "final_response": text,
+ "messages": [
+ {"role": "user", "content": "question"},
+ {"role": "assistant", "content": text},
+ ],
+ "tools": [],
+ "history_offset": 0,
+ "last_prompt_tokens": 0,
+ "api_calls": 1,
+ "failed": False,
+ })
+
+ response = await runner._handle_message_with_agent(
+ _event(), _source(), "agent:main:telegram:group:-1001:12345", 1
+ )
+
+ assert response == text
+
+
+async def test_agent_end_hook_includes_model_and_provider(monkeypatch, tmp_path):
+ """Gateway hooks receive the actual model/provider for post-turn routing."""
+ runner = _runner(monkeypatch, tmp_path)
+ runner._run_agent = AsyncMock(return_value={
+ "final_response": "done",
+ "messages": [
+ {"role": "user", "content": "question"},
+ {"role": "assistant", "content": "done"},
+ ],
+ "tools": [],
+ "history_offset": 0,
+ "last_prompt_tokens": 0,
+ "api_calls": 1,
+ "failed": False,
+ "model": "gpt-5.6-terra",
+ "provider": "openai-codex",
+ })
+
+ await runner._handle_message_with_agent(
+ _event(), _source(), "agent:main:telegram:group:-1001:12345", 1
+ )
+
+ end_context = next(
+ call.args[1]
+ for call in runner.hooks.emit.await_args_list
+ if call.args[0] == "agent:end"
+ )
+ assert end_context["model"] == "gpt-5.6-terra"
+ assert end_context["provider"] == "openai-codex"
diff --git a/website/docs/user-guide/features/hooks.md b/website/docs/user-guide/features/hooks.md
index be8b9c0caa2..bda14cef915 100644
--- a/website/docs/user-guide/features/hooks.md
+++ b/website/docs/user-guide/features/hooks.md
@@ -1278,6 +1278,11 @@ def my_callback(
**Use cases:** Apply a personality/vocabulary transform (pirate-speak, Spongebob), redact user-specific identifiers from the final text, append a project-specific signature footer, enforce a house style guide without burning tokens on SOUL instructions.
+When CLI streaming is enabled, an append-only transform is printed after the
+streamed body. A transform that replaces the response is printed in full after
+the streamed body, labeled as a post-stream transformation, so replacement
+content is never silently lost.
+
```python
import os, re