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
Share request recovery policy across provider transports (#1806)
Ali Khokhard4500afec825
diff --git a/pyproject.toml b/pyproject.tomlindex dc21dee8..318d716b 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -4,7 +4,7 @@ build-backend = "hatchling.build"[project]name = "free-claude-code"-version = "6.2.31"+version = "6.2.32"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/providers/anthropic_messages/transport.py b/src/free_claude_code/providers/anthropic_messages/transport.pyindex 848f677f..4579c7cf 100644--- a/src/free_claude_code/providers/anthropic_messages/transport.py+++ b/src/free_claude_code/providers/anthropic_messages/transport.py@@ -4,6 +4,7 @@ import asyncioimport jsonimport sysfrom collections.abc import AsyncIterator, Callable, Mapping+from functools import partialfrom typing import castimport httpx@@ -42,10 +43,10 @@ from free_claude_code.core.reasoning import (from free_claude_code.core.trace import trace_eventfrom free_claude_code.providers.admission import (ProviderAdmissionController,- ProviderCorrectionAction,ProviderExecution,ProviderOperationKind,)+from free_claude_code.providers.endpoint import RequestEndpointfrom free_claude_code.providers.endpoint_types import EndpointContextfrom free_claude_code.providers.failure_policy import (RetryableProviderProtocolError,@@ -56,7 +57,6 @@ from free_claude_code.providers.failure_policy import (is_retryable_stream_error,)from free_claude_code.providers.history_replay import (- history_retry_body,replay_origin,validate_history,)@@ -65,6 +65,10 @@ from free_claude_code.providers.reasoning_compatibility import (ReasoningCorrection,prepare_messages_reasoning,)+from free_claude_code.providers.request_recovery import (+ RequestCorrections,+ RequestRecovery,+)from free_claude_code.providers.stream_recovery import (RecoveryController,RecoveryFailureAction,@@ -253,8 +257,11 @@ class AnthropicMessagesTransport:reasoning_correction: ReasoningCorrection | None = None,) -> AsyncIterator[str]:recovery = RecoveryController()- refreshed = False- force_refresh = False+ request_endpoint = RequestEndpoint(endpoint_context)+ request_recovery = RequestRecovery(+ execution, endpoint=request_endpoint, stream=recovery+ )+ corrections = RequestCorrections("messages", reasoning_correction)while execution.can_attempt:scope: ProviderAttemptScope | None = Nonestream_opened = False@@ -266,8 +273,7 @@ class AnthropicMessagesTransport:provider_name=self._provider_name,request_id=execution.request_id,)- endpoint = await endpoint_context.endpoint(force_refresh=force_refresh)- force_refresh = False+ endpoint = await request_endpoint.resolve()origin = replay_origin(self._replay_scope,"messages",@@ -345,56 +351,26 @@ class AnthropicMessagesTransport:if isinstance(error, ExecutionFailure)else None)- if (- scope is not None- and status in {401, 403}- and not refreshed- and not recovery.committed- ):- retry = (- execution.can_attempt- if scope.attempt.accepted- else await scope.attempt.correct(error)- is ProviderCorrectionAction.RETRY- )- if retry:- refreshed = force_refresh = True- 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 scope is not None:+ corrected_body = await request_recovery.retry_request(+ error,+ status,+ scope.attempt,+ body,+ operation_kind=ProviderOperationKind.GENERATION,+ propose_correction=partial(+ corrections.next_body,+ raw_error,+ body,+ sent_body=sent_body,+ reasoning_error=error,+ ),)- 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()- continue- if (- scope is not None- and reasoning_correction is not None- and not recovery.committed- ):- corrected_body = reasoning_correction.retry_body(error, body)if corrected_body is not None:- retry = (- execution.can_attempt- if scope.attempt.accepted- else await scope.attempt.correct(error)- is ProviderCorrectionAction.RETRY- )- reasoning_correction = None- if retry:- body = corrected_body- recovery.discard()- continue+ body = corrected_body+ recovery.discard()+ continueif scope is not None and not scope.attempt.accepted:attempt_failure = await scope.attempt.fail(error)if attempt_failure is not None and attempt_failure.retry_allowed:diff --git a/src/free_claude_code/providers/endpoint.py b/src/free_claude_code/providers/endpoint.pyindex 819f4e50..eed4f4a7 100644--- a/src/free_claude_code/providers/endpoint.py+++ b/src/free_claude_code/providers/endpoint.py@@ -1,112 +1,21 @@-"""Request-scoped endpoint snapshots borrowed by provider transports."""+"""Request-scoped endpoint resolution borrowed from provider account owners."""-import httpx-import httpx2-from openai import AsyncOpenAI, Omit--from free_claude_code.providers.admission import (- ProviderAttempt,- ProviderCorrectionAction,- ProviderExecution,-)from free_claude_code.providers.endpoint_types import EndpointContext, HttpEndpoint-from free_claude_code.providers.failure_policy import provider_authentication_status---class _BorrowedTransport(httpx2.AsyncBaseTransport):- """Share connections while the provider generation retains pool ownership."""-- def __init__(self, transport: httpx2.AsyncBaseTransport) -> None:- self._transport = transport-- async def handle_async_request(self, request: httpx2.Request) -> httpx2.Response:- return await self._transport.handle_async_request(request)class RequestEndpoint:- """Resolve one request's credentials and permit one refresh before commitment."""+ """Resolve each attempt's snapshot, retaining a pending forced refresh."""- def __init__(- self,- context: EndpointContext,- transport: httpx2.AsyncBaseTransport | None = None,- ) -> None:+ def __init__(self, context: EndpointContext) -> None:self._context = context- self._transport = transport- self._http: httpx2.AsyncClient | None = None- self._refreshed = Falseself._refresh_pending = False- self._committed = False- self._omit_authorization = Falseself.snapshot: HttpEndpoint | None = None- def commit(self) -> None:- self._committed = True+ def request_refresh(self) -> None:+ self._refresh_pending = True- async def aclose(self) -> None:- if self._http is not None:- await self._http.aclose()-- async def openai_client(self, client: AsyncOpenAI) -> AsyncOpenAI:+ async def resolve(self) -> HttpEndpoint:endpoint = await self._context.endpoint(force_refresh=self._refresh_pending)self.snapshot = endpointself._refresh_pending = False- if self._http is None:- self._http = httpx2.AsyncClient(- transport=_BorrowedTransport(self._transport)- if self._transport is not None- else None,- follow_redirects=False,- )- # An endpoint is authoritative for every attempt, including after refresh.- self._http.cookies.clear()- headers = dict(httpx.Headers(endpoint.headers).items())- self._omit_authorization = (- endpoint.api_key is None and "authorization" not in headers- )- # SDK defaults are merged as a case-sensitive mapping before HTTP parsing.- # Match their spelling so an endpoint replaces, rather than duplicates, them.- sdk_header_names = {"authorization": "Authorization"}- for name in client.default_headers:- sdk_header_names.setdefault(name.lower(), name)- headers = {- sdk_header_names.get(name, name): value for name, value in headers.items()- }-- async def credential() -> str:- # A callable also overrides an inherited key with an empty credential.- return endpoint.api_key or ""-- view = client.with_options(- api_key=credential,- base_url=endpoint.base_url,- set_default_headers=headers,- set_default_query={},- http_client=self._http,- max_retries=0,- )- # SDK copy(None) inherits these values. Clear only this owned view.- view.organization = None- view.project = None- view.admin_api_key = None- return view-- def openai_headers(self) -> dict[str, str | Omit]:- return {"Authorization": Omit()} if self._omit_authorization else {}-- async def retry_authentication(- self, error: Exception, attempt: ProviderAttempt, execution: ProviderExecution- ) -> bool:- if self._refreshed or self._committed:- return False- status = provider_authentication_status(error)- if status not in {401, 403}:- return False- allowed = (- execution.can_attempt- if attempt.accepted- else await attempt.correct(error) is ProviderCorrectionAction.RETRY- )- if allowed:- self._refreshed = self._refresh_pending = True- return allowed+ return endpointdiff --git a/src/free_claude_code/providers/history_replay.py b/src/free_claude_code/providers/history_replay.pyindex e9c7be83..b462a36f 100644--- a/src/free_claude_code/providers/history_replay.py+++ b/src/free_claude_code/providers/history_replay.py@@ -5,11 +5,9 @@ import jsonimport refrom collections.abc import Iterator, Mappingfrom copy import deepcopy-from typing import Any+from typing import TYPE_CHECKING, Anyfrom urllib.parse import urlsplit, urlunsplit-from openai import AsyncOpenAI-from free_claude_code.application.errors import InvalidRequestErrorfrom free_claude_code.core.diagnostics import extract_upstream_error_detailfrom free_claude_code.core.history_replay import (@@ -22,7 +20,10 @@ from free_claude_code.core.history_replay import (reasoning_context,)-from .endpoint import HttpEndpoint+from .endpoint_types import HttpEndpoint++if TYPE_CHECKING:+ from openai import AsyncOpenAIdef validate_history(body: Mapping[str, Any]) -> None:diff --git a/src/free_claude_code/providers/openai_chat/transport.py b/src/free_claude_code/providers/openai_chat/transport.pyindex aebc6e10..c164f24a 100644--- a/src/free_claude_code/providers/openai_chat/transport.py+++ b/src/free_claude_code/providers/openai_chat/transport.py@@ -6,6 +6,7 @@ import uuidfrom collections.abc import AsyncIterator, Awaitable, Callable, Iterator, Mappingfrom dataclasses import dataclass, replacefrom enum import StrEnum+from functools import partialfrom typing import Any, castimport httpx2@@ -59,8 +60,6 @@ from free_claude_code.core.trace import provider_chat_body_snapshot, trace_eventfrom free_claude_code.providers.admission import (ProviderAdmissionController,ProviderAttempt,- ProviderCorrectionAction,- ProviderExecution,ProviderOperationKind,)from free_claude_code.providers.endpoint import RequestEndpoint@@ -71,10 +70,10 @@ from free_claude_code.providers.failure_policy import (context_window_exceeded_provider_failure,is_context_window_finish_reason,is_retryable_stream_error,+ provider_authentication_status,underlying_provider_error,)from free_claude_code.providers.history_replay import (- history_retry_body,replay_origin,validate_history,)@@ -83,11 +82,16 @@ from free_claude_code.providers.http import (close_provider_stream,maybe_await_aclose,)+from free_claude_code.providers.openai_client import OpenAIRequestClientfrom free_claude_code.providers.openai_stream import OpenAIStreamAdapterfrom free_claude_code.providers.reasoning_compatibility import (ReasoningCorrection,prepare_messages_reasoning,)+from free_claude_code.providers.request_recovery import (+ RequestCorrections,+ RequestRecovery,+)from free_claude_code.providers.stream_recovery import (RecoveryController,RecoveryFailureAction,@@ -644,18 +648,19 @@ class OpenAIChatTransport:async def _create_stream(self,body: dict,- execution: ProviderExecution,+ request_recovery: RequestRecovery,operation_kind: ProviderOperationKind,*,- used_retry_kinds: set[str] | None = None,+ corrections: RequestCorrections | None = None,endpoint: RequestEndpoint | None = None,+ request_client: OpenAIRequestClient | None = None,extra_headers: Mapping[str, str] | None = None,- reasoning_correction: ReasoningCorrection | None = None,) -> tuple[Any, dict, ProviderAttempt, dict]:"""Create a streaming chat completion with bounded request fallbacks."""+ execution = request_recovery.executionbody = self._apply_learned_output_cap(body)- if used_retry_kinds is None:- used_retry_kinds = set()+ if corrections is None:+ corrections = RequestCorrections("chat")while execution.can_attempt:attempt = await execution.open_attempt(operation_kind)@@ -664,17 +669,22 @@ class OpenAIChatTransport:create_body = bodytry:create_body = self._behavior.prepare_create_body(body)- client = (- await endpoint.openai_client(self._client)- if endpoint is not None- else self._client- )+ client = self._client+ if endpoint is not None:+ assert request_client is not None+ client = request_client.for_endpoint(+ self._client, await endpoint.resolve()+ )if extra_headers or endpoint is not None:create_body = create_body.copy()create_body["extra_headers"] = {**(create_body.get("extra_headers") or {}),**(extra_headers or {}),- **(endpoint.openai_headers() if endpoint is not None else {}),+ **(+ request_client.openai_headers()+ if request_client is not None+ else {}+ ),}origin = replay_origin(self._provider_name,@@ -705,23 +715,30 @@ class OpenAIChatTransport:except asyncio.CancelledError:raiseexcept Exception as error:- if endpoint is not None and await endpoint.retry_authentication(- error, attempt, execution- ):- continue- retry_body = self._next_create_retry_body(+ retry_body = await request_recovery.retry_request(error,+ provider_authentication_status(error),+ attempt,body,- used_retry_kinds,- reasoning_correction=reasoning_correction,- sent_body=create_body,+ operation_kind=operation_kind,+ propose_correction=partial(+ corrections.next_body,+ error,+ body,+ sent_body=create_body,+ reasoning_error=error,+ reasoning_sent_body=create_body,+ after_common=partial(+ self._next_chat_retry_body,+ error,+ body,+ sent_body=create_body,+ ),+ ),)if retry_body is not None:- correction = await attempt.correct(error)- if correction is ProviderCorrectionAction.RETRY:- body = self._apply_learned_output_cap(retry_body)- continue- raise+ body = self._apply_learned_output_cap(retry_body)+ continuedecision = await attempt.fail(error,provider_failure_override=self._behavior.failure_override,@@ -745,27 +762,14 @@ class OpenAIChatTransport:raise execution.last_failureraise RuntimeError("provider execution ended without a final error")- def _next_create_retry_body(+ def _next_chat_retry_body(self,error: Exception,body: dict,used_retry_kinds: set[str],*,- 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_history- if reasoning_correction is not None and "reasoning" not in used_retry_kinds:- retry_body = reasoning_correction.retry_body(- error, body, sent_body=sent_body- )- if retry_body is not None:- used_retry_kinds.add("reasoning")- return retry_bodyretry_body = self._retry_body_for_output_cap(error, body)if retry_body is not None:return retry_body@@ -953,10 +957,9 @@ class _OpenAIChatStreamRunner:self._reasoning_correction = reasoning_correctionself._extra_headers = dict(extra_headers or {})self._terminal_failure: ExecutionFailure | None = None+ self._request_client = OpenAIRequestClient(transport._endpoint_transport)self._endpoint = (- RequestEndpoint(endpoint_context, transport._endpoint_transport)- if endpoint_context is not None- else None+ RequestEndpoint(endpoint_context) if endpoint_context is not None else None)async def run(self) -> AsyncIterator[str]:@@ -964,11 +967,13 @@ class _OpenAIChatStreamRunner:execution = self._transport._admission.start_execution(request_id=self._request_id)- provider_stream = self._run_execution(execution)+ recovery = RecoveryController()+ request_recovery = RequestRecovery(+ execution, endpoint=self._endpoint, stream=recovery+ )+ provider_stream = self._run_execution(request_recovery, recovery)try:async for event in provider_stream:- if self._endpoint is not None:- self._endpoint.commit()yield eventexcept asyncio.CancelledError:raise@@ -985,19 +990,19 @@ class _OpenAIChatStreamRunner:await maybe_await_aclose(provider_stream)finally:try:- if self._endpoint is not None:- await self._endpoint.aclose()+ await self._request_client.aclose()finally:execution.abandon()async def _run_execution(self,- execution: ProviderExecution,+ request_recovery: RequestRecovery,+ recovery: RecoveryController,) -> AsyncIterator[str]:"""Run one provider execution while retaining transport-owned state."""tag = self._transport._provider_namereq_tag = f" request_id={self._request_id}" if self._request_id else ""- recovery = RecoveryController()+ execution = request_recovery.executiondef hold_event(event: str) -> Iterator[str]:yield from recovery.push(event)@@ -1005,7 +1010,7 @@ class _OpenAIChatStreamRunner:body = self._bodyrequest_stream_usage(body)output_reasoning = self._reasoning.output_enabled- used_retry_kinds: set[str] = set()+ corrections = RequestCorrections("chat", self._reasoning_correction)trace_event(stage="provider",event="provider.request.sent",@@ -1026,12 +1031,12 @@ class _OpenAIChatStreamRunner:try:stream, body, attempt, sent_body = await self._transport._create_stream(body,- execution,+ request_recovery,ProviderOperationKind.GENERATION,- used_retry_kinds=used_retry_kinds,+ corrections=corrections,endpoint=self._endpoint,+ request_client=self._request_client,extra_headers=self._extra_headers,- reasoning_correction=self._reasoning_correction,)scope = ProviderAttemptScope(attempt,@@ -1067,48 +1072,32 @@ 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()- continue- if (- scope is not None- and not recovery.committed- and self._reasoning_correction is not None- and "reasoning" not in used_retry_kinds- ):- corrected_body = self._reasoning_correction.retry_body(- error, body, sent_body=sent_body+ if scope is not None:+ corrected_body = await request_recovery.retry_request(+ error,+ provider_authentication_status(error),+ scope.attempt,+ body,+ operation_kind=ProviderOperationKind.GENERATION,+ propose_correction=partial(+ corrections.next_body,+ error,+ body,+ sent_body=sent_body,+ reasoning_error=error,+ reasoning_sent_body=sent_body,+ ),)if corrected_body is not None:- used_retry_kinds.add("reasoning")- retry = (- execution.can_attempt- if scope.attempt.accepted- else await scope.attempt.correct(error)- is ProviderCorrectionAction.RETRY- )- if retry:- body = self._transport._apply_learned_output_cap(- corrected_body- )- recovery.discard()- continue+ body = corrected_body+ recovery.discard()+ continueresolution = await self._resolve_attempt_failure(error=error,scope=scope,assembler=assembler,body=body,- execution=execution,+ request_recovery=request_recovery,recovery=recovery,req_tag=req_tag,)@@ -1189,20 +1178,12 @@ class _OpenAIChatStreamRunner:scope: ProviderAttemptScope | None,assembler: _OpenAIChatStreamAssembler,body: dict[str, Any],- execution: ProviderExecution,+ request_recovery: RequestRecovery,recovery: RecoveryController,req_tag: str,) -> _OpenAIChatFailureResolution:"""Resolve one failed generation attempt without owning retry policy."""- if (- scope is not None- and self._endpoint is not None- and await self._endpoint.retry_authentication(- error, scope.attempt, execution- )- ):- recovery.discard()- return _OpenAIChatFailureResolution(outcome=_OpenAIChatFailureOutcome.RETRY)+ execution = request_recovery.executionattempt_failure = Noneif scope is not None and not scope.attempt.accepted:attempt_failure = await scope.attempt.fail(@@ -1248,7 +1229,7 @@ class _OpenAIChatStreamRunner:error=error,tool_argument_alias_buffers=(assembler.tool_argument_alias_buffers),output_reasoning=self._reasoning.output_enabled,- execution=execution,+ request_recovery=request_recovery,)except Exception as recovery_error:trace_event(@@ -1342,13 +1323,14 @@ class _OpenAIChatStreamRunner:body: dict[str, Any],*,include_reasoning: bool,- execution: ProviderExecution,+ request_recovery: RequestRecovery,operation_kind: ProviderOperationKind,- used_retry_kinds: set[str] | None = None,+ corrections: RequestCorrections | None = None,) -> _CollectedRecoveryOutput:"""Collect one complete buffered continuation response."""- if used_retry_kinds is None:- used_retry_kinds = set()+ execution = request_recovery.execution+ if corrections is None:+ corrections = RequestCorrections("chat")last_error: Exception | None = Nonewhile execution.can_attempt:scope: ProviderAttemptScope | None = None@@ -1360,10 +1342,11 @@ class _OpenAIChatStreamRunner:_sent_body,) = await self._transport._create_stream(body,- execution,+ request_recovery,operation_kind,- used_retry_kinds=used_retry_kinds,+ corrections=corrections,endpoint=self._endpoint,+ request_client=self._request_client,)scope = ProviderAttemptScope(attempt,@@ -1463,7 +1446,7 @@ class _OpenAIChatStreamRunner:error: Exception,tool_argument_alias_buffers: Mapping[int, str],output_reasoning: bool,- execution: ProviderExecution,+ request_recovery: RequestRecovery,) -> list[str] | None:"""Build terminal recovery events when the interrupted stream permits it."""output = assembler.output@@ -1473,7 +1456,7 @@ class _OpenAIChatStreamRunner:body=body,output=output,tool_argument_alias_buffers=tool_argument_alias_buffers,- execution=execution,+ request_recovery=request_recovery,)if repair_events is None:return None@@ -1518,7 +1501,7 @@ class _OpenAIChatStreamRunner:recovered = await self._collect_recovery_output(recovery_body,include_reasoning=output_reasoning,- execution=execution,+ request_recovery=request_recovery,operation_kind=ProviderOperationKind.CONTINUATION,)text_suffix = continuation_suffix(partial_text, recovered.text)@@ -1560,8 +1543,9 @@ class _OpenAIChatStreamRunner:body: dict[str, Any],output: ChatStreamOutput,tool_argument_alias_buffers: Mapping[int, str],- execution: ProviderExecution,+ request_recovery: RequestRecovery,) -> list[str] | None:+ execution = request_recovery.executionschemas = self._tool_schemasevents: list[str] = []for tool_index, state in output.started_tool_states():@@ -1589,15 +1573,15 @@ class _OpenAIChatStreamRunner:)accepted_suffix: str | None = Nonerepair_attempt = 0- used_retry_kinds: set[str] = set()+ corrections = RequestCorrections("chat")while execution.can_attempt:repair_attempt += 1recovered = await self._collect_recovery_output(recovery_body,include_reasoning=False,- execution=execution,+ request_recovery=request_recovery,operation_kind=ProviderOperationKind.TOOL_REPAIR,- used_retry_kinds=used_retry_kinds,+ corrections=corrections,)repair = accept_tool_json_repair(repair_prefix,diff --git a/src/free_claude_code/providers/openai_client.py b/src/free_claude_code/providers/openai_client.pynew file mode 100644index 00000000..df4dd110--- /dev/null+++ b/src/free_claude_code/providers/openai_client.py@@ -0,0 +1,74 @@+"""Bind resolved endpoints to isolated OpenAI SDK request clients."""++import httpx+import httpx2+from openai import AsyncOpenAI, Omit++from free_claude_code.providers.endpoint_types import HttpEndpoint+++class _BorrowedTransport(httpx2.AsyncBaseTransport):+ """Share connections while the provider generation retains pool ownership."""++ def __init__(self, transport: httpx2.AsyncBaseTransport) -> None:+ self._transport = transport++ async def handle_async_request(self, request: httpx2.Request) -> httpx2.Response:+ return await self._transport.handle_async_request(request)+++class OpenAIRequestClient:+ """Own the request HTTP client while borrowing the base SDK client and pool."""++ def __init__(self, transport: httpx2.AsyncBaseTransport | None = None) -> None:+ self._transport = transport+ self._http: httpx2.AsyncClient | None = None+ self._omit_authorization = False++ async def aclose(self) -> None:+ if self._http is not None:+ await self._http.aclose()++ def for_endpoint(self, client: AsyncOpenAI, endpoint: HttpEndpoint) -> AsyncOpenAI:+ if self._http is None:+ self._http = httpx2.AsyncClient(+ transport=_BorrowedTransport(self._transport)+ if self._transport is not None+ else None,+ follow_redirects=False,+ )+ # An endpoint is authoritative for every attempt, including after refresh.+ self._http.cookies.clear()+ headers = dict(httpx.Headers(endpoint.headers).items())+ self._omit_authorization = (+ endpoint.api_key is None and "authorization" not in headers+ )+ # SDK defaults are merged as a case-sensitive mapping before HTTP parsing.+ # Match their spelling so an endpoint replaces, rather than duplicates, them.+ sdk_header_names = {"authorization": "Authorization"}+ for name in client.default_headers:+ sdk_header_names.setdefault(name.lower(), name)+ headers = {+ sdk_header_names.get(name, name): value for name, value in headers.items()+ }++ async def credential() -> str:+ # A callable also overrides an inherited key with an empty credential.+ return endpoint.api_key or ""++ view = client.with_options(+ api_key=credential,+ base_url=endpoint.base_url,+ set_default_headers=headers,+ set_default_query={},+ http_client=self._http,+ max_retries=0,+ )+ # SDK copy(None) inherits these values. Clear only this owned view.+ view.organization = None+ view.project = None+ view.admin_api_key = None+ return view++ def openai_headers(self) -> dict[str, str | Omit]:+ return {"Authorization": Omit()} if self._omit_authorization else {}diff --git a/src/free_claude_code/providers/openai_codex/provider.py b/src/free_claude_code/providers/openai_codex/provider.pyindex a7549f18..8c20bb02 100644--- a/src/free_claude_code/providers/openai_codex/provider.py+++ b/src/free_claude_code/providers/openai_codex/provider.py@@ -20,13 +20,16 @@ from free_claude_code.providers.admission import ()from free_claude_code.providers.base import BaseProvider, ProviderConfigfrom free_claude_code.providers.endpoint import RequestEndpoint+from free_claude_code.providers.failure_policy import provider_authentication_statusfrom free_claude_code.providers.http import ProviderAttemptScopefrom free_claude_code.providers.model_listing import (optional_input_modalities,optional_positive_int,reasoning_capability_from_options,)+from free_claude_code.providers.openai_client import OpenAIRequestClientfrom free_claude_code.providers.openai_responses import OpenAIResponsesTransport+from free_claude_code.providers.request_recovery import RequestRecoveryfrom .auth import OpenAIAuthManagerfrom .endpoint import CodexEndpointContext@@ -102,12 +105,16 @@ class OpenAICodexProvider(BaseProvider):async def _list_models_payload(self) -> Any:"""Admit each catalog GET while borrowing request-scoped SDK credentials."""execution = self._admission.start_execution()- endpoint = RequestEndpoint(self._endpoint(), self._pool)+ endpoint = RequestEndpoint(self._endpoint())+ request_client = OpenAIRequestClient(self._pool)+ recovery = RequestRecovery(execution, endpoint=endpoint)try:while execution.can_attempt:scope: ProviderAttemptScope | None = Nonetry:- client = await endpoint.openai_client(self._client)+ client = request_client.for_endpoint(+ self._client, await endpoint.resolve()+ )attempt = await execution.open_attempt(ProviderOperationKind.MODEL_DISCOVERY)@@ -128,8 +135,8 @@ class OpenAICodexProvider(BaseProvider):raiseexcept Exception as error:if scope is not None:- if await endpoint.retry_authentication(- error, scope.attempt, execution+ if await recovery.retry_authentication(+ error, provider_authentication_status(error), scope.attempt):continueif not scope.attempt.accepted:@@ -146,7 +153,7 @@ class OpenAICodexProvider(BaseProvider):raise RuntimeError("OpenAI model discovery ended without an outcome.")finally:try:- await endpoint.aclose()+ await request_client.aclose()finally:execution.abandon()diff --git a/src/free_claude_code/providers/openai_responses/transport.py b/src/free_claude_code/providers/openai_responses/transport.pyindex 88fc9da9..341c3b38 100644--- a/src/free_claude_code/providers/openai_responses/transport.py+++ b/src/free_claude_code/providers/openai_responses/transport.py@@ -5,6 +5,7 @@ import sysimport uuidfrom collections.abc import AsyncIterator, Callable, Mappingfrom dataclasses import replace+from functools import partialfrom typing import castimport httpx2@@ -38,7 +39,6 @@ from free_claude_code.core.reasoning import ReasoningControl, ReasoningPolicyfrom free_claude_code.core.trace import trace_eventfrom free_claude_code.providers.admission import (ProviderAdmissionController,- ProviderCorrectionAction,ProviderExecution,ProviderOperationKind,)@@ -54,16 +54,20 @@ from free_claude_code.providers.failure_policy import (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_aclose+from free_claude_code.providers.openai_client import OpenAIRequestClientfrom free_claude_code.providers.openai_stream import OpenAIStreamAdapterfrom free_claude_code.providers.reasoning_compatibility import (ReasoningCorrection,prepare_messages_reasoning,)+from free_claude_code.providers.request_recovery import (+ RequestCorrections,+ RequestRecovery,+)from free_claude_code.providers.stream_recovery import (RecoveryController,RecoveryFailureAction,@@ -252,10 +256,9 @@ class OpenAIResponsesTransport:execution = self._admission.start_execution(request_id=request_id)outcome = ResponsesExecutionOutcome()endpoint = (- RequestEndpoint(endpoint_context, self._endpoint_transport)- if endpoint_context is not None- else None+ RequestEndpoint(endpoint_context) if endpoint_context is not None else None)+ request_client = OpenAIRequestClient(self._endpoint_transport)provider_stream = self._run_execution(body,reasoning_correction=reasoning_correction,@@ -265,12 +268,11 @@ class OpenAIResponsesTransport:execution=execution,outcome=outcome,endpoint=endpoint,+ request_client=request_client,extra_headers=extra_headers,)try:async for event in provider_stream:- if endpoint is not None:- endpoint.commit()yield eventexcept asyncio.CancelledError:raise@@ -287,8 +289,7 @@ class OpenAIResponsesTransport:await maybe_await_aclose(provider_stream)finally:try:- if endpoint is not None:- await endpoint.aclose()+ await request_client.aclose()finally:execution.abandon()@@ -302,10 +303,15 @@ class OpenAIResponsesTransport:execution: ProviderExecution,outcome: ResponsesExecutionOutcome,endpoint: RequestEndpoint | None = None,+ request_client: OpenAIRequestClient,extra_headers: Mapping[str, str] | None = None,reasoning_correction: ReasoningCorrection | None = None,) -> AsyncIterator[str]:recovery = RecoveryController()+ request_recovery = RequestRecovery(+ execution, endpoint=endpoint, stream=recovery+ )+ corrections = RequestCorrections("responses", reasoning_correction)trace_event(stage="provider",event="provider.request.sent",@@ -332,7 +338,7 @@ class OpenAIResponsesTransport:stream_opened = Falsetry:client = (- await endpoint.openai_client(self._client)+ request_client.for_endpoint(self._client, await endpoint.resolve())if endpoint is not Noneelse self._client)@@ -353,7 +359,7 @@ class OpenAIResponsesTransport:sdk_stream = await self._create_sdk_stream(sent_body,client=client,- endpoint=endpoint,+ request_client=request_client,extra_headers=extra_headers,)stream = scope.retain(OpenAIStreamAdapter(sdk_stream))@@ -430,48 +436,25 @@ class OpenAIResponsesTransport:raiseexcept Exception as raw_error:error = _effective_error(raw_error)- if (- scope is not None- and endpoint is not None- and await endpoint.retry_authentication(- error, scope.attempt, execution- )- ):- recovery.discard()- continue- if scope is not None and not recovery.committed:- corrected_history = history_retry_body(- raw_error, sent_body, "responses"+ if scope is not None:+ corrected_body = await request_recovery.retry_request(+ error,+ provider_authentication_status(error),+ scope.attempt,+ body,+ operation_kind=ProviderOperationKind.GENERATION,+ propose_correction=partial(+ corrections.next_body,+ raw_error,+ body,+ sent_body=sent_body,+ reasoning_error=raw_error,+ ),)- 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()- continue- if (- scope is not None- and reasoning_correction is not None- and not recovery.committed- ):- corrected_body = reasoning_correction.retry_body(raw_error, body)if corrected_body is not None:- retry = (- execution.can_attempt- if scope.attempt.accepted- else await scope.attempt.correct(error)- is ProviderCorrectionAction.RETRY- )- reasoning_correction = None- if retry:- body = corrected_body- recovery.discard()- continue+ body = corrected_body+ recovery.discard()+ continueattempt_failure = Noneif scope is not None and not scope.attempt.accepted:attempt_failure = await scope.attempt.fail(error)@@ -545,7 +528,7 @@ class OpenAIResponsesTransport:body: JsonObject,*,client: AsyncOpenAI,- endpoint: RequestEndpoint | None = None,+ request_client: OpenAIRequestClient,extra_headers: Mapping[str, str] | None = None,) -> AsyncStream[ResponseStreamEvent]:model = body.get("model")@@ -565,7 +548,7 @@ class OpenAIResponsesTransport:extra_body=extra_body or None,extra_headers={**(extra_headers or {}),- **(endpoint.openai_headers() if endpoint is not None else {}),+ **request_client.openai_headers(),}or None,)diff --git a/src/free_claude_code/providers/request_recovery.py b/src/free_claude_code/providers/request_recovery.pynew file mode 100644index 00000000..56a0b1d3--- /dev/null+++ b/src/free_claude_code/providers/request_recovery.py@@ -0,0 +1,122 @@+"""Shared request correction and authentication recovery decisions."""++from collections.abc import Callable, Mapping+from typing import Any++from free_claude_code.core.history_replay import HistoryProtocol+from free_claude_code.core.json_types import JsonObject+from free_claude_code.providers.admission import (+ ProviderAttempt,+ ProviderCorrectionAction,+ ProviderExecution,+ ProviderOperationKind,+)+from free_claude_code.providers.endpoint import RequestEndpoint+from free_claude_code.providers.history_replay import history_retry_body+from free_claude_code.providers.reasoning_compatibility import ReasoningCorrection+from free_claude_code.providers.stream_recovery import RecoveryController+++class RequestRecovery:+ """Authorize shared corrections within one execution and public stream."""++ def __init__(+ self,+ execution: ProviderExecution,+ *,+ endpoint: RequestEndpoint | None = None,+ stream: RecoveryController | None = None,+ ) -> None:+ self._execution = execution+ self._endpoint = endpoint+ self._stream = stream+ self._refreshed = False++ @property+ def execution(self) -> ProviderExecution:+ return self._execution++ @property+ def _committed(self) -> bool:+ return self._stream is not None and self._stream.committed++ async def _authorize(self, error: Exception, attempt: ProviderAttempt) -> bool:+ return (+ self.execution.can_attempt+ if attempt.accepted+ else await attempt.correct(error) is ProviderCorrectionAction.RETRY+ )++ async def retry_authentication(+ self, error: Exception, auth_status: int | None, attempt: ProviderAttempt+ ) -> bool:+ if (+ self._endpoint is None+ or auth_status not in {401, 403}+ or self._refreshed+ or self._committed+ ):+ return False+ if not await self._authorize(error, attempt):+ return False+ self._refreshed = True+ self._endpoint.request_refresh()+ return True++ async def retry_request(+ self,+ error: Exception,+ auth_status: int | None,+ attempt: ProviderAttempt,+ body: JsonObject,+ *,+ operation_kind: ProviderOperationKind,+ propose_correction: Callable[[], JsonObject | None],+ ) -> JsonObject | None:+ if await self.retry_authentication(error, auth_status, attempt):+ return body+ if operation_kind is ProviderOperationKind.GENERATION and self._committed:+ return None+ # A separately buffered continuation/repair body can still be corrected+ # at creation, while authentication follows the original public stream.+ corrected = propose_correction()+ if corrected is not None and await self._authorize(error, attempt):+ return corrected+ return None+++class RequestCorrections:+ """Retain common and transport correction history for one request body."""++ def __init__(+ self,+ protocol: HistoryProtocol,+ reasoning: ReasoningCorrection | None = None,+ ) -> None:+ self._protocol = protocol+ self._reasoning = reasoning+ self._used_retry_kinds: set[str] = set()++ def next_body(+ self,+ history_error: Exception,+ body: JsonObject,+ *,+ sent_body: Mapping[str, Any],+ reasoning_error: Exception,+ reasoning_sent_body: Mapping[str, Any] | None = None,+ after_common: Callable[[set[str]], JsonObject | None] | None = None,+ ) -> JsonObject | None:+ corrected = history_retry_body(history_error, sent_body, self._protocol)+ if corrected is not None:+ return corrected+ if self._reasoning is not None and "reasoning" not in self._used_retry_kinds:+ corrected = self._reasoning.retry_body(+ reasoning_error, body, sent_body=reasoning_sent_body+ )+ if corrected is not None:+ self._used_retry_kinds.add("reasoning")+ return corrected+ return (+ after_common(self._used_retry_kinds) if after_common is not None else None+ )diff --git a/tests/contracts/test_import_boundaries.py b/tests/contracts/test_import_boundaries.pyindex f0f65d77..ac48c164 100644--- a/tests/contracts/test_import_boundaries.py+++ b/tests/contracts/test_import_boundaries.py@@ -141,6 +141,34 @@ def test_api_configuration_access_goes_through_runtime() -> None:)+def test_request_recovery_policy_has_no_client_or_transport_binding() -> None:+ owners = {+ f"{_PACKAGE_NAME}.providers.request_recovery",+ f"{_PACKAGE_NAME}.providers.endpoint",+ }+ forbidden = (+ "openai",+ "httpx",+ "httpx2",+ f"{_PACKAGE_NAME}.providers.openai_client",+ f"{_PACKAGE_NAME}.providers.openai_chat",+ f"{_PACKAGE_NAME}.providers.openai_responses",+ f"{_PACKAGE_NAME}.providers.anthropic_messages",+ )+ offenders = [+ record.describe()+ for record in _scan_imports(_PACKAGE_ROOT)+ if record.importer in owners+ and any(+ record.imported == prefix or record.imported.startswith(f"{prefix}.")+ for prefix in forbidden+ )+ ]+ assert not offenders, (+ "Request recovery policy depends on an adapter:\n" + "\n".join(offenders)+ )++def test_shared_harness_setup_has_no_terminal_owner() -> None:former_paths = {"cli/environment.py",diff --git a/tests/providers/test_endpoint_context_transports.py b/tests/providers/test_endpoint_context_transports.pyindex aa45352b..7918dd17 100644--- a/tests/providers/test_endpoint_context_transports.py+++ b/tests/providers/test_endpoint_context_transports.py@@ -3,6 +3,7 @@import asyncioimport jsonfrom collections.abc import AsyncIterator+from copy import deepcopyimport httpximport httpx2@@ -13,10 +14,11 @@ from free_claude_code.core.anthropic import ReasoningReplayModefrom free_claude_code.core.anthropic.models import MessagesRequestfrom free_claude_code.core.failures import ExecutionFailurefrom free_claude_code.core.openai_responses import OpenAIResponsesRequest-from free_claude_code.core.reasoning import DEFAULT_REASONING_POLICY+from free_claude_code.core.reasoning import DEFAULT_REASONING_POLICY, ReasoningPolicyfrom free_claude_code.providers.endpoint_types import HttpEndpointfrom free_claude_code.providers.openai_chat import (NO_REASONING,+ NamedEffortReasoning,OpenAIChatProfile,OpenAIChatProvider,OpenAIChatRequestPolicy,@@ -351,3 +353,78 @@ async def test_stream_authentication_refreshes_before_commit())assert calls == 2 and context.calls == [False, True]++[email protected]("correction", ["history", "reasoning"])+async def test_stream_authentication_precedes_overlapping_request_correction(+ correction: str,+) -> None:+ bodies = []++ def handler(request: httpx2.Request) -> httpx2.Response:+ bodies.append(json.loads(request.content))+ if len(bodies) > 1:+ return _response(request)+ failure = {+ "type": "authentication_error"+ if correction == "history"+ else "invalid_request_error",+ "code": "invalid_api_key",+ "message": "invalid signature in thinking block"+ if correction == "history"+ else "reasoning_effort is unsupported",+ }+ return httpx2.Response(+ 200,+ headers={"content-type": "text/event-stream"},+ text=f"data: {json.dumps({'error': failure})}\n\n",+ )++ request = MessagesRequest.model_validate(+ {+ "model": "upstream",+ "messages": [+ {+ "role": "assistant",+ "content": [+ {"type": "redacted_thinking", "data": "opaque-original"},+ {"type": "text", "text": "17"},+ ],+ },+ {"role": "user", "content": "continue"},+ ],+ }+ )+ original = deepcopy(request.model_dump())+ pool = httpx2.MockTransport(handler)+ async with AsyncOpenAI(+ api_key="base", http_client=httpx2.AsyncClient(transport=pool), max_retries=0+ ) as client:+ provider = OpenAIChatProvider(+ make_provider_config(None, "https://original.invalid"),+ profile=OpenAIChatProfile(+ OpenAIChatRequestPolicy("TEST", ReasoningReplayMode.REASONING_CONTENT),+ NamedEffortReasoning((), disabled_value="none"),+ structured_reasoning_details=True,+ ),+ admission=immediate_admission(max_attempts=3),+ client=client,+ endpoint_transport=pool,+ )+ context = Context("a")+ try:+ await _consume(+ provider.stream_messages(+ request,+ endpoint_context=context,+ reasoning=ReasoningPolicy.prefer_off(),+ )+ )+ finally:+ await provider.cleanup()+ assert context.calls == [False, True]+ assert len(bodies) == 2 and bodies[1] == bodies[0]+ assert "opaque-original" in json.dumps(bodies[0])+ assert bodies[0]["reasoning_effort"] == "none"+ assert request.model_dump() == originaldiff --git a/tests/providers/test_groq_reasoning.py b/tests/providers/test_groq_reasoning.pyindex 0286562a..88909a6c 100644--- a/tests/providers/test_groq_reasoning.py+++ b/tests/providers/test_groq_reasoning.py@@ -26,6 +26,7 @@ from free_claude_code.providers.groq.client import (_parse_reasoning_vocabulary,_rewrite_reasoning_effort,)+from free_claude_code.providers.request_recovery import RequestRecoveryfrom tests.providers.request_factory import make_messages_requestfrom tests.providers.support import (SDKStreamDouble,@@ -420,7 +421,7 @@ async def test_exact_issue_retries_with_default_and_learns_model() -> None:with patch.object(provider._client.chat.completions, "create", create):_stream, used_body, attempt, _sent_body = await provider._chat._create_stream(body,- provider._admission.start_execution(),+ RequestRecovery(provider._admission.start_execution()),ProviderOperationKind.GENERATION,)await _stream.aclose()@@ -443,7 +444,7 @@ async def test_exact_issue_retries_with_default_and_learns_model() -> None:_sent_body,) = await provider._chat._create_stream(next_body,- provider._admission.start_execution(),+ RequestRecovery(provider._admission.start_execution()),ProviderOperationKind.GENERATION,)await _stream.aclose()@@ -514,7 +515,7 @@ async def test_unknown_vocabulary_retries_without_effort_and_negative_caches() -with patch.object(provider._client.chat.completions, "create", create):_stream, used_body, attempt, _sent_body = await provider._chat._create_stream(body,- provider._admission.start_execution(),+ RequestRecovery(provider._admission.start_execution()),ProviderOperationKind.GENERATION,)await attempt.aclose()@@ -569,7 +570,7 @@ async def test_concurrent_first_requests_can_learn_without_state_corruption() ->async def execute(body: dict):_stream, used_body, attempt, _sent_body = await provider._chat._create_stream(body,- provider._admission.start_execution(),+ RequestRecovery(provider._admission.start_execution()),ProviderOperationKind.GENERATION,)await attempt.aclose()@@ -608,7 +609,7 @@ async def test_stale_cache_self_heals_without_guessing_original_effort() -> None_sent_body,) = await provider._chat._create_stream(cached_body,- provider._admission.start_execution(),+ RequestRecovery(provider._admission.start_execution()),ProviderOperationKind.GENERATION,)await attempt.aclose()@@ -636,7 +637,7 @@ async def test_unrelated_400_propagates_without_cache_poisoning() -> None:):await provider._chat._create_stream(body,- provider._admission.start_execution(),+ RequestRecovery(provider._admission.start_execution()),ProviderOperationKind.GENERATION,)@@ -666,7 +667,7 @@ async def test_nested_unrelated_allow_list_cannot_retry_or_poison_cache() -> Non):await provider._chat._create_stream(body,- provider._admission.start_execution(),+ RequestRecovery(provider._admission.start_execution()),ProviderOperationKind.GENERATION,)@@ -690,7 +691,7 @@ async def test_advertised_current_value_does_not_retry_or_cache() -> None:):await provider._chat._create_stream(body,- provider._admission.start_execution(),+ RequestRecovery(provider._admission.start_execution()),ProviderOperationKind.GENERATION,)@@ -711,7 +712,7 @@ async def test_last_attempt_learns_but_does_not_exceed_budget() -> None:):await provider._chat._create_stream(body,- provider._admission.start_execution(),+ RequestRecovery(provider._admission.start_execution()),ProviderOperationKind.GENERATION,)@@ -739,7 +740,7 @@ async def test_output_cap_and_reasoning_corrections_share_one_session() -> None:with patch.object(provider._client.chat.completions, "create", create):_stream, used_body, attempt, _sent_body = await provider._chat._create_stream(body,- execution,+ RequestRecovery(execution),ProviderOperationKind.GENERATION,)await attempt.aclose()@@ -769,7 +770,7 @@ async def test_corrected_request_cannot_enter_vocabulary_retry_loop() -> None:):await provider._chat._create_stream(body,- provider._admission.start_execution(),+ RequestRecovery(provider._admission.start_execution()),ProviderOperationKind.GENERATION,)diff --git a/tests/providers/test_groq_tpm.py b/tests/providers/test_groq_tpm.pyindex 4a1c47cf..ae6077c9 100644--- a/tests/providers/test_groq_tpm.py+++ b/tests/providers/test_groq_tpm.py@@ -13,6 +13,7 @@ from free_claude_code.core.reasoning import ReasoningEffort, ReasoningPolicyfrom free_claude_code.providers.admission import ProviderOperationKindfrom free_claude_code.providers.groq import GroqProviderfrom free_claude_code.providers.groq.tpm import correct_tpm_completion_budget+from free_claude_code.providers.request_recovery import RequestRecoveryfrom tests.providers.request_factory import make_messages_requestfrom tests.providers.support import (SDKStreamDouble,@@ -262,7 +263,7 @@ async def test_tpm_correction_is_one_shot_per_stream_creation() -> None:):await provider._chat._create_stream(_body(),- provider._admission.start_execution(),+ RequestRecovery(provider._admission.start_execution()),ProviderOperationKind.GENERATION,)@@ -280,7 +281,7 @@ async def test_tpm_correction_respects_physical_attempt_ceiling() -> None:):await provider._chat._create_stream(_body(),- provider._admission.start_execution(),+ RequestRecovery(provider._admission.start_execution()),ProviderOperationKind.GENERATION,)@@ -321,7 +322,7 @@ async def test_tpm_and_reasoning_corrections_compose(_sent_body,) = await provider._chat._create_stream(body,- execution,+ RequestRecovery(execution),ProviderOperationKind.GENERATION,)await attempt.aclose()@@ -349,7 +350,7 @@ async def test_distinct_bodies_get_independent_tpm_corrections() -> None:_sent_body,) = await provider._chat._create_stream(_body(),- execution,+ RequestRecovery(execution),ProviderOperationKind.CONTINUATION,)await first_attempt.accept()@@ -361,7 +362,7 @@ async def test_distinct_bodies_get_independent_tpm_corrections() -> None:_sent_body,) = await provider._chat._create_stream(_body(20_000),- execution,+ RequestRecovery(execution),ProviderOperationKind.TOOL_REPAIR,)await second_attempt.aclose()diff --git a/tests/providers/test_openai_chat_output_cap.py b/tests/providers/test_openai_chat_output_cap.pyindex 0e953cb5..c70e98bc 100644--- a/tests/providers/test_openai_chat_output_cap.py+++ b/tests/providers/test_openai_chat_output_cap.py@@ -16,6 +16,7 @@ from free_claude_code.providers.openai_chat.output_cap import (clamp_output_tokens,parse_output_token_cap,)+from free_claude_code.providers.request_recovery import RequestRecoveryfrom tests.providers.request_factory import make_messages_requestfrom tests.providers.support import (SDKStreamDouble,@@ -273,7 +274,7 @@ async def test_create_stream_clamps_and_learns_on_cap_rejection(groq_provider):_sent_body,) = await groq_provider._chat._create_stream(body,- groq_provider._admission.start_execution(),+ RequestRecovery(groq_provider._admission.start_execution()),ProviderOperationKind.GENERATION,)await _stream.aclose()@@ -306,7 +307,7 @@ async def test_learned_cap_clamps_next_request_without_a_400(groq_provider):_sent_body,) = await groq_provider._chat._create_stream(body,- groq_provider._admission.start_execution(),+ RequestRecovery(groq_provider._admission.start_execution()),ProviderOperationKind.GENERATION,)await _stream.aclose()@@ -334,7 +335,7 @@ async def test_unrelated_400_is_not_clamped_and_propagates(groq_provider):):await groq_provider._chat._create_stream(body,- groq_provider._admission.start_execution(),+ RequestRecovery(groq_provider._admission.start_execution()),ProviderOperationKind.GENERATION,)@@ -368,7 +369,7 @@ async def test_mixed_field_400_does_not_retry_or_poison_learned_cap(groq_provide):await groq_provider._chat._create_stream(body,- groq_provider._admission.start_execution(),+ RequestRecovery(groq_provider._admission.start_execution()),ProviderOperationKind.GENERATION,)diff --git a/tests/providers/test_openai_chat_usage.py b/tests/providers/test_openai_chat_usage.pyindex 94f0afc9..e0660e49 100644--- a/tests/providers/test_openai_chat_usage.py+++ b/tests/providers/test_openai_chat_usage.py@@ -31,6 +31,7 @@ from free_claude_code.providers.openai_chat.usage import (request_stream_usage,usage_int,)+from free_claude_code.providers.request_recovery import RequestRecoveryfrom tests.providers.request_factory import make_messages_requestfrom tests.providers.support import (SDKStreamDouble,@@ -554,7 +555,7 @@ async def test_openai_chat_stream_retries_without_usage_when_option_is_rejected(_sent_body,) = await provider._chat._create_stream(body,- provider._admission.start_execution(),+ RequestRecovery(provider._admission.start_execution()),ProviderOperationKind.GENERATION,)await attempt.aclose()diff --git a/tests/providers/test_request_recovery_transitions.py b/tests/providers/test_request_recovery_transitions.pynew file mode 100644index 00000000..f6f5053c--- /dev/null+++ b/tests/providers/test_request_recovery_transitions.py@@ -0,0 +1,453 @@+"""Recovery state survives transitions across the real upstream transports."""++import asyncio+import json+from contextlib import asynccontextmanager+from copy import deepcopy+from io import StringIO+from unittest.mock import patch++import httpx+import httpx2+import pytest+from openai import AsyncOpenAI++from free_claude_code.core.anthropic import ReasoningReplayMode+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+from free_claude_code.core.reasoning import ReasoningPolicy+from free_claude_code.providers.admission import (+ ProviderAdmissionController,+ ProviderOperationKind,+)+from free_claude_code.providers.endpoint_types import HttpEndpoint+from free_claude_code.providers.openai_chat import (+ NamedEffortReasoning,+ OpenAIChatProfile,+ OpenAIChatProvider,+ OpenAIChatRequestPolicy,+)+from free_claude_code.providers.openai_responses import OpenAIResponsesTransport+from tests.providers.support import make_provider_config+from tests.providers.test_anthropic_messages_transport import _events+from tests.providers.test_anthropic_messages_transport import (+ _transport as messages_transport,+)+from tests.providers.test_history_transports import _events_for+++class Endpoint:+ def __init__(self):+ self.calls = []+ self.token = "original"++ async def endpoint(self, *, force_refresh=False):+ self.calls.append(force_refresh)+ if force_refresh:+ self.token = "fresh"+ return HttpEndpoint("https://provider.invalid/v1/", {}, self.token)+++class Wire(httpx.AsyncByteStream, httpx2.AsyncByteStream):+ def __init__(self, content):+ self.content = content+ self.close_calls = 0++ async def __aiter__(self):+ yield self.content++ async def aclose(self):+ self.close_calls += 1+++@asynccontextmanager+async def _transport(protocol, responder, *, endpoint=None):+ endpoint = endpoint if endpoint is not None else Endpoint()+ bodies = []+ wires = []+ admission = ProviderAdmissionController(+ provider_name="TEST",+ rate_limit=1_000_000,+ rate_window=1,+ max_concurrency=1,+ max_attempts=5,+ base_delay=0,+ max_delay=0,+ jitter=0,+ )++ def handler(request):+ bodies.append(json.loads(request.content))+ status, payload = responder(len(bodies))+ module = httpx if protocol == "messages" else httpx2+ if status == 200:+ content = "".join(+ (f"event: {event['type']}\n" if protocol == "messages" else "")+ + f"data: {json.dumps(event)}\n\n"+ for event in payload+ )+ content_type = "text/event-stream"+ else:+ content = json.dumps({"error": payload})+ content_type = "application/json"+ wire = Wire(content.encode())+ wires.append(wire)+ return module.Response(+ status, headers={"content-type": content_type}, stream=wire+ )++ if protocol == "messages":+ client = httpx.AsyncClient(transport=httpx.MockTransport(handler))+ provider = messages_transport(client, admission)+ else:+ pool = httpx2.MockTransport(handler)+ client = AsyncOpenAI(+ api_key="unused",+ max_retries=0,+ http_client=httpx2.AsyncClient(transport=pool),+ )+ if protocol == "responses":+ provider = OpenAIResponsesTransport(+ client=client,+ admission=admission,+ provider_name="TEST",+ read_timeout_s=3,+ log_raw_sse_events=False,+ endpoint_transport=pool,+ )+ else:+ provider = OpenAIChatProvider(+ make_provider_config(None, "https://provider.invalid/v1/"),+ profile=OpenAIChatProfile(+ OpenAIChatRequestPolicy(+ "TEST", ReasoningReplayMode.REASONING_CONTENT+ ),+ NamedEffortReasoning((), disabled_value="none"),+ structured_reasoning_details=True,+ ),+ admission=admission,+ client=client,+ endpoint_transport=pool,+ )+ try:+ yield provider, endpoint, bodies, wires, admission+ finally:+ if isinstance(provider, OpenAIChatProvider):+ await provider.cleanup()+ if isinstance(client, httpx.AsyncClient):+ await client.aclose()+ else:+ await client.close()+++def _request(protocol):+ block = (+ {"type": "thinking", "thinking": "previous", "signature": "opaque-original"}+ if protocol == "messages"+ else {"type": "redacted_thinking", "data": "opaque-original"}+ )+ return MessagesRequest.model_validate(+ {+ "model": "upstream",+ "messages": [+ {+ "role": "assistant",+ "content": [block, {"type": "text", "text": "17"}],+ },+ {"role": "user", "content": "continue"},+ ],+ "thinking": {"type": "disabled"},+ }+ )+++def _stream(provider, endpoint, request):+ return provider.stream_messages(+ request,+ endpoint_context=endpoint,+ reasoning=ReasoningPolicy.prefer_off(),+ request_id="recovery-transition",+ response_model="public",+ **(+ {"input_tokens": 0}+ if isinstance(provider, OpenAIResponsesTransport)+ else {}+ ),+ )+++def _history_error(protocol):+ return {+ "type": "invalid_request_error",+ "code": "invalid_signature"+ if protocol == "messages"+ else "invalid_encrypted_content",+ "message": "invalid signature in thinking block",+ }+++def _reasoning_error():+ return {+ "type": "invalid_request_error",+ "message": "Reasoning is mandatory and cannot be disabled.",+ }+++def _partial(protocol, text=""):+ if protocol == "messages":+ return _events(text)[:3] if text else _events()[:1]+ if protocol == "responses":+ events = _events_for(protocol)[:1]+ if text:+ events.append(+ {+ "type": "response.output_text.delta",+ "sequence_number": 1,+ "item_id": "text",+ "content_index": 0,+ "output_index": 0,+ "delta": text,+ "logprobs": [],+ }+ )+ return events+ chunk = deepcopy(_events_for("chat")[-1])+ chunk["choices"][0] = {+ "index": 0,+ "delta": {"content": text} if text else {"role": "assistant"},+ "finish_reason": None,+ }+ return [chunk]++[email protected]("protocol", ["chat", "responses", "messages"])[email protected]("exhausted", [False, True])+async def test_mixed_recovery_keeps_one_budget_and_correction_history(+ protocol, exhausted+):+ def respond(ordinal):+ if ordinal == 1:+ return 401, {"type": "authentication_error", "message": "expired"}+ if ordinal == 2:+ return 400, _history_error(protocol)+ if ordinal == 3:+ return 400, _reasoning_error()+ if ordinal == 4:+ return 200, _partial(protocol)+ if exhausted:+ return 503, {"type": "overloaded_error", "message": "unavailable"}+ return 200, _events_for(protocol)++ request = _request(protocol)+ original = deepcopy(request.model_dump())+ async with _transport(protocol, respond) as (provider, endpoint, bodies, wires, _):+ with patch("free_claude_code.providers.admission.trace_event") as trace:+ if exhausted:+ with pytest.raises(ExecutionFailure):+ _ = [event async for event in _stream(provider, endpoint, request)]+ else:+ output = [event async for event in _stream(provider, endpoint, request)]+ parsed = parse_sse_text("".join(output))+ assert sum(event.event == "message_start" for event in parsed) == 1+ assert sum(event.event == "message_stop" for event in parsed) == 1+ starts = [+ call.kwargs+ for call in trace.call_args_list+ if call.kwargs.get("event") == "provider.attempt.started"+ ]+ assert len(starts) == 5+ assert len({start["execution_id"] for start in starts}) == 1+ assert endpoint.calls == [False, True, False, False, False]+ assert len(bodies) == 5 and bodies[0] == bodies[1]+ assert "opaque-original" in json.dumps(bodies[1])+ assert all("opaque-original" not in json.dumps(body) for body in bodies[2:])+ field = {+ "chat": "reasoning_effort",+ "responses": "reasoning",+ "messages": "thinking",+ }[protocol]+ assert field in bodies[2]+ assert all(field not in body for body in bodies[3:])+ assert all(wire.close_calls == 1 for wire in wires)+ assert request.model_dump() == original++[email protected]("protocol", ["chat", "responses", "messages"])+async def test_refresh_allowance_survives_an_intervening_correction(protocol):+ def respond(ordinal):+ if ordinal == 2:+ return 400, _history_error(protocol)+ return 401, {"type": "authentication_error", "message": "expired"}++ async with _transport(protocol, respond) as (provider, endpoint, bodies, wires, _):+ with pytest.raises(ExecutionFailure) as failure:+ _ = [+ event async for event in _stream(provider, endpoint, _request(protocol))+ ]+ assert failure.value.status_code == 401+ assert len(bodies) == 3 and endpoint.calls == [False, True, False]+ assert all(wire.close_calls == 1 for wire in wires)++[email protected]("protocol", ["chat", "responses", "messages"])[email protected]("refresh", [False, True])+async def test_credential_resolution_preserves_admission_order(protocol, refresh):+ class FailingEndpoint(Endpoint):+ failed = False++ async def endpoint(self, *, force_refresh=False):+ if force_refresh == refresh and not self.failed:+ self.failed = True+ self.calls.append(force_refresh)+ raise httpx.ReadError("credential service unavailable")+ return await super().endpoint(force_refresh=force_refresh)++ def respond(ordinal):+ if refresh and ordinal == 1:+ return 401, {"type": "authentication_error", "message": "expired"}+ return 200, _events_for(protocol)++ async with _transport(protocol, respond, endpoint=FailingEndpoint()) as (+ provider,+ endpoint,+ bodies,+ wires,+ _,+ ):+ if protocol == "responses":+ with pytest.raises(+ ExecutionFailure, match="credential service unavailable"+ ):+ _ = [+ event+ async for event in _stream(provider, endpoint, _request(protocol))+ ]+ assert endpoint.calls == ([False, True] if refresh else [False])+ assert len(bodies) == int(refresh)+ else:+ assert [+ event async for event in _stream(provider, endpoint, _request(protocol))+ ]+ assert endpoint.calls == (+ [False, True, True] if refresh else [False, False]+ )+ assert len(bodies) == 1 + int(refresh)+ assert all(wire.close_calls == 1 for wire in wires)++[email protected]("protocol", ["chat", "responses", "messages"])[email protected]("failure_kind", ["authentication", "reasoning"])+async def test_committed_output_prevents_generation_corrections(protocol, failure_kind):+ error = (+ {+ "type": "authentication_error",+ "code": "invalid_api_key",+ "message": "expired",+ }+ if failure_kind == "authentication"+ else _reasoning_error()+ )+ if protocol == "responses" and failure_kind == "reasoning":+ error["code"] = "invalid_request_error"+ events = _partial(protocol, "already visible " * 5000)+ events.append({"type": "error", "error": error})+ async with _transport(protocol, lambda _: (200, events)) as (+ provider,+ endpoint,+ bodies,+ wires,+ _,+ ):+ output = StringIO()+ with pytest.raises(ExecutionFailure):+ async for event in _stream(provider, endpoint, _request(protocol)):+ output.write(event)+ assert "already visible" in output.getvalue()+ assert len(bodies) == 1 and endpoint.calls == [False]+ assert all(wire.close_calls == 1 for wire in wires)++[email protected]("protocol", ["chat", "responses", "messages"])+async def test_cancelled_forced_resolution_closes_attempt_and_releases_admission(+ protocol,+):+ entered = asyncio.Event()+ wires = []++ class BlockingEndpoint(Endpoint):+ async def endpoint(self, *, force_refresh=False):+ if force_refresh:+ self.calls.append(force_refresh)+ assert wires and all(wire.close_calls == 1 for wire in wires)+ entered.set()+ await asyncio.Event().wait()+ return await super().endpoint(force_refresh=force_refresh)++ async def consume(provider, endpoint):+ return [+ event async for event in _stream(provider, endpoint, _request(protocol))+ ]++ async with _transport(+ protocol,+ lambda _: (401, {"type": "authentication_error", "message": "expired"}),+ endpoint=BlockingEndpoint(),+ ) as (provider, endpoint, bodies, owned_wires, admission):+ wires = owned_wires+ task = asyncio.create_task(consume(provider, endpoint))+ try:+ await asyncio.wait_for(entered.wait(), timeout=3)+ finally:+ task.cancel()+ with pytest.raises(asyncio.CancelledError):+ await task+ assert len(bodies) == 1 and endpoint.calls == [False, True]+ execution = admission.start_execution()+ attempt = await asyncio.wait_for(+ execution.open_attempt(ProviderOperationKind.GENERATION), timeout=3+ )+ await attempt.aclose()+ execution.abandon()++[email protected]("failure_kind", ["authentication", "stream_usage"])+async def test_committed_chat_continuation_has_separate_body_correction_scope(+ failure_kind,+):+ def respond(ordinal):+ if ordinal == 1:+ return 200, _partial("chat", "already visible " * 5000)+ if ordinal == 2:+ if failure_kind == "authentication":+ return 401, {"type": "authentication_error", "message": "expired"}+ return 400, {+ "type": "invalid_request_error",+ "message": "stream_options is unsupported",+ }+ return 200, _events_for("chat")++ async with _transport("chat", respond) as (provider, endpoint, bodies, wires, _):+ output = StringIO()+ if failure_kind == "authentication":+ with pytest.raises(ExecutionFailure):+ async for event in _stream(provider, endpoint, _request("chat")):+ output.write(event)+ assert len(bodies) == 2+ else:+ async for event in _stream(provider, endpoint, _request("chat")):+ output.write(event)+ assert len(bodies) == 3+ assert bodies[1]["stream_options"] == {"include_usage": True}+ assert "stream_options" not in bodies[2]+ parsed = parse_sse_text(output.getvalue())+ assert sum(event.event == "message_stop" for event in parsed) == 1+ assert "already visible" in output.getvalue()+ assert endpoint.calls == [False] * len(bodies)+ assert all(wire.close_calls == 1 for wire in wires)diff --git a/tests/providers/test_sdk_stream_lifecycle.py b/tests/providers/test_sdk_stream_lifecycle.pyindex 37082ae8..89d871fb 100644--- a/tests/providers/test_sdk_stream_lifecycle.py+++ b/tests/providers/test_sdk_stream_lifecycle.py@@ -24,6 +24,7 @@ from free_claude_code.providers.nvidia_nim.native_tool_stream import ()from free_claude_code.providers.openai_responses import OpenAIResponsesTransportfrom free_claude_code.providers.openai_stream import OpenAIStreamAdapter+from free_claude_code.providers.request_recovery import RequestRecoveryfrom tests.providers.request_factory import make_messages_requestfrom tests.providers.support import make_provider_config, profiled_providerfrom tests.providers.test_openai_responses_transport import (@@ -247,7 +248,7 @@ async def test_cancelled_normalizer_construction_cleanup_releases_admission():task = asyncio.create_task(provider._chat._create_stream({"model": "model", "messages": []},- admission.start_execution(),+ RequestRecovery(admission.start_execution()),ProviderOperationKind.GENERATION,))@@ -382,7 +383,7 @@ async def test_normalizer_construction_failure_closes_response_before_retry(operasync with asyncio.timeout(2):stream, _, attempt, _ = await provider._chat._create_stream({"model": "model", "messages": []},- admission.start_execution(),+ RequestRecovery(admission.start_execution()),operation,)try:diff --git a/tests/providers/test_streaming_errors.py b/tests/providers/test_streaming_errors.pyindex ed3f5c29..9c19e95f 100644--- a/tests/providers/test_streaming_errors.py+++ b/tests/providers/test_streaming_errors.py@@ -41,6 +41,7 @@ from free_claude_code.providers.openai_chat.transport import (_OpenAIChatStreamRunner,_reserved_anthropic_tool_ids,)+from free_claude_code.providers.request_recovery import RequestRecoveryfrom free_claude_code.providers.stream_recovery import TruncatedProviderStreamErrorfrom tests.providers.request_factory import make_messages_requestfrom tests.providers.support import (@@ -347,7 +348,7 @@ class TestStreamingExceptionHandling:):await provider._chat._create_stream({"model": "test-model", "messages": []},- execution,+ RequestRecovery(execution),ProviderOperationKind.GENERATION,)@@ -1754,7 +1755,7 @@ class TestStreamingExceptionHandling:await runner._collect_recovery_output({"model": "test-model", "messages": []},include_reasoning=True,- execution=execution,+ request_recovery=RequestRecovery(execution),operation_kind=ProviderOperationKind.CONTINUATION,)@@ -1787,7 +1788,7 @@ class TestStreamingExceptionHandling:await runner._collect_recovery_output({"model": "test-model", "messages": []},include_reasoning=True,- execution=execution,+ request_recovery=RequestRecovery(execution),operation_kind=ProviderOperationKind.CONTINUATION,)@@ -1839,7 +1840,7 @@ class TestStreamingExceptionHandling:recovered = await runner._collect_recovery_output(body,include_reasoning=True,- execution=execution,+ request_recovery=RequestRecovery(execution),operation_kind=ProviderOperationKind.CONTINUATION,)@@ -1851,8 +1852,8 @@ class TestStreamingExceptionHandling:assert "stream_options" not in create.await_args_list[2].kwargsassert create_stream.await_count == 2assert (- create_stream.await_args_list[0].kwargs["used_retry_kinds"]- is create_stream.await_args_list[1].kwargs["used_retry_kinds"]+ create_stream.await_args_list[0].kwargs["corrections"]+ is create_stream.await_args_list[1].kwargs["corrections"])assert recovered.text == "visible"assert failed_stream.closed@@ -1925,7 +1926,7 @@ class TestStreamingExceptionHandling:body=body,output=assembler.output,tool_argument_alias_buffers=assembler.tool_argument_alias_buffers,- execution=execution,+ request_recovery=RequestRecovery(execution),)assert events is not None@@ -1937,8 +1938,8 @@ class TestStreamingExceptionHandling:assert "stream_options" not in create.await_args_list[2].kwargsassert create_stream.await_count == 2assert (- create_stream.await_args_list[0].kwargs["used_retry_kinds"]- is create_stream.await_args_list[1].kwargs["used_retry_kinds"]+ create_stream.await_args_list[0].kwargs["corrections"]+ is create_stream.await_args_list[1].kwargs["corrections"])assert invalid_repair.closedassert valid_repair.closed@@ -1965,7 +1966,7 @@ class TestStreamingExceptionHandling:result = await runner._collect_recovery_output({"model": "test-model", "messages": []},include_reasoning=True,- execution=execution,+ request_recovery=RequestRecovery(execution),operation_kind=ProviderOperationKind.CONTINUATION,)@@ -2116,7 +2117,7 @@ class TestStreamingExceptionHandling:result = await runner._collect_recovery_output({"model": "test-model", "messages": []},include_reasoning=True,- execution=execution,+ request_recovery=RequestRecovery(execution),operation_kind=ProviderOperationKind.CONTINUATION,)@@ -2152,7 +2153,7 @@ class TestStreamingExceptionHandling:result = await runner._collect_recovery_output({"model": "test-model", "messages": []},include_reasoning=True,- execution=execution,+ request_recovery=RequestRecovery(execution),operation_kind=ProviderOperationKind.CONTINUATION,)@@ -2185,7 +2186,7 @@ class TestStreamingExceptionHandling:await runner._collect_recovery_output({"model": "test-model", "messages": []},include_reasoning=True,- execution=execution,+ request_recovery=RequestRecovery(execution),operation_kind=ProviderOperationKind.CONTINUATION,)@@ -2211,7 +2212,7 @@ class TestStreamingExceptionHandling:runner._collect_recovery_output({"model": "test-model", "messages": []},include_reasoning=True,- execution=execution,+ request_recovery=RequestRecovery(execution),operation_kind=ProviderOperationKind.CONTINUATION,))@@ -2260,7 +2261,7 @@ class TestStreamingExceptionHandling:result = await runner._collect_recovery_output({"model": "test-model", "messages": []},include_reasoning=True,- execution=execution,+ request_recovery=RequestRecovery(execution),operation_kind=ProviderOperationKind.CONTINUATION,)@@ -2342,7 +2343,7 @@ class TestStreamingExceptionHandling:error=TimeoutError("cutoff"),tool_argument_alias_buffers={},output_reasoning=True,- execution=execution,+ request_recovery=RequestRecovery(execution),)assert events is not None@@ -3222,7 +3223,7 @@ async def test_tool_argument_mapping_survives_correction_then_stream_reopen(collrecovered = await runner._collect_recovery_output(runner._body,include_reasoning=False,- execution=execution,+ request_recovery=RequestRecovery(execution),operation_kind=ProviderOperationKind.CONTINUATION,)arguments = json.loads(recovered.tool_calls[0]["function"]["arguments"])diff --git a/uv.lock b/uv.lockindex 6864825e..8d21f994 100644--- a/uv.lock+++ b/uv.lock@@ -598,7 +598,7 @@ wheels = [[[package]]name = "free-claude-code"-version = "6.2.31"+version = "6.2.32"source = { editable = "." }dependencies = [{ name = "aiohttp" },