Use Claude Code, Codex, VSCode, Pi, and OpenCode (and 6 other harnesses) for free (1.3B+ free tokens) from your terminal, app, IDE, or phone, and now from the browser with native browser sessions (multi-harness + multi-model) like OpenClaw (voice supported + ToS friendly)
Python
patch: remove generated reasoning headings (#2048)
Ali Khokharfa6adde24f1d
diff --git a/e2e/conftest.py b/e2e/conftest.pyindex bf4a655d..03b26761 100644--- a/e2e/conftest.py+++ b/e2e/conftest.py@@ -374,3 +374,6 @@ def close_browser_connections_before_server_teardown(yieldif not page.is_closed():page.goto("about:blank")+ # Context disposal can otherwise leak an unfinished route.fetch() error+ # into the next test's Playwright call.+ page.unroute_all(behavior="ignoreErrors")diff --git a/src/free_claude_code/core/anthropic/conversion.py b/src/free_claude_code/core/anthropic/conversion.pyindex 17fa5ec1..af3f7326 100644--- a/src/free_claude_code/core/anthropic/conversion.py+++ b/src/free_claude_code/core/anthropic/conversion.py@@ -10,7 +10,6 @@ from free_claude_code.core.history_replay import (HistoryReplayError,has_readable_replay,is_replay,- reasoning_context,reasoning_detail,tool_history_context,validate_hosted_tool_history,@@ -583,7 +582,7 @@ class AnthropicToOpenAIConverter:content_parts = [_think_tag_content(reasoning_content)if reasoning_replay == ReasoningReplayMode.THINK_TAGS- else reasoning_context(reasoning_content)+ else reasoning_content]if content:content_parts.append(content)@@ -692,7 +691,7 @@ class AnthropicToOpenAIConverter:details.append({"type": "reasoning.encrypted", "data": signature})if reasoning_replay == ReasoningReplayMode.DISABLED:if thinking:- content_parts.append(reasoning_context(thinking))+ content_parts.append(thinking)continueif reasoning_replay == ReasoningReplayMode.THINK_TAGS:content_parts.append(_think_tag_content(thinking))diff --git a/src/free_claude_code/core/history_replay.py b/src/free_claude_code/core/history_replay.pyindex 08fc6bef..e4bd09eb 100644--- a/src/free_claude_code/core/history_replay.py+++ b/src/free_claude_code/core/history_replay.py@@ -337,11 +337,6 @@ def _replay_readable(return native or readable_reasoning(item)-def reasoning_context(text: str, *, summary: bool = False) -> str:- label = "Earlier reasoning summary" if summary else "Earlier reasoning"- return f"[{label}]\n{text}" if text else ""--def tool_history_context(item: Mapping[str, JsonValue]) -> str:"""Keep available tool data as quoted history, never as new instructions."""return "[Earlier tool record]\n" + json.dumps(@@ -422,8 +417,7 @@ def responses_reasoning_blocks(item: Mapping[str, JsonValue]) -> list[JsonValue]if record is not None and readable_reasoning(record.native):return blocksblocks.extend(- {"type": "text", "text": reasoning_context(text, summary=summary)}- for text, summary in readable_reasoning(item)+ {"type": "text", "text": text} for text, _ in readable_reasoning(item))return blocks@@ -454,8 +448,7 @@ def prepare_history(projected.append(record.native)if not readable_reasoning(record.native):projected.extend(- _context_item(reasoning_context(text, summary=summary))- for text, summary in readable_reasoning(item)+ _context_item(text) for text, _ in readable_reasoning(item))continueif record is None and item.get("encrypted_content"):@@ -463,10 +456,8 @@ def prepare_history(item) # Older history: try native before precise recovery.continue- for text, summary in _replay_readable(item, record):- projected.append(- _context_item(reasoning_context(text, summary=summary))- )+ for text, _ in _replay_readable(item, record):+ projected.append(_context_item(text))result["input"] = projectedreturn resultmessages = result.get("messages")@@ -546,16 +537,14 @@ def _prepare_messages_content(message: JsonObject, destination: ReplayOrigin) ->blocks.append(record.native)if not readable_reasoning(record.native):blocks.extend(- {"type": "text", "text": reasoning_context(text, summary=summary)}- for text, summary in readable_reasoning(block)+ {"type": "text", "text": text}+ for text, _ in readable_reasoning(block))elif record is None and (block.get("signature") or block.get("data")):blocks.append(block)else:- for text, summary in _replay_readable(block, record):- blocks.append(- {"type": "text", "text": reasoning_context(text, summary=summary)}- )+ for text, _ in _replay_readable(block, record):+ blocks.append({"type": "text", "text": text})message["content"] = blocks@@ -622,9 +611,7 @@ def _prepare_chat_content(else text)else:- _append_context(- message, reasoning_context(text, summary=summary)- )+ _append_context(message, text)if restored:message["reasoning_details"] = restoredelse:@@ -633,7 +620,7 @@ def _prepare_chat_content(for key in ("reasoning_content", "reasoning"):text = message.pop(key, None)if isinstance(text, str) and text:- _append_context(message, reasoning_context(text))+ _append_context(message, text)if (had_reasoning_contentand reasoning_field == "reasoning_content"diff --git a/src/free_claude_code/core/openai_responses/chat_request.py b/src/free_claude_code/core/openai_responses/chat_request.pyindex 0f02ea48..8db179f3 100644--- a/src/free_claude_code/core/openai_responses/chat_request.py+++ b/src/free_claude_code/core/openai_responses/chat_request.py@@ -10,7 +10,6 @@ from free_claude_code.core.history_replay import (has_readable_replay,is_replay,readable_reasoning,- reasoning_context,reasoning_detail,tool_history_context,)@@ -344,7 +343,7 @@ class _ResponsesChatInputBuilder:if self._structured_reasoning_details:details.append({"type": "reasoning.summary", "summary": text})else:- contexts.append(reasoning_context(text, summary=True))+ contexts.append(text)if encrypted and not signed:details.extend(reasoning_detail(encrypted))if contexts:@@ -580,9 +579,7 @@ def _apply_reasoning_text()returnreplay = (- f"<think>\n{text}\n</think>"- if mode is ReasoningReplayMode.THINK_TAGS- else reasoning_context(text)+ f"<think>\n{text}\n</think>" if mode is ReasoningReplayMode.THINK_TAGS else text)if not replay:returndiff --git a/src/free_claude_code/providers/continuation.py b/src/free_claude_code/providers/continuation.pyindex da3acac5..ffeb4d7e 100644--- a/src/free_claude_code/providers/continuation.py+++ b/src/free_claude_code/providers/continuation.py@@ -9,7 +9,6 @@ from free_claude_code.core.delivered_response import (is_structured_text_format,)from free_claude_code.core.failures import ExecutionFailure, FailureKind-from free_claude_code.core.history_replay import reasoning_contextfrom free_claude_code.core.json_types import JsonObjectfrom free_claude_code.core.stream_recovery import (ContinuationSeed,@@ -237,7 +236,7 @@ def continuation_tail(seed: ContinuationSeed, *, tools: bool) -> list[dict[str,if tools:instruction += " No tool calls from this interrupted assistant turn were delivered or executed. Any unfinished calls were discarded. Emit the required tool calls using the provided tools."if seed.thinking:- instruction = f"{reasoning_context(seed.thinking)}\n\n{instruction}"+ instruction = f"{seed.thinking}\n\n{instruction}"tail = [{"role": "assistant", "content": seed.text}] if seed.text else []return [*tail, {"role": "user", "content": instruction}]diff --git a/src/free_claude_code/providers/history_replay.py b/src/free_claude_code/providers/history_replay.pyindex 224c3f4a..26a38bbc 100644--- a/src/free_claude_code/providers/history_replay.py+++ b/src/free_claude_code/providers/history_replay.py@@ -18,7 +18,6 @@ from free_claude_code.core.history_replay import (decode_replay,is_replay,readable_reasoning,- reasoning_context,resolve_messages_replay,)from free_claude_code.core.json_types import JsonValue@@ -181,8 +180,8 @@ def history_retry_body(item["id"] = correctedelse:context = "\n\n".join(- reasoning_context(text, summary=summary)- for text, summary in readable_reasoning(+ text+ for text, _ in readable_reasoning(originalif protocol != "chat"else {"reasoning_details": [original]}diff --git a/src/free_claude_code/providers/nvidia_nim/retry.py b/src/free_claude_code/providers/nvidia_nim/retry.pyindex 08b10dd8..fb64f201 100644--- a/src/free_claude_code/providers/nvidia_nim/retry.py+++ b/src/free_claude_code/providers/nvidia_nim/retry.py@@ -4,8 +4,6 @@ from collections.abc import Callablefrom copy import deepcopyfrom typing import Any-from free_claude_code.core.history_replay import reasoning_context-def clone_body_without_chat_template(body: dict[str, Any]) -> dict[str, Any] | None:"""Clone a request body and strip NIM chat-template control fields."""@@ -60,10 +58,11 @@ def _strip_message_reasoning_content(body: dict[str, Any]) -> bool:and reasoningand message.get("role") == "assistant"):- context = reasoning_context(reasoning)content = message.get("content")if isinstance(content, list):- content.append({"type": "text", "text": context})+ content.append({"type": "text", "text": reasoning})else:- message["content"] = f"{content}\n\n{context}" if content else context+ message["content"] = (+ f"{content}\n\n{reasoning}" if content else reasoning+ )return removeddiff --git a/tests/api/test_midstream_model_fallback.py b/tests/api/test_midstream_model_fallback.pyindex edeb956d..d96f4a09 100644--- a/tests/api/test_midstream_model_fallback.py+++ b/tests/api/test_midstream_model_fallback.py@@ -17,6 +17,7 @@ from tests.api.test_delivered_stream_recovery import (text_events,)from tests.api.test_hidden_stream_retries import partial_tool+from tests.api.test_recovery_reasoning import followed_by_text, reasoning_eventsfrom tests.api.test_response_streams import _servefrom tests.api.test_tool_call_buffer import _responsefrom tests.api.test_tool_call_buffer_transports import _tools@@ -114,6 +115,35 @@ async def test_exhausted_model_continues_on_next_candidate(source, target, wire))[email protected]("target", ["chat", "messages", "responses"])[email protected]("wire", ["messages", "responses"])+async def test_fallback_preserves_readable_reasoning_without_a_heading(target, wire):+ interrupted = followed_by_text(reasoning_events(closed=False), "Hello ")+ async with (+ _harness("responses", lambda _: (200, interrupted), max_attempts=1) as (+ first,+ _,+ _,+ ),+ _harness(target, lambda _: (200, text_events(target, "world."))) as (+ second,+ bodies,+ _,+ ),+ ):+ raw = await delivered_candidates([first, second], wire)++ assert len(bodies) == 1+ history = bodies[0].get("messages", bodies[0].get("input"))+ content = history[-1]["content"]+ instruction = content if isinstance(content, str) else content[0]["text"]+ assert instruction.split("\n\n", 1)[0] == "Find 17."+ events = parse_sse_text(raw)+ assert_completed(events, wire)+ assert public_text(events, wire) == "Hello world."++@pytest.mark.asyncio@pytest.mark.parametrize("protocol", ["chat", "messages", "responses"])@pytest.mark.parametrize("wire", ["messages", "responses"])diff --git a/tests/api/test_recovery_reasoning.py b/tests/api/test_recovery_reasoning.pyindex 987427f2..024eac26 100644--- a/tests/api/test_recovery_reasoning.py+++ b/tests/api/test_recovery_reasoning.py@@ -107,6 +107,9 @@ async def test_readable_reasoning_continues_from_released_content(field, closed,assert public_text(events, wire) == "Hello world."assert "Find 17." in str(bodies[1]["input"])assert "Hello " in str(bodies[1]["input"])+ assert (+ bodies[1]["input"][-1]["content"][0]["text"].split("\n\n", 1)[0] == "Find 17."+ )@pytest.mark.asynciodiff --git a/tests/core/openai_responses/test_chat_request.py b/tests/core/openai_responses/test_chat_request.pyindex 86fafa98..96e2979f 100644--- a/tests/core/openai_responses/test_chat_request.py+++ b/tests/core/openai_responses/test_chat_request.py@@ -224,7 +224,7 @@ def test_build_responses_chat_request_preserves_rich_supported_semantics() -> No(ReasoningReplayMode.THINK_TAGS, {"content": "<think>\nThink\n</think>"}),(ReasoningReplayMode.DISABLED,- {"content": "[Earlier reasoning]\nThink\n\nAnswer"},+ {"content": "Think\n\nAnswer"},),],)@@ -257,7 +257,7 @@ def test_build_responses_chat_request_uses_provider_reasoning_replay(if mode is ReasoningReplayMode.DISABLED:assert assistant == {"role": "assistant",- "content": "[Earlier reasoning]\nThink\n\nAnswer",+ "content": "Think\n\nAnswer",}diff --git a/tests/core/openai_responses/test_reasoning_replay.py b/tests/core/openai_responses/test_reasoning_replay.pyindex 480574bc..5028f580 100644--- a/tests/core/openai_responses/test_reasoning_replay.py+++ b/tests/core/openai_responses/test_reasoning_replay.py@@ -105,7 +105,7 @@ def test_completed_reasoning_keeps_both_display_and_opaque_replay() -> None:cast(JsonObject, body), ReplayOrigin("other", egress, "", "", "m"))serialized = json.dumps(projected)- assert "[Earlier reasoning]" in serialized+ assert "[Earlier reasoning]" not in serializedassert "visible" in serializedassert "opaque" not in serializedassert carrier not in serializeddiff --git a/tests/core/test_history_replay.py b/tests/core/test_history_replay.pyindex aab84ea0..6be718b4 100644--- a/tests/core/test_history_replay.py+++ b/tests/core/test_history_replay.py@@ -106,7 +106,7 @@ def test_foreign_readable_reasoning_keeps_context_without_ciphertext(protocol):result = prepare_history(saved, _origin("b", protocol))rendered = json.dumps(result)assert "Search for the value." in rendered- assert "summary" in rendered.lower()+ assert "[Earlier reasoning summary]" not in renderedassert "opaque-native" not in renderedassert "fcc:" not in renderedassert all(@@ -191,7 +191,7 @@ def test_chat_replay_keeps_full_text_and_summary_meaning(native_text):dict[str, Any],prepare_history(body, _origin("b", "chat"), scope=HistoryScope.ALL),)["messages"][0]- assert result["content"] == "answer\n\n[Earlier reasoning summary]\nShort summary."+ assert result["content"] == "answer\n\nShort summary."if native_text == "Short summary.":assert "reasoning_content" not in resultelse:@@ -199,6 +199,31 @@ def test_chat_replay_keeps_full_text_and_summary_meaning(native_text):assert body == original+ "thinking",+ [" Read first.\nThen edit. ", "[Earlier reasoning]\nOriginal text.", ""],+)+def test_plain_reasoning_context_preserves_original_text_and_history(thinking):+ body = {+ "messages": [+ {"role": "assistant", "content": "Answer.", "reasoning_content": thinking},+ {"role": "user", "content": "Continue."},+ ]+ }+ original = deepcopy(body)++ result = prepare_history(body, _origin(protocol="chat"))++ assert result["messages"] == [+ {+ "role": "assistant",+ "content": "Answer." + (f"\n\n{thinking}" if thinking else ""),+ },+ {"role": "user", "content": "Continue."},+ ]+ assert body == original++def _associated(part, data, *, group_id="group-a", origin=None):return encode_replay(AssociatedReplayRecord(diff --git a/tests/core/test_history_switching.py b/tests/core/test_history_switching.pyindex 5726dfdd..b259b5c5 100644--- a/tests/core/test_history_switching.py+++ b/tests/core/test_history_switching.py@@ -476,5 +476,5 @@ def test_destination_without_native_reasoning_keeps_readable_context(wire):)}rendered = json.dumps(body)- assert "[Earlier reasoning]" in rendered+ assert "[Earlier reasoning]" not in renderedassert "Preserve this thought." in rendereddiff --git a/tests/providers/test_chutes.py b/tests/providers/test_chutes.pyindex 2c5d5f48..069aa879 100644--- a/tests/providers/test_chutes.py+++ b/tests/providers/test_chutes.py@@ -112,10 +112,7 @@ def test_does_not_replay_reasoning_but_preserves_tool_history()assistant = body["messages"][1]- assert (- assistant["content"]- == "[Earlier reasoning]\nRead it first.\n\nI will inspect it."- )+ assert assistant["content"] == "Read it first.\n\nI will inspect it."assert assistant["tool_calls"][0]["id"] == "toolu_1"assert "reasoning_content" not in assistantassert "reasoning" not in assistantdiff --git a/tests/providers/test_cline_pass.py b/tests/providers/test_cline_pass.pyindex 77b3ca74..d97ae3e0 100644--- a/tests/providers/test_cline_pass.py+++ b/tests/providers/test_cline_pass.py@@ -273,10 +273,7 @@ def test_build_request_body_replays_only_opaque_reasoning_details(message for message in body["messages"] if message["role"] == "assistant")- assert (- assistant["content"]- == "[Earlier reasoning]\nNeed a tool.\n\nI will inspect it."- )+ assert assistant["content"] == "Need a tool.\n\nI will inspect it."assert assistant["reasoning_details"] == [detail]assert "reasoning" not in assistantassert "reasoning_content" not in assistantdiff --git a/tests/providers/test_converter.py b/tests/providers/test_converter.pyindex a41c7f0c..cff2e419 100644--- a/tests/providers/test_converter.py+++ b/tests/providers/test_converter.py@@ -814,10 +814,7 @@ def test_convert_assistant_message_thinking_becomes_context_when_disabled():assert len(result) == 1assert "reasoning_content" not in result[0]assert "<think>" not in result[0]["content"]- assert (- result[0]["content"]- == "[Earlier reasoning]\nI need to calculate this.\n\nThe answer is 4."- )+ assert result[0]["content"] == "I need to calculate this.\n\nThe answer is 4."def test_convert_assistant_top_level_reasoning_becomes_context_when_disabled():@@ -835,7 +832,7 @@ def test_convert_assistant_top_level_reasoning_becomes_context_when_disabled():assert result == [{"role": "assistant",- "content": "[Earlier reasoning]\nI need to calculate this.\n\nThe answer is 4.",+ "content": "I need to calculate this.\n\nThe answer is 4.",}]diff --git a/tests/providers/test_github_copilot_provider.py b/tests/providers/test_github_copilot_provider.pyindex c274d7a6..2e6d7415 100644--- a/tests/providers/test_github_copilot_provider.py+++ b/tests/providers/test_github_copilot_provider.py@@ -675,7 +675,7 @@ async def test_native_reasoning_carrier_replays_only_to_messages_egress(await collect(harness.provider.stream_responses(request))body = json.loads(harness.seen[0].content)wire = json.dumps(body)- assert "[Earlier reasoning]" in wire+ assert "[Earlier reasoning]" not in wireassert "private reasoning" in wireassert "exact-signature" not in wireassert carrier not in wirediff --git a/tests/providers/test_history_corrections.py b/tests/providers/test_history_corrections.pyindex c3f55e87..f9e74243 100644--- a/tests/providers/test_history_corrections.py+++ b/tests/providers/test_history_corrections.py@@ -59,7 +59,7 @@ def test_legacy_invalid_id_then_ciphertext_rejection_keeps_original():assert cleaned is not Noneassert cleaned["input"][1] == {"role": "assistant",- "content": "[Earlier reasoning summary]\nlook up 17",+ "content": "look up 17",}assert cleaned["input"][2:] == original["input"][2:]assert body == original@@ -140,7 +140,7 @@ def test_messages_signature_path_retains_readable_text_and_other_blocks():)assert result is not Noneassert result["messages"][0]["content"] == [- {"type": "text", "text": "[Earlier reasoning]\nread the file"},+ {"type": "text", "text": "read the file"},body["messages"][0]["content"][1],]diff --git a/tests/providers/test_history_transports.py b/tests/providers/test_history_transports.pyindex ad35145e..c74820ee 100644--- a/tests/providers/test_history_transports.py+++ b/tests/providers/test_history_transports.py@@ -356,7 +356,7 @@ async def test_legacy_responses_id_then_cipher_rejection_recovers_without_changiassert bodies[1]["input"][0]["encrypted_content"] == "opaque-original"assert bodies[2]["input"][0] == {"role": "assistant",- "content": "[Earlier reasoning summary]\nFind 17.",+ "content": "Find 17.",}assert all(body["reasoning"] == bodies[0]["reasoning"] for body in bodies)assert history == originaldiff --git a/tests/providers/test_huggingface.py b/tests/providers/test_huggingface.pyindex e84f4822..8733697d 100644--- a/tests/providers/test_huggingface.py+++ b/tests/providers/test_huggingface.py@@ -208,7 +208,7 @@ def test_build_request_body_does_not_replay_prior_thinking_blocks(assert body["messages"] == [{"role": "assistant",- "content": "[Earlier reasoning]\nhidden prior thought\n\nvisible answer",+ "content": "hidden prior thought\n\nvisible answer",}]assert "reasoning_content" not in body["messages"][0]@@ -234,7 +234,7 @@ def test_build_request_body_does_not_replay_top_level_reasoning_content(assert body["messages"] == [{"role": "assistant",- "content": "[Earlier reasoning]\nhidden prior reasoning\n\nvisible answer",+ "content": "hidden prior reasoning\n\nvisible answer",}]assert "hidden prior reasoning" in str(body)diff --git a/tests/providers/test_lmstudio.py b/tests/providers/test_lmstudio.pyindex 9184cf9d..dc28b1f2 100644--- a/tests/providers/test_lmstudio.py+++ b/tests/providers/test_lmstudio.py@@ -272,7 +272,7 @@ def test_build_request_body_never_replays_prior_thinking(lmstudio_provider):roles = [m.get("role") for m in body.get("messages", [])]assert "assistant_reasoning_content" not in roles- assert "[Earlier reasoning]" in str(body)+ assert "[Earlier reasoning]" not in str(body)assert "prior reasoning" in str(body)diff --git a/tests/providers/test_nvidia_nim.py b/tests/providers/test_nvidia_nim.pyindex 4b624381..39f3e9fb 100644--- a/tests/providers/test_nvidia_nim.py+++ b/tests/providers/test_nvidia_nim.py@@ -1376,9 +1376,7 @@ async def test_stream_messages_retries_without_reasoning_content(nim_provider):second_call = mock_create.await_args_list[1].kwargsassert first_call["messages"][0]["reasoning_content"] == "Need the tool."assert "reasoning_content" not in second_call["messages"][0]- assert (- "[Earlier reasoning]\nNeed the tool." in second_call["messages"][0]["content"]- )+ assert "Need the tool." in second_call["messages"][0]["content"]assert second_call["messages"][0]["tool_calls"][0]["id"] == "toolu_reasoning"assert any("Recovered" in event for event in events)assert any("message_stop" in event for event in events)diff --git a/tests/providers/test_openai_api_sampling.py b/tests/providers/test_openai_api_sampling.pyindex 7701d550..8e6c8ef7 100644--- a/tests/providers/test_openai_api_sampling.py+++ b/tests/providers/test_openai_api_sampling.py@@ -379,7 +379,7 @@ async def test_history_and_sampling_corrections_preserve_each_other(history_firsif error is history_error:expected["input"][0] = {"role": "assistant",- "content": "[Earlier reasoning summary]\nSaved reasoning",+ "content": "Saved reasoning",}else:expected.pop("temperature")diff --git a/tests/providers/test_wandb.py b/tests/providers/test_wandb.pyindex 9cf0d665..576cd780 100644--- a/tests/providers/test_wandb.py+++ b/tests/providers/test_wandb.py@@ -117,7 +117,7 @@ def test_build_request_body_drops_undocumented_reasoning_replay_but_keeps_tools(assert body["messages"][1] == {"role": "assistant",- "content": "[Earlier reasoning]\nRead it first.\n\nI will inspect it.",+ "content": "Read it first.\n\nI will inspect it.","tool_calls": [{"id": "toolu_1",