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): preserve thinking blocks during transcript compaction (#12574)
Zamil Majdyf28628e34bd1
diff --git a/autogpt_platform/backend/backend/copilot/sdk/conftest.py b/autogpt_platform/backend/backend/copilot/sdk/conftest.pyindex 3084c1cfd4..99f125afd4 100644--- a/autogpt_platform/backend/backend/copilot/sdk/conftest.py+++ b/autogpt_platform/backend/backend/copilot/sdk/conftest.py@@ -25,24 +25,64 @@ def build_test_transcript(pairs: list[tuple[str, str]]) -> str:Use this helper in any copilot SDK test that needs a well-formedtranscript without hitting the real storage layer.++ Delegates to ``build_structured_transcript`` — plain content strings+ are automatically wrapped in ``[{"type": "text", "text": ...}]`` for+ assistant messages.+ """+ # Cast widening: tuple[str, str] is structurally compatible with+ # tuple[str, str | list[dict]] but list invariance requires explicit+ # annotation.+ widened: list[tuple[str, str | list[dict]]] = list(pairs)+ return build_structured_transcript(widened)+++def build_structured_transcript(+ entries: list[tuple[str, str | list[dict]]],+) -> str:+ """Build a JSONL transcript with structured content blocks.++ Each entry is (role, content) where content is either a plain string+ (for user messages) or a list of content block dicts (for assistant+ messages with thinking/tool_use/text blocks).++ Example::++ build_structured_transcript([+ ("user", "Hello"),+ ("assistant", [+ {"type": "thinking", "thinking": "...", "signature": "sig1"},+ {"type": "text", "text": "Hi there"},+ ]),+ ])"""lines: list[str] = []last_uuid: str | None = None- for role, content in pairs:+ for role, content in entries:uid = str(uuid4())entry_type = "assistant" if role == "assistant" else "user"- msg: dict = {"role": role, "content": content}- if role == "assistant":- msg.update(- {- "model": "",- "id": f"msg_{uid[:8]}",- "type": "message",- "content": [{"type": "text", "text": content}],- "stop_reason": "end_turn",- "stop_sequence": None,- }- )+ if role == "assistant" and isinstance(content, list):+ msg: dict = {+ "role": "assistant",+ "model": "claude-test",+ "id": f"msg_{uid[:8]}",+ "type": "message",+ "content": content,+ "stop_reason": "end_turn",+ "stop_sequence": None,+ }+ elif role == "assistant":+ msg = {+ "role": "assistant",+ "model": "claude-test",+ "id": f"msg_{uid[:8]}",+ "type": "message",+ "content": [{"type": "text", "text": content}],+ "stop_reason": "end_turn",+ "stop_sequence": None,+ }+ else:+ msg = {"role": role, "content": content}entry = {"type": entry_type,"uuid": uid,diff --git a/autogpt_platform/backend/backend/copilot/sdk/prompt_too_long_test.py b/autogpt_platform/backend/backend/copilot/sdk/prompt_too_long_test.pyindex 31fb9e78a8..7d00e05163 100644--- a/autogpt_platform/backend/backend/copilot/sdk/prompt_too_long_test.py+++ b/autogpt_platform/backend/backend/copilot/sdk/prompt_too_long_test.py@@ -442,8 +442,11 @@ class TestCompactTranscript:assert result is not Noneassert validate_transcript(result)msgs = _transcript_to_messages(result)- assert len(msgs) == 2+ # 3 messages: compressed prefix (2) + preserved last assistant (1)+ assert len(msgs) == 3assert msgs[1]["content"] == "Summarized response"+ # The last assistant entry is preserved verbatim from original+ assert msgs[2]["content"] == "Details"@pytest.mark.asyncioasync def test_returns_none_on_compression_failure(self, mock_chat_config):diff --git a/autogpt_platform/backend/backend/copilot/sdk/response_adapter.py b/autogpt_platform/backend/backend/copilot/sdk/response_adapter.pyindex 764a6eb9c9..81b36f43a8 100644--- a/autogpt_platform/backend/backend/copilot/sdk/response_adapter.py+++ b/autogpt_platform/backend/backend/copilot/sdk/response_adapter.py@@ -15,6 +15,7 @@ from claude_agent_sdk import (ResultMessage,SystemMessage,TextBlock,+ ThinkingBlock,ToolResultBlock,ToolUseBlock,UserMessage,@@ -100,6 +101,11 @@ class SDKResponseAdapter:StreamTextDelta(id=self.text_block_id, delta=block.text))+ elif isinstance(block, ThinkingBlock):+ # Thinking blocks are preserved in the transcript but+ # not streamed to the frontend — skip silently.+ pass+elif isinstance(block, ToolUseBlock):self._end_text_if_open(responses)diff --git a/autogpt_platform/backend/backend/copilot/sdk/retry_scenarios_test.py b/autogpt_platform/backend/backend/copilot/sdk/retry_scenarios_test.pyindex dca02a4829..8606d2053d 100644--- a/autogpt_platform/backend/backend/copilot/sdk/retry_scenarios_test.py+++ b/autogpt_platform/backend/backend/copilot/sdk/retry_scenarios_test.py@@ -124,8 +124,11 @@ class TestScenarioCompactAndRetry:assert result != original # Must be differentassert validate_transcript(result)msgs = _transcript_to_messages(result)- assert len(msgs) == 2+ # 3 messages: compressed prefix (2) + preserved last assistant (1)+ assert len(msgs) == 3assert msgs[0]["content"] == "[summary of conversation]"+ # Last assistant preserved verbatim+ assert msgs[2]["content"] == "Long answer 2"def test_compacted_transcript_loads_into_builder(self):"""TranscriptBuilder can load a compacted transcript and continue."""@@ -737,7 +740,10 @@ class TestRetryEdgeCases:assert result is not Noneassert result != transcriptmsgs = _transcript_to_messages(result)- assert len(msgs) == 2+ # 3 messages: compressed prefix (2) + preserved last assistant (1)+ assert len(msgs) == 3+ # Last assistant preserved verbatim+ assert msgs[2]["content"] == "Answer 19"def test_messages_to_transcript_roundtrip_preserves_content(self):"""Verify messages → transcript → messages preserves all content."""diff --git a/autogpt_platform/backend/backend/copilot/sdk/service.py b/autogpt_platform/backend/backend/copilot/sdk/service.pyindex 06679765a0..4ea6d48b28 100644--- a/autogpt_platform/backend/backend/copilot/sdk/service.py+++ b/autogpt_platform/backend/backend/copilot/sdk/service.py@@ -670,7 +670,9 @@ def _format_sdk_content_blocks(blocks: list) -> list[dict[str, Any]]:"""Convert SDK content blocks to transcript format.Handles TextBlock, ToolUseBlock, ToolResultBlock, and ThinkingBlock.- Unknown block types are logged and skipped.+ Raw dicts (e.g. ``redacted_thinking`` blocks that the SDK may not have+ a typed class for) are passed through verbatim to preserve them in the+ transcript. Unknown typed block objects are logged and skipped."""result: list[dict[str, Any]] = []for block in blocks or []:@@ -702,6 +704,9 @@ def _format_sdk_content_blocks(blocks: list) -> list[dict[str, Any]]:"signature": block.signature,})+ elif isinstance(block, dict) and "type" in block:+ # Preserve raw dict blocks (e.g. redacted_thinking) verbatim.+ result.append(block)else:logger.warning(f"[SDK] Unknown content block type: {type(block).__name__}. "diff --git a/autogpt_platform/backend/backend/copilot/sdk/thinking_blocks_test.py b/autogpt_platform/backend/backend/copilot/sdk/thinking_blocks_test.pynew file mode 100644index 0000000000..3397160a55--- /dev/null+++ b/autogpt_platform/backend/backend/copilot/sdk/thinking_blocks_test.py@@ -0,0 +1,822 @@+"""Tests for thinking/redacted_thinking block preservation.++Validates the fix for the Anthropic API error:+ "thinking or redacted_thinking blocks in the latest assistant message+ cannot be modified. These blocks must remain as they were in the+ original response."++The API requires that thinking blocks in the LAST assistant message are+preserved value-identical. Older assistant messages may have thinking blocks+stripped entirely. This test suite covers:++ 1. _flatten_assistant_content — strips thinking from older messages+ 2. compact_transcript — preserves last assistant's thinking blocks+ 3. response_adapter — handles ThinkingBlock without error+ 4. _format_sdk_content_blocks — preserves redacted_thinking blocks+"""++from __future__ import annotations++from unittest.mock import AsyncMock, patch++import pytest+from claude_agent_sdk import AssistantMessage, TextBlock, ThinkingBlock++from backend.copilot.response_model import (+ StreamStartStep,+ StreamTextDelta,+ StreamTextStart,+)+from backend.util import json++from .conftest import build_structured_transcript+from .response_adapter import SDKResponseAdapter+from .service import _format_sdk_content_blocks+from .transcript import (+ _find_last_assistant_entry,+ _flatten_assistant_content,+ _messages_to_transcript,+ _rechain_tail,+ _transcript_to_messages,+ compact_transcript,+ validate_transcript,+)++# ---------------------------------------------------------------------------+# Fixtures: realistic thinking block content+# ---------------------------------------------------------------------------++THINKING_BLOCK = {+ "type": "thinking",+ "thinking": "Let me analyze the user's request carefully...",+ "signature": "ErUBCkYIAxgCIkD0V2MsRXPkuGolGexaW9V1kluijxXGF",+}++REDACTED_THINKING_BLOCK = {+ "type": "redacted_thinking",+ "data": "EmwKAhgBEgy2VEE8PJaS2oLJCPkaT...",+}+++def _make_thinking_transcript() -> str:+ """Build a transcript with thinking blocks in multiple assistant turns.++ Layout:+ User 1 → Assistant 1 (thinking + text + tool_use)+ User 2 (tool_result) → Assistant 2 (thinking + text)+ User 3 → Assistant 3 (thinking + redacted_thinking + text) ← LAST+ """+ return build_structured_transcript(+ [+ ("user", "What files are in this project?"),+ (+ "assistant",+ [+ {+ "type": "thinking",+ "thinking": "I should list the files.",+ "signature": "sig_old_1",+ },+ {"type": "text", "text": "Let me check the files."},+ {+ "type": "tool_use",+ "id": "tu1",+ "name": "list_files",+ "input": {"path": "/"},+ },+ ],+ ),+ ("user", "Here are the files: a.py, b.py"),+ (+ "assistant",+ [+ {+ "type": "thinking",+ "thinking": "Good, I see two Python files.",+ "signature": "sig_old_2",+ },+ {"type": "text", "text": "I found a.py and b.py."},+ ],+ ),+ ("user", "Tell me about a.py"),+ (+ "assistant",+ [+ THINKING_BLOCK,+ REDACTED_THINKING_BLOCK,+ {"type": "text", "text": "a.py contains the main entry point."},+ ],+ ),+ ]+ )+++def _last_assistant_content(transcript_jsonl: str) -> list[dict] | None:+ """Extract the content blocks of the last assistant entry in a transcript."""+ last_content = None+ for line in transcript_jsonl.strip().split("\n"):+ entry = json.loads(line)+ msg = entry.get("message", {})+ if msg.get("role") == "assistant":+ last_content = msg.get("content")+ return last_content+++# ---------------------------------------------------------------------------+# _find_last_assistant_entry — unit tests+# ---------------------------------------------------------------------------+++class TestFindLastAssistantEntry:+ def test_splits_at_last_assistant(self):+ """Prefix contains everything before last assistant; tail starts at it."""+ transcript = build_structured_transcript(+ [+ ("user", "Hello"),+ ("assistant", [{"type": "text", "text": "Hi"}]),+ ("user", "More"),+ ("assistant", [{"type": "text", "text": "Details"}]),+ ]+ )+ prefix, tail = _find_last_assistant_entry(transcript)+ # 3 entries in prefix (user, assistant, user), 1 in tail (last assistant)+ assert len(prefix) == 3+ assert len(tail) == 1++ def test_no_assistant_returns_all_in_prefix(self):+ """When there's no assistant, all lines are in prefix, tail is empty."""+ transcript = build_structured_transcript(+ [("user", "Hello"), ("user", "Another question")]+ )+ prefix, tail = _find_last_assistant_entry(transcript)+ assert len(prefix) == 2+ assert tail == []++ def test_assistant_at_index_zero(self):+ """When assistant is the first entry, prefix is empty."""+ transcript = build_structured_transcript(+ [("assistant", [{"type": "text", "text": "Start"}])]+ )+ prefix, tail = _find_last_assistant_entry(transcript)+ assert prefix == []+ assert len(tail) == 1++ def test_trailing_user_included_in_tail(self):+ """User message after last assistant is part of the tail."""+ transcript = build_structured_transcript(+ [+ ("user", "Q1"),+ ("assistant", [{"type": "text", "text": "A1"}]),+ ("user", "Q2"),+ ]+ )+ prefix, tail = _find_last_assistant_entry(transcript)+ assert len(prefix) == 1 # first user+ assert len(tail) == 2 # last assistant + trailing user++ def test_multi_entry_turn_fully_preserved(self):+ """An assistant turn spanning multiple JSONL entries (same message.id)+ must be entirely in the tail, not split across prefix and tail."""+ # Build manually because build_structured_transcript generates unique ids+ lines = [+ json.dumps(+ {+ "type": "user",+ "uuid": "u1",+ "parentUuid": "",+ "message": {"role": "user", "content": "Hello"},+ }+ ),+ json.dumps(+ {+ "type": "assistant",+ "uuid": "a1-think",+ "parentUuid": "u1",+ "message": {+ "role": "assistant",+ "id": "msg_same_turn",+ "type": "message",+ "content": [THINKING_BLOCK],+ "stop_reason": None,+ "stop_sequence": None,+ },+ }+ ),+ json.dumps(+ {+ "type": "assistant",+ "uuid": "a1-tool",+ "parentUuid": "u1",+ "message": {+ "role": "assistant",+ "id": "msg_same_turn",+ "type": "message",+ "content": [+ {+ "type": "tool_use",+ "id": "tu1",+ "name": "Bash",+ "input": {},+ },+ ],+ "stop_reason": "tool_use",+ "stop_sequence": None,+ },+ }+ ),+ ]+ transcript = "\n".join(lines) + "\n"+ prefix, tail = _find_last_assistant_entry(transcript)+ # Both assistant entries share msg_same_turn → both in tail+ assert len(prefix) == 1 # only the user entry+ assert len(tail) == 2 # both assistant entries (thinking + tool_use)++ def test_no_message_id_preserves_last_assistant(self):+ """When the last assistant entry has no message.id, it should still+ be preserved in the tail (fail closed) rather than being compressed."""+ lines = [+ json.dumps(+ {+ "type": "user",+ "uuid": "u1",+ "parentUuid": "",+ "message": {"role": "user", "content": "Hello"},+ }+ ),+ json.dumps(+ {+ "type": "assistant",+ "uuid": "a1",+ "parentUuid": "u1",+ "message": {+ "role": "assistant",+ "content": [THINKING_BLOCK, {"type": "text", "text": "Hi"}],+ },+ }+ ),+ ]+ transcript = "\n".join(lines) + "\n"+ prefix, tail = _find_last_assistant_entry(transcript)+ assert len(prefix) == 1 # user entry+ assert len(tail) == 1 # assistant entry preserved+++# ---------------------------------------------------------------------------+# _rechain_tail — UUID chain patching+# ---------------------------------------------------------------------------+++class TestRechainTail:+ def test_patches_first_entry_parentuuid(self):+ """First tail entry's parentUuid should point to last prefix uuid."""+ prefix = _messages_to_transcript(+ [+ {"role": "user", "content": "Hello"},+ {"role": "assistant", "content": "Hi"},+ ]+ )+ # Get the last uuid from the prefix+ last_prefix_uuid = None+ for line in prefix.strip().split("\n"):+ entry = json.loads(line)+ last_prefix_uuid = entry.get("uuid")++ tail_lines = [+ json.dumps(+ {+ "type": "assistant",+ "uuid": "tail-a1",+ "parentUuid": "old-parent",+ "message": {+ "role": "assistant",+ "content": [{"type": "text", "text": "Tail msg"}],+ },+ }+ )+ ]+ result = _rechain_tail(prefix, tail_lines)+ entry = json.loads(result.strip())+ assert entry["parentUuid"] == last_prefix_uuid+ assert entry["uuid"] == "tail-a1" # uuid preserved++ def test_chains_multiple_tail_entries(self):+ """Subsequent tail entries chain to each other."""+ prefix = _messages_to_transcript([{"role": "user", "content": "Hi"}])+ tail_lines = [+ json.dumps(+ {+ "type": "assistant",+ "uuid": "t1",+ "parentUuid": "old1",+ "message": {"role": "assistant", "content": []},+ }+ ),+ json.dumps(+ {+ "type": "user",+ "uuid": "t2",+ "parentUuid": "old2",+ "message": {"role": "user", "content": "Follow-up"},+ }+ ),+ ]+ result = _rechain_tail(prefix, tail_lines)+ entries = [json.loads(ln) for ln in result.strip().split("\n")]+ assert len(entries) == 2+ # Second entry's parentUuid should be first entry's uuid+ assert entries[1]["parentUuid"] == "t1"++ def test_empty_tail_returns_empty(self):+ """No tail entries → empty string."""+ prefix = _messages_to_transcript([{"role": "user", "content": "Hi"}])+ assert _rechain_tail(prefix, []) == ""++ def test_preserves_message_content_verbatim(self):+ """Tail message content (including thinking blocks) must not be modified."""+ prefix = _messages_to_transcript([{"role": "user", "content": "Hi"}])+ original_content = [+ THINKING_BLOCK,+ REDACTED_THINKING_BLOCK,+ {"type": "text", "text": "Response"},+ ]+ tail_lines = [+ json.dumps(+ {+ "type": "assistant",+ "uuid": "t1",+ "parentUuid": "old",+ "message": {+ "role": "assistant",+ "content": original_content,+ },+ }+ )+ ]+ result = _rechain_tail(prefix, tail_lines)+ entry = json.loads(result.strip())+ assert entry["message"]["content"] == original_content+++# ---------------------------------------------------------------------------+# _flatten_assistant_content — thinking blocks+# ---------------------------------------------------------------------------+++class TestFlattenThinkingBlocks:+ def test_thinking_blocks_are_stripped(self):+ """Thinking blocks should not appear in flattened text for compression."""+ blocks = [+ {"type": "thinking", "thinking": "secret thoughts", "signature": "sig"},+ {"type": "text", "text": "Hello user"},+ ]+ result = _flatten_assistant_content(blocks)+ assert "secret thoughts" not in result+ assert "Hello user" in result++ def test_redacted_thinking_blocks_are_stripped(self):+ """Redacted thinking blocks should not appear in flattened text."""+ blocks = [+ {"type": "redacted_thinking", "data": "encrypted_data"},+ {"type": "text", "text": "Response text"},+ ]+ result = _flatten_assistant_content(blocks)+ assert "encrypted_data" not in result+ assert "Response text" in result++ def test_thinking_only_message_flattens_to_empty(self):+ """A message with only thinking blocks flattens to empty string."""+ blocks = [+ {"type": "thinking", "thinking": "just thinking...", "signature": "sig"},+ ]+ result = _flatten_assistant_content(blocks)+ assert result == ""++ def test_mixed_thinking_text_tool(self):+ """Mixed blocks: only text and tool_use survive flattening."""+ blocks = [+ {"type": "thinking", "thinking": "hmm", "signature": "sig"},+ {"type": "redacted_thinking", "data": "xyz"},+ {"type": "text", "text": "I'll read the file."},+ {"type": "tool_use", "name": "Read", "input": {"path": "/x"}},+ ]+ result = _flatten_assistant_content(blocks)+ assert "hmm" not in result+ assert "xyz" not in result+ assert "I'll read the file." in result+ assert "[tool_use: Read]" in result+++# ---------------------------------------------------------------------------+# compact_transcript — thinking block preservation+# ---------------------------------------------------------------------------+++class TestCompactTranscriptThinkingBlocks:+ """Verify that compact_transcript preserves thinking blocks in the+ last assistant message while stripping them from older messages."""++ @pytest.mark.asyncio+ async def test_last_assistant_thinking_blocks_preserved(self, mock_chat_config):+ """After compaction, the last assistant entry must retain its+ original thinking and redacted_thinking blocks verbatim."""+ transcript = _make_thinking_transcript()++ compacted_msgs = [+ {"role": "user", "content": "[conversation summary]"},+ {"role": "assistant", "content": "Summarized response"},+ ]+ mock_result = type(+ "CompressResult",+ (),+ {+ "was_compacted": True,+ "messages": compacted_msgs,+ "original_token_count": 800,+ "token_count": 200,+ "messages_summarized": 4,+ "messages_dropped": 0,+ },+ )()+ with patch(+ "backend.copilot.sdk.transcript._run_compression",+ new_callable=AsyncMock,+ return_value=mock_result,+ ):+ result = await compact_transcript(transcript, model="test-model")++ assert result is not None+ assert validate_transcript(result)++ last_content = _last_assistant_content(result)+ assert last_content is not None, "No assistant entry found"+ assert isinstance(last_content, list)++ # The last assistant must have the thinking blocks preserved+ block_types = [b["type"] for b in last_content]+ assert (+ "thinking" in block_types+ ), "thinking block missing from last assistant message"+ assert (+ "redacted_thinking" in block_types+ ), "redacted_thinking block missing from last assistant message"+ assert "text" in block_types++ # Verify the thinking block content is value-identical+ thinking_blocks = [b for b in last_content if b["type"] == "thinking"]+ assert len(thinking_blocks) == 1+ assert thinking_blocks[0]["thinking"] == THINKING_BLOCK["thinking"]+ assert thinking_blocks[0]["signature"] == THINKING_BLOCK["signature"]++ redacted_blocks = [b for b in last_content if b["type"] == "redacted_thinking"]+ assert len(redacted_blocks) == 1+ assert redacted_blocks[0]["data"] == REDACTED_THINKING_BLOCK["data"]++ @pytest.mark.asyncio+ async def test_older_assistant_thinking_blocks_stripped(self, mock_chat_config):+ """Older assistant messages should NOT retain thinking blocks+ after compaction (they're compressed into summaries)."""+ transcript = _make_thinking_transcript()++ # The compressor will receive messages where older assistant+ # entries have already had thinking blocks stripped.+ captured_messages: list[dict] = []++ async def mock_compression(messages, model, log_prefix):+ captured_messages.extend(messages)+ return type(+ "CompressResult",+ (),+ {+ "was_compacted": True,+ "messages": messages,+ "original_token_count": 800,+ "token_count": 400,+ "messages_summarized": 2,+ "messages_dropped": 0,+ },+ )()++ with patch(+ "backend.copilot.sdk.transcript._run_compression",+ side_effect=mock_compression,+ ):+ await compact_transcript(transcript, model="test-model")++ # Check that the messages sent to compression don't contain+ # thinking content from older assistant messages+ for msg in captured_messages:+ if msg["role"] == "assistant":+ content = msg.get("content", "")+ assert (+ "I should list the files." not in content+ ), "Old thinking block content leaked into compression input"+ assert (+ "Good, I see two Python files." not in content+ ), "Old thinking block content leaked into compression input"++ @pytest.mark.asyncio+ async def test_trailing_user_message_after_last_assistant(self, mock_chat_config):+ """When the last entry is a user message, the last *assistant*+ message's thinking blocks should still be preserved."""+ transcript = build_structured_transcript(+ [+ ("user", "Hello"),+ (+ "assistant",+ [+ THINKING_BLOCK,+ {"type": "text", "text": "Hi there"},+ ],+ ),+ ("user", "Follow-up question"),+ ]+ )++ # The compressor only receives the prefix (1 user message); the+ # tail (assistant + trailing user) is preserved verbatim.+ compacted_msgs = [+ {"role": "user", "content": "Hello"},+ ]+ mock_result = type(+ "CompressResult",+ (),+ {+ "was_compacted": True,+ "messages": compacted_msgs,+ "original_token_count": 400,+ "token_count": 100,+ "messages_summarized": 0,+ "messages_dropped": 0,+ },+ )()+ with patch(+ "backend.copilot.sdk.transcript._run_compression",+ new_callable=AsyncMock,+ return_value=mock_result,+ ):+ result = await compact_transcript(transcript, model="test-model")++ assert result is not None++ last_content = _last_assistant_content(result)+ assert last_content is not None+ assert isinstance(last_content, list)+ block_types = [b["type"] for b in last_content]+ assert (+ "thinking" in block_types+ ), "thinking block lost from last assistant despite trailing user msg"++ @pytest.mark.asyncio+ async def test_single_assistant_with_thinking_preserved(self, mock_chat_config):+ """When there's only one assistant message (which is also the last),+ its thinking blocks must be preserved."""+ transcript = build_structured_transcript(+ [+ ("user", "Hello"),+ (+ "assistant",+ [+ THINKING_BLOCK,+ {"type": "text", "text": "World"},+ ],+ ),+ ]+ )++ compacted_msgs = [+ {"role": "user", "content": "Hello"},+ {"role": "assistant", "content": "World"},+ ]+ mock_result = type(+ "CompressResult",+ (),+ {+ "was_compacted": True,+ "messages": compacted_msgs,+ "original_token_count": 200,+ "token_count": 100,+ "messages_summarized": 0,+ "messages_dropped": 0,+ },+ )()+ with patch(+ "backend.copilot.sdk.transcript._run_compression",+ new_callable=AsyncMock,+ return_value=mock_result,+ ):+ result = await compact_transcript(transcript, model="test-model")++ assert result is not None++ last_content = _last_assistant_content(result)+ assert last_content is not None+ assert isinstance(last_content, list)+ block_types = [b["type"] for b in last_content]+ assert "thinking" in block_types++ @pytest.mark.asyncio+ async def test_tail_parentuuid_rewired_to_prefix(self, mock_chat_config):+ """After compaction, the first tail entry's parentUuid must point to+ the last entry in the compressed prefix — not its original parent."""+ transcript = _make_thinking_transcript()++ compacted_msgs = [+ {"role": "user", "content": "[conversation summary]"},+ {"role": "assistant", "content": "Summarized response"},+ ]+ mock_result = type(+ "CompressResult",+ (),+ {+ "was_compacted": True,+ "messages": compacted_msgs,+ "original_token_count": 800,+ "token_count": 200,+ "messages_summarized": 4,+ "messages_dropped": 0,+ },+ )()+ with patch(+ "backend.copilot.sdk.transcript._run_compression",+ new_callable=AsyncMock,+ return_value=mock_result,+ ):+ result = await compact_transcript(transcript, model="test-model")++ assert result is not None+ lines = [ln for ln in result.strip().split("\n") if ln.strip()]+ entries = [json.loads(ln) for ln in lines]++ # Find the boundary: the compressed prefix ends just before the+ # first tail entry (last assistant in original transcript).+ tail_start = None+ for i, entry in enumerate(entries):+ msg = entry.get("message", {})+ if isinstance(msg.get("content"), list):+ # Structured content = preserved tail entry+ tail_start = i+ break++ assert tail_start is not None, "Could not find preserved tail entry"+ assert tail_start > 0, "Tail should not be the first entry"++ # The tail entry's parentUuid must be the uuid of the preceding entry+ prefix_last_uuid = entries[tail_start - 1]["uuid"]+ tail_first_parent = entries[tail_start]["parentUuid"]+ assert tail_first_parent == prefix_last_uuid, (+ f"Tail parentUuid {tail_first_parent!r} != "+ f"last prefix uuid {prefix_last_uuid!r}"+ )++ @pytest.mark.asyncio+ async def test_no_thinking_blocks_still_works(self, mock_chat_config):+ """Compaction should still work normally when there are no thinking+ blocks in the transcript."""+ transcript = build_structured_transcript(+ [+ ("user", "Hello"),+ ("assistant", [{"type": "text", "text": "Hi"}]),+ ("user", "More"),+ ("assistant", [{"type": "text", "text": "Details"}]),+ ]+ )++ compacted_msgs = [+ {"role": "user", "content": "[summary]"},+ {"role": "assistant", "content": "Summary"},+ ]+ mock_result = type(+ "CompressResult",+ (),+ {+ "was_compacted": True,+ "messages": compacted_msgs,+ "original_token_count": 200,+ "token_count": 50,+ "messages_summarized": 2,+ "messages_dropped": 0,+ },+ )()+ with patch(+ "backend.copilot.sdk.transcript._run_compression",+ new_callable=AsyncMock,+ return_value=mock_result,+ ):+ result = await compact_transcript(transcript, model="test-model")++ assert result is not None+ assert validate_transcript(result)+ # Verify last assistant content is preserved even without thinking blocks+ last_content = _last_assistant_content(result)+ assert last_content is not None+ assert last_content == [{"type": "text", "text": "Details"}]+++# ---------------------------------------------------------------------------+# _transcript_to_messages — thinking block handling+# ---------------------------------------------------------------------------+++class TestTranscriptToMessagesThinking:+ def test_thinking_blocks_excluded_from_flattened_content(self):+ """When _transcript_to_messages flattens content, thinking block+ text should not leak into the message content string."""+ transcript = build_structured_transcript(+ [+ ("user", "Hello"),+ (+ "assistant",+ [+ {+ "type": "thinking",+ "thinking": "SECRET_THOUGHT",+ "signature": "sig",+ },+ {"type": "text", "text": "Visible response"},+ ],+ ),+ ]+ )+ messages = _transcript_to_messages(transcript)+ assistant_msg = [m for m in messages if m["role"] == "assistant"][0]+ assert "SECRET_THOUGHT" not in assistant_msg["content"]+ assert "Visible response" in assistant_msg["content"]+++# ---------------------------------------------------------------------------+# response_adapter — ThinkingBlock handling+# ---------------------------------------------------------------------------+++class TestResponseAdapterThinkingBlock:+ def test_thinking_block_does_not_crash(self):+ """ThinkingBlock in AssistantMessage should not cause an error."""+ adapter = SDKResponseAdapter(message_id="msg-1", session_id="sess-1")+ msg = AssistantMessage(+ content=[+ ThinkingBlock(+ thinking="Let me think about this...",+ signature="sig_test_123",+ ),+ TextBlock(text="Here is my response."),+ ],+ model="claude-test",+ )+ results = adapter.convert_message(msg)+ # Should produce stream events for text only, no crash+ types = [type(r) for r in results]+ assert StreamStartStep in types+ assert StreamTextStart in types or StreamTextDelta in types++ def test_thinking_block_does_not_emit_stream_events(self):+ """ThinkingBlock should NOT produce any StreamTextDelta events+ containing thinking content."""+ adapter = SDKResponseAdapter(message_id="msg-1", session_id="sess-1")+ msg = AssistantMessage(+ content=[+ ThinkingBlock(+ thinking="My secret thoughts",+ signature="sig_test_456",+ ),+ TextBlock(text="Public response"),+ ],+ model="claude-test",+ )+ results = adapter.convert_message(msg)+ text_deltas = [r for r in results if isinstance(r, StreamTextDelta)]+ for delta in text_deltas:+ assert "secret thoughts" not in (delta.delta or "")+++# ---------------------------------------------------------------------------+# _format_sdk_content_blocks — redacted_thinking handling+# ---------------------------------------------------------------------------+++class TestFormatSdkContentBlocks:+ def test_thinking_block_preserved(self):+ """ThinkingBlock should be serialized with type, thinking, and signature."""+ blocks = [+ ThinkingBlock(thinking="My thoughts", signature="sig123"),+ TextBlock(text="Response"),+ ]+ result = _format_sdk_content_blocks(blocks)+ assert len(result) == 2+ assert result[0] == {+ "type": "thinking",+ "thinking": "My thoughts",+ "signature": "sig123",+ }+ assert result[1] == {"type": "text", "text": "Response"}++ def test_raw_dict_redacted_thinking_preserved(self):+ """Raw dict blocks (e.g. redacted_thinking) pass through unchanged."""+ raw_block = {"type": "redacted_thinking", "data": "EmwKAh...encrypted"}+ blocks = [+ raw_block,+ TextBlock(text="Response"),+ ]+ result = _format_sdk_content_blocks(blocks)+ assert len(result) == 2+ assert result[0] == raw_block+ assert result[1] == {"type": "text", "text": "Response"}diff --git a/autogpt_platform/backend/backend/copilot/sdk/transcript.py b/autogpt_platform/backend/backend/copilot/sdk/transcript.pyindex 16a8f63756..dbdaf78d13 100644--- a/autogpt_platform/backend/backend/copilot/sdk/transcript.py+++ b/autogpt_platform/backend/backend/copilot/sdk/transcript.py@@ -605,20 +605,31 @@ COMPACT_MSG_ID_PREFIX = "msg_compact_"ENTRY_TYPE_MESSAGE = "message"+_THINKING_BLOCK_TYPES = frozenset({"thinking", "redacted_thinking"})++def _flatten_assistant_content(blocks: list) -> str:"""Flatten assistant content blocks into a single plain-text string.Structured ``tool_use`` blocks are converted to ``[tool_use: name]``- placeholders. This is intentional: ``compress_context`` requires plain- text for token counting and LLM summarization. The structural loss is- acceptable because compaction only runs when the original transcript was- already too large for the model — a summarized plain-text version is- better than no context at all.+ placeholders. ``thinking`` and ``redacted_thinking`` blocks are+ silently dropped — they carry no useful context for compression+ summaries and must not leak into compacted transcripts (the Anthropic+ API requires thinking blocks in the last assistant message to be+ value-identical to the original response; including stale thinking+ text would violate that constraint).++ This is intentional: ``compress_context`` requires plain text for+ token counting and LLM summarization. The structural loss is+ acceptable because compaction only runs when the original transcript+ was already too large for the model."""parts: list[str] = []for block in blocks:if isinstance(block, dict):btype = block.get("type", "")+ if btype in _THINKING_BLOCK_TYPES:+ continueif btype == "text":parts.append(block.get("text", ""))elif btype == "tool_use":@@ -805,6 +816,68 @@ async def _run_compression()+def _find_last_assistant_entry(+ content: str,+) -> tuple[list[str], list[str]]:+ """Split JSONL lines into (compressible_prefix, preserved_tail).++ The tail starts at the **first** entry of the last assistant turn and+ includes everything after it (typically trailing user messages). An+ assistant turn can span multiple consecutive JSONL entries sharing the+ same ``message.id`` (e.g., a thinking entry followed by a tool_use+ entry). All entries of the turn are preserved verbatim.++ The Anthropic API requires that ``thinking`` and ``redacted_thinking``+ blocks in the **last** assistant message remain value-identical to the+ original response (the API validates parsed signature values, not raw+ JSON bytes). By excluding the entire turn from compression we+ guarantee those blocks are never altered.++ Returns ``(all_lines, [])`` when no assistant entry is found.+ """+ lines = [ln for ln in content.strip().split("\n") if ln.strip()]++ # Parse all lines once to avoid double JSON deserialization.+ # json.loads with fallback=None returns Any; non-dict entries are+ # safely skipped by the isinstance(entry, dict) guards below.+ parsed: list = [json.loads(ln, fallback=None) for ln in lines]++ # Reverse scan: find the message.id and index of the last assistant entry.+ last_asst_msg_id: str | None = None+ last_asst_idx: int | None = None+ for i in range(len(parsed) - 1, -1, -1):+ entry = parsed[i]+ if not isinstance(entry, dict):+ continue+ msg = entry.get("message", {})+ if msg.get("role") == "assistant":+ last_asst_idx = i+ last_asst_msg_id = msg.get("id")+ break++ if last_asst_idx is None:+ return lines, []++ # If the assistant entry has no message.id, fall back to preserving+ # from that single entry onward — safer than compressing everything.+ if last_asst_msg_id is None:+ return lines[:last_asst_idx], lines[last_asst_idx:]++ # Forward scan: find the first entry of this turn (same message.id).+ first_turn_idx: int | None = None+ for i, entry in enumerate(parsed):+ if not isinstance(entry, dict):+ continue+ msg = entry.get("message", {})+ if msg.get("role") == "assistant" and msg.get("id") == last_asst_msg_id:+ first_turn_idx = i+ break++ if first_turn_idx is None:+ return lines, []+ return lines[:first_turn_idx], lines[first_turn_idx:]++async def compact_transcript(content: str,*,@@ -816,42 +889,50 @@ async def compact_transcript(Converts transcript entries to plain messages, runs ``compress_context``(the same compressor used for pre-query history), and rebuilds JSONL.- Structured content (``tool_use`` blocks, ``tool_result`` nesting, images)- is flattened to plain text for compression. This matches the fidelity of- the Plan C (DB compression) fallback path, where- ``_format_conversation_context`` similarly renders tool calls as- ``You called tool: name(args)`` and results as ``Tool result: ...``.- Neither path preserves structured API content blocks — the compacted- context serves as text history for the LLM, which creates proper- structured tool calls going forward.+ The **last assistant entry** (and any entries after it) are preserved+ verbatim — never flattened or compressed. The Anthropic API requires+ ``thinking`` and ``redacted_thinking`` blocks in the latest assistant+ message to be value-identical to the original response (the API+ validates parsed signature values, not raw JSON bytes); compressing+ them would destroy the cryptographic signatures and cause+ ``invalid_request_error``.- Images are per-turn attachments loaded from workspace storage by file ID- (via ``_prepare_file_attachments``), not part of the conversation history.- They are re-attached each turn and are unaffected by compaction.+ Structured content in *older* assistant entries (``tool_use`` blocks,+ ``thinking`` blocks, ``tool_result`` nesting, images) is flattened to+ plain text for compression. This matches the fidelity of the Plan C+ (DB compression) fallback path.Returns the compacted JSONL string, or ``None`` on failure.See also:``_compress_messages`` in ``service.py`` — compresses ``ChatMessage``- lists for pre-query DB history. Both share ``compress_context()``- but operate on different input formats (JSONL transcript entries- here vs. ChatMessage dicts there).+ lists for pre-query DB history."""- messages = _transcript_to_messages(content)- if len(messages) < 2:- logger.warning("%s Too few messages to compact (%d)", log_prefix, len(messages))+ prefix_lines, tail_lines = _find_last_assistant_entry(content)++ # Build the JSONL string for the compressible prefix+ prefix_content = "\n".join(prefix_lines) + "\n" if prefix_lines else ""+ messages = _transcript_to_messages(prefix_content) if prefix_content else []++ if len(messages) + len(tail_lines) < 2:+ total = len(messages) + len(tail_lines)+ logger.warning("%s Too few messages to compact (%d)", log_prefix, total)+ return None+ if not messages:+ logger.warning("%s Nothing to compress (only tail entries remain)", log_prefix)return Nonetry:result = await _run_compression(messages, model, log_prefix)if not result.was_compacted:- # Compressor says it's within budget, but the SDK rejected it.- # Return None so the caller falls through to DB fallback.logger.warning("%s Compressor reports within budget but SDK rejected — ""signalling failure",log_prefix,)return None+ if not result.messages:+ logger.warning("%s Compressor returned empty messages", log_prefix)+ return Nonelogger.info("%s Compacted transcript: %d->%d tokens (%d summarized, %d dropped)",log_prefix,@@ -860,7 +941,29 @@ async def compact_transcript(result.messages_summarized,result.messages_dropped,)- compacted = _messages_to_transcript(result.messages)+ compressed_part = _messages_to_transcript(result.messages)++ # Re-append the preserved tail (last assistant + trailing entries)+ # with parentUuid patched to chain onto the compressed prefix.+ tail_part = _rechain_tail(compressed_part, tail_lines)+ compacted = compressed_part + tail_part++ if len(compacted) >= len(content):+ # Byte count can increase due to preserved tail entries+ # (thinking blocks, JSON overhead) even when token count+ # decreased. Log a warning but still return — the API+ # validates tokens not bytes, and the caller falls through+ # to DB fallback if the transcript is still too large.+ logger.warning(+ "%s Compacted transcript (%d bytes) is not smaller than "+ "original (%d bytes) — may still reduce token count",+ log_prefix,+ len(compacted),+ len(content),+ )+ # Authoritative validation — the caller (_reduce_context) also+ # validates, but this is the canonical check that guarantees we+ # never return a malformed transcript from this function.if not validate_transcript(compacted):logger.warning("%s Compacted transcript failed validation", log_prefix)return None@@ -870,3 +973,43 @@ async def compact_transcript("%s Transcript compaction failed: %s", log_prefix, e, exc_info=True)return None+++def _rechain_tail(compressed_prefix: str, tail_lines: list[str]) -> str:+ """Patch tail entries so their parentUuid chain links to the compressed prefix.++ The first tail entry's ``parentUuid`` is set to the ``uuid`` of the+ last entry in the compressed prefix. Subsequent tail entries are+ rechained to point to their predecessor in the tail — their original+ ``parentUuid`` values may reference entries that were compressed away.+ """+ if not tail_lines:+ return ""+ # Find the last uuid in the compressed prefix+ last_prefix_uuid = ""+ for line in reversed(compressed_prefix.strip().split("\n")):+ if not line.strip():+ continue+ entry = json.loads(line, fallback=None)+ if isinstance(entry, dict) and "uuid" in entry:+ last_prefix_uuid = entry["uuid"]+ break++ result_lines: list[str] = []+ prev_uuid: str | None = None+ for i, line in enumerate(tail_lines):+ entry = json.loads(line, fallback=None)+ if not isinstance(entry, dict):+ # Safety guard: _find_last_assistant_entry already filters empty+ # lines, and well-formed JSONL always parses to dicts. Non-dict+ # lines are passed through unchanged; prev_uuid is intentionally+ # NOT updated so the next dict entry chains to the last known uuid.+ result_lines.append(line)+ continue+ if i == 0:+ entry["parentUuid"] = last_prefix_uuid+ elif prev_uuid is not None:+ entry["parentUuid"] = prev_uuid+ prev_uuid = entry.get("uuid")+ result_lines.append(json.dumps(entry, separators=(",", ":")))+ return "\n".join(result_lines) + "\n"