Skip to content

AutoGPT is the vision of accessible AI for everyone, to use and to build on. Our mission is to provide the tools, so that you can focus on what matters.

fix(backend/copilot): suppress empty-completion overlay false positives (orphan-flush + specific error subtypes) (#13090)

Zamil Majdy04ac81c17b4a
diff --git a/autogpt_platform/backend/backend/copilot/sdk/response_adapter.py b/autogpt_platform/backend/backend/copilot/sdk/response_adapter.py
index b27e536987..74dd7d121a 100644
--- a/autogpt_platform/backend/backend/copilot/sdk/response_adapter.py
+++ b/autogpt_platform/backend/backend/copilot/sdk/response_adapter.py
@@ -59,6 +59,15 @@ logger = logging.getLogger(__name__)
_THINKING_COALESCE_MIN_CHARS = 64
_THINKING_COALESCE_MAX_INTERVAL_MS = 50.0
+# ResultMessage subtypes that carry their own user-facing reason (budget
+# exhaustion, max turns). The empty-completion guard skips these so the
+# more specific message — emitted by the subtype routing in the
+# ResultMessage branch — isn't shadowed by a generic "model returned an
+# empty response" overlay.
+_SPECIFIC_ERROR_SUBTYPES: frozenset[str] = frozenset(
+ {"error_max_budget_usd", "error_max_turns"}
+)
+
class SDKResponseAdapter:
"""Adapter for converting Claude Agent SDK messages to Vercel AI SDK format.
@@ -99,6 +108,12 @@ class SDKResponseAdapter:
# case so the turn renders as cleanly complete.
self._text_since_last_tool_result = False
self._any_tool_results_seen = False
+ # Like ``_any_tool_results_seen`` but excludes empty-fallback flushes
+ # (orphan tool_use blocks whose stash was empty at flush time). The
+ # empty-completion guard uses this to distinguish a turn where real
+ # tool output actually reached the wire from one where only synthetic
+ # empty placeholders were emitted for tools that never returned.
+ self._any_real_tool_result_seen = False
# Set by the ResultMessage branch when a thinking-only final turn is
# detected and we have not yet asked the model for a closing TextBlock.
# The driver in ``service.py`` reads this after ``_iter_sdk_messages``
@@ -175,6 +190,23 @@ class SDKResponseAdapter:
or self.prior_attempt_emitted_visible_content
)
+ @property
+ def emitted_real_content_to_wire(self) -> bool:
+ """Stricter variant of ``emitted_visible_content`` for the empty-
+ completion guard.
+
+ Includes text, real (non-empty-fallback) tool results, and the
+ retry-recreate forwarded flag. **Excludes** ``has_started_reasoning``:
+ a turn that emitted only ``ThinkingBlock``s without ever producing
+ text or a tool result is itself the failure mode the empty-completion
+ guard is meant to catch.
+ """
+ return (
+ self.has_started_text
+ or self._any_real_tool_result_seen
+ or self.prior_attempt_emitted_visible_content
+ )
+
def convert_message(self, sdk_message: Message) -> list[StreamBaseResponse]:
"""Convert a single SDK message to Vercel AI SDK format."""
responses: list[StreamBaseResponse] = []
@@ -417,6 +449,9 @@ class SDKResponseAdapter:
# ``ResultMessage`` time stays accurate.
self._text_since_last_tool_result = False
self._any_tool_results_seen = True
+ # Real tool result from the SDK — distinct from the orphan-
+ # flush empty-fallback path.
+ self._any_real_tool_result_seen = True
# Stale thinking from before this tool call must not
# contaminate the post-tool fallback — only the model's
# NEXT thinking block (after seeing the tool result)
@@ -546,7 +581,10 @@ class SDKResponseAdapter:
if sdk_message.subtype == "success":
responses.append(StreamFinish())
- elif sdk_message.subtype in ("error", "error_during_execution"):
+ elif sdk_message.subtype in (
+ "error",
+ "error_during_execution",
+ ):
raw_error = str(sdk_message.result or "Unknown error")
if is_transient_api_error(raw_error):
error_text, code = FRIENDLY_TRANSIENT_MSG, "transient_api_error"
@@ -554,6 +592,34 @@ class SDKResponseAdapter:
error_text, code = raw_error, "sdk_error"
responses.append(StreamError(errorText=error_text, code=code))
responses.append(StreamFinish())
+ elif sdk_message.subtype == "error_max_budget_usd":
+ # SDK signalled the per-turn USD budget was exhausted.
+ # Surface a specific message instead of the generic empty-
+ # completion overlay (which would shadow the real reason).
+ responses.append(
+ StreamError(
+ errorText=(
+ "The turn ended because it exceeded the budget. "
+ "Try a smaller scope, or wait for the next "
+ "billing window."
+ ),
+ code="max_budget_exhausted",
+ )
+ )
+ responses.append(StreamFinish())
+ elif sdk_message.subtype == "error_max_turns":
+ # SDK signalled the maximum number of LLM calls was reached.
+ responses.append(
+ StreamError(
+ errorText=(
+ "The turn ended because it reached the maximum "
+ "number of LLM calls. Break the task into "
+ "smaller steps."
+ ),
+ code="max_turns_exhausted",
+ )
+ )
+ responses.append(StreamFinish())
else:
logger.warning(
f"Unexpected ResultMessage subtype: {sdk_message.subtype}"
@@ -596,6 +662,19 @@ class SDKResponseAdapter:
the time the ResultMessage lands, ``current_tool_calls`` looks
fully resolved even though the actual tool_results were synthetic.
"""
+ # Specific error subtypes (budget exhaustion, max turns) carry their
+ # own user-facing reason — don't shadow them with the generic empty-
+ # completion overlay; the ResultMessage subtype branch handles them.
+ if msg.subtype in _SPECIFIC_ERROR_SUBTYPES:
+ return False
+ # If real user-visible content has already reached the wire this turn
+ # (or a prior attempt), an empty trailing ResultMessage is not a ghost
+ # finish from the user's perspective — surfacing the overlay would
+ # render on top of working output. Excludes the orphan-flush empty-
+ # fallback case (``_any_real_tool_result_seen`` is False there) so the
+ # orphan guard below still fires for truly silent tool failures.
+ if self.emitted_real_content_to_wire:
+ return False
if msg.subtype == "success" and self._is_empty_completion(msg):
return True
had_orphan_tool_use = (
@@ -943,6 +1022,9 @@ class SDKResponseAdapter:
)
self.resolved_tool_calls.add(tool_id)
flushed = True
+ # Real stashed output recovered — distinct from the empty-
+ # fallback branch below.
+ self._any_real_tool_result_seen = True
logger.info(
"[SDK] [%s] Flushed stashed output for %s (call %s, %d chars)",
sid,
diff --git a/autogpt_platform/backend/backend/copilot/sdk/response_adapter_test.py b/autogpt_platform/backend/backend/copilot/sdk/response_adapter_test.py
index a054dc9aab..35d2b37625 100644
--- a/autogpt_platform/backend/backend/copilot/sdk/response_adapter_test.py
+++ b/autogpt_platform/backend/backend/copilot/sdk/response_adapter_test.py
@@ -1886,3 +1886,263 @@ def test_emitted_visible_content_property_combines_signals():
adapter.prior_attempt_emitted_visible_content = True
assert adapter.emitted_visible_content is True
+
+
+def test_empty_completion_suppressed_when_real_tool_result_already_seen():
+ """Regression: a long turn that successfully resolved tool results earlier
+ (real ToolResultBlock content via UserMessage) then ends with a trailing
+ empty AssistantMessage plus an orphan flush must NOT fire the
+ empty_completion error — the user already received content earlier in
+ the turn (dev session b0e8ca83).
+ """
+ adapter = _adapter()
+ adapter.convert_message(SystemMessage(subtype="init", data={}))
+
+ # Stage 1: model emits a tool_use and the SDK returns a real tool_result.
+ adapter.convert_message(
+ AssistantMessage(
+ content=[
+ ToolUseBlock(
+ id="t-real",
+ name=f"{MCP_TOOL_PREFIX}find_block",
+ input={"query": "linkedin"},
+ )
+ ],
+ model="test",
+ )
+ )
+ adapter.convert_message(
+ UserMessage(
+ content=[
+ ToolResultBlock(
+ tool_use_id="t-real",
+ content='{"blocks": [{"id": "abc", "name": "PostToLinkedInBlock"}]}',
+ )
+ ],
+ )
+ )
+ assert adapter._any_real_tool_result_seen is True
+ assert adapter.emitted_real_content_to_wire is True
+
+ # Stage 2: model emits another tool_use that never resolves (orphan).
+ adapter.convert_message(
+ AssistantMessage(
+ content=[
+ ToolUseBlock(
+ id="t-orphan",
+ name=f"{MCP_TOOL_PREFIX}run_block",
+ input={"block_id": "abc"},
+ )
+ ],
+ model="test",
+ )
+ )
+
+ # Stage 3: empty trailing AssistantMessage (no flush triggered yet —
+ # empty content is_tool_only-vacuously-true).
+ adapter.convert_message(AssistantMessage(content=[], model="test"))
+ assert adapter._last_assistant_had_empty_content is True
+
+ # Stage 4: ResultMessage success with empty result. The ResultMessage
+ # branch flushes the orphan t-orphan (stash empty → empty-fallback
+ # emitted) which sets _any_orphan_flush_seen=True. Without the
+ # emitted_real_content_to_wire gate, path B fires
+ # (_any_orphan_flush_seen + _last_assistant_had_empty_content) and
+ # emits a spurious "model returned an empty response" overlay on top
+ # of the working find_block widget the user already saw.
+ msg = ResultMessage(
+ subtype="success",
+ duration_ms=100,
+ duration_api_ms=50,
+ is_error=False,
+ num_turns=1,
+ session_id="s1",
+ result="",
+ usage={"output_tokens": 0},
+ )
+ results = adapter.convert_message(msg)
+ types = [type(r).__name__ for r in results]
+ assert adapter._any_orphan_flush_seen is True
+ # The critical guarantee: NO empty-completion StreamError is emitted on
+ # top of the user's working content. The success branch may either emit
+ # StreamFinish directly or hand off to the thinking-only-reprompt path
+ # (which returns early without StreamFinish) — both are correct outcomes;
+ # the bug is specifically the spurious error overlay.
+ assert "StreamError" not in types
+
+
+def test_empty_completion_still_fires_on_orphan_with_only_empty_fallbacks():
+ """Counter-test: the SECRT-2333 guard must still fire when the orphan
+ flush only emitted empty fallbacks (no real tool result ever reached the
+ wire) and the trailing AssistantMessage was also empty. The fix only
+ suppresses the overlay when real content was seen.
+ """
+ adapter = _adapter()
+ adapter.convert_message(SystemMessage(subtype="init", data={}))
+ # Model emits tool_use that never produces a real tool_result.
+ adapter.convert_message(
+ AssistantMessage(
+ content=[
+ ToolUseBlock(
+ id="t-orphan",
+ name=f"{MCP_TOOL_PREFIX}run_block",
+ input={"block_id": "abc"},
+ )
+ ],
+ model="test",
+ )
+ )
+ # Empty trailing AssistantMessage — sets _last_assistant_had_empty_content.
+ adapter.convert_message(AssistantMessage(content=[], model="test"))
+ assert adapter._any_real_tool_result_seen is False
+ assert adapter.emitted_real_content_to_wire is False
+ # ResultMessage success — flush at ResultMessage time emits empty
+ # fallback for t-orphan (stash empty), sets _any_orphan_flush_seen.
+ # SECRT-2333 path B fires (orphan + empty last) because the gate
+ # doesn't suppress (no real content was seen).
+ msg = ResultMessage(
+ subtype="success",
+ duration_ms=100,
+ duration_api_ms=50,
+ is_error=False,
+ num_turns=1,
+ session_id="s1",
+ result="",
+ usage={"output_tokens": 0},
+ )
+ results = adapter.convert_message(msg)
+ assert adapter._any_orphan_flush_seen is True
+ err = next((r for r in results if isinstance(r, StreamError)), None)
+ assert err is not None
+ assert err.code == "empty_completion"
+
+
+def test_empty_completion_suppressed_when_text_already_streamed():
+ """Counter-test for the text path: a turn that emitted text early then
+ ends with an empty AssistantMessage + orphan flush must not fire the
+ overlay either. has_started_text alone is enough.
+ """
+ adapter = _adapter()
+ adapter.convert_message(SystemMessage(subtype="init", data={}))
+ adapter.convert_message(
+ AssistantMessage(content=[TextBlock(text="here's what I found:")], model="test")
+ )
+ assert adapter.has_started_text is True
+ # Orphan tool_use + empty trailing AssistantMessage + flush of empty stash.
+ adapter.convert_message(
+ AssistantMessage(
+ content=[
+ ToolUseBlock(
+ id="t-orphan",
+ name=f"{MCP_TOOL_PREFIX}run_block",
+ input={},
+ )
+ ],
+ model="test",
+ )
+ )
+ adapter.convert_message(AssistantMessage(content=[], model="test"))
+ msg = ResultMessage(
+ subtype="success",
+ duration_ms=100,
+ duration_api_ms=50,
+ is_error=False,
+ num_turns=1,
+ session_id="s1",
+ result="",
+ usage={"output_tokens": 0},
+ )
+ results = adapter.convert_message(msg)
+ types = [type(r).__name__ for r in results]
+ # Same as the prior test: success branch may hand off to thinking-only-
+ # reprompt instead of emitting StreamFinish directly; the critical bug
+ # we're guarding against is the spurious empty-completion overlay.
+ assert "StreamError" not in types
+
+
+def test_real_tool_result_flag_set_by_stashed_flush():
+ """The flush path must set _any_real_tool_result_seen=True when it pops
+ REAL stashed output, but NOT when it has to emit an empty fallback.
+ """
+ adapter = _adapter()
+ adapter.convert_message(SystemMessage(subtype="init", data={}))
+ # Initialise the stash ContextVar (normally done by set_execution_context).
+ _pto.set({})
+ # Simulate PostToolUse hook stashing real output for a built-in tool.
+ _stash("ReadFile", "file content here")
+ adapter.convert_message(
+ AssistantMessage(
+ content=[ToolUseBlock(id="t-real", name="ReadFile", input={"path": "/x"})],
+ model="test",
+ )
+ )
+ # AssistantMessage with non-tool content triggers flush
+ adapter.convert_message(
+ AssistantMessage(content=[TextBlock(text="done")], model="test")
+ )
+ assert adapter._any_real_tool_result_seen is True
+ assert adapter._any_orphan_flush_seen is True
+ # Cleanup
+ _pto.set({}) # type: ignore[arg-type]
+
+
+def test_error_max_budget_usd_surfaces_specific_error_not_empty_overlay():
+ """When the SDK ends a turn with subtype=``error_max_budget_usd``, the
+ user-facing error must be the specific budget-exhausted message — even
+ if the orphan-flush guard would otherwise have fired the generic
+ empty-completion overlay.
+ """
+ adapter = _adapter()
+ adapter.convert_message(SystemMessage(subtype="init", data={}))
+ # Mimic 835da550 prefix: tool_use with no real result, empty trailing
+ # AssistantMessage, then a budget-exhausted ResultMessage.
+ adapter.convert_message(
+ AssistantMessage(
+ content=[
+ ToolUseBlock(
+ id="t-budget",
+ name=f"{MCP_TOOL_PREFIX}run_block",
+ input={},
+ )
+ ],
+ model="test",
+ )
+ )
+ adapter.convert_message(AssistantMessage(content=[], model="test"))
+ msg = ResultMessage(
+ subtype="error_max_budget_usd",
+ duration_ms=100,
+ duration_api_ms=50,
+ is_error=True,
+ num_turns=1,
+ session_id="s1",
+ result="budget exhausted",
+ usage={"output_tokens": 0},
+ )
+ results = adapter.convert_message(msg)
+ errors = [r for r in results if isinstance(r, StreamError)]
+ assert len(errors) == 1
+ assert errors[0].code == "max_budget_exhausted"
+ assert "budget" in errors[0].errorText.lower()
+ # Must NOT shadow with empty_completion overlay.
+ assert all(e.code != "empty_completion" for e in errors)
+
+
+def test_error_max_turns_surfaces_specific_error():
+ """``error_max_turns`` should similarly route to its own message."""
+ adapter = _adapter()
+ adapter.convert_message(SystemMessage(subtype="init", data={}))
+ msg = ResultMessage(
+ subtype="error_max_turns",
+ duration_ms=100,
+ duration_api_ms=50,
+ is_error=True,
+ num_turns=999,
+ session_id="s1",
+ result="hit cap",
+ usage={"output_tokens": 0},
+ )
+ results = adapter.convert_message(msg)
+ err = next((r for r in results if isinstance(r, StreamError)), None)
+ assert err is not None
+ assert err.code == "max_turns_exhausted"
diff --git a/autogpt_platform/backend/backend/copilot/sdk/service.py b/autogpt_platform/backend/backend/copilot/sdk/service.py
index f929324fba..f6d403cd01 100644
--- a/autogpt_platform/backend/backend/copilot/sdk/service.py
+++ b/autogpt_platform/backend/backend/copilot/sdk/service.py
@@ -4516,10 +4516,13 @@ async def stream_chat_completion_sdk( # pyright: ignore[reportGeneralTypeIssues
# Carry the per-turn re-prompt cap forward so a transient
# retry mid-turn does not unlock another re-prompt round.
state.adapter.thinking_only_reprompted = state.thinking_only_reprompted
- # Forward prior visibility so the empty-completion guard on this
- # retry adapter doesn't false-fire on top of content the user
- # already received.
- if prior_adapter.emitted_visible_content:
+ # Forward only REAL prior content (text or non-empty-fallback
+ # tool result) so the empty-completion guard on this retry
+ # adapter is suppressed exactly when the user has actually
+ # received content — and not when the prior attempt only
+ # emitted reasoning, which would otherwise hide a genuinely
+ # silent failure on the retry.
+ if prior_adapter.emitted_real_content_to_wire:
state.adapter.prior_attempt_emitted_visible_content = True
# Reset token accumulators so a failed attempt's partial
# usage is not double-counted in the successful attempt.
diff --git a/autogpt_platform/backend/scripts/replay_session_trace.py b/autogpt_platform/backend/scripts/replay_session_trace.py
new file mode 100644
index 0000000000..7a9024301f
--- /dev/null
+++ b/autogpt_platform/backend/scripts/replay_session_trace.py
@@ -0,0 +1,204 @@
+#!/usr/bin/env python3
+"""Replay a langfuse-captured copilot session trace through the response adapter.
+
+Local debugging utility for investigating "empty response" / spurious-overlay
+incidents on dev or prod. Pulls the trace by session ID, reconstructs the SDK
+message stream the adapter would have seen (AssistantMessage / UserMessage /
+ResultMessage), and prints whether ``StreamError(code="empty_completion")``
+would fire — with the current adapter code in this checkout.
+
+Usage (must be run as a module so package imports resolve):
+ LANGFUSE_PUBLIC_KEY=... LANGFUSE_SECRET_KEY=... LANGFUSE_HOST=... \
+ poetry run python -m scripts.replay_session_trace <session_id> [<session_id> ...]
+
+Optional flags:
+ --subtype <subtype> ResultMessage subtype to cap the stream with
+ (default: success). Use error_max_budget_usd /
+ error_max_turns / error / error_during_execution
+ when investigating those failure modes.
+
+Does NOT make any modifications. Read-only against langfuse + the local
+adapter code.
+"""
+
+from __future__ import annotations
+
+import argparse
+import json
+import os
+import sys
+
+from claude_agent_sdk import (
+ AssistantMessage,
+ ContentBlock,
+ ResultMessage,
+ SystemMessage,
+ TextBlock,
+ ThinkingBlock,
+ ToolResultBlock,
+ ToolUseBlock,
+ UserMessage,
+)
+
+from backend.copilot.response_model import StreamError
+from backend.copilot.sdk.response_adapter import SDKResponseAdapter
+
+
+def _block_from_dict(b: dict) -> ContentBlock | None:
+ t = b.get("type")
+ if t == "text":
+ return TextBlock(text=b.get("text", ""))
+ if t == "thinking":
+ return ThinkingBlock(
+ thinking=b.get("thinking", ""),
+ signature=b.get("signature", ""),
+ )
+ if t == "tool_use":
+ return ToolUseBlock(
+ id=b.get("id", ""),
+ name=b.get("name", "unknown"),
+ input=b.get("input") or {},
+ )
+ return None
+
+
+def _fetch_observations(session_id: str) -> list[dict]:
+ """Pull the largest trace for the session and return its observations
+ sorted by start_time.
+ """
+ from langfuse import Langfuse
+
+ lf = Langfuse(
+ public_key=os.environ["LANGFUSE_PUBLIC_KEY"],
+ secret_key=os.environ["LANGFUSE_SECRET_KEY"],
+ host=os.environ["LANGFUSE_HOST"],
+ )
+ traces = lf.api.trace.list(session_id=session_id, limit=20).data
+ if not traces:
+ return []
+ best = max(traces, key=lambda t: len(t.observations or []))
+ trace = lf.api.trace.get(best.id)
+ obs = sorted(trace.observations or [], key=lambda o: o.start_time)
+ out: list[dict] = []
+ for o in obs:
+ if o.type == "GENERATION" and o.name == "claude.assistant.turn":
+ if o.output:
+ content = (
+ o.output.get("content", []) if isinstance(o.output, dict) else []
+ )
+ out.append({"kind": "assistant", "content": content})
+ elif o.type == "TOOL":
+ output = o.output
+ if not isinstance(output, str):
+ output = json.dumps(output) if output is not None else ""
+ # Capture the input so the replay can match this tool_result to
+ # the right pending ToolUseBlock when multiple same-name calls
+ # are outstanding (e.g. two parallel ``find_block`` calls).
+ inp = o.input if isinstance(o.input, dict) else {}
+ out.append(
+ {"kind": "tool_result", "name": o.name, "input": inp, "output": output}
+ )
+ return out
+
+
+def replay_session(session_id: str, result_subtype: str = "success") -> dict:
+ """Replay one session through a fresh adapter; return summary dict."""
+ sequence = _fetch_observations(session_id)
+ if not sequence:
+ return {"session_id": session_id, "error": "no traces found"}
+
+ adapter = SDKResponseAdapter(session_id=session_id)
+ events: list = []
+ events.extend(adapter.convert_message(SystemMessage(subtype="init", data={})))
+
+ # Map name -> list of (tool_use_id, input_dict) for outstanding calls.
+ # Match tool_results by (name, input) when possible — same-name parallel
+ # calls (e.g. two ``find_block`` with different queries) would otherwise
+ # be replayed against the wrong ToolUseBlock under FIFO-by-name.
+ unresolved: dict[str, list[tuple[str, dict]]] = {}
+ for step in sequence:
+ if step["kind"] == "assistant":
+ blocks: list[ContentBlock] = []
+ for raw in step.get("content", []):
+ block = _block_from_dict(raw)
+ if block is None:
+ continue
+ if isinstance(block, ToolUseBlock):
+ unresolved.setdefault(block.name, []).append(
+ (block.id, block.input or {})
+ )
+ blocks.append(block)
+ events.extend(
+ adapter.convert_message(AssistantMessage(content=blocks, model="test"))
+ )
+ elif step["kind"] == "tool_result":
+ queue = unresolved.get(step["name"]) or []
+ if not queue:
+ continue
+ # Prefer matching the queued call whose input matches the
+ # tool_result's input; fall back to FIFO if no input match.
+ target_input = step.get("input") or {}
+ match_idx = next(
+ (i for i, (_, inp) in enumerate(queue) if inp == target_input),
+ 0,
+ )
+ tool_use_id, _ = queue.pop(match_idx)
+ events.extend(
+ adapter.convert_message(
+ UserMessage(
+ content=[
+ ToolResultBlock(
+ tool_use_id=tool_use_id,
+ content=step.get("output") or "",
+ )
+ ],
+ )
+ )
+ )
+
+ events.extend(
+ adapter.convert_message(
+ ResultMessage(
+ subtype=result_subtype,
+ duration_ms=100,
+ duration_api_ms=50,
+ is_error=result_subtype != "success",
+ num_turns=1,
+ session_id=session_id,
+ result="",
+ usage={"output_tokens": 0},
+ )
+ )
+ )
+
+ stream_errors = [
+ {"code": e.code, "text": e.errorText[:120]}
+ for e in events
+ if isinstance(e, StreamError)
+ ]
+ return {
+ "session_id": session_id,
+ "subtype": result_subtype,
+ "steps": len(sequence),
+ "any_real_tool_result_seen": adapter._any_real_tool_result_seen,
+ "any_orphan_flush_seen": adapter._any_orphan_flush_seen,
+ "has_started_text": adapter.has_started_text,
+ "emitted_real_content_to_wire": adapter.emitted_real_content_to_wire,
+ "stream_errors": stream_errors,
+ }
+
+
+def main() -> int:
+ p = argparse.ArgumentParser(description=__doc__)
+ p.add_argument("session_ids", nargs="+")
+ p.add_argument("--subtype", default="success")
+ args = p.parse_args()
+
+ for sid in args.session_ids:
+ result = replay_session(sid, result_subtype=args.subtype)
+ print(json.dumps(result, indent=2, default=str))
+ return 0
+
+
+if __name__ == "__main__":
+ sys.exit(main())