Skip to content

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
65.5 KB
Raw Blame
"""Shared Chat Completions transport and per-request stream execution."""

import asyncio
import sys
import uuid
from collections.abc import AsyncIterator, Awaitable, Callable, Iterator, Mapping
from dataclasses import dataclass
from enum import StrEnum
from functools import partial
from typing import Any, cast

import httpx2
from loguru import logger
from openai import AsyncOpenAI

from free_claude_code.application.errors import InvalidRequestError
from free_claude_code.application.model_metadata import ProviderModelInfo
from free_claude_code.core.anthropic import (
    ContentBlockToolUse,
    ContentType,
    ThinkTagParser,
)
from free_claude_code.core.anthropic.models import MessagesRequest
from free_claude_code.core.anthropic.streaming import (
    ToolSchema,
    accept_tool_json_repair,
    continuation_suffix,
    make_response_recovery_body,
    make_text_recovery_body,
    make_tool_repair_body,
    map_stop_reason,
    parse_complete_tool_input,
    tool_schemas_by_name,
)
from free_claude_code.core.diagnostics import (
    exception_cause_types,
    redacted_exception_traceback,
)
from free_claude_code.core.failures import ExecutionFailure, FailureKind
from free_claude_code.core.history_replay import prepare_history
from free_claude_code.core.json_types import JsonObject
from free_claude_code.core.openai_responses import (
    OpenAIResponsesRequest,
    ResponsesChatRequest,
    ResponsesConversionError,
    build_responses_chat_request,
)
from free_claude_code.core.openai_tool_names import (
    OpenAIToolNameCodec,
    encode_openai_chat_tool_names,
)
from free_claude_code.core.reasoning import (
    DEFAULT_REASONING_POLICY,
    ReasoningControl,
    ReasoningPolicy,
)
from free_claude_code.core.stream_recovery import ContinuationSeed
from free_claude_code.core.trace import provider_chat_body_snapshot, trace_event
from free_claude_code.providers.admission import (
    ProviderAdmissionController,
    ProviderAttempt,
    ProviderOperationKind,
)
from free_claude_code.providers.continuation import (
    ContinuationRequest,
    SourceRecoveryState,
    public_recovery,
    public_stream_failure,
)
from free_claude_code.providers.endpoint import RequestEndpoint
from free_claude_code.providers.endpoint_types import EndpointContext
from free_claude_code.providers.failure_policy import (
    RetryableToolProtocolError,
    classify_provider_failure,
    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 (
    replay_origin,
    validate_history,
)
from free_claude_code.providers.http import (
    ProviderAttemptScope,
    close_provider_stream,
    maybe_await_aclose,
)
from free_claude_code.providers.openai_client import OpenAIRequestClient
from free_claude_code.providers.openai_stream import OpenAIStreamAdapter
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 (
    HoldbackSignal,
    RecoveryController,
    RecoveryDecision,
    RecoveryFailureAction,
    TruncatedProviderStreamError,
)

from .behavior import OpenAIChatBehavior
from .output_cap import clamp_output_tokens, parse_output_token_cap
from .profiles import OpenAIChatProfile
from .reasoning_details import StructuredReasoningStream
from .request_policy import (
    apply_openai_chat_body_policy,
)
from .stream_output import (
    AnthropicChatStreamOutput,
    ChatStreamOutput,
    ChatStreamUsage,
    ResponsesChatStreamOutput,
)
from .tool_call_identity import AmbiguousToolCallIdentityError
from .tool_calls import (
    CompletedOpenAIToolCall,
    OpenAIToolCallAssembler,
    OpenAIToolCallCollector,
    tool_call_extra_content,
)
from .usage import (
    clone_without_stream_usage,
    is_stream_usage_rejection,
    nested_usage_int,
    request_stream_usage,
    usage_int,
)

OpenAIAsyncCredentialProvider = Callable[[], Awaitable[str]]
_ExtraReasoningEvents = Callable[[Any, ChatStreamOutput], Iterator[str]]
_ChatOutputFactory = Callable[[], ChatStreamOutput]


@dataclass(frozen=True, slots=True)
class _CollectedRecoveryOutput:
    text: str
    thinking: str
    tool_calls: tuple[CompletedOpenAIToolCall, ...]
    request_body: JsonObject


def _iter_visible_text_events(
    output: ChatStreamOutput,
    text: str,
) -> Iterator[str]:
    yield from output.ensure_text_block()
    yield output.emit_text_delta(text)


@dataclass(frozen=True, slots=True)
class _OpenAIChatCompletion:
    finish_reason: Any
    output_tokens: int
    input_tokens: int
    provider_input_tokens: int | None


class _OpenAIChatFailureOutcome(StrEnum):
    RETRY = "retry"
    COMPLETE = "complete"
    RAISE = "raise"


@dataclass(frozen=True, slots=True)
class _OpenAIChatFailureResolution:
    outcome: _OpenAIChatFailureOutcome
    events: tuple[str, ...] = ()
    failure: ExecutionFailure | None = None


def _reserved_anthropic_tool_ids(request: MessagesRequest) -> frozenset[str]:
    """Return prior tool-use IDs that generated output must not reuse."""
    return frozenset(
        block.id
        for message in request.messages
        if isinstance(message.content, list)
        for block in message.content
        if isinstance(block, ContentBlockToolUse) and block.id.strip()
    )


class _OpenAIChatStreamAssembler:
    """Own one discardable OpenAI-chat replay epoch."""

    def __init__(
        self,
        *,
        output: ChatStreamOutput,
        profile: OpenAIChatProfile,
        provider_name: str,
        output_reasoning: bool,
        tool_names: OpenAIToolNameCodec,
        tool_schemas: dict[str, ToolSchema],
        tool_calls: OpenAIToolCallAssembler,
        extra_reasoning_events: _ExtraReasoningEvents,
    ) -> None:
        self._output = output
        self._profile = profile
        self._provider_name = provider_name
        self._output_reasoning = output_reasoning
        self._tool_names = tool_names
        self._tool_schemas = tool_schemas
        self._tool_calls = tool_calls
        self._extra_reasoning_events = extra_reasoning_events
        self._think_parser = ThinkTagParser()
        self._structured_reasoning = (
            StructuredReasoningStream()
            if profile.structured_reasoning_details
            else None
        )
        if self._structured_reasoning is not None:
            self._output.reasoning_replay = self._structured_reasoning
        self._finish_reason: Any = None
        self._raw_stop_seen = False
        self._usage_info: Any = None
        self._tool_argument_aliases: dict[str, dict[str, str]] = {}
        self._tool_argument_alias_buffers: dict[int, str] = {}
        self._tool_name_buffers: dict[int, str] = {}
        self._started = False
        self._aliases_bound = False
        self._upstream_finished = False
        self._completion: _OpenAIChatCompletion | None = None
        self._completed = False

    @property
    def output(self) -> ChatStreamOutput:
        return self._output

    @property
    def usage_info(self) -> Any:
        return self._usage_info

    @property
    def completion(self) -> _OpenAIChatCompletion:
        if self._completion is None:
            raise RuntimeError("stream completion has not been prepared")
        return self._completion

    @property
    def generated_output(self) -> bool:
        return self._output.committed_output

    @property
    def complete_tool_salvageable(self) -> bool:
        return (
            self.generated_output
            and self._output.has_emitted_tool_block()
            and self._output.can_salvage_tool_use(self._tool_schemas)
        )

    @property
    def tool_argument_alias_buffers(self) -> Mapping[int, str]:
        return self._tool_argument_alias_buffers

    @property
    def normal_stop_seen(self) -> bool:
        return self._raw_stop_seen or self._finish_reason is not None

    def observe_upstream_chunk(self, chunk: Any) -> None:
        if chunk.choices and chunk.choices[0].finish_reason is not None:
            self._raw_stop_seen = True

    def recovered_tool_call_events(
        self, tool_calls: tuple[CompletedOpenAIToolCall, ...]
    ) -> Iterator[str]:
        """Import a complete recovery batch without inheriting abandoned tools."""
        if self._output.has_emitted_tool_block():
            raise RuntimeError("cannot replace started tool calls with recovery output")
        self._tool_name_buffers.clear()
        self._tool_argument_alias_buffers.clear()
        yield from self._tool_calls.process_completed_calls(tool_calls, self._output)

    def start_events(self) -> Iterator[str]:
        if self._started:
            return
        self._started = True
        yield from self._output.start_events()

    def bind_tool_argument_aliases(self, aliases: dict[str, dict[str, str]]) -> None:
        if self._aliases_bound:
            raise RuntimeError("tool argument aliases already bound")
        self._aliases_bound = True
        self._tool_argument_aliases = aliases

    def feed(self, chunk: Any) -> Iterator[str]:
        if not self._started or self._upstream_finished:
            raise RuntimeError("stream assembler is not accepting chunks")

        chunk_usage = getattr(chunk, "usage", None)
        if chunk_usage is not None:
            self._usage_info = chunk_usage

        if not chunk.choices:
            return

        choice = chunk.choices[0]
        delta = choice.delta
        if choice.finish_reason is not None:
            self._finish_reason = choice.finish_reason
        if delta is None:
            return

        if choice.finish_reason:
            self._finish_reason = choice.finish_reason
            logger.debug(
                "{} finish_reason: {}",
                self._provider_name,
                self._finish_reason,
            )

        reasoning = self._profile.reasoning_delta(delta)
        if self._structured_reasoning is not None:
            yield from self._structured_reasoning.events(
                delta,
                self._output,
                native_reasoning=reasoning if self._output_reasoning else None,
                output_reasoning=self._output_reasoning,
            )
        elif self._output_reasoning and reasoning:
            yield from self._output.ensure_reasoning_block()
            yield self._output.emit_reasoning_delta(reasoning)

        yield from self._extra_reasoning_events(delta, self._output)

        native_tool_calls = delta.tool_calls
        if delta.content:
            for part in self._think_parser.feed(delta.content):
                if part.type == ContentType.THINKING:
                    if not self._output_reasoning:
                        continue
                    yield from self._output.ensure_reasoning_block()
                    yield self._output.emit_reasoning_delta(part.content)
                else:
                    yield from _iter_visible_text_events(self._output, part.content)

        if native_tool_calls:
            yield from self._output.close_content_blocks()
            for tool_call in native_tool_calls:
                extra_content = tool_call_extra_content(tool_call)
                tool_call_info = {
                    "index": tool_call.index,
                    "id": tool_call.id,
                    "function": {
                        "name": tool_call.function.name,
                        "arguments": tool_call.function.arguments,
                    },
                }
                if extra_content:
                    tool_call_info["extra_content"] = extra_content
                yield from self._tool_calls.process_tool_call(
                    tool_call_info,
                    self._output,
                    tool_names=self._tool_names,
                    tool_name_buffers=self._tool_name_buffers,
                    tool_argument_aliases=self._tool_argument_aliases,
                    tool_argument_alias_buffers=self._tool_argument_alias_buffers,
                )

    def finish_upstream(self) -> Iterator[str]:
        if self._upstream_finished:
            return
        if self._finish_reason is None:
            raise TruncatedProviderStreamError(
                "Provider stream ended without finish_reason."
            )
        if is_context_window_finish_reason(self._finish_reason):
            raise context_window_exceeded_provider_failure()
        if any(
            not self._tool_names.is_unchanged_name(name)
            for name in self._tool_name_buffers.values()
        ):
            raise TruncatedProviderStreamError(
                "Provider stream ended with an incomplete tool name."
            )

        remaining = self._think_parser.flush()
        if remaining:
            if remaining.type == ContentType.THINKING:
                if self._output_reasoning:
                    yield from self._output.ensure_reasoning_block()
                    yield self._output.emit_reasoning_delta(remaining.content)
            else:
                yield from _iter_visible_text_events(self._output, remaining.content)

        yield from self._output.flush_reasoning_replay()
        self._upstream_finished = True

    def prepare_completion(self, *, pad_empty: bool) -> Iterator[str]:
        if not self._upstream_finished or self._completion is not None:
            raise RuntimeError("stream completion cannot be prepared")

        yield from self._tool_calls.flush_tool_name_buffers(
            self._output,
            tool_names=self._tool_names,
            tool_name_buffers=self._tool_name_buffers,
            tool_argument_aliases=self._tool_argument_aliases,
            tool_argument_alias_buffers=self._tool_argument_alias_buffers,
        )

        has_emitted_tool = self._output.has_emitted_tool_block()
        has_content_blocks = self._output.has_content_block()
        if pad_empty and (
            not has_content_blocks
            or (
                not has_emitted_tool
                and not self._output.accumulated_text.strip()
                and self._output.accumulated_reasoning.strip()
            )
        ):
            yield from self._output.ensure_text_block()
            yield self._output.emit_text_delta(" ")

        yield from self._tool_calls.flush_tool_argument_alias_buffers(
            self._output,
            self._tool_argument_aliases,
            self._tool_argument_alias_buffers,
        )
        yield from self._output.close_all_blocks()

        completion = usage_int(self._usage_info, "completion_tokens")
        output_tokens = (
            completion
            if isinstance(completion, int)
            else self._output.estimate_output_tokens()
        )
        provider_input = usage_int(self._usage_info, "prompt_tokens")
        input_tokens = (
            provider_input if provider_input is not None else self._output.input_tokens
        )
        self._completion = _OpenAIChatCompletion(
            finish_reason=self._finish_reason,
            output_tokens=output_tokens,
            input_tokens=input_tokens,
            provider_input_tokens=provider_input,
        )

    def terminal_events(self, *, usage: ChatStreamUsage) -> Iterator[str]:
        if self._completed:
            return
        completion = self.completion
        yield from self._output.finish_success(
            stop_reason=map_stop_reason(completion.finish_reason),
            usage=usage,
        )
        self._completed = True


class OpenAIChatTransport:
    """Execute Chat requests while borrowing provider-owned HTTP resources."""

    def __init__(
        self,
        *,
        client: AsyncOpenAI,
        admission: ProviderAdmissionController,
        behavior: OpenAIChatBehavior,
        read_timeout_s: float,
        log_raw_sse_events: bool,
        log_api_error_tracebacks: bool,
        endpoint_transport: httpx2.AsyncBaseTransport | None = None,
    ) -> None:
        self._client = client
        self._admission = admission
        self._behavior = behavior
        self._profile = behavior.profile
        self._provider_name = self._profile.provider_name
        self._read_timeout_s = read_timeout_s
        self._log_raw_sse_events = log_raw_sse_events
        self._log_api_error_tracebacks = log_api_error_tracebacks
        self._endpoint_transport = endpoint_transport
        self._model_output_caps: dict[str, int] = {}

    def _log_stream_transport_error(
        self,
        tag: str,
        req_tag: str,
        error: Exception,
        *,
        request_id: str | None = None,
    ) -> None:
        """Log streaming transport failures (metadata-only unless verbose is enabled)."""
        response = getattr(error, "response", None)
        http_status = (
            getattr(response, "status_code", None) if response is not None else None
        )
        cause_types = exception_cause_types(error)
        trace_event(
            stage="provider",
            event="provider.response.transport_error",
            source="provider",
            provider=tag,
            request_id=request_id,
            exc_type=type(error).__name__,
            http_status=http_status,
            cause_types=cause_types,
        )

        if self._log_api_error_tracebacks:
            logger.error(
                "{}_ERROR:{} exc_type={}\n{}",
                tag,
                req_tag,
                type(error).__name__,
                redacted_exception_traceback(error),
            )
            return
        logger.error(
            "{}_ERROR:{} exc_type={} http_status={} cause_types={}",
            tag,
            req_tag,
            type(error).__name__,
            http_status,
            ",".join(cause_types) if cause_types else None,
        )

    def _build_request_body(
        self,
        request: MessagesRequest,
        *,
        reasoning: ReasoningPolicy = DEFAULT_REASONING_POLICY,
        model_info: ProviderModelInfo | None = None,
    ) -> dict[str, Any]:
        """Build a provider request from the immutable profile."""
        request, reasoning = self._prepare_messages_reasoning(
            request, reasoning, model_info
        )
        return self._behavior.build_messages_body(request, reasoning=reasoning)

    def _prepare_messages_reasoning(
        self,
        request: MessagesRequest,
        reasoning: ReasoningPolicy,
        model_info: ProviderModelInfo | None,
    ) -> tuple[MessagesRequest, ReasoningPolicy]:
        return prepare_messages_reasoning(
            request,
            reasoning,
            model_info=model_info,
            can_disable=bool(self._behavior.reasoning_off_fields),
            normal_max_tokens=self._behavior.normal_max_tokens,
        )

    def _build_responses_request_body(
        self,
        request: OpenAIResponsesRequest,
        *,
        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,
                reasoning_replay=self._profile.request_policy.reasoning_replay,
                structured_reasoning_details=(
                    self._profile.structured_reasoning_details
                ),
            )
        except ResponsesConversionError as exc:
            raise InvalidRequestError(str(exc)) from exc
        body = translated.body
        apply_openai_chat_body_policy(body, self._profile.request_policy)
        self._profile.apply_reasoning_to_body(body, reasoning)
        body = self._behavior.finalize_chat_body(body, reasoning=reasoning)
        encode_openai_chat_tool_names(body, translated.tool_names)
        return ResponsesChatRequest(
            body=body,
            tool_names=translated.tool_names,
            tool_schemas=translated.tool_schemas,
            reserved_tool_ids=translated.reserved_tool_ids,
            tool_adapter=translated.tool_adapter,
        )

    async def _create_stream(
        self,
        body: dict,
        request_recovery: RequestRecovery,
        operation_kind: ProviderOperationKind,
        *,
        corrections: RequestCorrections | None = None,
        endpoint: RequestEndpoint | None = None,
        request_client: OpenAIRequestClient | None = None,
        extra_headers: Mapping[str, str] | None = None,
        on_event: Callable[[Any], None] | None = None,
    ) -> tuple[Any, dict, ProviderAttempt, dict]:
        """Create a streaming chat completion with bounded request fallbacks."""
        execution = request_recovery.execution
        body = self._apply_learned_output_cap(body)
        if corrections is None:
            corrections = RequestCorrections("chat")

        while execution.can_attempt:
            attempt = await execution.open_attempt(operation_kind)
            stream: Any | None = None
            retain_attempt = False
            create_body = body
            try:
                create_body = self._behavior.prepare_create_body(body)
                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 {}),
                        **(
                            request_client.openai_headers()
                            if request_client 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._behavior.history_scope(body),
                        reasoning_field=self._profile.request_policy.reasoning_replay.value,
                        structured_details=self._profile.structured_reasoning_details,
                    ),
                )
                stream = OpenAIStreamAdapter(
                    await client.chat.completions.create(
                        **create_body,
                        stream=True,
                    ),
                    on_event=on_event,
                )
                stream = self._behavior.normalize_stream(stream, body)
                retain_attempt = True
                return stream, body, attempt, create_body
            except asyncio.CancelledError:
                raise
            except Exception as error:
                retry_body = await request_recovery.retry_request(
                    error,
                    provider_authentication_status(error),
                    attempt,
                    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:
                    body = self._apply_learned_output_cap(retry_body)
                    continue
                decision = await attempt.fail(
                    error,
                    provider_failure_override=self._behavior.failure_override,
                )
                if not decision.retry_allowed:
                    raise
            finally:
                if not retain_attempt:
                    try:
                        if stream is not None:
                            await close_provider_stream(
                                stream,
                                active_error=sys.exception(),
                                provider_name=self._provider_name,
                                request_id=execution.request_id,
                            )
                    finally:
                        await attempt.aclose()

        if execution.last_failure is not None:
            raise execution.last_failure
        raise RuntimeError("provider execution ended without a final error")

    def _next_chat_retry_body(
        self,
        error: Exception,
        body: dict,
        used_retry_kinds: set[str],
        *,
        sent_body: Mapping[str, Any] | None = None,
    ) -> dict | None:
        retry_body = self._retry_body_for_output_cap(error, body)
        if retry_body is not None:
            return retry_body

        if "stream_usage" not in used_retry_kinds and is_stream_usage_rejection(error):
            retry_body = clone_without_stream_usage(body)
            if retry_body is not None:
                used_retry_kinds.add("stream_usage")
                logger.warning(
                    "{}_STREAM: retrying without stream_options.include_usage "
                    "after upstream rejection",
                    self._provider_name,
                )
                return retry_body

        if "provider_specific" not in used_retry_kinds:
            retry_body = self._behavior.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

        return self._behavior.retry_after_standard_corrections(
            error, body, used_retry_kinds
        )

    def _apply_learned_output_cap(self, body: dict) -> dict:
        """Clamp output tokens to a previously learned cap for this model."""
        model = body.get("model")
        if not isinstance(model, str):
            return body
        cap = self._model_output_caps.get(model)
        if cap is None:
            return body
        clamped = clamp_output_tokens(body, cap)
        return clamped if clamped is not None else body

    def _retry_body_for_output_cap(self, error: Exception, body: dict) -> dict | None:
        """Learn an upstream output-token cap from a 400 and clamp for one retry."""
        cap = parse_output_token_cap(error)
        if cap is None:
            return None
        model = body.get("model")
        if isinstance(model, str):
            previous = self._model_output_caps.get(model)
            cap = cap if previous is None else min(previous, cap)
            self._model_output_caps[model] = cap
        clamped = clamp_output_tokens(body, cap)
        if clamped is None:
            return None
        logger.warning(
            "{}_STREAM: clamping output tokens to {} after upstream cap rejection",
            self._provider_name,
            cap,
        )
        return clamped

    def stream_messages(
        self,
        request: MessagesRequest,
        input_tokens: int = 0,
        *,
        request_id: str | None = None,
        response_model: str | None = None,
        reasoning: ReasoningPolicy = DEFAULT_REASONING_POLICY,
        model_info: ProviderModelInfo | None = None,
        endpoint_context: EndpointContext | None = None,
        extra_headers: Mapping[str, str] | None = None,
        continuation: ContinuationSeed | None = None,
    ) -> AsyncIterator[str]:
        """Stream response in Anthropic SSE format."""
        prepared_request, wire_reasoning = self._prepare_messages_reasoning(
            request, reasoning, model_info
        )
        body = self._build_request_body(prepared_request, reasoning=wire_reasoning)
        off_fields = self._behavior.reasoning_off_fields
        correction = (
            ReasoningCorrection(
                off_fields,
                self._profile.request_policy.max_tokens_field,
                self._behavior.normal_max_tokens,
                provider_rejection=self._behavior.reasoning_disable_rejected,
            )
            if reasoning.control is ReasoningControl.PREFER_OFF
            and wire_reasoning.control is ReasoningControl.OFF
            and off_fields
            else None
        )
        tool_names = OpenAIToolNameCodec.from_request(request)
        message_id = f"msg_{uuid.uuid4()}"
        runner = _OpenAIChatStreamRunner(
            self,
            body=body,
            tool_names=tool_names,
            tool_schemas=tool_schemas_by_name(request),
            reserved_tool_ids=_reserved_anthropic_tool_ids(request),
            output_factory=lambda: AnthropicChatStreamOutput(
                message_id=message_id,
                model=request.model if response_model is None else response_model,
                input_tokens=input_tokens,
                log_raw_events=self._log_raw_sse_events,
            ),
            input_tokens=input_tokens,
            request_id=request_id,
            response_model=(
                request.model if response_model is None else response_model
            ),
            reasoning=reasoning,
            endpoint_context=endpoint_context,
            extra_headers=extra_headers or {},
            reasoning_correction=correction,
            continuation=continuation,
        )
        return runner.run()

    def stream_responses(
        self,
        request: OpenAIResponsesRequest,
        input_tokens: int = 0,
        *,
        request_id: str | None = None,
        response_model: str | None = None,
        reasoning: ReasoningPolicy = DEFAULT_REASONING_POLICY,
        endpoint_context: EndpointContext | None = None,
        extra_headers: Mapping[str, str] | None = None,
        continuation: ContinuationSeed | None = None,
    ) -> AsyncIterator[str]:
        """Stream a Chat upstream directly as OpenAI Responses SSE."""
        translated = self._build_responses_request_body(request, reasoning=reasoning)
        public_model = request.model if response_model is None else response_model
        tool_schemas = {
            name: ToolSchema(name=name, input_schema=schema)
            for name, schema in translated.tool_schemas.items()
        }
        runner = _OpenAIChatStreamRunner(
            self,
            body=translated.body,
            tool_names=translated.tool_names,
            tool_schemas=tool_schemas,
            reserved_tool_ids=translated.reserved_tool_ids,
            output_factory=lambda: ResponsesChatStreamOutput(
                translated.tool_adapter,
                input_tokens=input_tokens,
                response_model=public_model,
            ),
            input_tokens=input_tokens,
            request_id=request_id,
            response_model=public_model,
            reasoning=reasoning,
            endpoint_context=endpoint_context,
            extra_headers=extra_headers or {},
            continuation=continuation,
        )
        return runner.run()


class _OpenAIChatStreamRunner:
    """Orchestrate one OpenAI-chat request and its recovery lifecycle."""

    def __init__(
        self,
        transport: OpenAIChatTransport,
        *,
        body: dict[str, Any],
        tool_names: OpenAIToolNameCodec,
        tool_schemas: dict[str, ToolSchema],
        reserved_tool_ids: frozenset[str],
        output_factory: _ChatOutputFactory,
        input_tokens: int,
        request_id: str | None,
        response_model: str,
        reasoning: ReasoningPolicy,
        endpoint_context: EndpointContext | None = None,
        extra_headers: Mapping[str, str] | None = None,
        reasoning_correction: ReasoningCorrection | None = None,
        continuation: ContinuationSeed | None = None,
    ) -> None:
        self._transport = transport
        self._body = body
        self._continuation = continuation
        self._tool_argument_aliases = transport._behavior.tool_argument_aliases(body)
        self._tool_names = tool_names
        self._tool_schemas = tool_schemas
        self._reserved_tool_ids = reserved_tool_ids
        self._output_factory = output_factory
        self._input_tokens = input_tokens
        self._request_id = request_id
        self._response_model = response_model
        self._reasoning = reasoning
        self._reasoning_correction = reasoning_correction
        self._extra_headers = dict(extra_headers or {})
        self._terminal_failure: ExecutionFailure | None = None
        self._request_client = OpenAIRequestClient(transport._endpoint_transport)
        self._endpoint = (
            RequestEndpoint(endpoint_context) if endpoint_context is not None else None
        )

    async def run(self) -> AsyncIterator[str]:
        """Convert the upstream OpenAI-chat stream into Anthropic SSE."""
        execution = self._transport._admission.start_execution(
            request_id=self._request_id
        )
        recovery = RecoveryController(execution.delivery)
        request_recovery = RequestRecovery(
            execution, endpoint=self._endpoint, stream=recovery
        )
        provider_stream = self._run_execution(request_recovery, recovery)
        try:
            async for event in provider_stream:
                yield event
        except asyncio.CancelledError:
            raise
        except Exception as error:
            execution.fail(error)
            raise
        else:
            if self._terminal_failure is None:
                execution.succeed()
            else:
                execution.fail(self._terminal_failure)
        finally:
            try:
                await maybe_await_aclose(provider_stream)
            finally:
                try:
                    await self._request_client.aclose()
                finally:
                    execution.abandon()

    async def _run_execution(
        self,
        request_recovery: RequestRecovery,
        recovery: RecoveryController,
    ) -> AsyncIterator[str]:
        """Run one provider execution while retaining transport-owned state."""
        tag = self._transport._provider_name
        req_tag = f" request_id={self._request_id}" if self._request_id else ""
        execution = request_recovery.execution

        def hold_event(event: str) -> Iterator[str]:
            yield from recovery.push(event)

        body = self._body
        continuation_request = ContinuationRequest("chat")
        operation_kind = ProviderOperationKind.GENERATION
        if self._continuation is not None:
            body = continuation_request.build(
                body, self._continuation.text, self._continuation.thinking
            )
            operation_kind = ProviderOperationKind.CONTINUATION
        request_stream_usage(body)
        output_reasoning = self._reasoning.output_enabled
        corrections = RequestCorrections("chat", self._reasoning_correction)
        trace_event(
            lambda: {"body": provider_chat_body_snapshot(body)},
            stage="provider",
            event="provider.request.sent",
            source="provider",
            provider=tag,
            request_id=self._request_id,
            execution_id=execution.execution_id,
            gateway_model=self._response_model,
            downstream_model=body.get("model"),
            message_count=len(body.get("messages", [])),
            tool_count=len(body.get("tools", [])),
        )

        source: SourceRecoveryState | None = None
        while True:
            assembler = self._new_stream_assembler(output_reasoning=output_reasoning)
            source = SourceRecoveryState(execution, previous=source)

            def observe_chunk(
                chunk: Any,
                assembler: _OpenAIChatStreamAssembler = assembler,
                source: SourceRecoveryState = source,
                operation_kind: ProviderOperationKind = operation_kind,
            ) -> None:
                assembler.observe_upstream_chunk(chunk)
                source.observe(
                    "chat",
                    {
                        "usage": {
                            key: value
                            for key in (
                                "prompt_tokens",
                                "completion_tokens",
                                "total_tokens",
                            )
                            if (value := usage_int(getattr(chunk, "usage", None), key))
                            is not None
                        },
                        "choices": [
                            {
                                "delta": {
                                    "reasoning_details": getattr(
                                        getattr(choice, "delta", None),
                                        "reasoning_details",
                                        None,
                                    ),
                                    "audio": getattr(
                                        getattr(choice, "delta", None), "audio", None
                                    ),
                                }
                            }
                            for choice in (getattr(chunk, "choices", None) or ())
                        ],
                    },
                    continuing=operation_kind is ProviderOperationKind.CONTINUATION,
                )

            scope: ProviderAttemptScope | None = None
            try:
                stream, body, attempt, sent_body = await self._transport._create_stream(
                    body,
                    request_recovery,
                    operation_kind,
                    corrections=corrections,
                    endpoint=self._endpoint,
                    request_client=self._request_client,
                    extra_headers=self._extra_headers,
                    on_event=observe_chunk,
                )
                scope = ProviderAttemptScope(
                    attempt,
                    provider_name=tag,
                    request_id=self._request_id,
                )
                stream = scope.retain(stream)
                assembler.bind_tool_argument_aliases(self._tool_argument_aliases)
                async with recovery.read_stream(stream) as chunks:
                    async for chunk in chunks:
                        if chunk is HoldbackSignal.EXPIRED:
                            for event in recovery.flush():
                                yield event
                            continue
                        if not scope.attempt.accepted:
                            await scope.attempt.accept()
                        for event in assembler.start_events():
                            for out_event in hold_event(event):
                                yield out_event
                        for event in assembler.feed(chunk):
                            for out_event in hold_event(event):
                                yield out_event

                for event in assembler.finish_upstream():
                    for out_event in hold_event(event):
                        yield out_event
                break

            except asyncio.CancelledError, GeneratorExit:
                raise
            except Exception as error:
                if scope is not None:
                    corrected_body = await request_recovery.retry_request(
                        error,
                        provider_authentication_status(error),
                        scope.attempt,
                        body,
                        operation_kind=operation_kind,
                        normal_stop_seen=assembler.normal_stop_seen,
                        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:
                        body = corrected_body
                        recovery.discard()
                        continue
                if (
                    execution.delivery is not None
                    and execution.delivery.content_released
                ):
                    if scope is not None:
                        await scope.aclose(active_error=error)
                    recovered = public_recovery(
                        execution,
                        body=body,
                        request=continuation_request,
                        retryable=is_retryable_stream_error(error),
                        normal_stop_seen=assembler.normal_stop_seen,
                        source=source,
                    )
                    if recovered is not None:
                        recovery.discard()
                        if recovered.body is None:
                            return
                        body = recovered.body
                        operation_kind = ProviderOperationKind.CONTINUATION
                        corrections = RequestCorrections(
                            "chat", self._reasoning_correction
                        )
                        continue
                resolution = await self._resolve_attempt_failure(
                    error=error,
                    scope=scope,
                    assembler=assembler,
                    source=source,
                    body=body,
                    request_recovery=request_recovery,
                    recovery=recovery,
                    req_tag=req_tag,
                )
                if resolution.outcome is _OpenAIChatFailureOutcome.RETRY:
                    continue
                for event in resolution.events:
                    yield event
                if resolution.outcome is _OpenAIChatFailureOutcome.COMPLETE:
                    self._terminal_failure = resolution.failure
                    return
                if resolution.failure is None:
                    raise AssertionError(
                        "raise resolution requires a failure"
                    ) from error
                raise resolution.failure from error
            finally:
                if scope is not None:
                    await scope.aclose(active_error=sys.exception())

        for event in assembler.prepare_completion(
            pad_empty=operation_kind is ProviderOperationKind.GENERATION
        ):
            for out_event in hold_event(event):
                yield out_event
        completion = assembler.completion
        if completion.provider_input_tokens is not None:
            logger.debug(
                "TOKEN_ESTIMATE: our={} provider={} diff={:+d}",
                self._input_tokens,
                completion.provider_input_tokens,
                completion.provider_input_tokens - self._input_tokens,
            )
        trace_event(
            stage="provider",
            event="provider.response.completed",
            source="provider",
            provider=tag,
            request_id=self._request_id,
            finish_reason=(
                None
                if completion.finish_reason is None
                else str(completion.finish_reason)
            ),
            output_tokens=completion.output_tokens,
            prompt_tokens=completion.input_tokens,
            prompt_tokens_estimate=self._input_tokens,
        )
        usage = ChatStreamUsage(
            input_tokens=completion.input_tokens,
            output_tokens=completion.output_tokens,
            cached_tokens=self._transport._behavior.cached_input_tokens(
                assembler.usage_info
            )
            or 0,
            cache_write_tokens=self._transport._behavior.cache_write_input_tokens(
                assembler.usage_info
            ),
            reasoning_tokens=(
                nested_usage_int(
                    assembler.usage_info,
                    "completion_tokens_details",
                    "reasoning_tokens",
                )
                or 0
            ),
            anthropic_fields=self._transport._behavior.anthropic_usage_fields(
                assembler.usage_info
            ),
        )
        for event in assembler.terminal_events(usage=usage):
            for out_event in hold_event(event):
                yield out_event
        for event in recovery.flush():
            yield event

    async def _resolve_attempt_failure(
        self,
        *,
        error: Exception,
        scope: ProviderAttemptScope | None,
        assembler: _OpenAIChatStreamAssembler,
        source: SourceRecoveryState,
        body: dict[str, Any],
        request_recovery: RequestRecovery,
        recovery: RecoveryController,
        req_tag: str,
    ) -> _OpenAIChatFailureResolution:
        """Resolve one failed generation attempt without owning retry policy."""
        execution = request_recovery.execution
        attempt_failure = None
        if scope is not None and not scope.attempt.accepted:
            if (
                assembler.normal_stop_seen
                and execution.delivery is not None
                and not execution.delivery.content_released
            ):
                # The raw stop proves acceptance even if normalization rejected it.
                # Do not reserve a retry probe for this terminal execution.
                await scope.attempt.accept()
            else:
                attempt_failure = await scope.attempt.fail(
                    error,
                    provider_failure_override=self._transport._behavior.failure_override,
                )

        retryable = (
            attempt_failure.retryable
            if attempt_failure is not None
            else is_retryable_stream_error(error)
        )
        generated_output = assembler.generated_output
        identity_failure = isinstance(error, AmbiguousToolCallIdentityError)
        complete_tool_salvageable = (
            not identity_failure and assembler.complete_tool_salvageable
        )
        if identity_failure and execution.delivery is None:
            # Schema-valid arguments cannot prove which call owned a fragment.
            # Only private output still held here can be discarded and replayed.
            action = RecoveryFailureAction.FINAL_ERROR
            if (
                retryable
                and not recovery.committed
                and not assembler.normal_stop_seen
                and execution.can_attempt
            ):
                recovery.discard()
                action = RecoveryFailureAction.EARLY_RETRY
            decision = RecoveryDecision(
                action=action,
                retryable=retryable,
                committed=recovery.committed,
                has_buffered=recovery.has_buffered,
            )
        else:
            decision = recovery.advance_failure(
                retryable=retryable,
                stream_opened=scope is not None,
                generated_output=generated_output,
                complete_tool_salvageable=complete_tool_salvageable,
                attempts_remaining=execution.attempts_remaining,
                normal_stop_seen=assembler.normal_stop_seen,
            )
        tag = self._transport._provider_name
        if decision.action == RecoveryFailureAction.EARLY_RETRY:
            trace_event(
                stage="provider",
                event="provider.recovery.early_retry",
                source="provider",
                provider=tag,
                request_id=self._request_id,
                attempts_started=execution.attempts_started,
                max_attempts=execution.max_attempts,
                retryable=True,
            )
            return _OpenAIChatFailureResolution(outcome=_OpenAIChatFailureOutcome.RETRY)

        if (
            decision.action == RecoveryFailureAction.MIDSTREAM_RECOVERY
            and execution.delivery is None
        ):
            if scope is not None:
                await scope.aclose(active_error=error)
            try:
                recovery_events = await self._recovery_events(
                    body=body,
                    assembler=assembler,
                    error=error,
                    tool_argument_alias_buffers=(assembler.tool_argument_alias_buffers),
                    output_reasoning=self._reasoning.output_enabled,
                    request_recovery=request_recovery,
                )
            except Exception as recovery_error:
                trace_event(
                    stage="provider",
                    event="provider.recovery.failed",
                    source="provider",
                    provider=tag,
                    request_id=self._request_id,
                    exc_type=type(recovery_error).__name__,
                )
                recovery_failure = classify_provider_failure(
                    underlying_provider_error(recovery_error),
                    provider_name=tag,
                    read_timeout_s=self._transport._read_timeout_s,
                    request_id=self._request_id,
                    provider_failure_override=(
                        self._transport._behavior.failure_override
                    ),
                )
                if recovery_failure.kind is FailureKind.CONTEXT_WINDOW_EXCEEDED:
                    error = recovery_failure
                recovery_events = None
            if recovery_events is not None:
                return _OpenAIChatFailureResolution(
                    outcome=_OpenAIChatFailureOutcome.COMPLETE,
                    events=(
                        *recovery.flush_uncommitted(decision),
                        *recovery_events,
                    ),
                )

        reported_error = underlying_provider_error(error)
        self._transport._log_stream_transport_error(
            tag,
            req_tag,
            reported_error,
            request_id=self._request_id,
        )
        failure = classify_provider_failure(
            reported_error,
            provider_name=tag,
            read_timeout_s=self._transport._read_timeout_s,
            request_id=self._request_id,
            provider_failure_override=self._transport._behavior.failure_override,
        )
        error_trace: dict[str, Any] = {
            "stage": "provider",
            "event": "provider.response.error",
            "source": "provider",
            "provider": tag,
            "request_id": self._request_id,
            "exc_type": type(reported_error).__name__,
            "failure_kind": failure.kind.value,
            "status_code": failure.status_code,
            "provider_retryable": failure.retryable,
        }
        if self._transport._log_api_error_tracebacks:
            error_trace["error_message"] = failure.message
        trace_event(**error_trace)

        if execution.delivery is not None:
            recovery.discard()
            return _OpenAIChatFailureResolution(
                outcome=_OpenAIChatFailureOutcome.RAISE,
                failure=public_stream_failure(
                    failure,
                    source=source,
                    body=body,
                    protocol="chat",
                    normal_stop_seen=assembler.normal_stop_seen,
                    responses_failure_payload=assembler.output.failure_payload(failure),
                ),
            )

        failure_events: list[str] = []
        if (
            not decision.committed
            and decision.has_buffered
            and complete_tool_salvageable
        ):
            failure_events.extend(recovery.flush())
        elif not decision.committed:
            recovery.discard()
            return _OpenAIChatFailureResolution(
                outcome=_OpenAIChatFailureOutcome.RAISE,
                failure=failure,
            )
        output = assembler.output
        if output.consumes_terminal_failure:
            failure_events.extend(output.finish_failure(failure))
            return _OpenAIChatFailureResolution(
                outcome=_OpenAIChatFailureOutcome.COMPLETE,
                events=tuple(failure_events),
                failure=failure,
            )
        failure_events.extend(output.close_unclosed_blocks())
        return _OpenAIChatFailureResolution(
            outcome=_OpenAIChatFailureOutcome.RAISE,
            events=tuple(failure_events),
            failure=failure,
        )

    async def _collect_recovery_output(
        self,
        body: dict[str, Any],
        *,
        include_reasoning: bool,
        request_recovery: RequestRecovery,
        operation_kind: ProviderOperationKind,
        corrections: RequestCorrections | None = None,
    ) -> _CollectedRecoveryOutput:
        """Collect one complete buffered continuation response."""
        execution = request_recovery.execution
        if corrections is None:
            corrections = RequestCorrections("chat")
        last_error: Exception | None = None
        while execution.can_attempt:
            scope: ProviderAttemptScope | None = None
            terminal_seen = False
            try:
                (
                    stream,
                    body,
                    attempt,
                    _sent_body,
                ) = await self._transport._create_stream(
                    body,
                    request_recovery,
                    operation_kind,
                    corrections=corrections,
                    endpoint=self._endpoint,
                    request_client=self._request_client,
                    extra_headers=self._extra_headers,
                )
                scope = ProviderAttemptScope(
                    attempt,
                    provider_name=self._transport._provider_name,
                    request_id=self._request_id,
                )
                stream = scope.retain(stream)
                text_parts: list[str] = []
                thinking_parts: list[str] = []
                tool_calls = OpenAIToolCallCollector()
                async for chunk in stream:
                    if not scope.attempt.accepted:
                        await scope.attempt.accept()
                    if not getattr(chunk, "choices", None):
                        continue
                    choice = chunk.choices[0]
                    finish_reason = choice.finish_reason
                    if is_context_window_finish_reason(finish_reason):
                        raise context_window_exceeded_provider_failure()
                    if finish_reason is not None:
                        terminal_seen = True
                    delta = choice.delta
                    if delta is None:
                        continue
                    if include_reasoning:
                        reasoning = self._transport._profile.reasoning_delta(delta)
                        if reasoning:
                            thinking_parts.append(reasoning)
                    content = getattr(delta, "content", None)
                    if isinstance(content, str) and content:
                        text_parts.append(content)
                    native_tool_calls = getattr(delta, "tool_calls", None)
                    if isinstance(native_tool_calls, list | tuple):
                        for tool_call in native_tool_calls:
                            tool_calls.add(tool_call)

                completed_tool_calls = tool_calls.completed_calls(
                    self._tool_schemas,
                    tool_names=self._tool_names,
                    tool_argument_aliases=self._tool_argument_aliases,
                )
                if tool_calls.has_calls and completed_tool_calls is None:
                    raise TruncatedProviderStreamError(
                        "Recovery stream ended with an incomplete tool call."
                    )
                if not terminal_seen and not completed_tool_calls:
                    raise TruncatedProviderStreamError(
                        "Recovery stream ended without finish_reason."
                    )
                return _CollectedRecoveryOutput(
                    text="".join(text_parts),
                    thinking="".join(thinking_parts),
                    tool_calls=completed_tool_calls or (),
                    request_body=body,
                )
            except Exception as error:
                last_error = error
                retryable = is_retryable_stream_error(error)
                if scope is not None and not scope.attempt.accepted:
                    failure = await scope.attempt.fail(
                        error,
                        provider_failure_override=(
                            self._transport._behavior.failure_override
                        ),
                    )
                    retryable = failure.retryable
                if (
                    not retryable
                    or not execution.can_attempt
                    or (
                        isinstance(error, AmbiguousToolCallIdentityError)
                        and terminal_seen
                    )
                ):
                    raise
                trace_event(
                    stage="provider",
                    event="provider.recovery.retry",
                    source="provider",
                    provider=self._transport._provider_name,
                    recovery_kind="openai_text",
                    attempts_started=execution.attempts_started,
                    max_attempts=execution.max_attempts,
                    exc_type=type(error).__name__,
                )
            finally:
                if scope is not None:
                    await scope.aclose(active_error=sys.exception())
        if last_error is not None:
            raise last_error
        return _CollectedRecoveryOutput(
            text="",
            thinking="",
            tool_calls=(),
            request_body=body,
        )

    async def _recovery_events(
        self,
        *,
        body: dict[str, Any],
        assembler: _OpenAIChatStreamAssembler,
        error: Exception,
        tool_argument_alias_buffers: Mapping[int, str],
        output_reasoning: bool,
        request_recovery: RequestRecovery,
    ) -> list[str] | None:
        """Build terminal recovery events when the interrupted stream permits it."""
        output = assembler.output
        if output.has_emitted_tool_block():
            if not output.can_salvage_tool_use(self._tool_schemas):
                repair_events = await self._repair_tool_args(
                    body=body,
                    output=output,
                    tool_argument_alias_buffers=tool_argument_alias_buffers,
                    request_recovery=request_recovery,
                )
                if repair_events is None:
                    return None
            else:
                repair_events = []
            events = list(repair_events)
            events.extend(
                output.finish_success(
                    stop_reason="end_turn",
                    usage=ChatStreamUsage(
                        input_tokens=self._input_tokens,
                        output_tokens=output.estimate_output_tokens(),
                    ),
                )
            )
            trace_event(
                stage="provider",
                event="provider.recovery.tool_salvaged",
                source="provider",
                provider=self._transport._provider_name,
                request_id=self._request_id,
            )
            return events

        partial_text = output.accumulated_text
        partial_thinking = output.accumulated_reasoning
        if not partial_text and not partial_thinking:
            return None

        if isinstance(error, RetryableToolProtocolError):
            recovery_body = make_response_recovery_body(
                body,
                partial_text,
                partial_thinking,
            )
        else:
            recovery_body = make_text_recovery_body(
                body,
                partial_text,
                partial_thinking,
            )
        recovered = await self._collect_recovery_output(
            recovery_body,
            include_reasoning=output_reasoning,
            request_recovery=request_recovery,
            operation_kind=ProviderOperationKind.CONTINUATION,
        )
        text_suffix = continuation_suffix(partial_text, recovered.text)
        thinking_suffix = continuation_suffix(partial_thinking, recovered.thinking)
        if not (thinking_suffix or text_suffix or recovered.tool_calls):
            return None
        events = output.flush_reasoning_replay(completed=False)
        if thinking_suffix:
            events.extend(output.ensure_reasoning_block())
            events.append(output.emit_reasoning_delta(thinking_suffix))
        if text_suffix:
            events.extend(output.ensure_text_block())
            events.append(output.emit_text_delta(text_suffix))
        if recovered.tool_calls:
            events.extend(output.close_content_blocks())
            events.extend(assembler.recovered_tool_call_events(recovered.tool_calls))
        if not events:
            return None
        events.extend(
            output.finish_success(
                stop_reason="end_turn",
                usage=ChatStreamUsage(
                    input_tokens=self._input_tokens,
                    output_tokens=output.estimate_output_tokens(),
                ),
            )
        )
        trace_event(
            stage="provider",
            event="provider.recovery.continued",
            source="provider",
            provider=self._transport._provider_name,
            request_id=self._request_id,
        )
        return events

    async def _repair_tool_args(
        self,
        *,
        body: dict[str, Any],
        output: ChatStreamOutput,
        tool_argument_alias_buffers: Mapping[int, str],
        request_recovery: RequestRecovery,
    ) -> list[str] | None:
        execution = request_recovery.execution
        schemas = self._tool_schemas
        events: list[str] = []
        for tool_index, state in output.started_tool_states():
            block = output.tool_block_for_tool_index(tool_index)
            emitted_prefix = block.content if block is not None else ""
            repair_prefix = emitted_prefix
            if not repair_prefix and tool_index in tool_argument_alias_buffers:
                repair_prefix = tool_argument_alias_buffers[tool_index]
            if (
                parse_complete_tool_input(repair_prefix, state.name, schemas)
                is not None
            ):
                if not emitted_prefix and repair_prefix:
                    events.append(output.emit_tool_delta(tool_index, repair_prefix))
                continue

            schema = schemas.get(state.name)
            recovery_body = make_tool_repair_body(
                body,
                tool_name=state.name,
                prefix=repair_prefix,
                input_schema=schema.input_schema if schema is not None else None,
            )
            accepted_suffix: str | None = None
            repair_attempt = 0
            corrections = RequestCorrections("chat")
            while execution.can_attempt:
                repair_attempt += 1
                recovered = await self._collect_recovery_output(
                    recovery_body,
                    include_reasoning=False,
                    request_recovery=request_recovery,
                    operation_kind=ProviderOperationKind.TOOL_REPAIR,
                    corrections=corrections,
                )
                repair = accept_tool_json_repair(
                    repair_prefix,
                    recovered.text,
                    tool_name=state.name,
                    schemas=schemas,
                )
                if repair is not None:
                    accepted_suffix = repair.suffix
                    trace_event(
                        stage="provider",
                        event="provider.recovery.tool_repaired",
                        source="provider",
                        provider=self._transport._provider_name,
                        tool_name=state.name,
                        attempt=repair_attempt,
                    )
                    break
                recovery_body = recovered.request_body
            if accepted_suffix is None:
                return None
            to_emit = (
                accepted_suffix if emitted_prefix else repair_prefix + accepted_suffix
            )
            if to_emit:
                events.append(output.emit_tool_delta(tool_index, to_emit))
        if not output.can_salvage_tool_use(schemas):
            return None
        return events

    def _new_stream_assembler(
        self, *, output_reasoning: bool
    ) -> _OpenAIChatStreamAssembler:
        def extra_reasoning_events(
            delta: Any, output: ChatStreamOutput
        ) -> Iterator[str]:
            yield from self._transport._behavior.extra_reasoning_events(
                delta,
                output,
                output_reasoning=output_reasoning,
            )

        return _OpenAIChatStreamAssembler(
            output=self._output_factory(),
            profile=self._transport._profile,
            provider_name=self._transport._provider_name,
            output_reasoning=output_reasoning,
            tool_names=self._tool_names,
            tool_schemas=self._tool_schemas,
            tool_calls=OpenAIToolCallAssembler(
                reserved_tool_ids=self._reserved_tool_ids,
                record_extra_content=self._transport._behavior.record_tool_call_extra_content,
            ),
            extra_reasoning_events=extra_reasoning_events,
        )