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
Preserve reasoning history when switching providers (#1717)
Ali Khokharf094ae217f5b
diff --git a/pyproject.toml b/pyproject.tomlindex 6d164ff4..cf3e44cb 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -4,7 +4,7 @@ build-backend = "hatchling.build"[project]name = "free-claude-code"-version = "6.1.3"+version = "6.1.4"description = "Local proxy connecting coding agents to OpenAI-compatible AI providers"readme = "README.md"requires-python = ">=3.14.0"diff --git a/src/free_claude_code/core/anthropic/conversion.py b/src/free_claude_code/core/anthropic/conversion.pyindex 46ce097a..f232cd8f 100644--- a/src/free_claude_code/core/anthropic/conversion.py+++ b/src/free_claude_code/core/anthropic/conversion.py@@ -6,9 +6,19 @@ from dataclasses import dataclass, fieldfrom enum import StrEnumfrom typing import Any+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,+)from free_claude_code.core.json_types import JsonObjectfrom free_claude_code.core.openai_chat import (IMAGE_TOOL_RESULT_MARKER,+ ChatToolResultImages,close_chat_tool_result_turns,image_tool_result_label,)@@ -178,15 +188,6 @@ def _assert_no_forbidden_assistant_block(block: Any) -> None:raise OpenAIConversionError("Assistant image blocks are not supported for OpenAI chat conversion.")- if block_type in (- "server_tool_use",- "web_search_tool_result",- "web_fetch_tool_result",- ):- raise OpenAIConversionError(- "OpenAI chat conversion does not support Anthropic server tool blocks "- f"({block_type!r} in an assistant message). Remove the unsupported block."- )def _openai_system_text(@@ -266,7 +267,7 @@ def _openai_chat_tool_result(block: Any) -> _OpenAIChatToolResult:"tool_call_id": tool_id,"content": IMAGE_TOOL_RESULT_MARKER,},- rich_user_message={"role": "user", "content": rich_parts},+ rich_user_message=ChatToolResultImages(role="user", content=rich_parts),)@@ -518,6 +519,19 @@ class AnthropicToOpenAIConverter:# Reserve the downstream system role for request.system at index zero.return [_PlainSegment([{"role": "user", "content": system_text}])]if role == "assistant" and isinstance(content, list):+ try:+ validate_hosted_tool_history(+ [+ {+ "type": get_block_type(block),+ "id": get_block_attr(block, "id", None),+ "tool_use_id": get_block_attr(block, "tool_use_id", None),+ }+ for block in content+ ]+ )+ except HistoryReplayError as error:+ raise OpenAIConversionError(str(error)) from errorif (first_i := _index_first_tool_use(content)) is not None:for block in content:if get_block_type(block) == "tool_use":@@ -554,10 +568,15 @@ class AnthropicToOpenAIConverter:converted, reasoning_content, reasoning_replay)elif (- reasoning_replay == ReasoningReplayMode.THINK_TAGS+ reasoning_replay+ in {ReasoningReplayMode.THINK_TAGS, ReasoningReplayMode.DISABLED}and reasoning_content):- content_parts = [_think_tag_content(reasoning_content)]+ content_parts = [+ _think_tag_content(reasoning_content)+ if reasoning_replay == ReasoningReplayMode.THINK_TAGS+ else reasoning_context(reasoning_content)+ ]if content:content_parts.append(content)converted["content"] = "\n\n".join(content_parts)@@ -574,7 +593,12 @@ class AnthropicToOpenAIConverter:reasoning_content: str | None,reasoning_replay: ReasoningReplayMode,) -> _ToolTurnSegment:- pre = content[:first_tool_index]+ pre = [+ block+ for index, block in enumerate(content)+ if index < first_tool_index+ or get_block_type(block) in {"thinking", "redacted_thinking"}+ ]tool_calls = _iter_tool_uses_in_order(content)if not tool_calls:return _ToolTurnSegment(@@ -588,6 +612,11 @@ class AnthropicToOpenAIConverter:deferred_blocks = _deferred_post_tool_blocks(content, first_tool_index=first_tool_index)+ deferred_blocks = [+ block+ for block in deferred_blocks+ if get_block_type(block) not in {"thinking", "redacted_thinking"}+ ]pre_msg: dict[str, Any]if not pre:@@ -612,7 +641,6 @@ class AnthropicToOpenAIConverter:assistant_message=pre_msg,required_tool_ids=_tool_call_ids(tool_calls),deferred_blocks=deferred_blocks,- top_level_reasoning=reasoning_content,reasoning_replay=reasoning_replay,)@@ -627,23 +655,42 @@ class AnthropicToOpenAIConverter:thinking_parts: list[str] = []thinking_seen = Falsetool_calls: list[dict[str, Any]] = []+ details: list[Any] = []for block in content:block_type = get_block_type(block)if block_type == "text":content_parts.append(get_block_attr(block, "text", ""))elif block_type == "thinking":+ signature = get_block_attr(block, "signature", None)+ if is_replay(signature):+ details.extend(reasoning_detail(signature))+ if has_readable_replay(signature):+ continue+ thinking = get_block_attr(block, "thinking", "")if reasoning_replay == ReasoningReplayMode.DISABLED:+ if thinking:+ content_parts.append(reasoning_context(thinking))continue- thinking = get_block_attr(block, "thinking", "")if reasoning_replay == ReasoningReplayMode.THINK_TAGS:content_parts.append(_think_tag_content(thinking))elif reasoning_content is None:thinking_seen = Truethinking_parts.append(thinking)elif block_type == "redacted_thinking":- # Opaque provider continuation data; do not materialize as model-visible text- # or native reasoning fields for OpenAI chat upstreams.- continue+ data = get_block_attr(block, "data", None)+ if isinstance(data, str) and data:+ details.extend(reasoning_detail(data))+ elif block_type in {+ "server_tool_use",+ "web_search_tool_result",+ "web_fetch_tool_result",+ }:+ value = (+ block+ if isinstance(block, dict)+ else block.model_dump(mode="json", exclude_none=True)+ )+ content_parts.append(tool_history_context(value))elif block_type == "tool_use":tool_calls.append(_tool_call_from_tool_use(block))else:@@ -657,6 +704,8 @@ class AnthropicToOpenAIConverter:"role": "assistant","content": content_str,}+ if details:+ msg["reasoning_details"] = detailsif tool_calls:msg["tool_calls"] = tool_callsif _reasoning_replay_field(reasoning_replay) is not None:diff --git a/src/free_claude_code/core/anthropic/native_stream.py b/src/free_claude_code/core/anthropic/native_stream.pyindex 4c97220a..2ea0a166 100644--- a/src/free_claude_code/core/anthropic/native_stream.py+++ b/src/free_claude_code/core/anthropic/native_stream.py@@ -2,9 +2,14 @@import jsonfrom collections.abc import Mapping-from dataclasses import dataclass, field+from dataclasses import dataclass, field, replacefrom typing import cast+from free_claude_code.core.history_replay import (+ ReplayOrigin,+ ReplayRecord,+ encode_replay,+)from free_claude_code.core.json_types import JsonObject, JsonValuefrom .native import NativeMessagesError@@ -231,8 +236,11 @@ class NativeMessagesStreamState:class NativeMessagesRelay:"""Preserve upstream IDs, indexes, fields and event order for Messages clients."""- def __init__(self, *, public_model: str) -> None:+ def __init__(+ self, *, public_model: str, replay_origin: ReplayOrigin | None = None+ ) -> None:self._public_model = public_model+ self._replay_origin = replay_originself._state = NativeMessagesStreamState()@property@@ -244,11 +252,55 @@ class NativeMessagesRelay:return self._state.stop_reasondef feed(self, event_type: str, payload: Mapping[str, JsonValue]) -> str:- self._state.accept(event_type, payload)+ completed = self._state.accept(event_type, payload)body = dict(payload)if event_type == "message_start":message = body.get("message")if not isinstance(message, dict):raise AssertionError("Validated message_start must contain a message.")body["message"] = {**message, "model": self._public_model}- return f"event: {event_type}\ndata: {json.dumps(body, ensure_ascii=False)}\n\n"+ if (+ self._replay_origin is not None+ and isinstance(message.get("model"), str)+ and message["model"]+ ):+ self._replay_origin = replace(+ self._replay_origin, model=message["model"]+ )+ prefix = ""+ if self._replay_origin is not None:+ block = body.get("content_block")+ if event_type == "content_block_start" and isinstance(block, dict):+ if block.get("type") == "thinking":+ body["content_block"] = {**block, "signature": ""}+ elif block.get("type") == "redacted_thinking":+ body["content_block"] = {+ **block,+ "data": encode_replay(ReplayRecord(self._replay_origin, block)),+ }+ delta = body.get("delta")+ if (+ event_type == "content_block_delta"+ and isinstance(delta, dict)+ and delta.get("type") == "signature_delta"+ ):+ return ""+ if (+ completed is not None+ and completed.get("type") == "thinking"+ and completed.get("signature")+ ):+ signature = encode_replay(ReplayRecord(self._replay_origin, completed))+ prefix = _event(+ "content_block_delta",+ {+ "type": "content_block_delta",+ "index": body["index"],+ "delta": {"type": "signature_delta", "signature": signature},+ },+ )+ return prefix + _event(event_type, body)+++def _event(kind: str, payload: JsonObject) -> str:+ return f"event: {kind}\ndata: {json.dumps(payload, ensure_ascii=False)}\n\n"diff --git a/src/free_claude_code/core/history_replay.py b/src/free_claude_code/core/history_replay.pynew file mode 100644index 00000000..5e8c298f--- /dev/null+++ b/src/free_claude_code/core/history_replay.py@@ -0,0 +1,561 @@+"""Pure, request-local projection of reasoning retained by the native harness."""++import base64+import json+from collections.abc import Mapping+from copy import deepcopy+from dataclasses import asdict, dataclass+from enum import StrEnum+from typing import Literal, cast++from .json_types import JsonObject, JsonValue+from .openai_chat import ChatToolResultImages++type HistoryProtocol = Literal["responses", "messages", "chat"]+_PREFIX = "fcc:history:v1:"+_LEGACY_PREFIX = "fcc:anthropic-reasoning:v1:"+++class HistoryReplayError(ValueError):+ """A persisted replay record cannot be safely decoded or projected."""+++class HistoryScope(StrEnum):+ """Documented readable reasoning reuse, separate from its wire encoding."""++ UNKNOWN = "unknown"+ TOOL_CONTINUATION = "tool_continuation"+ ALL = "all"+++@dataclass(frozen=True, slots=True)+class ReplayOrigin:+ provider: str+ protocol: HistoryProtocol+ endpoint: str+ connection: str+ model: str++ def accepts(self, source: ReplayOrigin) -> bool:+ # The upstream owns model/key/prefix compatibility within this domain.+ return (+ self.provider == source.provider+ and self.protocol == source.protocol+ and (not source.endpoint or self.endpoint == source.endpoint)+ and (not source.connection or self.connection == source.connection)+ )+++@dataclass(frozen=True, slots=True)+class ReplayRecord:+ origin: ReplayOrigin+ native: JsonObject+++def _json_copy(value: object) -> JsonObject:+ if not isinstance(value, Mapping):+ raise HistoryReplayError("History replay must contain a native object.")+ pending: list[tuple[object, int]] = [(value, 0)]+ while pending:+ item, depth = pending.pop()+ if depth > 128:+ raise HistoryReplayError("History replay is too deeply nested.")+ if isinstance(item, Mapping):+ pending.extend((child, depth + 1) for child in item.values())+ elif isinstance(item, list):+ pending.extend((child, depth + 1) for child in item)+ try:+ return cast(+ JsonObject,+ json.loads(+ json.dumps(value, ensure_ascii=False, allow_nan=False).encode("utf-8")+ ),+ )+ except (TypeError, ValueError, UnicodeError, RecursionError) as exc:+ raise HistoryReplayError(+ "History replay requires finite, representable JSON."+ ) from exc+++def is_replay(value: object) -> bool:+ return isinstance(value, str) and value.startswith(+ ("fcc:history:", "fcc:anthropic-reasoning:")+ )+++def encode_replay(record: ReplayRecord) -> str:+ """Preserve native state, without claiming to encrypt or authenticate it."""+ payload = _json_copy({"origin": asdict(record.origin), "native": record.native})+ _validate_record(payload)+ raw = json.dumps(payload, ensure_ascii=False, separators=(",", ":")).encode("utf-8")+ return _PREFIX + base64.urlsafe_b64encode(raw).decode("ascii").rstrip("=")+++def _validate_record(payload: JsonObject) -> ReplayRecord:+ origin, native = payload.get("origin"), payload.get("native")+ if (+ set(payload) != {"origin", "native"}+ or not isinstance(origin, dict)+ or set(origin) != {"provider", "protocol", "endpoint", "connection", "model"}+ or not all(isinstance(value, str) for value in origin.values())+ or not origin["provider"]+ or not origin["model"]+ or origin["protocol"] not in {"responses", "messages", "chat"}+ or not isinstance(native, dict)+ ):+ raise HistoryReplayError(+ "History replay has invalid provenance or native data."+ )+ protocol = cast(HistoryProtocol, origin["protocol"])+ if protocol == "responses" and native.get("type") != "reasoning":+ raise HistoryReplayError("Responses replay requires a reasoning item.")+ if protocol == "messages":+ kind = native.get("type")+ if not (+ (+ kind == "thinking"+ and isinstance(native.get("thinking"), str)+ and isinstance(native.get("signature"), str)+ and native["signature"]+ )+ or (+ kind == "redacted_thinking"+ and isinstance(native.get("data"), str)+ and native["data"]+ )+ ):+ raise HistoryReplayError(+ "Messages replay requires signed thinking or redacted data."+ )+ if protocol == "chat" and not isinstance(native.get("reasoning_details"), list):+ raise HistoryReplayError("Chat replay requires structured reasoning details.")+ return ReplayRecord(+ ReplayOrigin(+ str(origin["provider"]),+ protocol,+ str(origin["endpoint"]),+ str(origin["connection"]),+ str(origin["model"]),+ ),+ native,+ )+++def decode_replay(value: str) -> ReplayRecord:+ prefix = next(+ (prefix for prefix in (_PREFIX, _LEGACY_PREFIX) if value.startswith(prefix)),+ None,+ )+ if prefix is None:+ raise HistoryReplayError("Unsupported history replay version.")+ try:+ encoded = value[len(prefix) :]+ payload = _json_copy(+ json.loads(+ base64.b64decode(+ encoded + "=" * (-len(encoded) % 4), altchars=b"-_", validate=True+ ).decode("utf-8")+ )+ )+ except (ValueError, UnicodeError, RecursionError) as exc:+ raise HistoryReplayError("Malformed history replay.") from exc+ if prefix == _LEGACY_PREFIX:+ if (+ set(payload) != {"protocol", "replay_scope", "source_model", "block"}+ or payload.get("protocol") != "anthropic_messages"+ ):+ raise HistoryReplayError("Malformed legacy Messages reasoning replay.")+ payload = {+ "origin": {+ "provider": payload["replay_scope"],+ "protocol": "messages",+ "endpoint": "",+ "connection": "",+ "model": payload["source_model"],+ },+ "native": payload["block"],+ }+ return _validate_record(payload)+++def readable_reasoning(item: Mapping[str, JsonValue]) -> list[tuple[str, bool]]:+ """Keep distinct readable representations and their summary/full-text meaning."""+ if item.get("type") == "thinking":+ text = str(item.get("thinking") or "")+ return [(text, False)] if text else []+ for key in ("content", "summary"):+ parts = item.get(key)+ if isinstance(parts, list):+ text = "\n\n".join(+ str(part["text"])+ for part in parts+ if isinstance(part, dict) and isinstance(part.get("text"), str)+ )+ if text:+ return [(text, key == "summary")]+ details = item.get("reasoning_details")+ parts: list[tuple[str, bool]] = []+ if isinstance(details, list):+ for detail in details:+ if not isinstance(detail, dict):+ continue+ kind = detail.get("type")+ if kind not in {"reasoning.text", "reasoning.summary"}:+ continue+ summary = kind == "reasoning.summary"+ text = (+ detail.get("summary", detail.get("text"))+ if summary+ else detail.get("text")+ )+ if isinstance(text, str) and text:+ parts.append((text, summary))+ # The native string and structured details can be alternate copies. Preserve+ # the typed version in that case, especially when the text is a summary.+ represented = {text for text, _ in parts}+ represented.add("".join(text for text, _ in parts))+ represented.add("\n\n".join(text for text, _ in parts))+ native_parts: list[tuple[str, bool]] = []+ for key in ("reasoning_content", "reasoning"):+ text = item.get(key)+ if isinstance(text, str) and text and text not in represented:+ native_parts.append((text, False))+ represented.add(text)+ return [*native_parts, *parts]+++def has_readable_replay(value: object) -> bool:+ return (+ isinstance(value, str)+ and is_replay(value)+ and bool(readable_reasoning(decode_replay(value).native))+ )+++def _replay_readable(+ item: Mapping[str, JsonValue], record: ReplayRecord | None+) -> list[tuple[str, bool]]:+ native = readable_reasoning(record.native) if record else []+ 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(+ dict(item), ensure_ascii=False, separators=(",", ":")+ )+++def validate_hosted_tool_history(blocks: list[JsonObject]) -> None:+ """A foreign harness cannot finish an upstream-owned pending tool call."""+ results = {+ block.get("tool_use_id")+ for block in blocks+ if str(block.get("type", "")).endswith("_tool_result")+ }+ if any(+ block.get("type") == "server_tool_use" and block.get("id") not in results+ for block in blocks+ ):+ raise HistoryReplayError(+ "An active server tool cannot continue through a different protocol."+ )+++def responses_replay_item(item: JsonObject, origin: ReplayOrigin) -> JsonObject:+ result = deepcopy(item)+ result["encrypted_content"] = encode_replay(ReplayRecord(origin, item))+ return result+++def preserve_responses_reasoning(+ payload: JsonObject, origin: ReplayOrigin+) -> JsonObject:+ """Wrap complete native reasoning before a presenter rewrites public metadata."""+ result = deepcopy(payload)+ item = result.get("item")+ if isinstance(item, dict) and item.get("type") == "reasoning":+ result["item"] = responses_replay_item(item, origin)+ response = result.get("response")+ if isinstance(response, dict):+ output = response.get("output")+ if isinstance(output, list):+ response["output"] = [+ responses_replay_item(item, origin)+ if isinstance(item, dict) and item.get("type") == "reasoning"+ else item+ for item in output+ ]+ return result+++def reasoning_detail(value: str) -> list[JsonValue]:+ """Decode older Chat detail strings while retaining unknown opaque state."""+ try:+ parsed = json.loads(value)+ except ValueError:+ parsed = None+ if isinstance(parsed, dict):+ return [parsed]+ if isinstance(parsed, list):+ return parsed+ return [{"type": "reasoning.encrypted", "data": value}]+++def _record(item: Mapping[str, JsonValue], *keys: str) -> ReplayRecord | None:+ for key in keys:+ value = item.get(key)+ if isinstance(value, str) and is_replay(value):+ return decode_replay(value)+ return None+++def _context_item(text: str) -> JsonObject:+ return {"role": "assistant", "content": text}+++def responses_reasoning_blocks(item: Mapping[str, JsonValue]) -> list[JsonValue]:+ """Carry Responses reasoning into Messages until destination preparation."""+ blocks: list[JsonValue] = []+ carrier = item.get("encrypted_content")+ if isinstance(carrier, str) and carrier:+ record = _record(item, "encrypted_content")+ if (+ record is not None+ and record.origin.protocol == "messages"+ and record.native.get("type") == "thinking"+ ):+ return [+ {+ "type": "thinking",+ "thinking": record.native["thinking"],+ "signature": carrier,+ }+ ]+ blocks.append({"type": "redacted_thinking", "data": carrier})+ if record is not None and readable_reasoning(record.native):+ return blocks+ blocks.extend(+ {"type": "text", "text": reasoning_context(text, summary=summary)}+ for text, summary in readable_reasoning(item)+ )+ return blocks+++def prepare_history(+ body: Mapping[str, JsonValue],+ destination: ReplayOrigin,+ *,+ scope: HistoryScope = HistoryScope.TOOL_CONTINUATION,+ reasoning_field: str = "reasoning_content",+ structured_details: bool = True,+) -> JsonObject:+ """Project a fresh wire copy. The caller's native transcript stays intact."""+ result = deepcopy(dict(body))+ if destination.protocol == "responses":+ items = result.get("input")+ if isinstance(items, dict):+ items = [items]+ if not isinstance(items, list):+ return result+ projected: list[JsonValue] = []+ for item in items:+ if not isinstance(item, dict) or item.get("type") != "reasoning":+ projected.append(item)+ continue+ record = _record(item, "encrypted_content")+ if record is not None and destination.accepts(record.origin):+ 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)+ )+ continue+ if record is None and item.get("encrypted_content"):+ projected.append(+ 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))+ )+ result["input"] = projected+ return result+ messages = result.get("messages")+ if not isinstance(messages, list):+ return result+ last_user = max(+ (+ index+ for index, msg in enumerate(messages)+ if isinstance(msg, dict)+ and msg.get("role") == "user"+ and not _tool_result_message(msg)+ ),+ default=-1,+ )+ for index, message in enumerate(messages):+ if not isinstance(message, dict) or message.get("role") != "assistant":+ continue+ if destination.protocol == "messages":+ _prepare_messages_content(message, destination)+ else:+ _prepare_chat_content(+ message,+ destination,+ native_text=scope == HistoryScope.ALL+ or (+ scope == HistoryScope.TOOL_CONTINUATION+ and index > last_user+ and any(+ isinstance(later, dict) and later.get("role") == "tool"+ for later in messages[index + 1 :]+ )+ ),+ reasoning_field=reasoning_field,+ structured_details=structured_details,+ )+ result["messages"] = [+ message+ for message in messages+ if not (+ isinstance(message, dict)+ and message.get("role") == "assistant"+ and message.get("content") == []+ )+ ]+ return result+++def _tool_result_message(message: JsonObject) -> bool:+ if isinstance(message, ChatToolResultImages):+ return True+ content = message.get("content")+ return (+ isinstance(content, list)+ and bool(content)+ and all(+ isinstance(block, dict) and block.get("type") == "tool_result"+ for block in content+ )+ )+++def _prepare_messages_content(message: JsonObject, destination: ReplayOrigin) -> None:+ content = message.get("content")+ if not isinstance(content, list):+ return+ blocks: list[JsonValue] = []+ for block in content:+ if not isinstance(block, dict) or block.get("type") not in {+ "thinking",+ "redacted_thinking",+ }:+ blocks.append(block)+ continue+ record = _record(block, "signature", "data")+ if record is not None and destination.accepts(record.origin):+ 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)+ )+ 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)}+ )+ message["content"] = blocks+++def _append_context(message: JsonObject, text: str) -> None:+ if not text:+ return+ content = message.get("content")+ if isinstance(content, list):+ content.append({"type": "text", "text": text})+ else:+ message["content"] = (+ f"{content}\n\n{text}"+ if isinstance(content, str) and content.strip()+ else text+ )+++def _prepare_chat_content(+ message: JsonObject,+ destination: ReplayOrigin,+ *,+ native_text: bool,+ reasoning_field: str,+ structured_details: bool,+) -> None:+ had_reasoning_content = "reasoning_content" in message+ details = message.get("reasoning_details")+ restored: list[JsonValue] = []+ original_reasoning = message.get("reasoning_content", message.get("reasoning"))+ if isinstance(details, list):+ for detail in details:+ if not isinstance(detail, dict):+ continue+ record = _record(detail, "data", "signature")+ if record is None and structured_details:+ restored.append(detail)+ continue+ elif (+ record is not None+ and destination.accepts(record.origin)+ and structured_details+ ):+ native = record.native.get("reasoning_details")+ if isinstance(native, list):+ restored.extend(native)+ parts = readable_reasoning(record.native)+ native_parts = readable_reasoning({"reasoning_details": native})+ parts = [part for part in parts if part not in native_parts]+ else:+ parts = readable_reasoning(+ record.native if record else {"reasoning_details": [detail]}+ )+ for text, summary in parts:+ existing = message.get("reasoning_content", message.get("reasoning"))+ if text != original_reasoning:+ if (+ native_text+ and not summary+ and reasoning_field in {"reasoning_content", "reasoning"}+ ):+ message[reasoning_field] = (+ f"{existing}\n{text}"+ if isinstance(existing, str) and existing+ else text+ )+ else:+ _append_context(+ message, reasoning_context(text, summary=summary)+ )+ if restored:+ message["reasoning_details"] = restored+ else:+ message.pop("reasoning_details", None)+ if not native_text:+ for key in ("reasoning_content", "reasoning"):+ text = message.pop(key, None)+ if isinstance(text, str) and text:+ _append_context(message, reasoning_context(text))+ if (+ had_reasoning_content+ and reasoning_field == "reasoning_content"+ and message.get("tool_calls")+ ):+ message.setdefault("reasoning_content", "")diff --git a/src/free_claude_code/core/openai_chat.py b/src/free_claude_code/core/openai_chat.pyindex 07ba63fc..50ced0cd 100644--- a/src/free_claude_code/core/openai_chat.py+++ b/src/free_claude_code/core/openai_chat.py@@ -7,6 +7,12 @@ from free_claude_code.core.json_types import JsonObject, JsonValueIMAGE_TOOL_RESULT_MARKER = "[Image-bearing tool output follows in user content.]"+class ChatToolResultImages(dict[str, JsonValue]):+ """Relocated tool output, retaining turn ownership until serialization."""++ __slots__ = ()++def image_tool_result_label(tool_call_id: str) -> str:"""Label relocated visual output with its source function-call identity."""return (diff --git a/src/free_claude_code/core/openai_responses/__init__.py b/src/free_claude_code/core/openai_responses/__init__.pyindex be29f52b..0d410d26 100644--- a/src/free_claude_code/core/openai_responses/__init__.py+++ b/src/free_claude_code/core/openai_responses/__init__.py@@ -26,7 +26,6 @@ from .provider_stream import (responses_stream_failure_from_event,)from .reasoning import responses_reasoning_config, responses_reasoning_policy-from .reasoning_replay import MessagesReplayOriginfrom .streaming.blocks import ReasoningBlockState, TextBlockState, ToolBlockStatefrom .streaming.completion import (ResponseBlockCompleter,@@ -51,7 +50,6 @@ from .tools import (__all__ = ["OPENAI_RESPONSES_SSE_HEADERS","AnthropicToResponsesStream",- "MessagesReplayOrigin","NativeResponsesRelay","OpenAIResponsesRequest","ReasoningBlockState",diff --git a/src/free_claude_code/core/openai_responses/chat_request.py b/src/free_claude_code/core/openai_responses/chat_request.pyindex 5504526b..105ddc7a 100644--- a/src/free_claude_code/core/openai_responses/chat_request.py+++ b/src/free_claude_code/core/openai_responses/chat_request.py@@ -6,9 +6,18 @@ from dataclasses import dataclass, fieldfrom typing import castfrom free_claude_code.core.anthropic import ReasoningReplayMode+from free_claude_code.core.history_replay import (+ has_readable_replay,+ is_replay,+ readable_reasoning,+ reasoning_context,+ reasoning_detail,+ tool_history_context,+)from free_claude_code.core.json_types import JsonObject, JsonValuefrom free_claude_code.core.openai_chat import (IMAGE_TOOL_RESULT_MARKER,+ ChatToolResultImages,close_chat_tool_result_turns,computer_screenshot_label,image_tool_result_label,@@ -21,9 +30,7 @@ from .models import OpenAIResponsesRequestfrom .reasoning import (combine_reasoning,encrypted_reasoning_from_item,- reasoning_text_from_item,)-from .reasoning_replay import reject_messages_reasoning_for_other_egressfrom .tools import (call_id_from_item,custom_tool_description,@@ -74,22 +81,31 @@ class ResponsesChatRequest:class _PendingReasoning:text: str | None = Noneencrypted: list[str] = field(default_factory=list)+ contexts: list[str] = field(default_factory=list)def add(self, item: Mapping[str, JsonValue]) -> None:- self.text = combine_reasoning(self.text, reasoning_text_from_item(item))if encrypted := encrypted_reasoning_from_item(item):self.encrypted.append(encrypted)+ if has_readable_replay(encrypted):+ return+ for text, summary in readable_reasoning(item):+ if summary:+ self.contexts.append(reasoning_context(text, summary=True))+ else:+ self.text = combine_reasoning(self.text, text)@propertydef empty(self) -> bool:- return self.text is None and not self.encrypted+ return self.text is None and not self.encrypted and not self.contexts- def take(self) -> tuple[str | None, list[str]]:+ def take(self) -> tuple[str | None, list[str], list[str]]:text = self.textencrypted = list(self.encrypted)self.text = Noneself.encrypted.clear()- return text, encrypted+ contexts = list(self.contexts)+ self.contexts.clear()+ return text, encrypted, contextsclass _ResponsesChatInputBuilder:@@ -147,6 +163,22 @@ class _ResponsesChatInputBuilder:image = _image_part(item, context="input_image")self._flush_reasoning()self.messages.append({"role": "user", "content": [image]})+ return+ if isinstance(item_type, str) and item_type.endswith(("_call", "_result")):+ if item.get("status") not in {+ None,+ "completed",+ "failed",+ "incomplete",+ "interrupted",+ }:+ raise ResponsesConversionError(+ "An active hosted tool cannot continue through Chat Completions."+ )+ self._flush_reasoning()+ self.messages.append(+ {"role": "assistant", "content": tool_history_context(item)}+ )def finish(self) -> tuple[list[str], list[dict[str, object]]]:self._flush_rich_outputs()@@ -189,6 +221,7 @@ class _ResponsesChatInputBuilder:parse_arguments(raw_arguments)except ResponsesConversionError as exc:self._quarantined_call_ids.add(call_id)+ self._pending_reasoning.take()trace_event(stage="responses",event="responses.input.function_call_quarantined",@@ -217,6 +250,8 @@ class _ResponsesChatInputBuilder:"function": {"name": name, "arguments": arguments},})+ if self._reasoning_replay is ReasoningReplayMode.REASONING_CONTENT:+ message.setdefault("reasoning_content", "")def _add_tool_output(self, item: Mapping[str, JsonValue], *, function: bool@@ -288,21 +323,34 @@ class _ResponsesChatInputBuilder:if not self._pending_rich_output_parts:returnself.messages.append(- {- "role": "user",- "content": list(self._pending_rich_output_parts),- }+ cast(+ dict[str, object],+ ChatToolResultImages(+ role="user",+ content=cast(+ list[JsonValue], list(self._pending_rich_output_parts)+ ),+ ),+ ))self._pending_rich_output_parts.clear()def _apply_pending_reasoning(self, message: dict[str, object]) -> None:- text, encrypted = self._pending_reasoning.take()+ text, encrypted, contexts = self._pending_reasoning.take()+ if contexts:+ message["content"] = "\n\n".join(+ [*contexts, str(message.get("content") or "")]+ ).rstrip()if text is not None:_apply_reasoning_text(message, text, self._reasoning_replay)- if encrypted and self._structured_reasoning_details:- message["reasoning_details"] = [- _encrypted_reasoning_detail(value) for value in encrypted- ]+ if encrypted:+ details = message.setdefault("reasoning_details", [])+ if isinstance(details, list):+ for value in encrypted:+ if self._structured_reasoning_details or is_replay(value):+ details.extend(reasoning_detail(value))+ if not details:+ message.pop("reasoning_details", None)def build_responses_chat_request(@@ -312,7 +360,6 @@ def build_responses_chat_request(structured_reasoning_details: bool = False,) -> ResponsesChatRequest:"""Translate a Responses request directly into one Chat Completions body."""- reject_messages_reasoning_for_other_egress(request.input)builder = _ResponsesChatInputBuilder(reasoning_replay=reasoning_replay,structured_reasoning_details=structured_reasoning_details,@@ -509,11 +556,18 @@ def _apply_reasoning_text(message: dict[str, object], text: str, mode: ReasoningReplayMode) -> None:if mode in {ReasoningReplayMode.REASONING_CONTENT, ReasoningReplayMode.REASONING}:- message[mode.value] = text+ previous = message.get(mode.value)+ message[mode.value] = combine_reasoning(+ previous if isinstance(previous, str) else None, text+ )return- if mode is not ReasoningReplayMode.THINK_TAGS:+ replay = (+ f"<think>\n{text}\n</think>"+ if mode is ReasoningReplayMode.THINK_TAGS+ else reasoning_context(text)+ )+ if not replay:return- replay = f"<think>\n{text}\n</think>"content = message.get("content")if isinstance(content, str) and content:message["content"] = f"{replay}\n\n{content}"@@ -521,18 +575,6 @@ def _apply_reasoning_text(message["content"] = replay-def _encrypted_reasoning_detail(value: str) -> object:- try:- parsed = json.loads(value)- except json.JSONDecodeError:- parsed = None- if isinstance(parsed, Mapping):- return dict(parsed)- if isinstance(parsed, list):- return parsed- return {"type": "reasoning.encrypted", "data": value}--def _chat_tools(tools: list[JsonObject] | None,) -> tuple[list[dict[str, object]], frozenset[str]]:diff --git a/src/free_claude_code/core/openai_responses/messages_request.py b/src/free_claude_code/core/openai_responses/messages_request.pyindex 6c57b75b..99737f30 100644--- a/src/free_claude_code/core/openai_responses/messages_request.py+++ b/src/free_claude_code/core/openai_responses/messages_request.py@@ -17,12 +17,15 @@ from free_claude_code.core.anthropic.native import (apply_messages_options,validate_messages_json,)+from free_claude_code.core.history_replay import (+ responses_reasoning_blocks,+ tool_history_context,+)from free_claude_code.core.json_types import JsonObject, JsonValuefrom free_claude_code.core.openai_tool_names import OpenAIToolNameCodecfrom .errors import ResponsesConversionErrorfrom .models import OpenAIResponsesRequest-from .reasoning_replay import decode_messages_reasoningfrom .tools import (ResponsesToolIdentity,custom_tool_input_schema,@@ -336,11 +339,10 @@ def _content(value: JsonValue, *, images: bool, empty: bool = False) -> list[Jsoclass _MessagesInput:- def __init__(self, tools: _ToolScope, replay_scope: str) -> None:+ def __init__(self, tools: _ToolScope) -> None:self.messages: list[JsonObject] = []self.system: list[JsonValue] = []self._tools = tools- self._replay_scope = replay_scopeself._calls: dict[str, Literal["function", "custom"]] = {}self._pending: set[str] = set()@@ -398,16 +400,8 @@ class _MessagesInput:raise ResponsesConversionError("Unsupported Responses message role.")returnif kind == "reasoning":- _fields(- value,- {"type", "id", "status", "summary", "content", "encrypted_content"},- "Reasoning item",- )- carrier = _string(- value.get("encrypted_content"), "reasoning.encrypted_content"- )- block = decode_messages_reasoning(carrier, replay_scope=self._replay_scope)- self._append("assistant", [block])+ if blocks := responses_reasoning_blocks(value):+ self._append("assistant", blocks)returnif kind in ("function_call", "custom_tool_call"):self._call(value, custom=kind == "custom_tool_call")@@ -418,6 +412,16 @@ class _MessagesInput:if kind in ("input_text", "output_text", "text", "input_image"):self._append("user", _content([value], images=True))return+ if (+ isinstance(kind, str)+ and kind.endswith(("_call", "_result"))+ and value.get("status")+ in {None, "completed", "failed", "incomplete", "interrupted"}+ ):+ self._append(+ "assistant", [{"type": "text", "text": tool_history_context(value)}]+ )+ returnraise ResponsesConversionError(f"Messages upstream cannot represent input item {kind!r}.")@@ -559,7 +563,6 @@ def build_responses_messages_request(request: OpenAIResponsesRequest,*,options: NativeMessagesOptions,- replay_scope: str,) -> ResponsesMessagesRequest:"""Convert caller-owned history directly to the native Messages wire shape."""@@ -585,7 +588,7 @@ def build_responses_messages_request()items = _items(request.input)scope = _ToolScope(request.tools, items)- builder = _MessagesInput(scope, replay_scope)+ builder = _MessagesInput(scope)if request.instructions is not None:builder.system.append({"type": "text", "text": request.instructions})for item in items:diff --git a/src/free_claude_code/core/openai_responses/messages_stream.py b/src/free_claude_code/core/openai_responses/messages_stream.pyindex 2d937a71..161e1705 100644--- a/src/free_claude_code/core/openai_responses/messages_stream.py+++ b/src/free_claude_code/core/openai_responses/messages_stream.py@@ -4,18 +4,23 @@ import jsonimport timeimport uuidfrom collections.abc import Mapping+from dataclasses import replacefrom typing import castfrom free_claude_code.core.anthropic.native import NativeMessagesErrorfrom free_claude_code.core.anthropic.native_stream import NativeMessagesStreamStatefrom free_claude_code.core.failures import ExecutionFailure+from free_claude_code.core.history_replay import (+ ReplayOrigin,+ ReplayRecord,+ encode_replay,+)from free_claude_code.core.json_types import JsonObject, JsonValuefrom .errors import ResponsesConversionError, openai_error_from_failurefrom .ids import new_message_item_id, new_reasoning_item_id, new_response_idfrom .items import message_item, reasoning_itemfrom .models import OpenAIResponsesRequest-from .reasoning_replay import MessagesReplayOrigin, encode_messages_reasoningfrom .streaming.blocks import ReasoningBlockState, TextBlockState, ToolBlockStatefrom .streaming.completion import ResponseBlockCompleter, tool_itemfrom .streaming.event_builders import ResponseEventBuilder@@ -102,7 +107,7 @@ class AnthropicToResponsesStream:*,public_model: str,tool_identities: Mapping[str, ResponsesToolIdentity],- replay_origin: MessagesReplayOrigin,+ replay_origin: ReplayOrigin,) -> None:self._request = requestself._public_model = public_model@@ -177,6 +182,10 @@ class AnthropicToResponsesStream:if not isinstance(message, Mapping):raise AssertionError("Validated message_start must contain a message.")self._usage.update(message.get("usage"))+ if isinstance(message.get("model"), str) and message["model"]:+ self._replay_origin = replace(+ self._replay_origin, model=message["model"]+ )self._started = Truereturn [self._events.response_created(self._payload("in_progress"))]if event_type == "message_delta":@@ -335,8 +344,8 @@ class AnthropicToResponsesStream:"Native block has no corresponding Responses item.")if isinstance(state, ReasoningBlockState):- state.encrypted_content = encode_messages_reasoning(- block, origin=self._replay_origin+ state.encrypted_content = encode_replay(+ ReplayRecord(self._replay_origin, block))elif isinstance(state, ToolBlockState):arguments = block.get("input")diff --git a/src/free_claude_code/core/openai_responses/native.py b/src/free_claude_code/core/openai_responses/native.pyindex 16716c02..2829ec3f 100644--- a/src/free_claude_code/core/openai_responses/native.py+++ b/src/free_claude_code/core/openai_responses/native.py@@ -13,7 +13,6 @@ from .errors import openai_error_from_failurefrom .events import format_response_sse_eventfrom .models import OpenAIResponsesRequestfrom .reasoning import responses_reasoning_config, responses_reasoning_policy-from .reasoning_replay import reject_messages_reasoning_for_other_egress_TERMINAL_EVENT_TYPES = frozenset({"response.completed", "response.incomplete", "response.failed"}@@ -28,7 +27,6 @@ def build_native_responses_request() -> JsonObject:"""Build the stateless upstream body without translating Responses input."""- reject_messages_reasoning_for_other_egress(request.input)body = cast(JsonObject,request.model_dump(mode="json", exclude_none=True),diff --git a/src/free_claude_code/core/openai_responses/provider_input.py b/src/free_claude_code/core/openai_responses/provider_input.pyindex da7caaac..35bb3f31 100644--- a/src/free_claude_code/core/openai_responses/provider_input.py+++ b/src/free_claude_code/core/openai_responses/provider_input.py@@ -1,7 +1,7 @@"""Convert Anthropic Messages into an upstream OpenAI Responses request."""import json-from typing import Any+from typing import Any, castfrom free_claude_code.core.anthropic.content import get_block_attr, get_block_typefrom free_claude_code.core.anthropic.conversion import resolve_anthropic_tool_choice@@ -18,6 +18,16 @@ from free_claude_code.core.anthropic.tool_results import (ToolResultText,decompose_tool_result_content,)+from free_claude_code.core.history_replay import (+ HistoryReplayError,+ ReplayOrigin,+ ReplayRecord,+ encode_replay,+ has_readable_replay,+ is_replay,+ tool_history_context,+ validate_hosted_tool_history,+)from free_claude_code.core.json_types import JsonObjectfrom free_claude_code.core.openai_tool_names import OpenAIToolNameCodecfrom free_claude_code.core.reasoning import ReasoningPolicy@@ -168,49 +178,92 @@ def _assistant_items(reasoning_content: str | None,tool_names: OpenAIToolNameCodec,) -> list[dict[str, Any]]:- if isinstance(content, str):- items = [_assistant_message([{"type": "output_text", "text": content}])]- if reasoning_content is not None:- items.insert(- 0,- {- "type": "reasoning",- "summary": [{"type": "summary_text", "text": reasoning_content}],- },- )- return items- if not isinstance(content, list):+ blocks = (+ [{"type": "text", "text": content}] if isinstance(content, str) else content+ )+ if not isinstance(blocks, list):raise ResponsesConversionError("Assistant content must be text or content blocks.")-+ try:+ validate_hosted_tool_history(+ [+ {+ "type": get_block_type(block),+ "id": get_block_attr(block, "id", None),+ "tool_use_id": get_block_attr(block, "tool_use_id", None),+ }+ for block in blocks+ ]+ )+ except HistoryReplayError as error:+ raise ResponsesConversionError(str(error)) from erroritems: list[dict[str, Any]] = []text_parts: list[dict[str, Any]] = []- thinking_parts: list[str] = (- [reasoning_content] if reasoning_content is not None else []- )- encrypted_parts: list[str] = []def flush_text() -> None:if text_parts:items.append(_assistant_message(list(text_parts)))text_parts.clear()- for block in content:- block_type = get_block_type(block)- if block_type == "text":+ if reasoning_content is not None and not any(+ get_block_type(block) == "thinking" for block in blocks+ ):+ items.append(+ {+ "type": "reasoning",+ "content": [{"type": "reasoning_text", "text": reasoning_content}],+ "summary": [],+ }+ )+ for block in blocks:+ kind = get_block_type(block)+ if kind == "text":text_parts.append(+ {"type": "output_text", "text": str(get_block_attr(block, "text", ""))}+ )+ continue+ flush_text()+ if kind == "thinking":+ signature = get_block_attr(block, "signature", None)+ item: dict[str, Any] = {"type": "reasoning", "summary": []}+ if isinstance(signature, str) and signature:+ native = (+ block+ if isinstance(block, dict)+ else block.model_dump(mode="json", exclude_none=True)+ )+ item["encrypted_content"] = (+ signature+ if is_replay(signature)+ else encode_replay(+ ReplayRecord(+ ReplayOrigin(+ "unattributed/messages", "messages", "", "", "unknown"+ ),+ cast(JsonObject, native),+ )+ )+ )+ if not signature or (+ is_replay(signature) and not has_readable_replay(signature)+ ):+ item["content"] = [+ {+ "type": "reasoning_text",+ "text": str(get_block_attr(block, "thinking", "")),+ }+ ]+ items.append(item)+ elif kind == "redacted_thinking":+ items.append({- "type": "output_text",- "text": str(get_block_attr(block, "text", "")),+ "type": "reasoning",+ "summary": [],+ "encrypted_content": str(get_block_attr(block, "data", "")),})- elif block_type == "thinking":- thinking_parts.append(str(get_block_attr(block, "thinking", "")))- elif block_type == "redacted_thinking":- encrypted_parts.append(str(get_block_attr(block, "data", "")))- elif block_type == "tool_use":- flush_text()+ elif kind == "tool_use":items.append({"type": "function_call",@@ -223,25 +276,25 @@ def _assistant_items(),})+ elif kind in {+ "server_tool_use",+ "web_search_tool_result",+ "web_fetch_tool_result",+ }:+ native = (+ block+ if isinstance(block, dict)+ else block.model_dump(mode="json", exclude_none=True)+ )+ items.append(+ _assistant_message(+ [{"type": "output_text", "text": tool_history_context(native)}]+ )+ )else:raise ResponsesConversionError(- "OpenAI Responses cannot represent assistant content block "- f"{block_type!r}."+ f"OpenAI Responses cannot represent assistant content block {kind!r}.")- if thinking_parts or encrypted_parts:- summary = [- {"type": "summary_text", "text": text} for text in thinking_parts if text- ]- if encrypted_parts:- for index, encrypted in enumerate(encrypted_parts):- item: dict[str, Any] = {- "type": "reasoning",- "summary": summary if index == 0 else [],- "encrypted_content": encrypted,- }- items.insert(index, item)- else:- items.insert(0, {"type": "reasoning", "summary": summary})flush_text()return itemsdiff --git a/src/free_claude_code/core/openai_responses/provider_stream.py b/src/free_claude_code/core/openai_responses/provider_stream.pyindex 51a2ac17..477360b8 100644--- a/src/free_claude_code/core/openai_responses/provider_stream.py+++ b/src/free_claude_code/core/openai_responses/provider_stream.py@@ -5,6 +5,7 @@ from typing import Anyfrom free_claude_code.core.anthropic.streaming import AnthropicStreamLedgerfrom free_claude_code.core.anthropic.usage import anthropic_input_usage_fields+from free_claude_code.core.history_replay import is_replayfrom free_claude_code.core.openai_tool_names import OpenAIToolNameCodec@@ -180,6 +181,15 @@ class ResponsesProviderStream:if not isinstance(encrypted, str) or not encrypted:encrypted = self._encrypted_reasoning.get(item_id)if isinstance(encrypted, str) and encrypted:+ if is_replay(encrypted) and self.ledger.blocks.thinking_started:+ return [+ self.ledger.content_block_delta(+ self.ledger.blocks.thinking_index,+ "signature_delta",+ encrypted,+ ),+ self.ledger.stop_thinking_block(),+ ]events = list(self.ledger.close_content_blocks())index = self.ledger.blocks.allocate_index()events.append(diff --git a/src/free_claude_code/core/openai_responses/reasoning.py b/src/free_claude_code/core/openai_responses/reasoning.pyindex b40cadff..19ea9580 100644--- a/src/free_claude_code/core/openai_responses/reasoning.py+++ b/src/free_claude_code/core/openai_responses/reasoning.py@@ -12,20 +12,6 @@ from free_claude_code.core.reasoning import (from .tools import optional_str-def reasoning_text_from_item(item: Mapping[str, Any]) -> str | None:- content_parts = _text_parts_from_items(- item.get("content"), item_type="reasoning_text"- )- if content_parts:- return "\n".join(content_parts)- summary_parts = _text_parts_from_items(- item.get("summary"), item_type="summary_text"- )- if summary_parts:- return "\n".join(summary_parts)- return None--def encrypted_reasoning_from_item(item: Mapping[str, Any]) -> str | None:"""Return opaque reasoning content without interpreting it."""@@ -85,15 +71,3 @@ def responses_reasoning_config(reasoning: ReasoningPolicy) -> dict[str, str]:if reasoning.requests_reasoning:return {"summary": "auto"}return {}---def _text_parts_from_items(value: Any, *, item_type: str) -> list[str]:- if not isinstance(value, list):- return []- parts: list[str] = []- for item in value:- if isinstance(item, dict) and item.get("type") == item_type:- text = optional_str(item.get("text"))- if text is not None:- parts.append(text)- return partsdiff --git a/src/free_claude_code/core/openai_responses/reasoning_replay.py b/src/free_claude_code/core/openai_responses/reasoning_replay.pydeleted file mode 100644index 5203cbf9..00000000--- a/src/free_claude_code/core/openai_responses/reasoning_replay.py+++ /dev/null@@ -1,155 +0,0 @@-"""Versioned native-thinking replay carried by Responses reasoning items."""--import base64-import json-from collections.abc import Mapping, Sequence-from dataclasses import dataclass-from typing import cast--from free_claude_code.core.json_types import JsonObject, JsonValue--from .errors import ResponsesConversionError--_REASONING_FAMILY = "fcc:anthropic-reasoning:"-_REASONING_PREFIX = _REASONING_FAMILY + "v1:"-_MAX_REPLAY_DEPTH = 128---@dataclass(frozen=True, slots=True)-class MessagesReplayOrigin:- replay_scope: str- source_model: str---def is_messages_reasoning_carrier(value: object) -> bool:- return isinstance(value, str) and value.startswith(_REASONING_FAMILY)---def _validate_block(block: JsonValue) -> JsonObject:- if not isinstance(block, Mapping):- raise ResponsesConversionError(- "Native reasoning replay block must be an object."- )- kind = block.get("type")- if kind == "thinking":- if not isinstance(block.get("thinking"), str):- raise ResponsesConversionError(- "Native thinking replay requires thinking text."- )- if not isinstance(block.get("signature"), str) or not block["signature"]:- raise ResponsesConversionError(- "Native thinking replay requires its signature."- )- elif kind == "redacted_thinking":- if not isinstance(block.get("data"), str) or not block["data"]:- raise ResponsesConversionError(- "Redacted native thinking requires its data."- )- else:- raise ResponsesConversionError("Unsupported native reasoning replay block.")- pending: list[tuple[JsonValue, int]] = [(block, 0)]- while pending:- value, depth = pending.pop()- if depth > _MAX_REPLAY_DEPTH:- raise ResponsesConversionError(- "Native reasoning replay is too deeply nested."- )- if isinstance(value, Mapping):- pending.extend((child, depth + 1) for child in value.values())- elif isinstance(value, Sequence) and not isinstance(value, str | bytes):- pending.extend((child, depth + 1) for child in value)- try:- # A carrier can hide malformed JSON inside an otherwise ordinary string.- # Validate finite numbers and nesting before HTTP serialization.- return cast(- JsonObject,- json.loads(- json.dumps(dict(block), ensure_ascii=False, allow_nan=False).encode(- "utf-8"- )- ),- )- except (TypeError, ValueError, RecursionError) as exc:- raise ResponsesConversionError(- "Native reasoning replay must contain finite, representable JSON."- ) from exc---def encode_messages_reasoning(- block: JsonObject, *, origin: MessagesReplayOrigin-) -> str:- """Serialize native signed data; this does not add encryption or authentication."""-- if not origin.replay_scope or not origin.source_model:- raise ResponsesConversionError(- "Native reasoning replay requires provider provenance."- )- payload: JsonObject = {- "protocol": "anthropic_messages",- "replay_scope": origin.replay_scope,- "source_model": origin.source_model,- "block": _validate_block(block),- }- try:- encoded = json.dumps(- payload, ensure_ascii=False, separators=(",", ":"), allow_nan=False- ).encode("utf-8")- except (ValueError, UnicodeError, RecursionError) as exc:- raise ResponsesConversionError(- "Malformed native Messages reasoning replay."- ) from exc- return _REASONING_PREFIX + base64.urlsafe_b64encode(encoded).decode("ascii").rstrip(- "="- )---def decode_messages_reasoning(value: str, *, replay_scope: str) -> JsonObject:- """Validate provenance and return the exact authoritative replay block."""-- if not value.startswith(_REASONING_PREFIX):- raise ResponsesConversionError(- "This reasoning item is not a supported native Messages replay carrier."- )- encoded = value[len(_REASONING_PREFIX) :]- try:- raw = base64.b64decode(- encoded + "=" * (-len(encoded) % 4), altchars=b"-_", validate=True- )- payload = cast(JsonValue, json.loads(raw.decode("utf-8")))- except (ValueError, UnicodeError, RecursionError) as exc:- raise ResponsesConversionError(- "Malformed native Messages reasoning replay."- ) from exc- if (- not isinstance(payload, Mapping)- or set(payload) != {"protocol", "replay_scope", "source_model", "block"}- or payload.get("protocol") != "anthropic_messages"- or payload.get("replay_scope") != replay_scope- or not isinstance(payload.get("source_model"), str)- or not payload["source_model"]- ):- raise ResponsesConversionError(- "Native reasoning replay has incompatible provenance."- )- return _validate_block(payload.get("block"))---def reject_messages_reasoning_for_other_egress(value: JsonValue) -> None:- """Prevent routing native signatures into a different reasoning protocol."""-- items: Sequence[JsonValue]- if isinstance(value, Mapping):- items = (value,)- elif isinstance(value, Sequence) and not isinstance(value, str | bytes):- items = value- else:- return- for item in items:- if (- isinstance(item, Mapping)- and item.get("type") == "reasoning"- and is_messages_reasoning_carrier(item.get("encrypted_content"))- ):- raise ResponsesConversionError(- "Native Messages reasoning history requires a Messages upstream model."- )diff --git a/src/free_claude_code/providers/anthropic_messages/transport.py b/src/free_claude_code/providers/anthropic_messages/transport.pyindex 7a029ce8..0e9d2312 100644--- a/src/free_claude_code/providers/anthropic_messages/transport.py+++ b/src/free_claude_code/providers/anthropic_messages/transport.py@@ -25,10 +25,10 @@ from free_claude_code.core.diagnostics import (redact_sensitive_error_text,)from free_claude_code.core.failures import ExecutionFailure, FailureKind+from free_claude_code.core.history_replay import ReplayOrigin, prepare_historyfrom free_claude_code.core.json_types import JsonObjectfrom free_claude_code.core.openai_responses import (AnthropicToResponsesStream,- MessagesReplayOrigin,OpenAIResponsesRequest,ResponsesConversionError,ResponsesMessagesRequest,@@ -55,6 +55,11 @@ from free_claude_code.providers.failure_policy import (is_context_window_finish_reason,is_retryable_stream_error,)+from free_claude_code.providers.history_replay import (+ history_retry_body,+ replay_origin,+ validate_history,+)from free_claude_code.providers.http import ProviderAttemptScope, maybe_await_aclosefrom free_claude_code.providers.reasoning_compatibility import (ReasoningCorrection,@@ -100,6 +105,7 @@ class AnthropicMessagesTransport:reasoning: ReasoningPolicy,model_info: ProviderModelInfo | None = None,) -> PreparedMessagesRequest:+ validate_history(request.model_dump(mode="json"))request, reasoning = prepare_messages_reasoning(request,reasoning,@@ -125,6 +131,7 @@ class AnthropicMessagesTransport:def _responses_body(self, request: OpenAIResponsesRequest, reasoning: ReasoningPolicy) -> ResponsesMessagesRequest:+ validate_history(request.model_dump(mode="json"))try:options = resolve_messages_options(model=request.model,@@ -135,9 +142,7 @@ class AnthropicMessagesTransport:if request.reasoningelse None,)- return build_responses_messages_request(- request, options=options, replay_scope=self._replay_scope- )+ return build_responses_messages_request(request, options=options)except (NativeMessagesError, ResponsesConversionError, ValueError) as error:raise InvalidRequestError(str(error)) from error@@ -193,8 +198,8 @@ class AnthropicMessagesTransport:betas=prepared.betas,endpoint_context=endpoint_context,request_id=request_id,- presenter_factory=lambda: NativeMessagesRelay(- public_model=response_model or request.model+ presenter_factory=lambda origin: NativeMessagesRelay(+ public_model=response_model or request.model, replay_origin=origin),)@@ -213,11 +218,11 @@ class AnthropicMessagesTransport:betas=(),endpoint_context=endpoint_context,request_id=request_id,- presenter_factory=lambda: AnthropicToResponsesStream(+ presenter_factory=lambda origin: AnthropicToResponsesStream(request,public_model=response_model or request.model,tool_identities=prepared.tool_identities,- replay_origin=MessagesReplayOrigin(self._replay_scope, request.model),+ replay_origin=origin,),)@@ -228,7 +233,7 @@ class AnthropicMessagesTransport:betas: tuple[str, ...],endpoint_context: EndpointContext,request_id: str | None,- presenter_factory: Callable[[], _Presenter],+ presenter_factory: Callable[[ReplayOrigin], _Presenter],reasoning_correction: ReasoningCorrection | None = None,) -> AsyncIterator[str]:execution = self._admission.start_execution(request_id=request_id)@@ -261,16 +266,16 @@ class AnthropicMessagesTransport:betas: tuple[str, ...],endpoint_context: EndpointContext,execution: ProviderExecution,- presenter_factory: Callable[[], _Presenter],+ presenter_factory: Callable[[ReplayOrigin], _Presenter],reasoning_correction: ReasoningCorrection | None = None,) -> AsyncIterator[str]:recovery = RecoveryController()refreshed = Falseforce_refresh = Falsewhile execution.can_attempt:- presenter = presenter_factory()scope: ProviderAttemptScope | None = Nonestream_opened = False+ sent_body = bodytry:attempt = await execution.open_attempt(ProviderOperationKind.GENERATION)scope = ProviderAttemptScope(@@ -280,6 +285,14 @@ class AnthropicMessagesTransport:)endpoint = await endpoint_context.endpoint(force_refresh=force_refresh)force_refresh = False+ origin = replay_origin(+ self._replay_scope,+ "messages",+ str(body["model"]),+ endpoint=endpoint,+ )+ sent_body = prepare_history(body, origin)+ presenter = presenter_factory(origin)headers = httpx.Headers({"anthropic-version": "2023-06-01",@@ -303,7 +316,7 @@ class AnthropicMessagesTransport:self._client.build_request("POST",f"{base_url}{path}",- json=body,+ json=sent_body,headers=headers,),stream=True,@@ -366,6 +379,21 @@ class AnthropicMessagesTransport:recovery.discard()continueattempt_failure = None+ if scope is not None and not recovery.committed:+ corrected_history = history_retry_body(+ raw_error, sent_body, "messages"+ )+ if corrected_history is not None:+ retry = (+ execution.can_attempt+ if scope.attempt.accepted+ else await scope.attempt.correct(error)+ is ProviderCorrectionAction.RETRY+ )+ if retry:+ body = corrected_history+ recovery.discard()+ continueif (scope is not Noneand reasoning_correction is not Nonediff --git a/src/free_claude_code/providers/deepseek/client.py b/src/free_claude_code/providers/deepseek/client.pyindex 7c4697c4..450093bb 100644--- a/src/free_claude_code/providers/deepseek/client.py+++ b/src/free_claude_code/providers/deepseek/client.py@@ -1,10 +1,12 @@"""DeepSeek provider implementation (OpenAI-compatible Chat Completions)."""+from collections.abc import Mappingfrom typing import Anyfrom free_claude_code.application.model_metadata import ProviderModelInfofrom free_claude_code.config.constants import ANTHROPIC_DEFAULT_MAX_OUTPUT_TOKENSfrom free_claude_code.core.anthropic.models import MessagesRequest+from free_claude_code.core.history_replay import HistoryScopefrom free_claude_code.core.reasoning import DEFAULT_REASONING_POLICY, ReasoningPolicyfrom free_claude_code.providers.admission import ProviderAdmissionControllerfrom free_claude_code.providers.base import ProviderConfig@@ -24,6 +26,7 @@ from .compat import (_PROFILE = OpenAIChatProfile(DEEPSEEK_REQUEST_POLICY,NO_REASONING,+ history_scope=HistoryScope.ALL,)@@ -51,6 +54,9 @@ def _deepseek_cache_partition(class DeepSeekProvider(OpenAIChatProvider):"""DeepSeek using ``https://api.deepseek.com`` Chat Completions."""+ def _history_scope(self, body: Mapping[str, Any]) -> HistoryScope:+ return HistoryScope.ALL if body.get("tools") else HistoryScope.UNKNOWN+@propertydef _reasoning_off_fields(self) -> tuple[tuple[str, ...], ...]:return (("extra_body", "thinking"),)diff --git a/src/free_claude_code/providers/deepseek/compat.py b/src/free_claude_code/providers/deepseek/compat.pyindex b8913872..2376ec3e 100644--- a/src/free_claude_code/providers/deepseek/compat.py+++ b/src/free_claude_code/providers/deepseek/compat.py@@ -33,9 +33,6 @@ _UNSUPPORTED_MESSAGE_BLOCK_TYPES = frozenset({"image","document",- "server_tool_use",- "web_search_tool_result",- "web_fetch_tool_result",})_STRIPPABLE_MESSAGE_BLOCK_TYPES = frozenset({"image", "document"})@@ -75,51 +72,17 @@ def build_deepseek_request_body(data["messages"], allow_attachments=vision_capable)_validate_deepseek_request_dict(data, allow_attachments=vision_capable)- has_tool_history = _has_tool_history(data)- has_replayable_tool_thinking = _all_tool_calls_have_replayable_thinking(data)- unsafe_tool_followup = has_tool_history and not has_replayable_tool_thinking- effective_reasoning = reasoning- if reasoning.control is not ReasoningControl.OFF:- if unsafe_tool_followup:- logger.debug(- "DEEPSEEK_REQUEST: disabling thinking for tool follow-up without "- "replayable thinking model={} msgs={} tools={}",- data.get("model"),- len(data.get("messages", [])),- len(data.get("tools", [])),- )- _remove_deepseek_thinking_hints(data)- effective_reasoning = ReasoningPolicy.off()- elif has_tool_history:- logger.debug(- "DEEPSEEK_REQUEST: keeping thinking for tool follow-up with "- "replayable thinking model={} msgs={} tools={}",- data.get("model"),- len(data.get("messages", [])),- len(data.get("tools", [])),- )- elif data.get("tools") or data.get("tool_choice"):- logger.debug(- "DEEPSEEK_REQUEST: keeping thinking for initial tool request "- "model={} msgs={} tools={}",- data.get("model"),- len(data.get("messages", [])),- len(data.get("tools", [])),- )-if "messages" in data:- data["messages"] = _normalize_tool_result_content(- sanitize_deepseek_messages_for_openai(data["messages"])- )+ data["messages"] = _normalize_tool_result_content(data["messages"])sanitized_request = MessagesRequest.model_validate(data)body = build_openai_chat_request_body(sanitized_request,- reasoning=effective_reasoning,+ reasoning=reasoning,policy=DEEPSEEK_REQUEST_POLICY,postprocessors=(lambda body, _request, _policy: finalize_deepseek_chat_body(- body, effective_reasoning+ body, reasoning),),)@@ -137,57 +100,20 @@ def finalize_deepseek_chat_body(body: dict[str, Any], reasoning: ReasoningPolicy) -> None:"""Apply source-independent DeepSeek policy to one Chat body."""- effective_reasoning = reasoning- if reasoning.control is not ReasoningControl.OFF:- has_tool_history = _has_chat_tool_history(body)- has_replayable_tool_thinking = _all_chat_tool_calls_have_reasoning(body)- if has_tool_history and not has_replayable_tool_thinking:- _remove_deepseek_thinking_hints(body)- effective_reasoning = ReasoningPolicy.off()+ if body.get("tools") and reasoning.control is not ReasoningControl.OFF:+ for message in body.get("messages", []):+ if (+ message.get("role") == "assistant"+ and message.get("reasoning_content") is None+ ):+ message["reasoning_content"] = message.get("reasoning") or ""_downgrade_chat_forced_tool_choice(body)- _apply_deepseek_chat_extras(body, effective_reasoning)+ _apply_deepseek_chat_extras(body, reasoning)if body.get("max_tokens") is None:body["max_tokens"] = ANTHROPIC_DEFAULT_MAX_OUTPUT_TOKENS-def _has_chat_tool_history(body: Mapping[str, Any]) -> bool:- messages = body.get("messages")- if not isinstance(messages, list):- return False- return any(- isinstance(message, Mapping)- and (- message.get("role") == "tool"- or (- message.get("role") == "assistant"- and isinstance(message.get("tool_calls"), list)- and bool(message["tool_calls"])- )- )- for message in messages- )---def _all_chat_tool_calls_have_reasoning(body: Mapping[str, Any]) -> bool:- messages = body.get("messages")- if not isinstance(messages, list):- return False- found_tool_call = False- for message in messages:- if (- not isinstance(message, Mapping)- or message.get("role") != "assistant"- or not isinstance(message.get("tool_calls"), list)- or not message["tool_calls"]- ):- continue- found_tool_call = True- if "reasoning_content" not in message and "reasoning" not in message:- return False- return found_tool_call--def _downgrade_chat_forced_tool_choice(body: dict[str, Any]) -> None:tool_choice = body.get("tool_choice")if not isinstance(tool_choice, dict) or tool_choice.get("type") != "function":@@ -203,44 +129,6 @@ def _downgrade_chat_forced_tool_choice(body: dict[str, Any]) -> None:body["tool_choice"] = "auto"-def sanitize_deepseek_messages_for_openai(messages: Any) -> Any:- """Keep only DeepSeek-required reasoning history on assistant tool calls."""- if not isinstance(messages, list):- return messages-- sanitized: list[Any] = []- for message in messages:- if not isinstance(message, dict):- sanitized.append(message)- continue- if message.get("role") != "assistant":- sanitized.append(message)- continue- replay_tool_reasoning = _assistant_has_tool_use(message)- new_msg = dict(message)- if not replay_tool_reasoning:- new_msg.pop("reasoning_content", None)- content = message.get("content")- if not isinstance(content, list):- sanitized.append(new_msg)- continue-- filtered = [- block- for block in content- if not (- isinstance(block, dict)- and (- block.get("type") == "redacted_thinking"- or (block.get("type") == "thinking" and not replay_tool_reasoning)- )- )- ]- new_msg["content"] = filtered or ""- sanitized.append(new_msg)- return sanitized--def _strip_unsupported_attachment_blocks(messages: Any, *, allow_attachments: bool = False) -> Any:@@ -391,109 +279,6 @@ def _validate_deepseek_request_dict()-def _has_tool_history_blocks(message: Mapping[str, Any]) -> bool:- role = message.get("role")- content = message.get("content")- if not isinstance(content, list):- return False-- for block in content:- if not isinstance(block, dict):- continue- btype = block.get("type")- if role == "assistant" and btype == "tool_use":- return True- if role == "user" and btype == "tool_result":- return True- return False---def _has_replayable_thinking_before_tool_use(message: Mapping[str, Any]) -> bool:- if message.get("role") != "assistant":- return False- content = message.get("content")- if not isinstance(content, list):- return False-- has_thinking = isinstance(message.get("reasoning_content"), str)- for block in content:- if not isinstance(block, dict):- continue- btype = block.get("type")- if btype == "thinking" and isinstance(block.get("thinking"), str):- has_thinking = True- continue- if btype == "tool_use":- return has_thinking- return False---def _assistant_has_tool_use(message: Mapping[str, Any]) -> bool:- if message.get("role") != "assistant":- return False- content = message.get("content")- return isinstance(content, list) and any(- isinstance(block, dict) and block.get("type") == "tool_use" for block in content- )---def _has_tool_history(data: dict[str, Any]) -> bool:- for message in data.get("messages") or ():- if isinstance(message, Mapping) and _has_tool_history_blocks(message):- return True- return False---def _all_tool_calls_have_replayable_thinking(data: dict[str, Any]) -> bool:- found_tool_call = False- for message in data.get("messages") or ():- if not isinstance(message, Mapping) or not _assistant_has_tool_use(message):- continue- found_tool_call = True- if not _has_replayable_thinking_before_tool_use(message):- return False- return found_tool_call---def _remove_deepseek_thinking_hints(data: dict[str, Any]) -> None:- output_config = data.get("output_config")- if isinstance(output_config, dict) and "effort" in output_config:- cleaned_output_config = dict(output_config)- cleaned_output_config.pop("effort", None)- if cleaned_output_config:- data["output_config"] = cleaned_output_config- else:- data.pop("output_config", None)-- context_management = data.get("context_management")- if not isinstance(context_management, dict):- return- edits = context_management.get("edits")- if not isinstance(edits, list):- return- filtered_edits = [- edit- for edit in edits- if not (- isinstance(edit, dict)- and isinstance(edit.get("type"), str)- and edit["type"].startswith("clear_thinking_")- )- ]- if len(filtered_edits) == len(edits):- return- cleaned_context_management = dict(context_management)- if filtered_edits:- cleaned_context_management["edits"] = filtered_edits- data["context_management"] = cleaned_context_management- else:- cleaned_context_management.pop("edits", None)- if cleaned_context_management:- data["context_management"] = cleaned_context_management- else:- data.pop("context_management", None)--def _normalize_tool_result_content(messages: Any) -> Any:if not isinstance(messages, list):return messagesdiff --git a/src/free_claude_code/providers/endpoint.py b/src/free_claude_code/providers/endpoint.pyindex c01b6bc3..5f947e67 100644--- a/src/free_claude_code/providers/endpoint.py+++ b/src/free_claude_code/providers/endpoint.py@@ -23,6 +23,7 @@ class HttpEndpoint:base_url: strheaders: Mapping[str, str] = field(repr=False)api_key: str | None = field(default=None, repr=False)+ account_id: str | None = field(default=None, repr=False)class EndpointContext(Protocol):@@ -56,6 +57,7 @@ class RequestEndpoint:self._refresh_pending = Falseself._committed = Falseself._omit_authorization = False+ self.snapshot: HttpEndpoint | None = Nonedef commit(self) -> None:self._committed = True@@ -66,6 +68,7 @@ class RequestEndpoint:async def openai_client(self, client: AsyncOpenAI) -> AsyncOpenAI:endpoint = await self._context.endpoint(force_refresh=self._refresh_pending)+ self.snapshot = endpointself._refresh_pending = Falseif self._http is None:self._http = httpx2.AsyncClient(diff --git a/src/free_claude_code/providers/github_copilot/broker.py b/src/free_claude_code/providers/github_copilot/broker.pyindex 8a9fcf6b..400b0269 100644--- a/src/free_claude_code/providers/github_copilot/broker.py+++ b/src/free_claude_code/providers/github_copilot/broker.py@@ -4,6 +4,7 @@ import asyncioimport timefrom collections.abc import AsyncIterator, Mappingfrom contextlib import asynccontextmanager+from dataclasses import replacefrom types import MappingProxyTypefrom free_claude_code.application.errors import InvalidRequestError@@ -92,13 +93,13 @@ class CopilotLease:await self._broker.validate_identity()self._broker.validate_model(self.model.info.model_id)snapshot = await self._owner.endpoint(force_refresh=force_refresh)- await self._broker.validate_identity()+ identity = await self._broker.validate_identity()self._broker.validate_model(self.model.info.model_id)if snapshot.egress is not self.egress:raise CopilotUnavailable("Copilot changed this model's upstream protocol. Retry the request to use its new endpoint.")- return snapshot.http+ return replace(snapshot.http, account_id=f"{identity.host}/{identity.login}")def release(self) -> None:self._released = Truediff --git a/src/free_claude_code/providers/history_replay.py b/src/free_claude_code/providers/history_replay.pynew file mode 100644index 00000000..e9c7be83--- /dev/null+++ b/src/free_claude_code/providers/history_replay.py@@ -0,0 +1,259 @@+"""Provider connection provenance and precise historical request corrections."""++import hashlib+import json+import re+from collections.abc import Iterator, Mapping+from copy import deepcopy+from typing import Any+from urllib.parse import urlsplit, urlunsplit++from openai import AsyncOpenAI++from free_claude_code.application.errors import InvalidRequestError+from free_claude_code.core.diagnostics import extract_upstream_error_detail+from free_claude_code.core.history_replay import (+ HistoryProtocol,+ HistoryReplayError,+ ReplayOrigin,+ decode_replay,+ is_replay,+ readable_reasoning,+ reasoning_context,+)++from .endpoint import HttpEndpoint+++def validate_history(body: Mapping[str, Any]) -> None:+ """Reject malformed persisted carriers before credentials or inference."""+ try:+ for protocol in ("responses", "messages", "chat"):+ for _, item in _reasoning_records(body, protocol):+ for key in ("encrypted_content", "signature", "data"):+ value = item.get(key)+ if isinstance(value, str) and is_replay(value):+ decode_replay(value)+ except HistoryReplayError as error:+ raise InvalidRequestError(str(error)) from error+++def replay_origin(+ provider: str,+ protocol: HistoryProtocol,+ model: str,+ *,+ client: AsyncOpenAI | None = None,+ endpoint: HttpEndpoint | None = None,+) -> ReplayOrigin:+ """Identify the actual connection without storing its credentials."""+ base_url = (+ endpoint.base_url+ if endpoint is not None+ else str(client.base_url)+ if client is not None+ else ""+ )+ headers: Mapping[str, object] = (+ endpoint.headers+ if endpoint is not None+ else client.default_headers+ if client is not None+ else {}+ )+ normalized_headers = {+ key.lower(): value for key, value in headers.items() if isinstance(value, str)+ }+ key = (+ endpoint.api_key+ if endpoint is not None+ else client.api_key+ if client is not None+ else None+ )+ account = endpoint.account_id if endpoint is not None else None+ credential = (+ "account:" + account+ if account+ else "key:" + key+ if isinstance(key, str) and key+ else "auth:"+ + normalized_headers.get(+ "authorization", normalized_headers.get("x-api-key", "")+ )+ )+ parsed = urlsplit(base_url)+ host = parsed.hostname or ""+ if ":" in host:+ host = f"[{host}]"+ if parsed.port:+ host += f":{parsed.port}"+ address = urlunsplit((parsed.scheme, host, parsed.path.rstrip("/"), "", ""))+ return ReplayOrigin(+ provider,+ protocol,+ address,+ hashlib.sha256(credential.encode()).hexdigest(),+ model,+ )+++def history_retry_body(+ error: Exception, body: Mapping[str, Any], protocol: HistoryProtocol+) -> dict[str, Any] | None:+ """Repair one explicitly rejected historical record on an independent copy."""+ detail = extract_upstream_error_detail(error)+ if detail.status_code not in {None, 200, 400, 422}:+ return None+ try:+ payload = json.loads(detail.body_text or "")+ except ValueError:+ payload = {+ "message": detail.exception_text or str(error),+ "code": getattr(error, "code", None),+ }+ candidates = list(_reasoning_records(body, protocol))+ for record in _error_records(payload):+ message = str(record.get("message", ""))+ code = record.get("code", record.get("type"))+ invalid_id = bool(+ re.search(+ r"invalid.+(?:input|messages).+\.id.+(?:letters|characters|ID)",+ message,+ re.I,+ )+ )+ invalid_native = code in {+ "invalid_encrypted_content",+ "invalid_signature",+ } or bool(+ re.search(+ r"invalid signature in thinking block|referenced reasoning item .+ (?:not found|expired)",+ message,+ re.I,+ )+ )+ if not (invalid_id or invalid_native):+ continue+ matched = _rejected_record(record, candidates)+ if matched is None:+ continue+ path, original = matched+ result = deepcopy(dict(body))+ parent: Any = result+ for key in path[:-1]:+ parent = parent[key]+ if invalid_id:+ value = original.get("id")+ if not isinstance(value, str) or re.fullmatch(r"[A-Za-z0-9_-]+", value):+ continue+ corrected = "rs_" + hashlib.sha256(value.encode()).hexdigest()[:24]+ parent[path[-1]]["id"] = corrected+ for item in result.get("input", []):+ if (+ isinstance(item, dict)+ and item.get("type") == "item_reference"+ and item.get("id") == value+ ):+ item["id"] = corrected+ else:+ context = "\n\n".join(+ reasoning_context(text, summary=summary)+ for text, summary in readable_reasoning(+ original+ if protocol != "chat"+ else {"reasoning_details": [original]}+ )+ )+ if protocol == "responses" and context:+ parent[path[-1]] = {"role": "assistant", "content": context}+ elif protocol == "messages" and context:+ parent[path[-1]] = {"type": "text", "text": context}+ else:+ del parent[path[-1]]+ if protocol == "chat":+ assistant = result["messages"][path[1]]+ if context:+ assistant["content"] = (+ (assistant.get("content") or "") + "\n\n" + context+ )+ if not parent:+ assistant.pop("reasoning_details", None)+ return result+ return None+++def _reasoning_records(+ body: Mapping[str, Any], protocol: HistoryProtocol+) -> Iterator[tuple[tuple[str | int, ...], Mapping[str, Any]]]:+ if protocol == "responses":+ items = body.get("input")+ if isinstance(items, Mapping):+ items = [items]+ for index, item in enumerate(items if isinstance(items, list) else []):+ if isinstance(item, Mapping) and item.get("type") == "reasoning":+ yield ("input", index), item+ return+ for index, message in enumerate(body.get("messages", [])):+ if not isinstance(message, Mapping) or message.get("role") != "assistant":+ continue+ field = "content" if protocol == "messages" else "reasoning_details"+ blocks = message.get(field)+ if not isinstance(blocks, list):+ continue+ for block_index, block in enumerate(blocks):+ if isinstance(block, Mapping) and (+ protocol == "chat"+ or block.get("type") in {"thinking", "redacted_thinking"}+ ):+ yield ("messages", index, field, block_index), block+++def _error_records(payload: object) -> Iterator[Mapping[str, Any]]:+ if isinstance(payload, Mapping):+ if isinstance(payload.get("message"), str):+ yield payload+ for key in ("error", "errors", "metadata", "raw", "previous_errors"):+ nested = payload.get(key)+ if key == "raw" and isinstance(nested, str):+ try:+ nested = json.loads(nested)+ except ValueError:+ continue+ yield from _error_records(nested)+ elif isinstance(payload, list):+ for item in payload:+ yield from _error_records(item)+++def _rejected_record(+ error: Mapping[str, Any],+ candidates: list[tuple[tuple[str | int, ...], Mapping[str, Any]]],+) -> tuple[tuple[str | int, ...], Mapping[str, Any]] | None:+ location = str(error.get("param") or error.get("loc") or error.get("message") or "")+ match = re.search(+ r"(?:input|messages)(?:\[\d+\]|\.\d+)(?:(?:\.content|\.reasoning_details)(?:\[\d+\]|\.\d+))?",+ location,+ )+ if match:+ path = tuple(+ int(part) if part.isdigit() else part+ for part in re.findall(r"[a-z_]+|\d+", match[0])+ )+ return next((entry for entry in candidates if entry[0] == path), None)+ message = str(error.get("message", ""))+ identified = [+ entry+ for entry in candidates+ if isinstance(entry[1].get("id"), str) and f"'{entry[1]['id']}'" in message+ ]+ if len(identified) == 1:+ return identified[0]+ opaque = [+ entry+ for entry in candidates+ if any(entry[1].get(key) for key in ("encrypted_content", "signature", "data"))+ ]+ if len(opaque) == 1:+ return opaque[0]+ return Nonediff --git a/src/free_claude_code/providers/kilo/client.py b/src/free_claude_code/providers/kilo/client.pyindex 86a9ccbc..62492f94 100644--- a/src/free_claude_code/providers/kilo/client.py+++ b/src/free_claude_code/providers/kilo/client.py@@ -10,7 +10,6 @@ from free_claude_code.providers.openai_chat import (OpenAIChatProvider,OpenAIChatRequestPolicy,ReasoningObject,- apply_reasoning_details_replay,validate_extra_body_does_not_override_canonical_fields,)@@ -24,7 +23,6 @@ _PROFILE = OpenAIChatProfile(extra_body_validator=validate_extra_body_does_not_override_canonical_fields,),ReasoningObject(tuple((effort, effort.value) for effort in ReasoningEffort)),- postprocessors=(apply_reasoning_details_replay,),reasoning_delta_field="reasoning",structured_reasoning_details=True,)diff --git a/src/free_claude_code/providers/nvidia_nim/retry.py b/src/free_claude_code/providers/nvidia_nim/retry.pyindex 335a0b6d..60d46b39 100644--- a/src/free_claude_code/providers/nvidia_nim/retry.py+++ b/src/free_claude_code/providers/nvidia_nim/retry.py@@ -4,6 +4,8 @@ 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_reasoning_budget(body: dict[str, Any]) -> dict[str, Any] | None:"""Clone a request body and strip only reasoning_budget fields."""@@ -18,7 +20,7 @@ def clone_body_without_chat_template(body: dict[str, Any]) -> dict[str, Any] | Ndef clone_body_without_reasoning_content(body: dict[str, Any],) -> dict[str, Any] | None:- """Clone a request body and strip assistant message ``reasoning_content`` fields."""+ """Move rejected native reasoning fields into readable assistant context."""cloned_body = deepcopy(body)if not _strip_message_reasoning_content(cloned_body):return None@@ -64,9 +66,20 @@ def _strip_message_reasoning_content(body: dict[str, Any]) -> bool:if not isinstance(messages, list):return Falsefor message in messages:+ if not isinstance(message, dict):+ continue+ reasoning = message.pop("reasoning_content", None)+ if reasoning is not None:+ removed = Trueif (- isinstance(message, dict)- and message.pop("reasoning_content", None) is not None+ isinstance(reasoning, str)+ and reasoning+ and message.get("role") == "assistant"):- removed = True+ context = reasoning_context(reasoning)+ content = message.get("content")+ if isinstance(content, list):+ content.append({"type": "text", "text": context})+ else:+ message["content"] = f"{content}\n\n{context}" if content else contextreturn removeddiff --git a/src/free_claude_code/providers/open_router/client.py b/src/free_claude_code/providers/open_router/client.pyindex 57b96fe9..1aff6fd8 100644--- a/src/free_claude_code/providers/open_router/client.py+++ b/src/free_claude_code/providers/open_router/client.py@@ -15,7 +15,6 @@ from free_claude_code.providers.openai_chat import (OpenAIChatProvider,OpenAIChatRequestPolicy,ReasoningObject,- apply_reasoning_details_replay,validate_extra_body_does_not_override_canonical_fields,)from free_claude_code.providers.reasoning_compatibility import (@@ -74,6 +73,5 @@ class OpenRouterProvider(OpenAIChatProvider):_PROFILE = OpenAIChatProfile(_REQUEST_POLICY,ReasoningObject(tuple((effort, effort.value) for effort in ReasoningEffort)),- postprocessors=(apply_reasoning_details_replay,),structured_reasoning_details=True,)diff --git a/src/free_claude_code/providers/openai_chat/__init__.py b/src/free_claude_code/providers/openai_chat/__init__.pyindex e6e5a019..123b80d8 100644--- a/src/free_claude_code/providers/openai_chat/__init__.py+++ b/src/free_claude_code/providers/openai_chat/__init__.py@@ -16,7 +16,6 @@ from .reasoning import (NamedEffortReasoning,ReasoningObject,)-from .reasoning_details import apply_reasoning_details_replayfrom .request_policy import (OpenAIChatRequestPolicy,apply_openai_chat_body_policy,@@ -58,7 +57,6 @@ __all__ = ["OpenAIModelListing","ReasoningObject","apply_openai_chat_body_policy",- "apply_reasoning_details_replay","build_openai_chat_request_body","create_openai_chat_provider","openai_v1_base_url",diff --git a/src/free_claude_code/providers/openai_chat/profiles.py b/src/free_claude_code/providers/openai_chat/profiles.pyindex 8626d464..1c5cdf78 100644--- a/src/free_claude_code/providers/openai_chat/profiles.py+++ b/src/free_claude_code/providers/openai_chat/profiles.py@@ -9,6 +9,7 @@ from free_claude_code.application.errors import InvalidRequestErrorfrom free_claude_code.config.constants import ANTHROPIC_DEFAULT_MAX_OUTPUT_TOKENSfrom free_claude_code.core.anthropic import ReasoningReplayModefrom free_claude_code.core.anthropic.models import MessagesRequest+from free_claude_code.core.history_replay import HistoryScopefrom free_claude_code.core.model_capabilities import ModelInputModalityfrom free_claude_code.core.reasoning import ReasoningEffort, ReasoningPolicyfrom free_claude_code.providers.model_listing import (@@ -33,7 +34,6 @@ from .reasoning import (ReasoningObject,ThinkingObjectReasoning,)-from .reasoning_details import apply_reasoning_details_replayfrom .request_policy import OpenAIChatPostprocessor, OpenAIChatRequestPolicy_ALL_EFFORTS = tuple((effort, effort.value) for effort in ReasoningEffort)@@ -128,6 +128,7 @@ class OpenAIChatProfile:None)structured_reasoning_details: bool = False+ history_scope: HistoryScope = HistoryScope.TOOL_CONTINUATIONuser_agent: str | None = None@property@@ -237,7 +238,6 @@ OPENAI_CHAT_PROFILES: dict[str, OpenAIChatProfile] = {"cline_pass": OpenAIChatProfile(_policy("CLINE_PASS", ReasoningReplayMode.DISABLED),NO_REASONING,- postprocessors=(apply_reasoning_details_replay,),model_listing=OpenAIModelListing(path="/ai/cline/recommended-models",collection_field="clinePass",@@ -419,7 +419,6 @@ OPENAI_CHAT_PROFILES: dict[str, OpenAIChatProfile] = {max_tokens_field="max_completion_tokens",),ReasoningObject(_MINIMAL_TO_XHIGH),- postprocessors=(apply_reasoning_details_replay,),model_listing=OpenAIModelListing(required_sequence_items=(("input_modalities", "text"),diff --git a/src/free_claude_code/providers/openai_chat/provider.py b/src/free_claude_code/providers/openai_chat/provider.pyindex 612f9040..475b4ad2 100644--- a/src/free_claude_code/providers/openai_chat/provider.py+++ b/src/free_claude_code/providers/openai_chat/provider.py@@ -6,7 +6,7 @@ import uuidfrom collections.abc import AsyncIterator, Awaitable, Callable, Iterator, Mappingfrom dataclasses import dataclass, replacefrom enum import StrEnum-from typing import Any+from typing import Any, castimport httpx2from loguru import logger@@ -35,6 +35,7 @@ from free_claude_code.core.anthropic.streaming import ()from free_claude_code.core.anthropic.usage import anthropic_input_usage_fieldsfrom free_claude_code.core.failures import ExecutionFailure, FailureKind+from free_claude_code.core.history_replay import HistoryScope, prepare_historyfrom free_claude_code.core.json_types import JsonObjectfrom free_claude_code.core.openai_responses import (OpenAIResponsesRequest,@@ -69,6 +70,11 @@ from free_claude_code.providers.failure_policy import (is_retryable_stream_error,underlying_provider_error,)+from free_claude_code.providers.history_replay import (+ history_retry_body,+ replay_origin,+ validate_history,+)from free_claude_code.providers.http import (ProviderAttemptScope,close_provider_stream,@@ -242,6 +248,8 @@ class _OpenAIChatStreamAssembler:if profile.structured_reasoning_detailselse None)+ if self._structured_reasoning is not None:+ self._output.reasoning_replay_events = self._structured_reasoning.flushself._finish_reason: Any = Noneself._usage_info: Any = Noneself._native_reasoning_seen = False@@ -313,8 +321,18 @@ class _OpenAIChatStreamAssembler:if not chunk.choices:return+ if (+ self._output.replay_origin is not None+ and isinstance(getattr(chunk, "model", None), str)+ and chunk.model+ ):+ self._output.replay_origin = replace(+ self._output.replay_origin, model=chunk.model+ )choice = chunk.choices[0]delta = choice.delta+ if choice.finish_reason:+ self._finish_reason = choice.finish_reasonif delta is None:return@@ -438,6 +456,7 @@ class _OpenAIChatStreamAssembler:self._heuristic_parser.flush(),tool_names=self._tool_names,)+ yield from self._output.flush_reasoning_replay()self._upstream_finished = Truedef prepare_completion(self) -> Iterator[str]:@@ -717,6 +736,7 @@ class OpenAIChatProvider(BaseProvider):reasoning: ReasoningPolicy = DEFAULT_REASONING_POLICY,) -> ResponsesChatRequest:"""Build a Chat body directly from Responses ingress."""+ validate_history(request.model_dump(mode="json"))try:translated = build_responses_chat_request(request,@@ -748,6 +768,9 @@ class OpenAIChatProvider(BaseProvider):"""Apply provider behavior that is independent of client protocol."""return body+ def _history_scope(self, body: Mapping[str, Any]) -> HistoryScope:+ return self._profile.history_scope+def preflight_messages(self,request: MessagesRequest,@@ -863,6 +886,23 @@ class OpenAIChatProvider(BaseProvider):**(extra_headers or {}),**(endpoint.openai_headers() if endpoint is not None else {}),}+ origin = replay_origin(+ self._provider_name,+ "chat",+ str(body["model"]),+ client=client,+ endpoint=endpoint.snapshot if endpoint is not None else None,+ )+ create_body = cast(+ dict[str, Any],+ prepare_history(+ create_body,+ origin,+ scope=self._history_scope(body),+ reasoning_field=self._profile.request_policy.reasoning_replay.value,+ structured_details=self._profile.structured_reasoning_details,+ ),+ )stream = await client.chat.completions.create(**create_body,stream=True,@@ -924,6 +964,11 @@ class OpenAIChatProvider(BaseProvider):reasoning_correction: ReasoningCorrection | None = None,sent_body: Mapping[str, Any] | None = None,) -> dict | None:+ corrected_history = history_retry_body(+ error, sent_body if sent_body is not None else body, "chat"+ )+ if corrected_history is not None:+ return corrected_historyif reasoning_correction is not None and "reasoning" not in used_retry_kinds:retry_body = reasoning_correction.retry_body(error, body, sent_body=sent_body@@ -947,7 +992,9 @@ class OpenAIChatProvider(BaseProvider):return retry_bodyif "provider_specific" not in used_retry_kinds:- retry_body = self._get_retry_request_body(error, body)+ retry_body = self._get_retry_request_body(+ error, dict(sent_body) if sent_body is not None else body+ )if retry_body is not None:used_retry_kinds.add("provider_specific")return retry_body@@ -1102,6 +1149,7 @@ class _OpenAIChatStreamRunner:) -> None:self._provider = providerself._body = body+ self._tool_argument_aliases = provider._tool_argument_aliases(body)self._tool_names = tool_namesself._tool_schemas = tool_schemasself._reserved_tool_ids = reserved_tool_ids@@ -1199,9 +1247,16 @@ class _OpenAIChatStreamRunner:request_id=self._request_id,)stream = scope.retain(stream)- assembler.bind_tool_argument_aliases(- self._provider._tool_argument_aliases(body)+ assembler.output.replay_origin = replay_origin(+ tag,+ "chat",+ str(body["model"]),+ client=self._provider._client,+ endpoint=self._endpoint.snapshot+ if self._endpoint is not None+ else None,)+ assembler.bind_tool_argument_aliases(self._tool_argument_aliases)async for chunk in stream:if not scope.attempt.accepted:await scope.attempt.accept()@@ -1220,6 +1275,19 @@ class _OpenAIChatStreamRunner:except asyncio.CancelledError, GeneratorExit:raiseexcept Exception as error:+ if scope is not None and not recovery.committed:+ corrected_history = history_retry_body(error, sent_body, "chat")+ if corrected_history is not None:+ retry = (+ execution.can_attempt+ if scope.attempt.accepted+ else await scope.attempt.correct(error)+ is ProviderCorrectionAction.RETRY+ )+ if retry:+ body = corrected_history+ recovery.discard()+ continueif (scope is not Noneand not recovery.committed@@ -1537,7 +1605,7 @@ class _OpenAIChatStreamRunner:completed_tool_calls = tool_calls.completed_calls(self._tool_schemas,tool_names=self._tool_names,- tool_argument_aliases=self._provider._tool_argument_aliases(body),+ tool_argument_aliases=self._tool_argument_aliases,)if tool_calls.has_calls and completed_tool_calls is None:raise TruncatedProviderStreamError(diff --git a/src/free_claude_code/providers/openai_chat/reasoning_details.py b/src/free_claude_code/providers/openai_chat/reasoning_details.pyindex 93bbd337..27eb3db4 100644--- a/src/free_claude_code/providers/openai_chat/reasoning_details.py+++ b/src/free_claude_code/providers/openai_chat/reasoning_details.py@@ -1,53 +1,23 @@"""OpenRouter-format structured reasoning replay and stream conversion."""-import jsonfrom collections.abc import Iterator, Mapping, Sequence-from typing import Any, Literal+from copy import deepcopy+from typing import Any, Literal, cast-from free_claude_code.core.anthropic.models import MessagesRequest-from free_claude_code.core.openai_chat import (- is_synthetic_chat_tool_turn_boundary,-)-from free_claude_code.core.reasoning import ReasoningPolicy+from free_claude_code.core.history_replay import readable_reasoning+from free_claude_code.core.json_types import JsonObject, JsonValuefrom .stream_output import ChatStreamOutput-def apply_reasoning_details_replay(- body: dict[str, Any], request: MessagesRequest, _policy: ReasoningPolicy-) -> None:- """Replay opaque reasoning details on their converted assistant messages."""- assistant_details = _assistant_reasoning_details(request.messages)- if not assistant_details:- return- messages = body.get("messages")- if not isinstance(messages, list):- return-- cursor = 0- for details in assistant_details:- for index in range(cursor, len(messages)):- message = messages[index]- if (- not isinstance(message, dict)- or message.get("role") != "assistant"- or is_synthetic_chat_tool_turn_boundary(message)- ):- continue- existing = message.get("reasoning_details")- if isinstance(existing, list):- existing.extend(details)- else:- message["reasoning_details"] = list(details)- cursor = index + 1- break--class StructuredReasoningStream:"""Reconcile alternate plaintext reasoning representations for one stream."""def __init__(self) -> None:self._text_source: Literal["native", "details"] | None = None+ self._details: list[dict[str, Any]] = []+ self._slots: dict[tuple[object, object], int] = {}+ self._native_parts: list[str] = []def events(self,@@ -58,6 +28,8 @@ class StructuredReasoningStream:) -> Iterator[str]:"""Emit plaintext once while preserving every opaque reasoning detail."""details = _reasoning_details(delta)+ if native_reasoning is not None:+ self._native_parts.append(native_reasoning)if self._text_source is None:if native_reasoning:self._text_source = "native"@@ -75,9 +47,45 @@ class StructuredReasoningStream:yield from output.ensure_reasoning_block()yield output.emit_reasoning_delta(text)- preserved = _preserved_reasoning_detail(detail)- if preserved:- yield from output.emit_opaque_reasoning(preserved)+ if isinstance(detail, Mapping):+ value = deepcopy(dict(detail))+ identity = value.get("index", value.get("id"))+ key = (identity, value.get("type"))+ if isinstance(identity, str | int) and key in self._slots:+ current = self._details[self._slots[key]]+ for field, part in value.items():+ if (+ field+ in {+ "text",+ "summary",+ "content",+ "reasoning",+ "data",+ "signature",+ }+ and isinstance(part, str)+ and isinstance(current.get(field), str)+ ):+ current[field] += part+ else:+ current[field] = part+ else:+ if isinstance(identity, str | int):+ self._slots[key] = len(self._details)+ self._details.append(value)++ def flush(self, output: ChatStreamOutput) -> Iterator[str]:+ if self._details:+ native: JsonObject = {+ "reasoning_details": cast(list[JsonValue], self._details)+ }+ if self._native_parts:+ native["reasoning_content"] = "".join(self._native_parts)+ yield from output.emit_reasoning_replay(native)+ self._details.clear()+ self._slots.clear()+ self._native_parts.clear()def _reasoning_details(delta: Any) -> Sequence[Any]:@@ -89,40 +97,15 @@ def _reasoning_details(delta: Any) -> Sequence[Any]:return details if _is_sequence(details) else ()-def _assistant_reasoning_details(messages: Any) -> list[list[dict[str, Any]]]:- if not _is_sequence(messages):- return []- result: list[list[dict[str, Any]]] = []- for message in messages:- if _field(message, "role") != "assistant":- continue- details = _redacted_reasoning_details(_field(message, "content"))- if details:- result.append(details)- return result---def _redacted_reasoning_details(content: Any) -> list[dict[str, Any]]:- if not _is_sequence(content):- return []- details: list[dict[str, Any]] = []- for block in content:- if _field(block, "type") != "redacted_thinking":- continue- data = _field(block, "data")- if not isinstance(data, str) or not data:- continue- parsed = _json_payload(data)- if isinstance(parsed, list):- details.extend(item for item in parsed if isinstance(item, dict))- elif isinstance(parsed, dict):- details.append(parsed)- else:- details.append({"type": "reasoning.encrypted", "data": data})- return details--def _reasoning_detail_text(detail: Any) -> str | None:+ if isinstance(detail, Mapping) and detail.get("type") == "reasoning.summary":+ return (+ "".join(+ text+ for text, _ in readable_reasoning({"reasoning_details": [dict(detail)]})+ )+ or None+ )kind = str(_field(detail, "type") or "").lower()if "encrypted" in kind or "redacted" in kind:return None@@ -133,29 +116,6 @@ def _reasoning_detail_text(detail: Any) -> str | None:return None-def _preserved_reasoning_detail(detail: Any) -> str | None:- if not isinstance(detail, Mapping):- return None- kind = str(_field(detail, "type") or "").lower()- signature = _field(detail, "signature")- if (- "encrypted" in kind- or "redacted" in kind- or "summary" in kind- or isinstance(signature, str)- or _reasoning_detail_text(detail) is None- ):- return json.dumps(dict(detail), separators=(",", ":"))- return None---def _json_payload(value: str) -> Any:- try:- return json.loads(value)- except json.JSONDecodeError:- return None--def _field(item: Any, name: str) -> Any:if isinstance(item, Mapping):return item.get(name)diff --git a/src/free_claude_code/providers/openai_chat/request_policy.py b/src/free_claude_code/providers/openai_chat/request_policy.pyindex 4dba4ef4..65378cf6 100644--- a/src/free_claude_code/providers/openai_chat/request_policy.py+++ b/src/free_claude_code/providers/openai_chat/request_policy.py@@ -19,6 +19,7 @@ from free_claude_code.core.openai_tool_names import (encode_openai_chat_tool_names,)from free_claude_code.core.reasoning import ReasoningPolicy+from free_claude_code.providers.history_replay import validate_historyMaxTokensField = Literal["max_tokens", "max_completion_tokens"]OpenAIChatPostprocessor = Callable[@@ -51,6 +52,7 @@ def build_openai_chat_request_body(postprocessors: Iterable[OpenAIChatPostprocessor] = (),) -> dict[str, Any]:"""Build an OpenAI-compatible chat request body from an Anthropic request."""+ validate_history(request_data.model_dump(mode="json"))logger.debug("{}_REQUEST: conversion start model={} msgs={}",policy.provider_name,diff --git a/src/free_claude_code/providers/openai_chat/stream_output.py b/src/free_claude_code/providers/openai_chat/stream_output.pyindex 288299e4..f328bf61 100644--- a/src/free_claude_code/providers/openai_chat/stream_output.py+++ b/src/free_claude_code/providers/openai_chat/stream_output.py@@ -5,7 +5,7 @@ import jsonimport timeimport uuidfrom abc import ABC, abstractmethod-from collections.abc import Mapping+from collections.abc import Callable, Iterator, Mappingfrom dataclasses import dataclass, fieldfrom loguru import logger@@ -16,6 +16,11 @@ from free_claude_code.core.anthropic.streaming import (parse_complete_tool_input,)from free_claude_code.core.failures import ExecutionFailure+from free_claude_code.core.history_replay import (+ ReplayOrigin,+ ReplayRecord,+ encode_replay,+)from free_claude_code.core.json_types import JsonObjectfrom free_claude_code.core.openai_responses import (OpenAIResponsesRequest,@@ -78,6 +83,10 @@ class ChatStreamOutput(ABC):def __init__(self, *, input_tokens: int) -> None:self.input_tokens = input_tokens+ self.replay_origin: ReplayOrigin | None = None+ self.reasoning_replay_events: (+ Callable[[ChatStreamOutput], Iterator[str]] | None+ ) = Noneself.tool_states: dict[int, ChatToolState] = {}self._text_parts: list[str] = []self._reasoning_parts: list[str] = []@@ -116,15 +125,26 @@ class ChatStreamOutput(ABC):self._reasoning_parts.append(content)return self._emit_reasoning_delta(content)- def emit_opaque_reasoning(self, data: str) -> list[str]:- events = self.close_content_blocks()+ def emit_reasoning_replay(self, native: JsonObject) -> list[str]:+ data = json.dumps(native["reasoning_details"], separators=(",", ":"))+ if self.replay_origin is not None:+ data = encode_replay(ReplayRecord(self.replay_origin, native))+ if self._reasoning_started:+ return self._attach_reasoning_replay(data)+ events = self._close_content_blocks()events.extend(self._emit_opaque_reasoning(data))if data:self._content_started = Truereturn events+ def flush_reasoning_replay(self) -> list[str]:+ """Save the complete record when parsed output ends a reasoning block."""+ if self.reasoning_replay_events is None:+ return []+ return list(self.reasoning_replay_events(self))+def ensure_text_block(self) -> list[str]:- events: list[str] = []+ events = self.flush_reasoning_replay()if self._reasoning_started:events.extend(self._stop_reasoning_block())self._reasoning_started = False@@ -139,6 +159,11 @@ class ChatStreamOutput(ABC):return self._emit_text_delta(content)def close_content_blocks(self) -> list[str]:+ events = self.flush_reasoning_replay()+ events.extend(self._close_content_blocks())+ return events++ def _close_content_blocks(self) -> list[str]:events: list[str] = []if self._reasoning_started:events.extend(self._stop_reasoning_block())@@ -326,6 +351,9 @@ class ChatStreamOutput(ABC):@abstractmethoddef _emit_opaque_reasoning(self, data: str) -> list[str]: ...+ @abstractmethod+ def _attach_reasoning_replay(self, data: str) -> list[str]: ...+@abstractmethoddef _stop_reasoning_block(self) -> list[str]: ...@@ -378,7 +406,8 @@ class AnthropicChatStreamOutput(ChatStreamOutput):)def close_unclosed_blocks(self) -> list[str]:- events = list(self._ledger.close_unclosed_blocks())+ events = self.flush_reasoning_replay()+ events.extend(self._ledger.close_unclosed_blocks())self._text_started = Falseself._reasoning_started = Falsefor state in self.tool_states.values():@@ -401,6 +430,13 @@ class AnthropicChatStreamOutput(ChatStreamOutput):self._ledger.content_block_stop(index),]+ def _attach_reasoning_replay(self, data: str) -> list[str]:+ return [+ self._ledger.content_block_delta(+ self._ledger.blocks.thinking_index, "signature_delta", data+ )+ ]+def _stop_reasoning_block(self) -> list[str]:return [self._ledger.stop_thinking_block()]@@ -561,6 +597,11 @@ class ResponsesChatStreamOutput(ChatStreamOutput):events.extend(self._completer.complete_block(state))return events+ def _attach_reasoning_replay(self, data: str) -> list[str]:+ if self._reasoning_state is not None:+ self._reasoning_state.encrypted_content = data+ return []+def _stop_reasoning_block(self) -> list[str]:state = self._reasoning_stateself._reasoning_state = Nonediff --git a/src/free_claude_code/providers/openai_codex/endpoint.py b/src/free_claude_code/providers/openai_codex/endpoint.pyindex ebd2d7e0..3628e9dc 100644--- a/src/free_claude_code/providers/openai_codex/endpoint.py+++ b/src/free_claude_code/providers/openai_codex/endpoint.py@@ -50,4 +50,4 @@ class CodexEndpointContext:}if access.fedramp:headers["X-OpenAI-Fedramp"] = "true"- return HttpEndpoint(self._base_url, headers)+ return HttpEndpoint(self._base_url, headers, account_id=access.account_id)diff --git a/src/free_claude_code/providers/openai_responses/transport.py b/src/free_claude_code/providers/openai_responses/transport.pyindex c7a6b2e1..3964ea87 100644--- a/src/free_claude_code/providers/openai_responses/transport.py+++ b/src/free_claude_code/providers/openai_responses/transport.py@@ -4,6 +4,7 @@ import asyncioimport sysimport uuidfrom collections.abc import AsyncIterator, Callable, Mapping+from dataclasses import replacefrom typing import castimport httpx2@@ -16,6 +17,10 @@ from free_claude_code.application.model_metadata import ProviderModelInfofrom free_claude_code.core.anthropic.models import MessagesRequestfrom free_claude_code.core.diagnostics import extract_upstream_error_detailfrom free_claude_code.core.failures import ExecutionFailure, FailureKind+from free_claude_code.core.history_replay import (+ prepare_history,+ preserve_responses_reasoning,+)from free_claude_code.core.json_types import JsonObjectfrom free_claude_code.core.openai_responses import (OpenAIResponsesRequest,@@ -47,6 +52,11 @@ from free_claude_code.providers.failure_policy import (provider_authentication_status,reports_context_window_incomplete,)+from free_claude_code.providers.history_replay import (+ history_retry_body,+ replay_origin,+ validate_history,+)from free_claude_code.providers.http import ProviderAttemptScope, maybe_await_aclosefrom free_claude_code.providers.reasoning_compatibility import (ReasoningCorrection,@@ -215,6 +225,7 @@ class OpenAIResponsesTransport:model_info: ProviderModelInfo | None = None,can_disable_reasoning: bool = True,) -> JsonObject:+ validate_history(request.model_dump(mode="json"))request, reasoning = prepare_messages_reasoning(request,reasoning,@@ -241,6 +252,7 @@ class OpenAIResponsesTransport:*,reasoning: ReasoningPolicy,) -> tuple[JsonObject, ResponsesToolAdapter]:+ validate_history(request.model_dump(mode="json"))if not request.model.strip():raise InvalidRequestError("Responses request model must not be empty.")if request.input is None or request.input == "" or request.input == []:@@ -361,6 +373,14 @@ class OpenAIResponsesTransport:if endpoint is not Noneelse self._client)+ origin = replay_origin(+ self._provider_name,+ "responses",+ str(body["model"]),+ client=client,+ endpoint=endpoint.snapshot if endpoint is not None else None,+ )+ sent_body = prepare_history(body, origin)attempt = await execution.open_attempt(ProviderOperationKind.GENERATION)scope = ProviderAttemptScope(attempt,@@ -368,7 +388,10 @@ class OpenAIResponsesTransport:request_id=request_id,)sdk_stream = await self._create_sdk_stream(- body, client=client, endpoint=endpoint, extra_headers=extra_headers+ sent_body,+ client=client,+ endpoint=endpoint,+ extra_headers=extra_headers,)stream = scope.retain(_ClosableResponsesStream(sdk_stream))stream_opened = True@@ -412,6 +435,14 @@ class OpenAIResponsesTransport:raise context_window_exceeded_provider_failure()if adapt_event is not None:payload = adapt_event(upstream_event.type, payload)+ response = payload.get("response")+ if (+ isinstance(response, dict)+ and isinstance(response.get("model"), str)+ and response["model"]+ ):+ origin = replace(origin, model=response["model"])+ payload = preserve_responses_reasoning(payload, origin)for event in presenter.feed(upstream_event.type, payload):for held in recovery.push(event):yield held@@ -445,6 +476,21 @@ class OpenAIResponsesTransport:):recovery.discard()continue+ if scope is not None and not recovery.committed:+ corrected_history = history_retry_body(+ raw_error, sent_body, "responses"+ )+ if corrected_history is not None:+ retry = (+ execution.can_attempt+ if scope.attempt.accepted+ else await scope.attempt.correct(error)+ is ProviderCorrectionAction.RETRY+ )+ if retry:+ body = corrected_history+ recovery.discard()+ continueif (scope is not Noneand reasoning_correction is not Nonediff --git a/tests/core/openai_responses/test_chat_request.py b/tests/core/openai_responses/test_chat_request.pyindex 977a9745..7539439d 100644--- a/tests/core/openai_responses/test_chat_request.py+++ b/tests/core/openai_responses/test_chat_request.py@@ -138,8 +138,8 @@ def test_build_responses_chat_request_preserves_rich_supported_semantics() -> No},{"role": "assistant",- "content": "",- "reasoning_content": "Use the tool.",+ "content": "[Earlier reasoning summary]\nUse the tool.",+ "reasoning_content": "","reasoning_details": [{"type": "reasoning.encrypted", "data": "opaque-replay"}],@@ -220,7 +220,10 @@ def test_build_responses_chat_request_preserves_rich_supported_semantics() -> No(ReasoningReplayMode.REASONING_CONTENT, {"reasoning_content": "Think"}),(ReasoningReplayMode.REASONING, {"reasoning": "Think"}),(ReasoningReplayMode.THINK_TAGS, {"content": "<think>\nThink\n</think>"}),- (ReasoningReplayMode.DISABLED, {}),+ (+ ReasoningReplayMode.DISABLED,+ {"content": "[Earlier reasoning]\nThink\n\nAnswer"},+ ),],)def test_build_responses_chat_request_uses_provider_reasoning_replay(@@ -250,7 +253,10 @@ def test_build_responses_chat_request_uses_provider_reasoning_replay(for key, value in expected.items():assert assistant[key] == valueif mode is ReasoningReplayMode.DISABLED:- assert assistant == {"role": "assistant", "content": "Answer"}+ assert assistant == {+ "role": "assistant",+ "content": "[Earlier reasoning]\nThink\n\nAnswer",+ }def test_build_responses_chat_request_quarantines_one_malformed_call_pair() -> None:@@ -290,6 +296,7 @@ def test_build_responses_chat_request_quarantines_one_malformed_call_pair() -> N{"role": "assistant","content": "",+ "reasoning_content": "","tool_calls": [{"id": "call_good",diff --git a/tests/core/openai_responses/test_messages_request.py b/tests/core/openai_responses/test_messages_request.pyindex abbe8d9c..997c1e34 100644--- a/tests/core/openai_responses/test_messages_request.py+++ b/tests/core/openai_responses/test_messages_request.py@@ -5,6 +5,12 @@ from collections.abc import Mappingimport pytestfrom free_claude_code.core.anthropic.native import NativeMessagesOptions+from free_claude_code.core.history_replay import (+ ReplayOrigin,+ ReplayRecord,+ encode_replay,+ prepare_history,+)from free_claude_code.core.json_types import JsonObject, JsonValuefrom free_claude_code.core.openai_responses import (OpenAIResponsesRequest,@@ -12,10 +18,6 @@ from free_claude_code.core.openai_responses import (ResponsesMessagesRequest,build_responses_messages_request,)-from free_claude_code.core.openai_responses.reasoning_replay import (- MessagesReplayOrigin,- encode_messages_reasoning,-)_SCOPE = "github_copilot/anthropic_messages"_FUNCTION: JsonObject = {@@ -90,7 +92,6 @@ def _build({"model": "public", "input": "hi", **payload}),options=NativeMessagesOptions("concrete", 4096, thinking),- replay_scope=_SCOPE,)@@ -129,8 +130,10 @@ def test_parallel_function_and_custom_roundtrip_preserves_replay_order_and_image"signature": "opaque","extension": {"record": 1},}- carrier = encode_messages_reasoning(- native_thinking, origin=MessagesReplayOrigin(_SCOPE, "source")+ carrier = encode_replay(+ ReplayRecord(+ ReplayOrigin(_SCOPE, "messages", "", "", "source"), native_thinking+ ))tools: list[JsonValue] = [{@@ -209,7 +212,9 @@ def test_parallel_function_and_custom_roundtrip_preserves_replay_order_and_image{"type": "text", "text": "first"},{"type": "text", "text": "second"},]- messages = built.body["messages"]+ messages = prepare_history(+ built.body, ReplayOrigin(_SCOPE, "messages", "", "", "target")+ )["messages"]assert isinstance(messages, list) and len(messages) == 3assistant = messages[1]assert isinstance(assistant, Mapping)@@ -383,15 +388,6 @@ def test_malformed_tool_history_is_rejected_before_inference(}]},- {"input": [{"type": "reasoning", "encrypted_content": "foreign-openai-blob"}]},- {- "input": [- {- "type": "reasoning",- "content": [{"type": "reasoning_text", "text": "unsigned"}],- }- ]- },{"tools": [{diff --git a/tests/core/openai_responses/test_provider_input.py b/tests/core/openai_responses/test_provider_input.pyindex afc9fac2..2f1a05c9 100644--- a/tests/core/openai_responses/test_provider_input.py+++ b/tests/core/openai_responses/test_provider_input.py@@ -85,11 +85,16 @@ def test_build_responses_provider_request_preserves_multiturn_protocol() -> Noneassert body["tool_choice"] == {"type": "function", "name": "lookup"}assert body["input"][0] == {"type": "reasoning",- "summary": [{"type": "summary_text", "text": "summary"}],+ "summary": [],+ "content": [{"type": "reasoning_text", "text": "summary"}],+ }+ assert body["input"][1] == {+ "type": "reasoning",+ "summary": [],"encrypted_content": "opaque",}- assert body["input"][1]["role"] == "assistant"- assert body["input"][2] == {+ assert body["input"][2]["role"] == "assistant"+ assert body["input"][3] == {"type": "function_call","call_id": "call_1","name": "lookup",@@ -97,12 +102,12 @@ def test_build_responses_provider_request_preserves_multiturn_protocol() -> None{"q": "value"}, ensure_ascii=False, separators=(",", ":")),}- assert body["input"][3] == {+ assert body["input"][4] == {"type": "function_call_output","call_id": "call_1","output": '{"answer": 42}',}- assert body["input"][4]["content"][1] == {+ assert body["input"][5]["content"][1] == {"type": "input_image","image_url": "data:image/png;base64,aGVsbG8=",}diff --git a/tests/core/openai_responses/test_reasoning_replay.py b/tests/core/openai_responses/test_reasoning_replay.pyindex aa830e90..480574bc 100644--- a/tests/core/openai_responses/test_reasoning_replay.py+++ b/tests/core/openai_responses/test_reasoning_replay.py@@ -2,27 +2,32 @@import base64import json+from typing import castimport pytestfrom free_claude_code.core.anthropic import ReasoningReplayMode+from free_claude_code.core.history_replay import (+ HistoryReplayError,+ ReplayOrigin,+ ReplayRecord,+ decode_replay,+ encode_replay,+ prepare_history,+)from free_claude_code.core.json_types import JsonObjectfrom free_claude_code.core.openai_responses import (OpenAIResponsesRequest,ReasoningBlockState,- ResponsesConversionError,build_native_responses_request,build_responses_chat_request,reasoning_output_item,)-from free_claude_code.core.openai_responses.reasoning_replay import (- MessagesReplayOrigin,- decode_messages_reasoning,- encode_messages_reasoning,-)from free_claude_code.core.reasoning import ReasoningPolicy-_ORIGIN = MessagesReplayOrigin("github_copilot/anthropic_messages", "upstream")+_ORIGIN = ReplayOrigin(+ "github_copilot/anthropic_messages", "messages", "", "", "upstream"+)@pytest.mark.parametrize(@@ -39,14 +44,9 @@ _ORIGIN = MessagesReplayOrigin("github_copilot/anthropic_messages", "upstream")],)def test_replay_round_trip_preserves_exact_native_block(block: JsonObject) -> None:- carrier = encode_messages_reasoning(block, origin=_ORIGIN)- assert (- decode_messages_reasoning(carrier, replay_scope=_ORIGIN.replay_scope) == block- )- with pytest.raises(ResponsesConversionError, match="provenance"):- decode_messages_reasoning(- carrier, replay_scope="another-provider/anthropic_messages"- )+ carrier = encode_replay(ReplayRecord(_ORIGIN, block))+ assert decode_replay(carrier).native == block+ assert decode_replay(carrier).origin == _ORIGIN@pytest.mark.parametrize(@@ -60,14 +60,14 @@ def test_replay_round_trip_preserves_exact_native_block(block: JsonObject) -> No],)def test_malformed_or_foreign_replay_rejected(carrier: str) -> None:- with pytest.raises(ResponsesConversionError):- decode_messages_reasoning(carrier, replay_scope=_ORIGIN.replay_scope)+ with pytest.raises(HistoryReplayError):+ decode_replay(carrier)def test_missing_signature_is_not_accepted_as_signed_history() -> None:data = {"protocol": "anthropic_messages",- "replay_scope": _ORIGIN.replay_scope,+ "replay_scope": _ORIGIN.provider,"source_model": "m","block": {"type": "thinking", "thinking": "visible-only"},}@@ -75,14 +75,15 @@ def test_missing_signature_is_not_accepted_as_signed_history() -> None:"fcc:anthropic-reasoning:v1:"+ base64.urlsafe_b64encode(json.dumps(data).encode()).decode())- with pytest.raises(ResponsesConversionError, match="signature"):- decode_messages_reasoning(carrier, replay_scope=_ORIGIN.replay_scope)+ with pytest.raises(HistoryReplayError, match="signed"):+ decode_replay(carrier)def test_completed_reasoning_keeps_both_display_and_opaque_replay() -> None:- carrier = encode_messages_reasoning(- {"type": "thinking", "thinking": "visible", "signature": "opaque"},- origin=_ORIGIN,+ carrier = encode_replay(+ ReplayRecord(+ _ORIGIN, {"type": "thinking", "thinking": "visible", "signature": "opaque"}+ ))state = ReasoningBlockState(0, 0, "rs_1", text_parts=["vis", "ible"], encrypted_content=carrier@@ -92,30 +93,46 @@ def test_completed_reasoning_keeps_both_display_and_opaque_replay() -> None:assert item["encrypted_content"] == carrierfor egress in ("chat", "responses"):request = OpenAIResponsesRequest.model_validate({"model": "m", "input": [item]})- with pytest.raises(ResponsesConversionError, match="Messages upstream"):- if egress == "chat":- build_responses_chat_request(- request, reasoning_replay=ReasoningReplayMode.REASONING_CONTENT- )- else:- build_native_responses_request(- request, model="m", reasoning=ReasoningPolicy()- )+ if egress == "chat":+ body = build_responses_chat_request(+ request, reasoning_replay=ReasoningReplayMode.REASONING_CONTENT+ ).body+ else:+ body = build_native_responses_request(+ request, model="m", reasoning=ReasoningPolicy()+ )+ projected = prepare_history(+ cast(JsonObject, body), ReplayOrigin("other", egress, "", "", "m")+ )+ serialized = json.dumps(projected)+ assert "[Earlier reasoning]" in serialized+ assert "visible" in serialized+ assert "opaque" not in serialized+ assert carrier not in serializeddef test_singleton_reasoning_item_cannot_bypass_egress_guard() -> None:- carrier = encode_messages_reasoning(- {"type": "redacted_thinking", "data": "opaque"}, origin=_ORIGIN+ carrier = encode_replay(+ ReplayRecord(_ORIGIN, {"type": "redacted_thinking", "data": "opaque"}))request = OpenAIResponsesRequest(model="m", input={"type": "reasoning", "encrypted_content": carrier})- with pytest.raises(ResponsesConversionError, match="Messages upstream"):- build_native_responses_request(request, model="m", reasoning=ReasoningPolicy())- with pytest.raises(ResponsesConversionError, match="Messages upstream"):- build_responses_chat_request(- request, reasoning_replay=ReasoningReplayMode.REASONING_CONTENT+ body = build_native_responses_request(+ request, model="m", reasoning=ReasoningPolicy()+ )+ assert (+ prepare_history(body, ReplayOrigin("other", "responses", "", "", "m"))["input"]+ == []+ )+ chat = build_responses_chat_request(+ request, reasoning_replay=ReasoningReplayMode.REASONING_CONTENT+ )+ assert carrier not in json.dumps(+ prepare_history(+ cast(JsonObject, chat.body), ReplayOrigin("other", "chat", "", "", "m"))+ )@pytest.mark.parametrize("value", [True, False])@@ -147,20 +164,22 @@ def test_carrier_cannot_hide_non_json_numbers_or_excessive_nesting(carrier = ("fcc:anthropic-reasoning:v1:" + base64.urlsafe_b64encode(raw.encode()).decode())- with pytest.raises(ResponsesConversionError):- decode_messages_reasoning(carrier, replay_scope=_ORIGIN.replay_scope)+ with pytest.raises(HistoryReplayError):+ decode_replay(carrier)def test_encoder_rejects_non_finite_extension_values() -> None:- with pytest.raises(ResponsesConversionError, match="finite"):- encode_messages_reasoning(- {- "type": "thinking",- "thinking": "ok",- "signature": "sig",- "extension": float("nan"),- },- origin=_ORIGIN,+ with pytest.raises(HistoryReplayError, match="finite"):+ encode_replay(+ ReplayRecord(+ _ORIGIN,+ {+ "type": "thinking",+ "thinking": "ok",+ "signature": "sig",+ "extension": float("nan"),+ },+ ))@@ -174,5 +193,5 @@ def test_decoder_rejects_unpaired_surrogate_before_http_serialization() -> None:carrier = ("fcc:anthropic-reasoning:v1:" + base64.urlsafe_b64encode(raw.encode()).decode())- with pytest.raises(ResponsesConversionError):- decode_messages_reasoning(carrier, replay_scope=_ORIGIN.replay_scope)+ with pytest.raises(HistoryReplayError):+ decode_replay(carrier)diff --git a/tests/core/openai_responses/test_responses_from_messages_stream.py b/tests/core/openai_responses/test_responses_from_messages_stream.pyindex 0de34ff8..23b8fa50 100644--- a/tests/core/openai_responses/test_responses_from_messages_stream.py+++ b/tests/core/openai_responses/test_responses_from_messages_stream.py@@ -11,16 +11,16 @@ from free_claude_code.core.anthropic.native import ()from free_claude_code.core.anthropic.stream_contracts import parse_sse_linesfrom free_claude_code.core.failures import ExecutionFailure, FailureKind+from free_claude_code.core.history_replay import (+ ReplayOrigin,+ decode_replay,+)from free_claude_code.core.json_types import JsonObject, JsonValuefrom free_claude_code.core.openai_responses import (AnthropicToResponsesStream,OpenAIResponsesRequest,build_responses_messages_request,)-from free_claude_code.core.openai_responses.reasoning_replay import (- MessagesReplayOrigin,- decode_messages_reasoning,-)_SCOPE = "github_copilot/anthropic_messages"@@ -28,13 +28,13 @@ _SCOPE = "github_copilot/anthropic_messages"def _stream(*, tools: list[JsonObject] | None = None) -> AnthropicToResponsesStream:request = OpenAIResponsesRequest(model="public", input="hi", tools=tools)prepared = build_responses_messages_request(- request, options=NativeMessagesOptions("upstream", 4096), replay_scope=_SCOPE+ request, options=NativeMessagesOptions("upstream", 4096))return AnthropicToResponsesStream(request,public_model="public",tool_identities=prepared.tool_identities,- replay_origin=MessagesReplayOrigin(_SCOPE, "upstream"),+ replay_origin=ReplayOrigin(_SCOPE, "messages", "", "", "upstream"),)@@ -155,18 +155,15 @@ def test_text_thinking_and_redacted_blocks_keep_order_replay_and_exact_usage() -first = output[0]assert isinstance(first, Mapping)assert first["content"] == [{"type": "reasoning_text", "text": "think"}]- assert decode_messages_reasoning(- cast(str, first["encrypted_content"]), replay_scope=_SCOPE- ) == {+ assert decode_replay(cast(str, first["encrypted_content"])).native == {"type": "thinking","thinking": "think","signature": "sig-end","extension": {"x": 1},}- assert decode_messages_reasoning(- cast(str, cast(Mapping[str, JsonValue], output[1])["encrypted_content"]),- replay_scope=_SCOPE,- ) == {"type": "redacted_thinking", "data": "opaque"}+ assert decode_replay(+ cast(str, cast(Mapping[str, JsonValue], output[1])["encrypted_content"])+ ).native == {"type": "redacted_thinking", "data": "opaque"}assert cast(Mapping[str, JsonValue], output[2])["content"] == [{"type": "output_text", "text": "Hello world", "annotations": []}]@@ -284,12 +281,7 @@ def test_signature_only_thinking_has_replay_without_invented_visible_text() -> Nresponse = cast(Mapping[str, JsonValue], events[-1]["response"])item = cast(list[JsonObject], response["output"])[0]assert "content" not in item- assert (- decode_messages_reasoning(- cast(str, item["encrypted_content"]), replay_scope=_SCOPE- )["thinking"]- == ""- )+ assert decode_replay(cast(str, item["encrypted_content"])).native["thinking"] == ""assert "output_tokens_details" not in cast(Mapping[str, JsonValue], response["usage"])diff --git a/tests/core/test_history_replay.py b/tests/core/test_history_replay.pynew file mode 100644index 00000000..222fe936--- /dev/null+++ b/tests/core/test_history_replay.py@@ -0,0 +1,192 @@+"""Portable history preserves originals while adapting each destination copy."""++import json+from copy import deepcopy+from typing import Any, cast++import pytest++from free_claude_code.core.history_replay import (+ HistoryReplayError,+ HistoryScope,+ ReplayOrigin,+ ReplayRecord,+ decode_replay,+ encode_replay,+ prepare_history,+ responses_replay_item,+)+++def _origin(+ provider="a", protocol="responses", connection="connection-a", model="arbitrary"+):+ return ReplayOrigin(provider, protocol, "https://example.org/v1", connection, model)+++def _native():+ return {+ "type": "reasoning",+ "id": "rs_native:original",+ "summary": [],+ "encrypted_content": "opaque-native",+ "native_extension": {"v": 17},+ }+++def test_response_history_roundtrip_across_providers_and_restart():+ native = _native()+ item = responses_replay_item(native, _origin())+ saved = {+ "input": [+ item,+ {"role": "assistant", "content": "hello"},+ {"role": "user", "content": "continue"},+ ]+ }+ original = deepcopy(saved)+ foreign = prepare_history(saved, _origin("b"))+ assert foreign["input"] == saved["input"][1:]+ restored = cast(+ dict[str, Any],+ prepare_history(+ json.loads(json.dumps(saved)), _origin(model="completely-different")+ ),+ )+ assert restored["input"][0] == native+ assert saved == original+ assert prepare_history(saved, _origin("b")) == foreign++[email protected]("protocol", ["responses", "messages", "chat"])+def test_foreign_readable_reasoning_keeps_context_without_ciphertext(protocol):+ native = {+ **_native(),+ "summary": [{"type": "summary_text", "text": "Search for the value."}],+ }+ carrier = encode_replay(ReplayRecord(_origin(), native))+ if protocol == "responses":+ saved = {+ "input": [+ {+ "type": "reasoning",+ "encrypted_content": carrier,+ "summary": native["summary"],+ },+ {"role": "user", "content": "continue"},+ ]+ }+ elif protocol == "messages":+ saved = {+ "messages": [+ {+ "role": "assistant",+ "content": [{"type": "redacted_thinking", "data": carrier}],+ },+ {"role": "user", "content": "continue"},+ ]+ }+ else:+ saved = {+ "messages": [+ {+ "role": "assistant",+ "content": "",+ "reasoning_details": [+ {"type": "reasoning.encrypted", "data": carrier}+ ],+ },+ {"role": "user", "content": "continue"},+ ]+ }+ result = prepare_history(saved, _origin("b", protocol))+ rendered = json.dumps(result)+ assert "Search for the value." in rendered+ assert "summary" in rendered.lower()+ assert "opaque-native" not in rendered+ assert "fcc:" not in rendered+ assert all(+ item.get("role") not in {"system", "developer"}+ for item in result.get("input", result.get("messages", []))+ )+++ "block",+ [+ {+ "type": "thinking",+ "thinking": "",+ "signature": "empty-signed",+ "extension": 17,+ },+ {"type": "thinking", "thinking": "keep exactly", "signature": "signature"},+ {"type": "redacted_thinking", "data": "hidden"},+ ],+)+def test_messages_native_blocks_are_exact_after_carrier_replay(block):+ origin = _origin(protocol="messages")+ carrier = encode_replay(ReplayRecord(origin, block))+ public = (+ {**block, "signature": carrier}+ if block["type"] == "thinking"+ else {"type": "redacted_thinking", "data": carrier}+ )+ saved = {"messages": [{"role": "assistant", "content": [public]}]}+ result = cast(dict[str, Any], prepare_history(saved, origin))+ assert result["messages"][0]["content"] == [block]+++def test_native_replay_connection_is_scoped_but_model_name_is_not_a_rule():+ item = responses_replay_item(_native(), _origin())+ assert (+ prepare_history({"input": [item]}, _origin(connection="other"))["input"] == []+ )+ assert prepare_history({"input": [item]}, _origin(model="any-model"))["input"] == [+ _native()+ ]+++def test_codec_rejects_malformed_and_nonfinite_payloads():+ with pytest.raises(HistoryReplayError):+ decode_replay("fcc:history:v1:broken")+ with pytest.raises(HistoryReplayError):+ encode_replay(+ ReplayRecord(_origin(), {"type": "reasoning", "extension": float("nan")})+ )+++def test_legacy_naked_opaque_history_is_tried_unchanged():+ saved = {"input": [_native()]}+ assert prepare_history(saved, _origin("other")) == saved++[email protected]("native_text", ["Full reasoning.", "Short summary."])+def test_chat_replay_keeps_full_text_and_summary_meaning(native_text):+ native = {+ "reasoning_content": native_text,+ "reasoning_details": [+ {"type": "reasoning.summary", "summary": "Short summary.", "index": 0}+ ],+ }+ carrier = encode_replay(ReplayRecord(_origin(protocol="chat"), native))+ body = {+ "messages": [+ {+ "role": "assistant",+ "content": "answer",+ "reasoning_details": [{"type": "reasoning.encrypted", "data": carrier}],+ }+ ]+ }+ original = deepcopy(body)+ result = cast(+ 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."+ if native_text == "Short summary.":+ assert "reasoning_content" not in result+ else:+ assert result["reasoning_content"] == "Full reasoning."+ assert body == originaldiff --git a/tests/core/test_history_switching.py b/tests/core/test_history_switching.pynew file mode 100644index 00000000..b3391a10--- /dev/null+++ b/tests/core/test_history_switching.py@@ -0,0 +1,459 @@+"""Regressions for history loss when changing upstream providers."""++import json+from copy import deepcopy+from typing import Any, cast++import pytest++from free_claude_code.core.anthropic import ReasoningReplayMode+from free_claude_code.core.anthropic.conversion import AnthropicToOpenAIConverter+from free_claude_code.core.anthropic.models import MessagesRequest+from free_claude_code.core.history_replay import (+ HistoryScope,+ ReplayOrigin,+ prepare_history,+)+from free_claude_code.core.openai_responses.chat_request import (+ build_responses_chat_request,+)+from free_claude_code.core.openai_responses.models import OpenAIResponsesRequest+from free_claude_code.core.reasoning import ReasoningPolicy+from free_claude_code.providers.deepseek.client import DeepSeekProvider+from free_claude_code.providers.deepseek.compat import finalize_deepseek_chat_body+from free_claude_code.providers.open_router import OpenRouterProvider+from tests.providers.support import immediate_admission, make_provider_config+++def _chat(items):+ return build_responses_chat_request(+ OpenAIResponsesRequest(model="synthetic", input=items),+ reasoning_replay=ReasoningReplayMode.REASONING_CONTENT,+ structured_reasoning_details=True,+ ).body["messages"]+++def _reasoning(text, opaque):+ return {+ "type": "reasoning",+ "content": [{"type": "reasoning_text", "text": text}],+ "encrypted_content": opaque,+ }+++def _call(call_id, arguments="{}"):+ return {+ "type": "function_call",+ "call_id": call_id,+ "name": "lookup",+ "arguments": arguments,+ }+++def test_grouped_tool_calls_keep_both_reasoning_records():+ messages = _chat(+ [+ {"role": "user", "content": "look up both"},+ _reasoning("first", "opaque1"),+ _call("call_a"),+ _reasoning("second", "opaque2"),+ _call("call_b"),+ {"type": "function_call_output", "call_id": "call_a", "output": "17"},+ {"type": "function_call_output", "call_id": "call_b", "output": "18"},+ ]+ )+ assistant = messages[1]+ assert assistant["reasoning_content"] == "first\nsecond"+ assert [detail["data"] for detail in assistant["reasoning_details"]] == [+ "opaque1",+ "opaque2",+ ]+++def test_quarantined_tool_call_does_not_donate_its_reasoning():+ messages = _chat(+ [+ {"role": "user", "content": "continue"},+ _reasoning("broken call only", "opaque-broken"),+ _call("broken", "{"),+ _call("valid"),+ {"type": "function_call_output", "call_id": "valid", "output": "17"},+ ]+ )+ assistant = next(message for message in messages if message.get("tool_calls"))+ assert not assistant.get("reasoning_content")+ assert "reasoning_details" not in assistant+++def test_completed_hosted_tool_history_remains_readable():+ messages = _chat(+ [+ {"role": "user", "content": "find the sample"},+ {+ "type": "web_search_call",+ "id": "search_1",+ "status": "completed",+ "action": {+ "type": "search",+ "query": "sample",+ "sources": [{"url": "https://example.org/result"}],+ },+ },+ {"role": "assistant", "content": "Found it."},+ {"role": "user", "content": "which source?"},+ ]+ )+ rendered = json.dumps(messages)+ assert "https://example.org/result" in rendered+ assert "web_search_call" in rendered+ assert any(+ message["role"] == "assistant"+ and "web_search_call" in str(message.get("content"))+ for message in messages+ )+++def test_opaque_details_stay_with_the_assistant_that_produced_them():+ provider = OpenRouterProvider(+ make_provider_config(api_key="synthetic", base_url="https://example.org/v1"),+ admission=immediate_admission(),+ )+ detail = {"type": "reasoning.encrypted", "data": "second-only"}+ request = MessagesRequest.model_validate(+ {+ "model": "synthetic",+ "messages": [+ {"role": "user", "content": "hello"},+ {"role": "assistant", "content": "first reply"},+ {"role": "user", "content": "continue"},+ {+ "role": "assistant",+ "content": [+ {"type": "redacted_thinking", "data": json.dumps(detail)},+ {"type": "text", "text": "second reply"},+ ],+ },+ {"role": "user", "content": "continue again"},+ ],+ }+ )+ original = request.model_dump()+ assistants = [+ message+ for message in provider._build_request_body(request)["messages"]+ if message["role"] == "assistant"+ ]+ assert "reasoning_details" not in assistants[0]+ assert assistants[1]["reasoning_details"] == [detail]+ assert request.model_dump() == original+++def test_deepseek_tools_require_reasoning_on_earlier_plain_assistant_turns():+ body: dict[str, Any] = {+ "messages": [+ {"role": "user", "content": "hello"},+ {"role": "assistant", "content": "hi"},+ {"role": "user", "content": "look up a value"},+ ],+ "tools": [+ {+ "type": "function",+ "function": {"name": "lookup", "parameters": {"type": "object"}},+ }+ ],+ }+ finalize_deepseek_chat_body(body, ReasoningPolicy.on())+ assert body["extra_body"]["thinking"] == {"type": "enabled"}+ assert body["messages"][1]["reasoning_content"] == ""++[email protected]("wire", ["messages", "responses"])+def test_deepseek_off_to_on_preserves_effort_and_all_available_history(wire):+ provider = DeepSeekProvider(+ make_provider_config(api_key="synthetic", base_url="https://example.invalid"),+ admission=immediate_admission(),+ )+ function = {"type": "object", "properties": {}}+ if wire == "messages":+ request = MessagesRequest.model_validate(+ {+ "model": "synthetic",+ "messages": [+ {"role": "user", "content": "first"},+ {+ "role": "assistant",+ "content": [+ {+ "type": "tool_use",+ "name": "lookup",+ "id": "call_1",+ "input": {},+ }+ ],+ },+ {+ "role": "user",+ "content": [+ {+ "type": "tool_result",+ "tool_use_id": "call_1",+ "content": "17",+ }+ ],+ },+ {"role": "assistant", "content": "old answer"},+ {"role": "user", "content": "second"},+ {+ "role": "assistant",+ "content": [+ {"type": "thinking", "thinking": "real reasoning"},+ {"type": "text", "text": "answer"},+ ],+ },+ {"role": "user", "content": "new question, thinking on"},+ ],+ "tools": [{"name": "lookup", "input_schema": function}],+ }+ )+ original = deepcopy(request.model_dump())+ body = provider._build_request_body(request, reasoning=ReasoningPolicy.on())+ else:+ request = OpenAIResponsesRequest(+ model="synthetic",+ input=[+ {"role": "user", "content": "first"},+ _call("call_1"),+ {"type": "function_call_output", "call_id": "call_1", "output": "17"},+ {"role": "assistant", "content": "old answer"},+ {"role": "user", "content": "second"},+ {+ "type": "reasoning",+ "content": [{"type": "reasoning_text", "text": "real reasoning"}],+ },+ {"role": "assistant", "content": "answer"},+ {"role": "user", "content": "new question, thinking on"},+ ],+ tools=[{"type": "function", "name": "lookup", "parameters": function}],+ )+ original = deepcopy(request.model_dump())+ body = cast(+ dict[str, Any],+ provider._build_responses_request_body(+ request, reasoning=ReasoningPolicy.on()+ ).body,+ )+ assert body["extra_body"]["thinking"] == {"type": "enabled"}+ assistants = [+ message for message in body["messages"] if message["role"] == "assistant"+ ]+ assert [message["reasoning_content"] for message in assistants] == [+ "",+ "",+ "real reasoning",+ ]+ assert request.model_dump() == original+++def test_summary_is_context_even_when_destination_replays_full_reasoning():+ messages = _chat(+ [+ {"role": "user", "content": "first"},+ {+ "type": "reasoning",+ "summary": [+ {"type": "summary_text", "text": "A summary, not the hidden chain."}+ ],+ },+ {"role": "assistant", "content": "17"},+ {"role": "user", "content": "continue"},+ ]+ )+ assert "reasoning_content" not in messages[1]+ assert "[Earlier reasoning summary]" in messages[1]["content"]+++def test_image_tool_result_does_not_start_a_new_user_turn():+ messages = _chat(+ [+ {"role": "user", "content": "look"},+ _reasoning("inspect the image", ""),+ _call("image"),+ {+ "type": "function_call_output",+ "call_id": "image",+ "output": [+ {+ "type": "input_image",+ "image_url": "https://example.org/image.png",+ }+ ],+ },+ ]+ )+ body = prepare_history(+ {"messages": messages},+ ReplayOrigin("a", "chat", "", "", "m"),+ scope=HistoryScope.TOOL_CONTINUATION,+ )+ assert body["messages"] == messages+++def test_messages_interleaved_reasoning_belongs_to_the_tool_group():+ provider = OpenRouterProvider(+ make_provider_config(api_key="synthetic", base_url="https://example.org/v1"),+ admission=immediate_admission(),+ )+ request = MessagesRequest.model_validate(+ {+ "model": "m",+ "messages": [+ {"role": "user", "content": "look up both"},+ {+ "role": "assistant",+ "content": [+ {"type": "thinking", "thinking": "first"},+ {"type": "tool_use", "id": "a", "name": "lookup", "input": {}},+ {"type": "thinking", "thinking": "second"},+ {"type": "redacted_thinking", "data": "second-opaque"},+ {"type": "tool_use", "id": "b", "name": "lookup", "input": {}},+ ],+ },+ {+ "role": "user",+ "content": [+ {"type": "tool_result", "tool_use_id": "a", "content": "17"},+ {"type": "tool_result", "tool_use_id": "b", "content": "18"},+ ],+ },+ ],+ }+ )+ messages = provider._build_request_body(request)["messages"]+ assistant = next(message for message in messages if message.get("tool_calls"))+ assert assistant["reasoning_content"] == "first\nsecond"+ assert assistant["reasoning_details"] == [+ {"type": "reasoning.encrypted", "data": "second-opaque"}+ ]+ assert len([message for message in messages if message["role"] == "assistant"]) == 1+++def test_completed_native_hosted_tools_become_readable_chat_history():+ provider = OpenRouterProvider(+ make_provider_config(api_key="synthetic", base_url="https://example.org/v1"),+ admission=immediate_admission(),+ )+ request = MessagesRequest.model_validate(+ {+ "model": "m",+ "messages": [+ {+ "role": "assistant",+ "content": [+ {+ "type": "server_tool_use",+ "id": "search",+ "name": "web_search",+ "input": {"query": "sample"},+ },+ {+ "type": "web_search_tool_result",+ "tool_use_id": "search",+ "content": [],+ },+ {"type": "text", "text": "No results."},+ ],+ },+ {"role": "user", "content": "continue"},+ ],+ }+ )+ body = provider._build_request_body(request)+ rendered = json.dumps(body["messages"])+ assert "[Earlier tool record]" in rendered+ assert "sample" in rendered and "web_search_tool_result" in rendered+ assert "tool_calls" not in body["messages"][0]++[email protected]("wire", ["messages", "responses"])+def test_malformed_carrier_fails_preflight_before_inference(wire):+ from free_claude_code.application.errors import InvalidRequestError++ provider = OpenRouterProvider(+ make_provider_config(api_key="synthetic", base_url="https://example.org/v1"),+ admission=immediate_admission(),+ )+ with pytest.raises(InvalidRequestError, match="replay"):+ if wire == "messages":+ provider.preflight_messages(+ MessagesRequest.model_validate(+ {+ "model": "m",+ "messages": [+ {+ "role": "assistant",+ "content": [+ {+ "type": "redacted_thinking",+ "data": "fcc:history:v2:unsupported",+ }+ ],+ }+ ],+ }+ )+ )+ else:+ provider.preflight_responses(+ OpenAIResponsesRequest(+ model="m",+ input=[+ {+ "type": "reasoning",+ "encrypted_content": "fcc:history:v2:unsupported",+ }+ ],+ )+ )++[email protected]("wire", ["messages", "responses"])+def test_destination_without_native_reasoning_keeps_readable_context(wire):+ if wire == "responses":+ body = build_responses_chat_request(+ OpenAIResponsesRequest(+ model="m",+ input=[+ {+ "type": "reasoning",+ "content": [+ {"type": "reasoning_text", "text": "Preserve this thought."}+ ],+ },+ {"role": "assistant", "content": "17"},+ ],+ ),+ reasoning_replay=ReasoningReplayMode.DISABLED,+ ).body+ else:+ request = MessagesRequest.model_validate(+ {+ "model": "m",+ "messages": [+ {+ "role": "assistant",+ "content": [+ {"type": "thinking", "thinking": "Preserve this thought."},+ {"type": "text", "text": "17"},+ ],+ }+ ],+ }+ )+ body = {+ "messages": AnthropicToOpenAIConverter.convert_messages(+ request.messages, reasoning_replay=ReasoningReplayMode.DISABLED+ )+ }+ rendered = json.dumps(body)+ assert "[Earlier reasoning]" in rendered+ assert "Preserve this thought." in rendereddiff --git a/tests/providers/test_chutes.py b/tests/providers/test_chutes.pyindex 3a3ce438..785d484c 100644--- a/tests/providers/test_chutes.py+++ b/tests/providers/test_chutes.py@@ -114,7 +114,10 @@ def test_does_not_replay_reasoning_but_preserves_tool_history()assistant = body["messages"][1]- assert assistant["content"] == "I will inspect it."+ assert (+ assistant["content"]+ == "[Earlier reasoning]\nRead 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 ee8a632f..c513b73f 100644--- a/tests/providers/test_cline_pass.py+++ b/tests/providers/test_cline_pass.py@@ -17,6 +17,7 @@ from free_claude_code.core.anthropic.stream_contracts import (text_content,thinking_content,)+from free_claude_code.core.history_replay import decode_replayfrom free_claude_code.core.json_types import JsonObject, JsonValuefrom free_claude_code.core.reasoning import ReasoningPolicyfrom free_claude_code.providers.model_listing import ModelListResponseError@@ -278,7 +279,10 @@ def test_build_request_body_replays_only_opaque_reasoning_details(message for message in body["messages"] if message["role"] == "assistant")- assert assistant["content"] == "I will inspect it."+ assert (+ assistant["content"]+ == "[Earlier reasoning]\nNeed a tool.\n\nI will inspect it."+ )assert assistant["reasoning_details"] == [detail]assert "reasoning" not in assistantassert "reasoning_content" not in assistant@@ -330,14 +334,13 @@ async def test_stream_uses_upstream_sse_and_preserves_reasoning_details(assert await_args.kwargs["model"] == "cline-pass/kimi-k3"assert thinking_content(events) == "plan "assert text_content(events) == "done"- redacted_blocks = [- event.data["content_block"]+ records = [+ decode_replay(event.data["delta"]["signature"]).nativefor event in events- if event.event == "content_block_start"- and event.data.get("content_block", {}).get("type") == "redacted_thinking"+ if event.data.get("delta", {}).get("type") == "signature_delta"]- assert len(redacted_blocks) == 1- assert json.loads(redacted_blocks[0]["data"]) == detail+ assert len(records) == 1+ assert records[0]["reasoning_details"] == [detail]assert stream.closeddiff --git a/tests/providers/test_converter.py b/tests/providers/test_converter.pyindex 47a98e37..4d8c2e7f 100644--- a/tests/providers/test_converter.py+++ b/tests/providers/test_converter.py@@ -29,6 +29,9 @@ class MockBlock:setattr(self, k, v)self._data = kwargs+ def model_dump(self, **kwargs):+ return dict(self._data)+def get(self, key, default=None):return self._data.get(key, default)@@ -743,7 +746,10 @@ def test_convert_redacted_thinking_tool_use_replays_empty_reasoning_without_data)assert result[0]["reasoning_content"] == ""- assert "opaque-secret" not in json.dumps(result)+ assert result[0]["reasoning_details"] == [+ {"type": "reasoning.encrypted", "data": "opaque-secret"}+ ]+ assert "opaque-secret" not in result[0]["reasoning_content"]def test_convert_text_only_assistant_without_thinking_omits_reasoning_content():@@ -774,7 +780,7 @@ def test_convert_tool_use_without_thinking_does_not_change_other_replay_modes(assert "reasoning_content" not in result[0]-def test_convert_assistant_message_thinking_removed_when_disabled():+def test_convert_assistant_message_thinking_becomes_context_when_disabled():content = [MockBlock(type="thinking", thinking="I need to calculate this."),MockBlock(type="text", text="The answer is 4."),@@ -788,10 +794,13 @@ def test_convert_assistant_message_thinking_removed_when_disabled():assert len(result) == 1assert "reasoning_content" not in result[0]assert "<think>" not in result[0]["content"]- assert result[0]["content"] == "The answer is 4."+ assert (+ result[0]["content"]+ == "[Earlier reasoning]\nI need to calculate this.\n\nThe answer is 4."+ )-def test_convert_assistant_top_level_reasoning_stripped_when_disabled():+def test_convert_assistant_top_level_reasoning_becomes_context_when_disabled():messages = [MockMessage("assistant",@@ -803,7 +812,12 @@ def test_convert_assistant_top_level_reasoning_stripped_when_disabled():messages, reasoning_replay=ReasoningReplayMode.DISABLED)- assert result == [{"role": "assistant", "content": "The answer is 4."}]+ assert result == [+ {+ "role": "assistant",+ "content": "[Earlier reasoning]\nI need to calculate this.\n\nThe answer is 4.",+ }+ ]def test_convert_assistant_message_tool_use():@@ -2000,7 +2014,13 @@ def test_openai_build_rejects_unknown_top_level_extras() -> None:],],)-def test_convert_assistant_server_tool_blocks_raise(content) -> None:+def test_convert_hosted_tool_history_preserves_results_and_rejects_active_calls(+ content,+) -> None:messages = [MockMessage("assistant", content)]- with pytest.raises(OpenAIConversionError, match="server tool"):- AnthropicToOpenAIConverter.convert_messages(messages)+ if content[0].type == "server_tool_use":+ with pytest.raises(OpenAIConversionError, match="active server tool"):+ AnthropicToOpenAIConverter.convert_messages(messages)+ else:+ result = AnthropicToOpenAIConverter.convert_messages(messages)+ assert "[Earlier tool record]" in result[0]["content"]diff --git a/tests/providers/test_deepseek.py b/tests/providers/test_deepseek.pyindex b1b82d23..7fc89cca 100644--- a/tests/providers/test_deepseek.py+++ b/tests/providers/test_deepseek.py@@ -96,7 +96,7 @@ def test_responses_request_uses_deepseek_chat_policy(deepseek_provider):assert translated.body["max_tokens"] == ANTHROPIC_DEFAULT_MAX_OUTPUT_TOKENSassert translated.body["tool_choice"] == "auto"- assert translated.body["extra_body"] == {"thinking": {"type": "disabled"}}+ assert translated.body["extra_body"] == {"thinking": {"type": "enabled"}}def test_responses_tool_history_keeps_deepseek_replayable_reasoning(@@ -108,7 +108,7 @@ def test_responses_tool_history_keeps_deepseek_replayable_reasoning("input": [{"type": "reasoning",- "summary": [{"type": "summary_text", "text": "Inspect first"}],+ "content": [{"type": "reasoning_text", "text": "Inspect first"}],},{"type": "function_call",@@ -376,7 +376,7 @@ def test_build_request_body_encodes_reasoning_off():assert "stream_options" not in body-def test_non_tool_thinking_is_omitted_from_first_replay(deepseek_provider):+def test_non_tool_thinking_survives_conversion(deepseek_provider):request = MessagesRequest.model_validate({"model": "m",@@ -398,10 +398,14 @@ def test_non_tool_thinking_is_omitted_from_first_replay(deepseek_provider):body = deepseek_provider._build_request_body(request, reasoning=reasoning_for(request))- assert body["messages"][0] == {"role": "assistant", "content": "out"}+ assert body["messages"][0] == {+ "role": "assistant",+ "content": "out",+ "reasoning_content": "plain",+ }-def test_strip_redacted_thinking_when_thinking_on(deepseek_provider):+def test_redacted_thinking_is_kept_until_destination_preparation(deepseek_provider):request = MessagesRequest.model_validate({"model": "m",@@ -419,7 +423,10 @@ def test_strip_redacted_thinking_when_thinking_on(deepseek_provider):body = deepseek_provider._build_request_body(request, reasoning=reasoning_for(request))- assert body["messages"][0] == {"role": "assistant", "content": "out"}+ assert body["messages"][0]["reasoning_details"] == [+ {"type": "reasoning.encrypted", "data": "opaque"}+ ]+ assert request.model_dump()["messages"][0]["content"][0]["data"] == "opaque"def test_tool_history_with_replayable_thinking_preserves_thinking(deepseek_provider):@@ -522,7 +529,7 @@ def test_tool_history_with_unsigned_thinking_preserves_thinking(deepseek_provideassert body["messages"][0]["reasoning_content"] == "plain"-def test_tool_history_without_thinking_disables_thinking_and_hints(deepseek_provider):+def test_tool_history_without_thinking_keeps_selected_effort(deepseek_provider):request = MessagesRequest.model_validate({"model": "m",@@ -573,7 +580,9 @@ def test_tool_history_without_thinking_disables_thinking_and_hints(deepseek_provrequest, reasoning=reasoning_for(request))- assert body["extra_body"]["thinking"] == {"type": "disabled"}+ assert body["reasoning_effort"] == "high"+ assert body["extra_body"].get("thinking") != {"type": "disabled"}+ assert body["messages"][0]["reasoning_content"] == ""assert "context_management" not in bodyassert "output_config" not in bodyassert body["tools"][0]["function"]["name"] == "Read"@@ -666,7 +675,7 @@ def test_tool_history_with_empty_top_level_reasoning_preserves_reasoning_state(assert body["messages"][0]["tool_calls"][0]["function"]["name"] == "Read"-def test_thinking_off_strips_thinking_history():+def test_thinking_off_preserves_historical_reasoning():provider = DeepSeekProvider(make_provider_config(api_key="k",@@ -691,8 +700,8 @@ def test_thinking_off_strips_thinking_history():})body = provider._build_request_body(request, reasoning=REASONING_OFF)- assert "reasoning_content" not in body["messages"][0]- assert "sec" not in str(body["messages"])+ assert body["extra_body"]["thinking"] == {"type": "disabled"}+ assert body["messages"][0]["reasoning_content"] == "sec"def test_thinking_off_still_replays_required_tool_reasoning():@@ -952,7 +961,7 @@ def test_preflight_rejects_listed_server_tools_in_tools_list():provider.preflight_messages(request)-def test_preflight_rejects_server_tool_result_blocks():+def test_preflight_preserves_completed_server_tool_history():request = MessagesRequest.model_validate({"model": "m",@@ -985,11 +994,12 @@ def test_preflight_rejects_server_tool_result_blocks():),admission=immediate_admission(),)- with pytest.raises(InvalidRequestError, match=r"web_search_tool_result|server"):- provider.preflight_messages(request)+ provider.preflight_messages(request)+ body = provider._build_request_body(request)+ assert "[Earlier tool record]" in body["messages"][0]["content"]-def test_non_tool_top_level_reasoning_is_not_replayed(deepseek_provider):+def test_non_tool_top_level_reasoning_survives_conversion(deepseek_provider):request = MessagesRequest(model="m",messages=[@@ -1003,7 +1013,11 @@ def test_non_tool_top_level_reasoning_is_not_replayed(deepseek_provider):body = deepseek_provider._build_request_body(request, reasoning=reasoning_for(request))- assert body["messages"][0] == {"role": "assistant", "content": "hi"}+ assert body["messages"][0] == {+ "role": "assistant",+ "content": "hi",+ "reasoning_content": "r",+ }def test_tool_call_top_level_reasoning_is_replayed(deepseek_provider):@@ -1045,7 +1059,7 @@ def test_tool_call_top_level_reasoning_is_replayed(deepseek_provider):@pytest.mark.asyncio-async def test_wire_messages_keep_prefix_across_tool_thinking_fallback(+async def test_wire_messages_keep_prefix_and_effort_when_old_reasoning_is_absent(deepseek_provider,):prefix_messages = [@@ -1128,10 +1142,10 @@ async def test_wire_messages_keep_prefix_across_tool_thinking_fallback(assistant_messages = [message for message in first_messages if message["role"] == "assistant"]- assert "reasoning_content" not in assistant_messages[0]+ assert assistant_messages[0]["reasoning_content"] == "ordinary reasoning"assert assistant_messages[1]["reasoning_content"] == "required tool reasoning"assert first_wire["thinking"] == {"type": "enabled"}- assert continued_wire["thinking"] == {"type": "disabled"}+ assert continued_wire["thinking"] == {"type": "enabled"}@pytest.mark.asynciodiff --git a/tests/providers/test_github_copilot_broker.py b/tests/providers/test_github_copilot_broker.pyindex efaa4767..5dac1ce7 100644--- a/tests/providers/test_github_copilot_broker.py+++ b/tests/providers/test_github_copilot_broker.py@@ -14,6 +14,7 @@ from free_claude_code.providers.github_copilot.types import (CopilotIdentity,CopilotUnavailable,)+from free_claude_code.providers.history_replay import replay_originfrom tests.providers.copilot_support import FakeRuntime, model@@ -66,6 +67,28 @@ async def test_concurrent_leases_reuse_session_and_refresh_known_expiry() -> Nonassert session.closed+async def test_replay_origin_survives_copilot_token_refresh() -> None:+ runtime = FakeRuntime()+ broker = CopilotBroker(runtime)+ async with broker.lease("model") as lease:+ first = await lease.endpoint()+ session = runtime.sessions[0]+ session.value = replace(+ session.value,+ http=replace(+ session.value.http,+ api_key="refreshed-token",+ headers={"Authorization": "Bearer refreshed-token"},+ ),+ )+ second = await lease.endpoint(force_refresh=True)+ assert replay_origin("copilot", "messages", "a", endpoint=first).accepts(+ replay_origin("copilot", "messages", "b", endpoint=second)+ )+ await broker.close()++@pytest.mark.asyncioasync def test_identity_change_and_removed_models_cannot_publish_new_credentials() -> (Nonediff --git a/tests/providers/test_github_copilot_provider.py b/tests/providers/test_github_copilot_provider.pyindex f3d25959..23c9e089 100644--- a/tests/providers/test_github_copilot_provider.py+++ b/tests/providers/test_github_copilot_provider.py@@ -19,14 +19,15 @@ from free_claude_code.core.anthropic.stream_contracts import (text_content,)from free_claude_code.core.failures import ExecutionFailure+from free_claude_code.core.history_replay import (+ ReplayOrigin,+ ReplayRecord,+ encode_replay,+)from free_claude_code.core.json_types import JsonObjectfrom free_claude_code.core.openai_responses import (- MessagesReplayOrigin,OpenAIResponsesRequest,)-from free_claude_code.core.openai_responses.reasoning_replay import (- encode_messages_reasoning,-)from free_claude_code.core.reasoning import (DEFAULT_REASONING_POLICY,ReasoningCapability,@@ -572,9 +573,13 @@ async def test_native_reasoning_carrier_replays_only_to_messages_egress("thinking": "private reasoning","signature": "exact-signature",}- carrier = encode_messages_reasoning(- block,- origin=MessagesReplayOrigin("github_copilot/anthropic_messages", "prior-model"),+ carrier = encode_replay(+ ReplayRecord(+ ReplayOrigin(+ "github_copilot/anthropic_messages", "messages", "", "", "prior-model"+ ),+ block,+ ))request = OpenAIResponsesRequest.model_validate({@@ -595,11 +600,13 @@ async def test_native_reasoning_carrier_replays_only_to_messages_egress(body = json.loads(harness.seen[0].content)assert body["messages"][0]["content"][0] == blockelse:- with pytest.raises(- (InvalidRequestError, ValueError), match=r"[Rr]easoning"- ):- await collect(harness.provider.stream_responses(request))- assert not harness.seen+ await collect(harness.provider.stream_responses(request))+ body = json.loads(harness.seen[0].content)+ wire = json.dumps(body)+ assert "[Earlier reasoning]" in wire+ assert "private reasoning" in wire+ assert "exact-signature" not in wire+ assert carrier not in wirefinally:await harness.close()diff --git a/tests/providers/test_github_copilot_responses_identity.py b/tests/providers/test_github_copilot_responses_identity.pyindex 82662012..b3f651b9 100644--- a/tests/providers/test_github_copilot_responses_identity.py+++ b/tests/providers/test_github_copilot_responses_identity.py@@ -19,6 +19,7 @@ from free_claude_code.core.anthropic.stream_contracts import (parse_sse_text,)from free_claude_code.core.failures import ExecutionFailure+from free_claude_code.core.history_replay import decode_replayfrom free_claude_code.core.json_types import JsonObjectfrom free_claude_code.core.openai_responses import OpenAIResponsesRequestfrom free_claude_code.providers.github_copilot.types import CopilotEgress@@ -381,6 +382,12 @@ async def test_copilot_interleaved_tools_use_output_positions_and_preserve_finaltry:received = await _run(harness, _input(True, harness.runtime.name))output = _assert_native_identity(received)+ output = [+ decode_replay(str(item["encrypted_content"])).native+ if item.get("type") == "reasoning"+ else item+ for item in output+ ]assert output == [{**final_output[0], "id": first["id"]},{**final_output[1], "id": second["id"]},diff --git a/tests/providers/test_history_corrections.py b/tests/providers/test_history_corrections.pynew file mode 100644index 00000000..f943ae8f--- /dev/null+++ b/tests/providers/test_history_corrections.py@@ -0,0 +1,198 @@+"""Provider corrections target explicit history failures, never arbitrary 400s."""++from copy import deepcopy++import httpx2+import pytest+from openai import BadRequestError++from free_claude_code.providers.endpoint import HttpEndpoint+from free_claude_code.providers.history_replay import history_retry_body, replay_origin+++def _error(message, *, code="invalid_request_error", param=None, status=400):+ return BadRequestError(+ message,+ response=httpx2.Response(+ status, request=httpx2.Request("POST", "https://example.invalid")+ ),+ body={"error": {"message": message, "code": code, "param": param}},+ )+++def test_legacy_invalid_id_then_ciphertext_rejection_keeps_original():+ body = {+ "model": "synthetic",+ "input": [+ {"role": "user", "content": "hello"},+ {+ "type": "reasoning",+ "id": "rs_a:rs_b",+ "encrypted_content": "opaque-a",+ "summary": [{"type": "summary_text", "text": "look up 17"}],+ },+ {"role": "assistant", "content": "17"},+ {"role": "user", "content": "continue"},+ ],+ }+ original = deepcopy(body)+ fixed = history_retry_body(+ _error(+ "Invalid 'input[1].id': 'rs_a:rs_b'. Expected an ID that contains letters, numbers, underscores, or dashes",+ code="invalid_value",+ param="input[1].id",+ ),+ body,+ "responses",+ )+ assert fixed is not None+ assert ":" not in fixed["input"][1]["id"]+ assert fixed["input"][1]["encrypted_content"] == "opaque-a"+ cleaned = history_retry_body(+ _error(+ "The encrypted content could not be verified.",+ code="invalid_encrypted_content",+ ),+ fixed,+ "responses",+ )+ assert cleaned is not None+ assert cleaned["input"][1] == {+ "role": "assistant",+ "content": "[Earlier reasoning summary]\nlook up 17",+ }+ assert cleaned["input"][2:] == original["input"][2:]+ assert body == original+++ "message,code",+ [+ ("Invalid request", "invalid_request_error"),+ ("Tool schema has invalid parameters", "invalid_request_error"),+ ("Too many tokens", "context_length_exceeded"),+ ],+)+def test_unrelated_validation_does_not_drop_history(message, code):+ body = {+ "input": [{"type": "reasoning", "id": "rs_a", "encrypted_content": "opaque"}]+ }+ assert history_retry_body(_error(message, code=code), body, "responses") is None+++def test_unidentified_cipher_failure_with_multiple_records_is_not_guessed():+ body = {+ "input": [+ {"type": "reasoning", "id": f"rs_{i}", "encrypted_content": f"opaque{i}"}+ for i in range(2)+ ]+ }+ assert (+ history_retry_body(+ _error(+ "Cannot decrypt encrypted content", code="invalid_encrypted_content"+ ),+ body,+ "responses",+ )+ is None+ )+++def test_missing_reference_targets_its_item_only():+ body = {+ "input": [+ {"type": "reasoning", "id": f"rs_{i}", "encrypted_content": f"opaque{i}"}+ for i in range(2)+ ]+ }+ result = history_retry_body(+ _error("Referenced reasoning item 'rs_1' was not found or has expired."),+ body,+ "responses",+ )+ assert result is not None+ assert result["input"] == [body["input"][0]]+++def test_messages_signature_path_retains_readable_text_and_other_blocks():+ body = {+ "messages": [+ {+ "role": "assistant",+ "content": [+ {+ "type": "thinking",+ "thinking": "read the file",+ "signature": "old-signature",+ },+ {"type": "text", "text": "answer"},+ ],+ }+ ]+ }+ result = history_retry_body(+ _error(+ "messages.0.content.0: Invalid signature in thinking block. The block is bound to a different conversation."+ ),+ body,+ "messages",+ )+ assert result is not None+ assert result["messages"][0]["content"] == [+ {"type": "text", "text": "[Earlier reasoning]\nread the file"},+ body["messages"][0]["content"][1],+ ]+++def test_origin_does_not_expose_credentials_and_survives_account_token_refresh():+ first = replay_origin(+ "provider",+ "responses",+ "actual",+ endpoint=HttpEndpoint(+ "https://example.org/v1",+ {"Authorization": "Bearer secret1"},+ account_id="account1",+ ),+ )+ refreshed = replay_origin(+ "provider",+ "responses",+ "different-model",+ endpoint=HttpEndpoint(+ "https://example.org/v1",+ {"Authorization": "Bearer secret2"},+ account_id="account1",+ ),+ )+ other = replay_origin(+ "provider",+ "responses",+ "actual",+ endpoint=HttpEndpoint(+ "https://example.org/v1",+ {"Authorization": "Bearer secret3"},+ account_id="account2",+ ),+ )+ assert first.accepts(refreshed)+ assert not first.accepts(other)+ assert "secret" not in repr(first) and "account1" not in repr(first)++[email protected]("status", [401, 403, 429, 500])+def test_non_validation_failures_cannot_discard_history(status):+ body = {"input": [{"type": "reasoning", "encrypted_content": "opaque"}]}+ assert (+ history_retry_body(+ _error(+ "Could not verify encrypted content",+ code="invalid_encrypted_content",+ status=status,+ ),+ body,+ "responses",+ )+ is None+ )diff --git a/tests/providers/test_history_transports.py b/tests/providers/test_history_transports.pynew file mode 100644index 00000000..5af26e00--- /dev/null+++ b/tests/providers/test_history_transports.py@@ -0,0 +1,897 @@+"""History crosses the real SDK/HTTP and both public presentation boundaries."""++import json+from contextlib import asynccontextmanager+from copy import deepcopy+from typing import Any++import httpx+import httpx2+import pytest++from free_claude_code.application.execution import ProviderExecutor+from free_claude_code.core.anthropic import aggregate_anthropic_sse_to_message+from free_claude_code.core.anthropic.models import MessagesRequest+from free_claude_code.core.anthropic.stream_contracts import parse_sse_text+from free_claude_code.core.failures import ExecutionFailure, FailureKind+from free_claude_code.core.history_replay import decode_replay, encode_replay+from free_claude_code.core.openai_responses import OpenAIResponsesRequest+from free_claude_code.core.reasoning import ReasoningPolicy+from free_claude_code.providers.open_router import OpenRouterProvider+from tests.application.test_execution import (+ ControlledProvider,+ _routed_request,+ _target,+)+from tests.providers.support import immediate_admission, make_provider_config+from tests.providers.test_anthropic_messages_transport import Endpoint, _events+from tests.providers.test_anthropic_messages_transport import (+ _transport as messages_transport,+)+from tests.providers.test_openai_responses_transport import _client, _completed_response+from tests.providers.test_openai_responses_transport import (+ _transport as responses_transport,+)+++def _native(protocol):+ if protocol == "responses":+ return {+ "type": "reasoning",+ "id": "rs_a:rs_b",+ "status": "completed",+ "summary": [{"type": "summary_text", "text": "Find 17."}],+ "encrypted_content": "opaque-original",+ "extension": {"keep": 17},+ }+ if protocol == "messages":+ return {+ "type": "thinking",+ "thinking": "Find 17.",+ "signature": "opaque-original",+ "extension": {"keep": 17},+ }+ return {+ "reasoning_details": [+ {"type": "reasoning.text", "text": "Find 17.", "index": 0},+ {+ "type": "reasoning.encrypted",+ "data": "opaque-original",+ "format": "native-test",+ "index": 1,+ "extension": {"keep": 17},+ },+ ]+ }+++def _events_for(protocol):+ native = _native(protocol)+ if protocol == "messages":+ events = _events()+ return [+ events[0],+ {"type": "content_block_start", "index": 0, "content_block": native},+ {"type": "content_block_stop", "index": 0},+ *events[-2:],+ ]+ if protocol == "responses":+ completed = _completed_response(model="actual-returned")+ completed["output"] = [native]+ return [+ {+ "type": "response.created",+ "sequence_number": 0,+ "response": {**completed, "status": "in_progress", "output": []},+ },+ {+ "type": "response.output_item.added",+ "sequence_number": 1,+ "output_index": 0,+ "item": {+ **native,+ "status": "in_progress",+ "encrypted_content": None,+ "summary": [],+ },+ },+ {+ "type": "response.reasoning_summary_text.delta",+ "sequence_number": 2,+ "item_id": native["id"],+ "output_index": 0,+ "summary_index": 0,+ "delta": "Find 17.",+ },+ {+ "type": "response.output_item.done",+ "sequence_number": 3,+ "output_index": 0,+ "item": native,+ },+ {"type": "response.completed", "sequence_number": 4, "response": completed},+ ]+ return [+ {+ "id": "chat_test",+ "object": "chat.completion.chunk",+ "created": 0,+ "model": "actual-returned",+ "choices": [{"index": 0, "delta": delta, "finish_reason": finish}],+ }+ for delta, finish in [+ (+ {"role": "assistant", "reasoning_details": native["reasoning_details"]},+ None,+ ),+ ({"content": "17"}, "stop"),+ ]+ ]+++@asynccontextmanager+async def _harness(protocol, responder=None, *, key="a", chat_provider=None):+ bodies: list[dict[str, Any]] = []++ def reply(request):+ bodies.append(json.loads(request.content))+ status, payload = (+ responder(bodies) if responder else (200, _events_for(protocol))+ )+ module = httpx if protocol == "messages" else httpx2+ if status != 200:+ return module.Response(status, json={"error": payload})+ raw = "".join(+ (f"event: {event['type']}\n" if protocol == "messages" else "")+ + f"data: {json.dumps(event)}\n\n"+ for event in payload+ )+ return module.Response(+ 200, headers={"content-type": "text/event-stream"}, content=raw+ )++ if protocol == "messages":+ client = httpx.AsyncClient(transport=httpx.MockTransport(reply))+ provider = messages_transport(client, immediate_admission(max_attempts=5))+ endpoint = Endpoint()+ endpoint.token = key+ extras = {"endpoint_context": endpoint}+ else:+ client = _client(reply)+ client.api_key = key+ if protocol == "responses":+ provider = responses_transport(client)+ else:+ provider = chat_provider or OpenRouterProvider(+ make_provider_config(+ api_key=key, base_url="https://provider.invalid/v1"+ ),+ admission=immediate_admission(max_attempts=5),+ )+ await provider._client.close()+ provider._client = client+ extras = {}++ def stream(wire, history):+ options: dict[str, Any] = dict(+ input_tokens=0,+ request_id="history-test",+ response_model="public-alias",+ reasoning=ReasoningPolicy.on(),+ **extras,+ )+ if protocol == "messages":+ options.pop("input_tokens")+ options["reasoning"] = ReasoningPolicy.provider_default()+ if wire == "responses":+ return provider.stream_responses(+ OpenAIResponsesRequest.model_validate(+ {"model": "requested", "input": history}+ ),+ **options,+ )+ return provider.stream_messages(+ MessagesRequest.model_validate({"model": "requested", "messages": history}),+ **options,+ )++ try:+ yield stream, bodies+ finally:+ if isinstance(client, httpx.AsyncClient):+ await client.aclose()+ else:+ await client.close()+++async def _saved_reply(stream, wire):+ if wire == "messages":+ message, error, saw_stop = await aggregate_anthropic_sse_to_message(stream)+ assert error is None and saw_stop+ return [{"role": "assistant", "content": message["content"]}]+ events = parse_sse_text("".join([event async for event in stream]))+ return events[-1].data["response"]["output"]+++def _carrier(history, wire):+ if wire == "responses":+ return next(+ item["encrypted_content"]+ for item in history+ if item.get("type") == "reasoning"+ )+ return next(+ block.get("signature", block.get("data"))+ for block in history[0]["content"]+ if block["type"] in {"thinking", "redacted_thinking"}+ )++[email protected]("protocol", ["responses", "messages", "chat"])[email protected]("wire", ["responses", "messages"])+async def test_provider_a_b_a_preserves_exact_native_history(protocol, wire):+ async with _harness(protocol) as (send, bodies):+ saved = await _saved_reply(+ send(wire, [{"role": "user", "content": "hello"}]), wire+ )+ record = decode_replay(_carrier(saved, wire))+ assert record.native == _native(protocol)+ assert record.origin.model == (+ "native" if protocol == "messages" else "actual-returned"+ )+ assert record.origin.model != "public-alias"+ history = json.loads(+ json.dumps([*saved, {"role": "user", "content": "continue"}])+ )+ original = deepcopy(history)+ async with _harness(protocol, key="b") as (foreign, foreign_bodies):+ await _saved_reply(foreign(wire, history), wire)+ foreign_wire = json.dumps(foreign_bodies[-1])+ assert (+ "opaque-original" not in foreign_wire+ and "fcc:history" not in foreign_wire+ )+ assert "Find 17." in foreign_wire+ await _saved_reply(send(wire, history), wire)+ if protocol == "responses":+ assert bodies[-1]["input"][0] == _native(protocol)+ elif protocol == "messages":+ assert bodies[-1]["messages"][0]["content"][0] == _native(protocol)+ else:+ assert (+ bodies[-1]["messages"][0]["reasoning_details"]+ == _native(protocol)["reasoning_details"]+ )+ assert history == original+++async def test_legacy_responses_id_then_cipher_rejection_recovers_without_changing_effort():+ wire = "responses"++ def responder(bodies):+ if len(bodies) == 1:+ return 400, {+ "code": "invalid_value",+ "param": "input[0].id",+ "message": "Invalid 'input[0].id': 'rs_a:rs_b'. Expected an ID that contains letters, numbers, underscores, or dashes.",+ }+ if len(bodies) == 2:+ return 400, {+ "code": "invalid_encrypted_content",+ "param": "input[0].encrypted_content",+ "message": "The encrypted content could not be verified.",+ }+ return 200, _events_for("responses")++ history = [+ _native("responses"),+ {"role": "assistant", "content": "17"},+ {"role": "user", "content": "continue"},+ ]+ original = deepcopy(history)+ async with _harness("responses", responder) as (send, bodies):+ await _saved_reply(send(wire, history), wire)+ assert len(bodies) == 3+ assert ":" not in bodies[1]["input"][0]["id"]+ assert bodies[1]["input"][0]["encrypted_content"] == "opaque-original"+ assert bodies[2]["input"][0] == {+ "role": "assistant",+ "content": "[Earlier reasoning summary]\nFind 17.",+ }+ assert all(body["reasoning"] == bodies[0]["reasoning"] for body in bodies)+ assert history == original++[email protected]("protocol", ["responses", "messages", "chat"])+async def test_explicit_legacy_rejection_corrects_only_history_before_commit(protocol):+ def responder(bodies):+ if len(bodies) == 1:+ return 400, {+ "code": "invalid_encrypted_content"+ if protocol != "messages"+ else "invalid_signature",+ "message": "The encrypted content or signature could not be verified.",+ }+ return 200, _events_for(protocol)++ block = (+ _native("messages")+ if protocol == "messages"+ else {"type": "redacted_thinking", "data": "opaque-original"}+ )+ history = [+ {"role": "assistant", "content": [block, {"type": "text", "text": "17"}]},+ {"role": "user", "content": "continue"},+ ]+ original = deepcopy(history)+ async with _harness(protocol, responder) as (send, bodies):+ await _saved_reply(send("messages", history), "messages")+ assert len(bodies) == 2+ assert "opaque-original" in json.dumps(bodies[0])+ assert "opaque-original" not in json.dumps(bodies[1])+ assert "17" in json.dumps(bodies[1])+ assert history == original++[email protected]("protocol", ["responses", "messages", "chat"])[email protected]("committed", [False, True])+async def test_stream_history_rejection_respects_the_public_commit_boundary(+ protocol, committed+):+ visible = "already visible " * 5000 # Exceeds the existing holdback budget.+ error = {+ "code": "invalid_signature"+ if protocol == "messages"+ else "invalid_encrypted_content",+ "type": "invalid_request_error",+ "message": "The encrypted content or signature could not be verified.",+ }++ def responder(bodies):+ if len(bodies) > 1:+ return 200, _events_for(protocol)+ if protocol == "messages":+ events = _events(visible)[:3] if committed else _events()[:1]+ return 200, [*events, {"type": "error", "error": error}]+ if protocol == "responses":+ events = _events_for(protocol)[:1]+ if committed:+ events.append(+ {+ "type": "response.output_text.delta",+ "sequence_number": 1,+ "item_id": "text",+ "content_index": 0,+ "output_index": 0,+ "delta": visible,+ "logprobs": [],+ }+ )+ return 200, [*events, {**error, "type": "error", "sequence_number": 2}]+ events = []+ if committed:+ chunk = deepcopy(_events_for(protocol)[-1])+ chunk["choices"][0] = {+ "index": 0,+ "delta": {"content": visible},+ "finish_reason": None,+ }+ events.append(chunk)+ return 200, [*events, {"error": error}]++ block = (+ _native("messages")+ if protocol == "messages"+ else {"type": "redacted_thinking", "data": "opaque-original"}+ )+ history = [+ {"role": "assistant", "content": [block, {"type": "text", "text": "17"}]},+ {"role": "user", "content": "continue"},+ ]+ async with _harness(protocol, responder) as (send, bodies):+ if committed:+ output = ""+ with pytest.raises(ExecutionFailure):+ async for event in send("messages", history):+ output += event+ assert visible in output+ assert len(bodies) == 1+ else:+ await _saved_reply(send("messages", history), "messages")+ assert len(bodies) == 2+ assert "opaque-original" not in json.dumps(bodies[1])+++async def test_successful_fallback_stamps_its_own_origin_and_gets_unmodified_input():+ class MutatingPrimary(ControlledProvider):+ async def stream_messages(self, request, input_tokens=0, **kwargs):+ request.messages[0].content = "primary mutation"+ async for event in super().stream_messages(request, input_tokens, **kwargs):+ yield event++ primary = MutatingPrimary(+ [ExecutionFailure(FailureKind.UNAVAILABLE, 503, "unavailable", True)]+ )+ bodies = []++ def reply(request):+ bodies.append(json.loads(request.content))+ return httpx2.Response(+ 200,+ headers={"content-type": "text/event-stream"},+ content="".join(+ f"data: {json.dumps(event)}\n\n" for event in _events_for("chat")+ ),+ )++ provider = OpenRouterProvider(+ make_provider_config(+ api_key="fallback-key", base_url="https://provider.invalid/v1"+ ),+ admission=immediate_admission(),+ )+ await provider._client.close()+ provider._client = _client(reply)+ routed = _routed_request(_target("open_router", "fallback-model"))+ original = routed.request.model_dump()+ executor = ProviderExecutor(+ lambda name: primary if name == "provider" else provider,+ progress_timeout_seconds=10,+ )+ try:+ saved = await _saved_reply(+ executor.stream_messages(+ routed, raw_log_payload={}, request_id="actual-fallback"+ ),+ "messages",+ )+ record = decode_replay(_carrier(saved, "messages"))+ assert record.origin.provider == "OPENROUTER"+ assert record.origin.model == "actual-returned"+ assert bodies[0]["messages"][0]["content"] == "hello"+ assert routed.request.model_dump() == original+ finally:+ await provider._client.close()+++async def test_history_corrections_exhaust_the_shared_attempt_budget():+ history = [+ {+ "type": "reasoning",+ "id": f"rs_{index}",+ "summary": [],+ "encrypted_content": f"opaque{index}",+ }+ for index in range(7)+ ]+ history += [{"role": "user", "content": "continue"}]+ original = deepcopy(history)++ def responder(bodies):+ return 400, {+ "code": "invalid_encrypted_content",+ "param": "input[0].encrypted_content",+ "message": "The encrypted content could not be verified.",+ }++ async with _harness("responses", responder) as (send, bodies):+ with pytest.raises(ExecutionFailure):+ await _saved_reply(send("responses", history), "responses")+ assert len(bodies) == 5+ assert [len(body["input"]) for body in bodies] == [8, 7, 6, 5, 4]+ assert history == original+++def _chat_reasoning_events(deltas):+ template = _events_for("chat")[0]+ return [+ {**template, "choices": [{"index": 0, "delta": delta, "finish_reason": None}]}+ for delta in deltas+ ] + [_events_for("chat")[-1]]++[email protected]("wire", ["messages", "responses"])[email protected]("fragmented", [False, True])+ ("prefix", "suffix", "finish", "has_tool"),+ [+ ("<", "17", "stop", False),+ ("<th", "ink>inline</think>17", "stop", False),+ (+ "<tool_call>",+ "<function=lookup><parameter=query>x</parameter></function></tool_call>",+ "stop",+ True,+ ),+ (+ "● <function=lookup>",+ "<parameter=query>x</parameter></function>",+ "stop",+ True,+ ),+ ("<", None, "tool_calls", True),+ ("<", "", "length", False),+ ("<think>", "", "stop", False),+ ],+ ids=[+ "text",+ "thinking",+ "function-tag",+ "heuristic-tool",+ "native-tool",+ "length",+ "thinking-end",+ ],+)+async def test_chat_buffered_content_preserves_reasoning_through_next_request(+ wire, fragmented, prefix, suffix, finish, has_tool+):+ first = {"type": "reasoning.encrypted", "data": "first", "index": 0}+ second = {+ "type": "reasoning.encrypted",+ "data": "second",+ "index": 0 if fragmented else 1,+ }+ expected = [{**first, "data": "firstsecond"}] if fragmented else [first, second]+ deltas = [+ {"reasoning_content": "Plan.", "reasoning_details": [first]},+ {"content": prefix},+ {"reasoning_details": [second]},+ {"content": suffix}+ if suffix is not None+ else {+ "tool_calls": [+ {+ "index": 0,+ "id": "call_lookup",+ "type": "function",+ "function": {"name": "lookup", "arguments": '{"query":"x"}'},+ }+ ]+ },+ ]+ events = _chat_reasoning_events(deltas)+ events[-1]["choices"][0].update(delta={}, finish_reason=finish)+ schema = {+ "type": "object",+ "properties": {"query": {"type": "string"}},+ "required": ["query"],+ }+ provider = OpenRouterProvider(+ make_provider_config(api_key="a", base_url="https://provider.invalid/v1"),+ admission=immediate_admission(),+ )++ def send(history):+ if wire == "messages":+ return provider.stream_messages(+ MessagesRequest.model_validate(+ {+ "model": "requested",+ "messages": history,+ "tools": [{"name": "lookup", "input_schema": schema}],+ }+ ),+ reasoning=ReasoningPolicy.on(),+ )+ return provider.stream_responses(+ OpenAIResponsesRequest.model_validate(+ {+ "model": "requested",+ "input": history,+ "tools": [+ {"type": "function", "name": "lookup", "parameters": schema}+ ],+ }+ ),+ reasoning=ReasoningPolicy.on(),+ )++ async with _harness(+ "chat", lambda bodies: (200, events), chat_provider=provider+ ) as (_, bodies):+ saved = await _saved_reply(send([{"role": "user", "content": "hello"}]), wire)+ assert decode_replay(_carrier(saved, wire)).native == {+ "reasoning_content": "Plan.",+ "reasoning_details": expected,+ }+ history = deepcopy(saved)+ blocks = saved[0]["content"] if wire == "messages" else saved+ calls = [+ block for block in blocks if block["type"] in {"tool_use", "function_call"}+ ]+ assert len(calls) == int(has_tool)+ for call in calls:+ assert call["name"] == "lookup"+ if wire == "messages":+ assert call["input"] == {"query": "x"}+ history.append(+ {+ "role": "user",+ "content": [+ {+ "type": "tool_result",+ "tool_use_id": call["id"],+ "content": "result",+ }+ ],+ }+ )+ else:+ assert json.loads(call["arguments"]) == {"query": "x"}+ history.append(+ {+ "type": "function_call_output",+ "call_id": call["call_id"],+ "output": "result",+ }+ )+ history.append({"role": "user", "content": "next"})+ original = deepcopy(history)+ await _saved_reply(send(history), wire)+ assert len(bodies) == 2+ assert [+ detail+ for message in bodies[-1]["messages"]+ for detail in message.get("reasoning_details", [])+ ] == expected+ assert history == original++[email protected]("wire", ["messages", "responses"])+async def test_chat_encrypted_only_completion_does_not_add_blank_text(wire):+ details = [{"type": "reasoning.encrypted", "data": "opaque-only", "index": 0}]+ events = _chat_reasoning_events([{"reasoning_details": details}])+ events[-1]["choices"][0]["delta"] = {}+ async with _harness("chat", lambda bodies: (200, events)) as (send, _):+ saved = await _saved_reply(+ send(wire, [{"role": "user", "content": "hello"}]), wire+ )+ assert decode_replay(_carrier(saved, wire)).native == {"reasoning_details": details}+ blocks = saved[0]["content"] if wire == "messages" else saved+ assert [block["type"] for block in blocks] == [+ "redacted_thinking" if wire == "messages" else "reasoning"+ ]++[email protected]("wire", ["messages", "responses"])[email protected]("committed", [False, True])+async def test_chat_pending_reasoning_is_finalized_on_failure_or_discarded_on_retry(+ wire, committed+):+ text = "Plan." * (30000 if committed else 1)+ first = {"type": "reasoning.encrypted", "data": "first", "index": 0}+ second = {"type": "reasoning.encrypted", "data": "second", "index": 1}+ events = _chat_reasoning_events(+ [+ {"reasoning_content": text, "reasoning_details": [first]},+ {"content": "<"},+ {"reasoning_details": [second]},+ ]+ )[:-1]+ # A cutoff retries before commitment; a terminal API error closes visible output.+ if committed:+ events.append(+ {"error": {"type": "invalid_request_error", "message": "stream failed"}}+ )++ def responder(bodies):+ return 200, events if len(bodies) == 1 else _events_for("chat")++ async with _harness("chat", responder) as (send, bodies):+ stream = send(wire, [{"role": "user", "content": "hello"}])+ if not committed:+ saved = await _saved_reply(stream, wire)+ assert len(bodies) == 2+ assert decode_replay(_carrier(saved, wire)).native == _native("chat")+ return+ if wire == "messages":+ output = ""+ with pytest.raises(ExecutionFailure):+ async for frame in stream:+ output += frame++ async def replay_frames():+ yield output++ message, _, saw_stop = await aggregate_anthropic_sse_to_message(+ replay_frames()+ )+ assert not saw_stop+ saved = [{"role": "assistant", "content": message["content"]}]+ else:+ frames = [frame async for frame in stream]+ response = parse_sse_text("".join(frames))[-1].data["response"]+ assert response["status"] == "failed"+ saved = response["output"]+ assert len(bodies) == 1+ assert decode_replay(_carrier(saved, wire)).native == {+ "reasoning_content": text,+ "reasoning_details": [first, second],+ }++[email protected]("wire", ["messages", "responses"])[email protected]("destination", ["chat", "messages", "responses"])[email protected]("incomplete_saved_record", [False, True])+async def test_chat_plaintext_beside_encrypted_details_survives_switching(+ wire, destination, incomplete_saved_record+):+ text = "The crucial visible reasoning."+ details = [{"type": "reasoning.encrypted", "data": "opaque-only", "index": 0}]+ events = _chat_reasoning_events(+ [{"reasoning_content": text, "reasoning_details": details}]+ )+ async with _harness("chat", lambda bodies: (200, events)) as (source, sent):+ saved = await _saved_reply(+ source(wire, [{"role": "user", "content": "hello"}]), wire+ )+ record = decode_replay(_carrier(saved, wire))+ if incomplete_saved_record:+ record.native.pop("reasoning_content", None)+ carrier = encode_replay(record)+ if wire == "responses":+ saved[0]["encrypted_content"] = carrier+ else:+ saved[0]["content"][0]["signature"] = carrier+ else:+ assert record.native["reasoning_content"] == text+ history = json.loads(json.dumps([*saved, {"role": "user", "content": "next"}]))+ original = deepcopy(history)+ async with _harness(destination, key="b") as (foreign, bodies):+ await _saved_reply(foreign(wire, history), wire)+ outgoing = json.dumps(bodies[-1])+ assert outgoing.count(text) == 1+ assert "opaque-only" not in outgoing and "fcc:history" not in outgoing+ await _saved_reply(source(wire, history), wire)+ assert sent[-1]["messages"][0]["reasoning_details"] == details+ assert json.dumps(sent[-1]).count(text) == 1+ assert history == original++[email protected]("wire", ["messages", "responses"])[email protected]("encrypted", [False, True])+async def test_chat_summary_fragments_remain_readable_and_restore_exactly(+ wire, encrypted+):+ first = {"type": "reasoning.summary", "summary": "Short ", "index": 0}+ second = {"type": "reasoning.summary", "summary": "summary.", "index": 0}+ opaque = {"type": "reasoning.encrypted", "data": "opaque-only", "index": 1}+ details = [{**first, "summary": "Short summary."}, *([opaque] if encrypted else [])]+ events = _chat_reasoning_events(+ [+ {"reasoning_details": [first]},+ {"reasoning_details": [second, *([opaque] if encrypted else [])]},+ ]+ )+ async with _harness("chat", lambda bodies: (200, events)) as (source, sent):+ saved = await _saved_reply(+ source(wire, [{"role": "user", "content": "hello"}]), wire+ )+ assert json.dumps(saved).count("Short summary.") == 1+ record = decode_replay(_carrier(saved, wire))+ assert record.native["reasoning_details"] == details+ history = [*saved, {"role": "user", "content": "next"}]+ async with _harness("responses", key="b") as (foreign, bodies):+ await _saved_reply(foreign(wire, history), wire)+ assert bodies[-1]["input"][0] == {+ "role": "assistant",+ "content": "[Earlier reasoning summary]\nShort summary.",+ }+ await _saved_reply(source(wire, history), wire)+ assert sent[-1]["messages"][0]["reasoning_details"] == details++[email protected]("native_first", [False, True])+async def test_chat_alternate_readable_fields_replay_once(native_first):+ native = {"reasoning_content": "One readable thought."}+ typed = {+ "reasoning_details": [+ {+ "type": "reasoning.text",+ "text": "One readable thought.",+ "index": 0,+ }+ ]+ }+ events = _chat_reasoning_events(+ [native, typed] if native_first else [typed, native]+ )+ async with _harness("chat", lambda bodies: (200, events)) as (source, sent):+ saved = await _saved_reply(+ source("messages", [{"role": "user", "content": "hi"}]), "messages"+ )+ assert json.dumps(saved).count("One readable thought.") == 1+ history = [*saved, {"role": "user", "content": "next"}]+ async with _harness("responses", key="b") as (foreign, bodies):+ await _saved_reply(foreign("messages", history), "messages")+ assert json.dumps(bodies[-1]).count("One readable thought.") == 1+ await _saved_reply(source("messages", history), "messages")+ assert json.dumps(sent[-1]).count("One readable thought.") == 1+++async def test_chat_reasoning_groups_do_not_inherit_previous_plaintext():+ events = _chat_reasoning_events(+ [+ {+ "reasoning_content": "First thought.",+ "reasoning_details": [+ {"type": "reasoning.encrypted", "data": "first-", "index": 0}+ ],+ },+ {+ "reasoning_details": [+ {"type": "reasoning.encrypted", "data": "secret", "index": 0}+ ]+ },+ {"content": "First answer."},+ {+ "reasoning_content": "Second thought.",+ "reasoning_details": [+ {"type": "reasoning.encrypted", "data": "second-secret", "index": 0}+ ],+ },+ ]+ )+ async with _harness("chat", lambda bodies: (200, events)) as (source, _):+ saved = await _saved_reply(+ source("messages", [{"role": "user", "content": "hi"}]), "messages"+ )+ records = [+ decode_replay(block["signature"]).native+ for block in saved[0]["content"]+ if block["type"] == "thinking"+ ]+ assert records == [+ {+ "reasoning_content": "First thought.",+ "reasoning_details": [+ {"type": "reasoning.encrypted", "data": "first-secret", "index": 0}+ ],+ },+ {+ "reasoning_content": "Second thought.",+ "reasoning_details": [+ {"type": "reasoning.encrypted", "data": "second-secret", "index": 0}+ ],+ },+ ]+++async def test_chat_plaintext_matching_multiple_detail_parts_is_not_repeated():+ events = _chat_reasoning_events(+ [+ {+ "reasoning_content": "First part. Second part.",+ "reasoning_details": [+ {"type": "reasoning.text", "text": "First part. ", "index": 0},+ {"type": "reasoning.text", "text": "Second part.", "index": 1},+ ],+ }+ ]+ )+ async with _harness("chat", lambda bodies: (200, events)) as (source, _):+ saved = await _saved_reply(+ source("messages", [{"role": "user", "content": "hi"}]), "messages"+ )+ async with _harness("responses", key="b") as (foreign, bodies):+ await _saved_reply(+ foreign("messages", [*saved, {"role": "user", "content": "next"}]),+ "messages",+ )+ outgoing = json.dumps(bodies[-1])+ assert outgoing.count("First part.") == outgoing.count("Second part.") == 1diff --git a/tests/providers/test_huggingface.py b/tests/providers/test_huggingface.pyindex fb4417dd..9abf51b9 100644--- a/tests/providers/test_huggingface.py+++ b/tests/providers/test_huggingface.py@@ -206,9 +206,14 @@ def test_build_request_body_does_not_replay_prior_thinking_blocks(body = huggingface_provider._build_request_body(req)- assert body["messages"] == [{"role": "assistant", "content": "visible answer"}]+ assert body["messages"] == [+ {+ "role": "assistant",+ "content": "[Earlier reasoning]\nhidden prior thought\n\nvisible answer",+ }+ ]assert "reasoning_content" not in body["messages"][0]- assert "hidden prior thought" not in str(body)+ assert "hidden prior thought" in str(body)def test_build_request_body_does_not_replay_top_level_reasoning_content(@@ -227,8 +232,13 @@ def test_build_request_body_does_not_replay_top_level_reasoning_content(body = huggingface_provider._build_request_body(req)- assert body["messages"] == [{"role": "assistant", "content": "visible answer"}]- assert "hidden prior reasoning" not in str(body)+ assert body["messages"] == [+ {+ "role": "assistant",+ "content": "[Earlier reasoning]\nhidden prior reasoning\n\nvisible answer",+ }+ ]+ assert "hidden prior reasoning" in str(body)@pytest.mark.asynciodiff --git a/tests/providers/test_kilo.py b/tests/providers/test_kilo.pyindex 74e88ffe..87542093 100644--- a/tests/providers/test_kilo.py+++ b/tests/providers/test_kilo.py@@ -15,6 +15,7 @@ from free_claude_code.core.anthropic.stream_contracts import (text_content,thinking_content,)+from free_claude_code.core.history_replay import decode_replayfrom free_claude_code.core.model_capabilities import ModelInputModalityfrom free_claude_code.core.reasoning import ReasoningPolicyfrom free_claude_code.providers.kilo import KiloProvider@@ -272,14 +273,16 @@ async def test_stream_uses_reasoning_field_without_duplicating_plain_details(events = parse_sse_text(event_text)assert thinking_content(events) == "plan "assert text_content(events) == "done"- redacted_blocks = [- event.data["content_block"]+ records = [+ decode_replay(event.data["delta"]["signature"]).nativefor event in events- if event.event == "content_block_start"- and event.data.get("content_block", {}).get("type") == "redacted_thinking"+ if event.data.get("delta", {}).get("type") == "signature_delta"+ ]+ assert len(records) == 1+ assert records[0]["reasoning_details"] == [+ {"type": "reasoning.text", "text": "plan "},+ encrypted,]- assert len(redacted_blocks) == 1- assert json.loads(redacted_blocks[0]["data"]) == encryptedassert stream.closeddiff --git a/tests/providers/test_lmstudio.py b/tests/providers/test_lmstudio.pyindex 903a40f9..bf7d11b2 100644--- a/tests/providers/test_lmstudio.py+++ b/tests/providers/test_lmstudio.py@@ -89,8 +89,7 @@ def test_exact_client_budget_is_not_derived_from_output_tokens(lmstudio_providerdef test_build_request_body_never_replays_prior_thinking(lmstudio_provider):- """Mistral-family templates have no assistant reasoning field; prior-turn- thinking must never be replayed regardless of current-turn reasoning policy."""+ """Retain prior thinking as ordinary context without a reasoning role."""req = make_request(messages=[{"role": "user", "content": "hi"},@@ -110,7 +109,8 @@ 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 "prior reasoning" not in str(body)+ assert "[Earlier reasoning]" in str(body)+ assert "prior reasoning" in str(body)def test_preflight_builds_before_context_budget_and_preserves_policy(diff --git a/tests/providers/test_nvidia_nim.py b/tests/providers/test_nvidia_nim.pyindex 1bb801ff..5084ce2d 100644--- a/tests/providers/test_nvidia_nim.py+++ b/tests/providers/test_nvidia_nim.py@@ -1,4 +1,6 @@import json+from copy import deepcopy+from dataclasses import replacefrom unittest.mock import AsyncMock, MagicMock, patchimport openai@@ -8,6 +10,11 @@ from httpx2 import Request, Responsefrom free_claude_code.config.nim import NimSettingsfrom free_claude_code.config.provider_catalog import NVIDIA_NIM_DEFAULT_BASEfrom free_claude_code.core.failures import ExecutionFailure+from free_claude_code.core.history_replay import (+ ReplayOrigin,+ ReplayRecord,+ encode_replay,+)from free_claude_code.core.openai_responses.models import OpenAIResponsesRequestfrom free_claude_code.core.reasoning import ReasoningEffort, ReasoningPolicyfrom free_claude_code.providers.admission import UPSTREAM_TRANSIENT_TOTAL_ATTEMPTS@@ -24,6 +31,7 @@ from tests.providers.support import (make_provider_config,reasoning_for,)+from tests.providers.test_history_transports import _events_for, _harness, _saved_replydef message(role, content):@@ -44,6 +52,195 @@ def make_request(**overrides):return make_messages_request(model, **overrides)+def _alias_provider():+ return NvidiaNimProvider(+ make_provider_config(api_key="a", base_url="https://provider.invalid/v1"),+ nim_settings=NimSettings(chat_template="custom_template"),+ admission=immediate_admission(max_attempts=4),+ )+++def _alias_request(wire="messages", *, reasoning_history=False):+ schema = {+ "type": "object",+ "properties": {"pattern": {"type": "string"}, "type": {"type": "string"}},+ "required": ["pattern", "type"],+ "additionalProperties": False,+ }+ history = [{"role": "user", "content": "Search"}]+ if reasoning_history:+ carrier = encode_replay(+ ReplayRecord(+ ReplayOrigin(+ "source", "chat", "https://source.invalid/v1", "a", "test"+ ),+ {+ "reasoning_details": [+ {+ "type": "reasoning.text",+ "text": "Need the tool.",+ "index": 0,+ }+ ]+ },+ )+ )+ history = [+ {+ "role": "assistant",+ "content": [+ {+ "type": "thinking",+ "thinking": "Need the tool.",+ "signature": carrier,+ },+ {+ "type": "tool_use",+ "name": "Grep",+ "id": "prior",+ "input": {"pattern": "needle", "type": "py"},+ },+ ],+ },+ {+ "role": "user",+ "content": [+ {+ "type": "tool_result",+ "tool_use_id": "prior",+ "content": "result",+ },+ ],+ },+ ]+ if wire == "messages":+ return make_request(+ system=None,+ messages=history,+ tools=[tool("Grep", "Search file contents", schema)],+ )+ return OpenAIResponsesRequest.model_validate(+ {+ "model": "test-model",+ "input": history,+ "tools": [{"type": "function", "name": "Grep", "parameters": schema}],+ }+ )+++def _alias_events():+ template = _events_for("chat")[0]+ return [+ {+ **template,+ "choices": [+ {"index": 0, "delta": {"tool_calls": [call]}, "finish_reason": finish}+ ],+ }+ for call, finish in [+ (+ {+ "index": 0,+ "id": "call_grep",+ "type": "function",+ "function": {+ "name": "Grep",+ "arguments": '{"pattern":"needle","_fcc_arg_',+ },+ },+ None,+ ),+ ({"index": 0, "function": {"arguments": 'type":"py"}'}}, "tool_calls"),+ ]+ ]+++ "wire,correction",+ [+ ("messages", None),+ ("responses", None),+ ("messages", "chat_template"),+ ("responses", "chat_template"),+ ("messages", "reasoning_budget"),+ ("messages", "reasoning_content"),+ ],+)+async def test_argument_aliases_survive_request_corrections(wire, correction):+ provider = _alias_provider()+ request = _alias_request(wire, reasoning_history=correction == "reasoning_content")+ original = deepcopy(request.model_dump())++ def responder(bodies):+ if len(bodies) == 1 and correction:+ return 400, {"message": f"Unsupported field: {correction}"}+ return 200, _alias_events()++ async with _harness("chat", responder, chat_provider=provider) as (_, bodies):+ stream = (+ provider.stream_messages+ if wire == "messages"+ else provider.stream_responses+ )+ saved = await _saved_reply(+ stream(request, reasoning=ReasoningPolicy.on(budget_tokens=4096)), wire+ )+ if wire == "messages":+ call = next(+ block for block in saved[0]["content"] if block["type"] == "tool_use"+ )+ assert call["input"] == {"pattern": "needle", "type": "py"}+ assert call["id"] == "call_grep"+ else:+ call = next(item for item in saved if item["type"] == "function_call")+ assert json.loads(call["arguments"]) == {"pattern": "needle", "type": "py"}+ assert call["call_id"] == "call_grep"+ assert len(bodies) == (2 if correction else 1)+ assert all(NIM_TOOL_ARGUMENT_ALIASES_KEY not in body for body in bodies)+ if correction == "reasoning_content":+ assert "reasoning_content" not in bodies[-1]["messages"][0]+ assert json.dumps(bodies[-1]).count("Need the tool.") == 1+ assert request.model_dump() == original++[email protected]("early_sse", [False, True])+async def test_argument_aliases_survive_shared_history_correction(early_sse):+ provider = _alias_provider()+ # Test adapter exercises the shared history path; native NIM disables details.+ provider._profile = replace(provider._profile, structured_reasoning_details=True)+ request = _alias_request()+ request.messages.insert(+ 0,+ type(request.messages[0]).model_validate(+ {+ "role": "assistant",+ "content": [+ {"type": "redacted_thinking", "data": "opaque-original"},+ ],+ }+ ),+ )++ def responder(bodies):+ if len(bodies) == 1:+ error = {+ "code": "invalid_encrypted_content",+ "message": "The encrypted content could not be verified.",+ }+ return (200, [{"error": error}]) if early_sse else (400, error)+ return 200, _alias_events()++ async with _harness("chat", responder, chat_provider=provider) as (_, bodies):+ saved = await _saved_reply(provider.stream_messages(request), "messages")+ call = next(block for block in saved[0]["content"] if block["type"] == "tool_use")+ assert call["input"] == {"pattern": "needle", "type": "py"}+ assert len(bodies) == 2+ assert "opaque-original" not in json.dumps(bodies[-1])+ assert all(NIM_TOOL_ARGUMENT_ALIASES_KEY not in body for body in bodies)++def _input_json_deltas(events):deltas = []for event in events:@@ -1253,6 +1450,9 @@ 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 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_open_router.py b/tests/providers/test_open_router.pyindex 2f728d92..76339b46 100644--- a/tests/providers/test_open_router.py+++ b/tests/providers/test_open_router.py@@ -15,6 +15,7 @@ from free_claude_code.core.anthropic.stream_contracts import (text_content,thinking_content,)+from free_claude_code.core.history_replay import decode_replayfrom free_claude_code.core.model_capabilities import ModelInputModalityfrom free_claude_code.providers.open_router import OpenRouterProviderfrom free_claude_code.providers.openai_chat import OpenAIChatProvider@@ -327,8 +328,16 @@ async def test_stream_maps_reasoning_content_and_details(open_router_provider):event_text = "".join(events)parsed = parse_sse_text(event_text)assert thinking_content(parsed) == "plan "- assert "redacted_thinking" in event_text- assert "opaque" in event_text+ carriers = [+ event.data["delta"]["signature"]+ for event in parsed+ if event.data.get("delta", {}).get("type") == "signature_delta"+ ]+ assert len(carriers) == 1+ assert decode_replay(carriers[0]).native["reasoning_details"] == [+ {"type": "reasoning.text", "text": "plan "},+ redacted,+ ]assert text_content(parsed) == "done"assert stream.closeddiff --git a/tests/providers/test_streaming_errors.py b/tests/providers/test_streaming_errors.pyindex 5427e612..4a36d640 100644--- a/tests/providers/test_streaming_errors.py+++ b/tests/providers/test_streaming_errors.py@@ -49,6 +49,12 @@ from tests.providers.support import (make_provider_config,profiled_provider,)+from tests.providers.test_history_transports import _events_for, _harness, _saved_reply+from tests.providers.test_nvidia_nim import (+ _alias_events,+ _alias_provider,+ _alias_request,+)class AsyncStreamMock:@@ -339,7 +345,7 @@ class TestStreamingExceptionHandling:pytest.raises(ValueError, match="invalid stream wrapper"),):await provider._create_stream(- {"messages": []},+ {"model": "test-model", "messages": []},execution,ProviderOperationKind.GENERATION,)@@ -1745,7 +1751,7 @@ class TestStreamingExceptionHandling:pytest.raises(TruncatedProviderStreamError),):await runner._collect_recovery_output(- {"messages": []},+ {"model": "test-model", "messages": []},include_reasoning=True,execution=execution,operation_kind=ProviderOperationKind.CONTINUATION,@@ -1778,7 +1784,7 @@ class TestStreamingExceptionHandling:pytest.raises(TimeoutError),):await runner._collect_recovery_output(- {"messages": []},+ {"model": "test-model", "messages": []},include_reasoning=True,execution=execution,operation_kind=ProviderOperationKind.CONTINUATION,@@ -1810,6 +1816,7 @@ class TestStreamingExceptionHandling:[_make_chunk(content="visible"), _make_chunk(finish_reason="stop")])body = {+ "model": "test-model","messages": [],"stream_options": {"include_usage": True},}@@ -1955,7 +1962,7 @@ class TestStreamingExceptionHandling:return_value=stream,):result = await runner._collect_recovery_output(- {"messages": []},+ {"model": "test-model", "messages": []},include_reasoning=True,execution=execution,operation_kind=ProviderOperationKind.CONTINUATION,@@ -2106,7 +2113,7 @@ class TestStreamingExceptionHandling:return_value=stream,):result = await runner._collect_recovery_output(- {"messages": []},+ {"model": "test-model", "messages": []},include_reasoning=True,execution=execution,operation_kind=ProviderOperationKind.CONTINUATION,@@ -2142,7 +2149,7 @@ class TestStreamingExceptionHandling:side_effect=[failed, recovered],) as create:result = await runner._collect_recovery_output(- {"messages": []},+ {"model": "test-model", "messages": []},include_reasoning=True,execution=execution,operation_kind=ProviderOperationKind.CONTINUATION,@@ -2175,7 +2182,7 @@ class TestStreamingExceptionHandling:pytest.raises(ValueError, match="original terminal failure"),):await runner._collect_recovery_output(- {"messages": []},+ {"model": "test-model", "messages": []},include_reasoning=True,execution=execution,operation_kind=ProviderOperationKind.CONTINUATION,@@ -2201,7 +2208,7 @@ class TestStreamingExceptionHandling:):task = asyncio.create_task(runner._collect_recovery_output(- {"messages": []},+ {"model": "test-model", "messages": []},include_reasoning=True,execution=execution,operation_kind=ProviderOperationKind.CONTINUATION,@@ -2250,7 +2257,7 @@ class TestStreamingExceptionHandling:side_effect=[rejected, recovered],) as create:result = await runner._collect_recovery_output(- {"messages": []},+ {"model": "test-model", "messages": []},include_reasoning=True,execution=execution,operation_kind=ProviderOperationKind.CONTINUATION,@@ -3178,3 +3185,54 @@ async def test_openai_compat_stream_ends_with_contract_when_tool_name_never_arrierror = await _collect_stream_error(provider, request)assert "Provider stream ended without finish_reason." in error.message++[email protected]("collector", [False, True])+async def test_tool_argument_mapping_survives_correction_then_stream_reopen(collector):+ provider = _alias_provider()+ request = _alias_request()++ def responder(bodies):+ if len(bodies) == 1:+ return 400, {"message": "chat_template is unsupported"}+ if len(bodies) == 2:+ template = _events_for("chat")[0]+ return 200, [+ {+ **template,+ "choices": [+ {+ "index": 0,+ "delta": {"content": "discarded"},+ "finish_reason": None,+ }+ ],+ }+ ]+ return 200, _alias_events()++ async with _harness("chat", responder, chat_provider=provider) as (_, bodies):+ if collector:+ runner = _make_stream_runner(provider, request=request)+ execution = provider._admission.start_execution()+ try:+ recovered = await runner._collect_recovery_output(+ runner._body,+ include_reasoning=False,+ execution=execution,+ operation_kind=ProviderOperationKind.CONTINUATION,+ )+ arguments = json.loads(recovered.tool_calls[0]["function"]["arguments"])+ finally:+ execution.abandon()+ else:+ saved = await _saved_reply(provider.stream_messages(request), "messages")+ call = next(+ block for block in saved[0]["content"] if block["type"] == "tool_use"+ )+ arguments = call["input"]+ assert arguments == {"pattern": "needle", "type": "py"}+ assert len(bodies) == 3+ assert all("chat_template" not in body for body in bodies[1:])+ assert all("_fcc_nim_tool_argument_aliases" not in body for body in bodies)diff --git a/tests/providers/test_wandb.py b/tests/providers/test_wandb.pyindex 33a5b26c..f3b929be 100644--- a/tests/providers/test_wandb.py+++ b/tests/providers/test_wandb.py@@ -119,7 +119,7 @@ def test_build_request_body_drops_undocumented_reasoning_replay_but_keeps_tools(assert body["messages"][1] == {"role": "assistant",- "content": "I will inspect it.",+ "content": "[Earlier reasoning]\nRead it first.\n\nI will inspect it.","tool_calls": [{"id": "toolu_1",diff --git a/tests/providers/test_zenmux.py b/tests/providers/test_zenmux.pyindex 13a23f43..3f02a380 100644--- a/tests/providers/test_zenmux.py+++ b/tests/providers/test_zenmux.py@@ -18,6 +18,7 @@ from free_claude_code.core.anthropic.stream_contracts import (text_content,thinking_content,)+from free_claude_code.core.history_replay import decode_replayfrom free_claude_code.core.model_capabilities import ModelInputModalityfrom free_claude_code.core.reasoning import (ReasoningCapability,@@ -344,14 +345,13 @@ async def test_stream_preserves_signed_details_without_duplicating_reasoning(events = parse_sse_text(event_text)assert thinking_content(events) == "plan "assert text_content(events) == "done"- redacted_blocks = [- event.data["content_block"]+ records = [+ decode_replay(event.data["delta"]["signature"]).nativefor event in events- if event.event == "content_block_start"- and event.data.get("content_block", {}).get("type") == "redacted_thinking"+ if event.data.get("delta", {}).get("type") == "signature_delta"]- assert len(redacted_blocks) == 1- assert json.loads(redacted_blocks[0]["data"]) == detail+ assert len(records) == 1+ assert records[0]["reasoning_details"] == [detail]assert stream.closeddiff --git a/uv.lock b/uv.lockindex 026cbdc0..84468ef7 100644--- a/uv.lock+++ b/uv.lock@@ -598,7 +598,7 @@ wheels = [[[package]]name = "free-claude-code"-version = "6.1.3"+version = "6.1.4"source = { editable = "." }dependencies = [{ name = "aiohttp" },