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
Refactor Responses streaming into package (#932)
Ali Khokhar156a5d55c1f1
diff --git a/ARCHITECTURE.md b/ARCHITECTURE.mdindex 746b3ca8..1f9647c1 100644--- a/ARCHITECTURE.md+++ b/ARCHITECTURE.md@@ -417,11 +417,13 @@ streaming. Request conversion, stream transformation, Anthropic SSE parsing,Responses SSE event formatting, output item construction, tool identity mapping,reasoning mapping, ID generation, and error envelope construction each livebehind the adapter boundary. `stream.py` is the public streaming entrypoint;-`stream_state.py` owns the block-indexed Responses output ledger used to-preserve streamed item order, pending block finalization, and terminal response-lifecycle events. API code should depend on the adapter, not on those internal-module owners directly. Responses output payloads stay OpenAI-shaped; Anthropic-terminal metadata is used internally only when it affects streamed behavior.+[core/openai_responses/streaming/](core/openai_responses/streaming/) owns the+block-indexed Responses stream assembler. The package separates Anthropic SSE+dispatch, block state, output ledger ordering, block completion, SSE event+builders, and error mapping. API code should depend on the adapter, not on+those internal module owners directly. Responses output payloads stay+OpenAI-shaped; Anthropic terminal metadata is used internally only when it+affects streamed behavior.Responses custom tools are also boundary-owned. The adapter accepts nativeResponses `custom` tool declarations, represents them internally as Anthropicdiff --git a/core/openai_responses/stream.py b/core/openai_responses/stream.pyindex 78cdb66a..8de78c72 100644--- a/core/openai_responses/stream.py+++ b/core/openai_responses/stream.py@@ -6,7 +6,7 @@ from collections.abc import AsyncIterable, AsyncIterator, Mappingfrom typing import Anyfrom .anthropic_sse import iter_sse_events-from .stream_state import ResponsesStreamAssembler+from .streaming import ResponsesStreamAssemblerasync def iter_responses_sse_from_anthropic(diff --git a/core/openai_responses/stream_state.py b/core/openai_responses/stream_state.pydeleted file mode 100644index 7307a586..00000000--- a/core/openai_responses/stream_state.py+++ /dev/null@@ -1,711 +0,0 @@-"""Block-indexed OpenAI Responses stream assembly."""--from __future__ import annotations--import json-import time-import uuid-from collections.abc import Mapping-from dataclasses import dataclass, field-from typing import Any, Literal--from core.trace import trace_event--from .anthropic_sse import AnthropicSseEvent-from .errors import ResponsesConversionError-from .events import format_response_sse_event-from .ids import (- new_call_id,- new_message_item_id,- new_reasoning_item_id,- new_response_id,-)-from .items import (- encrypted_reasoning_item,- message_item,- reasoning_item,-)-from .tools import (- custom_tool_input_text_from_arguments,- normalized_function_call_arguments,- responses_tool_identity_from_anthropic_name,-)-from .usage import estimate_text_tokens---@dataclass(slots=True)-class _TextBlockState:- index: int- output_index: int- item_id: str- text_parts: list[str] = field(default_factory=list)---@dataclass(slots=True)-class _ReasoningBlockState:- index: int- output_index: int- item_id: str- text_parts: list[str] = field(default_factory=list)- encrypted_content: str | None = None---@dataclass(slots=True)-class _ToolBlockState:- index: int- output_index: int- item_id: str- call_id: str- kind: Literal["function", "custom"]- name: str- namespace: str | None = None- argument_parts: list[str] = field(default_factory=list)---_BlockState = _TextBlockState | _ReasoningBlockState | _ToolBlockState---class ResponsesStreamAssembler:- """Assemble Responses SSE events from indexed Anthropic content blocks."""-- def __init__(self, request: Mapping[str, Any]) -> None:- self._request = request- self._response_id = new_response_id()- self._created_at = int(time.time())- self._output_slots: list[dict[str, Any] | None] = []- self._active_blocks: dict[int, _BlockState] = {}- self._fallback_text_index = -1- self._input_tokens: int | None = None- self._output_tokens: int | None = None- self._reasoning_tokens_estimate = 0- self._started = False- self.terminal = False- self.final_response: dict[str, Any] | None = None-- def process_anthropic_event(self, event: AnthropicSseEvent) -> list[str]:- if self.terminal:- return []-- chunks = self._ensure_started()- if event.event == "content_block_start":- chunks.extend(self._handle_content_block_start(event.data))- elif event.event == "content_block_delta":- chunks.extend(self._handle_content_block_delta(event.data))- elif event.event == "content_block_stop":- chunks.extend(self._handle_content_block_stop(event.data))- elif event.event == "message_delta":- self._handle_message_delta(event.data)- elif event.event == "message_stop":- chunks.extend(self.complete_response())- elif event.event == "error":- chunks.extend(self.fail_response(event.data))- return chunks-- def finish_if_needed(self) -> list[str]:- if self.terminal:- return []- chunks = self._ensure_started()- chunks.extend(self.complete_response())- return chunks-- def response_payload(- self, *, status: str, error: dict[str, Any] | None = None- ) -> dict[str, Any]:- return {- "id": self._response_id,- "object": "response",- "created_at": self._created_at,- "status": status,- "model": str(self._request.get("model", "")),- "output": self._output(),- "parallel_tool_calls": bool(self._request.get("parallel_tool_calls", True)),- "tool_choice": self._request.get("tool_choice", "auto"),- "temperature": self._request.get("temperature"),- "top_p": self._request.get("top_p"),- "max_output_tokens": self._request.get("max_output_tokens"),- "usage": self._usage(),- "error": error,- }-- def complete_response(self) -> list[str]:- chunks = self._flush_active_blocks()- if self.terminal:- return chunks- self.final_response = self.response_payload(status="completed")- chunks.append(- format_response_sse_event(- "response.completed",- {"type": "response.completed", "response": self.final_response},- )- )- self.terminal = True- return chunks-- def fail_response(self, data: Mapping[str, Any]) -> list[str]:- chunks = self._flush_active_blocks()- if self.terminal:- return chunks- error = _openai_error_from_anthropic_error(data)- self.final_response = self.response_payload(status="failed", error=error)- chunks.append(- format_response_sse_event(- "response.failed",- {"type": "response.failed", "response": self.final_response},- )- )- self.terminal = True- return chunks-- def _ensure_started(self) -> list[str]:- if self._started:- return []- self._started = True- return [- format_response_sse_event(- "response.created",- {- "type": "response.created",- "response": self.response_payload(status="in_progress"),- },- )- ]-- def _handle_content_block_start(self, data: Mapping[str, Any]) -> list[str]:- block = data.get("content_block")- if not isinstance(block, dict):- return []- block_type = block.get("type")- index = _event_index(data)- if block_type == "text":- index = self._safe_index(index)- chunks, state = self._start_text_block(index)- if state is None:- return chunks- if text := _string_value(block.get("text")):- chunks.extend(self._emit_text_delta(state, text))- return chunks- if block_type == "thinking":- if index is None:- return []- chunks, state = self._start_reasoning_block(index)- if state is None:- return chunks- if text := _string_value(block.get("thinking")):- chunks.extend(self._emit_reasoning_delta(state, text))- return chunks- if block_type == "redacted_thinking":- if index is None:- return []- chunks, _state = self._start_reasoning_block(- index, encrypted_content=_string_value(block.get("data"))- )- return chunks- if block_type == "tool_use":- if index is None:- return []- return self._start_tool_block(index, block)- return []-- def _handle_content_block_delta(self, data: Mapping[str, Any]) -> list[str]:- delta = data.get("delta")- if not isinstance(delta, dict):- return []- delta_type = delta.get("type")- index = _event_index(data)- if delta_type == "text_delta":- index = self._safe_index(index)- state = self._active_blocks.get(index)- chunks: list[str] = []- if not isinstance(state, _TextBlockState):- chunks, state = self._start_text_block(index)- if state is None:- return chunks- chunks.extend(- self._emit_text_delta(state, _string_value(delta.get("text")))- )- return chunks- if delta_type == "thinking_delta":- if index is None:- return []- state = self._active_blocks.get(index)- chunks = []- if not isinstance(state, _ReasoningBlockState):- chunks, state = self._start_reasoning_block(index)- if state is None:- return chunks- chunks.extend(- self._emit_reasoning_delta(state, _string_value(delta.get("thinking")))- )- return chunks- if delta_type == "input_json_delta":- state = self._active_blocks.get(index) if index is not None else None- if isinstance(state, _ToolBlockState):- state.argument_parts.append(_string_value(delta.get("partial_json")))- return []-- def _handle_content_block_stop(self, data: Mapping[str, Any]) -> list[str]:- index = _event_index(data)- if index is None:- return []- state = self._active_blocks.pop(index, None)- if state is None:- return []- return self._complete_block(state)-- def _handle_message_delta(self, data: Mapping[str, Any]) -> None:- usage = data.get("usage")- if not isinstance(usage, dict):- return- if isinstance(usage.get("input_tokens"), int):- self._input_tokens = usage["input_tokens"]- if isinstance(usage.get("output_tokens"), int):- self._output_tokens = usage["output_tokens"]-- def _start_text_block(self, index: int) -> tuple[list[str], _TextBlockState | None]:- chunks = self._complete_existing_block(index)- if self.terminal:- return chunks, None- output_index = self._reserve_output_slot()- state = _TextBlockState(- index=index,- output_index=output_index,- item_id=new_message_item_id(),- )- self._active_blocks[index] = state- item = {- "id": state.item_id,- "type": "message",- "status": "in_progress",- "role": "assistant",- "content": [],- }- chunks.extend(- [- format_response_sse_event(- "response.output_item.added",- {- "type": "response.output_item.added",- "output_index": output_index,- "item": item,- },- ),- format_response_sse_event(- "response.content_part.added",- {- "type": "response.content_part.added",- "item_id": state.item_id,- "output_index": output_index,- "content_index": 0,- "part": {- "type": "output_text",- "text": "",- "annotations": [],- },- },- ),- ]- )- return chunks, state-- def _start_reasoning_block(- self, index: int, *, encrypted_content: str | None = None- ) -> tuple[list[str], _ReasoningBlockState | None]:- chunks = self._complete_existing_block(index)- if self.terminal:- return chunks, None- output_index = self._reserve_output_slot()- state = _ReasoningBlockState(- index=index,- output_index=output_index,- item_id=new_reasoning_item_id(),- encrypted_content=encrypted_content,- )- self._active_blocks[index] = state- chunks.append(- format_response_sse_event(- "response.output_item.added",- {- "type": "response.output_item.added",- "output_index": output_index,- "item": _reasoning_output_item(state, status="in_progress"),- },- )- )- return chunks, state-- def _start_tool_block(self, index: int, block: Mapping[str, Any]) -> list[str]:- chunks = self._complete_existing_block(index)- if self.terminal:- return chunks- identity = responses_tool_identity_from_anthropic_name(- self._request, _string_value(block.get("name"))- )- state = _ToolBlockState(- index=index,- output_index=self._reserve_output_slot(),- item_id=f"{'ctc' if identity.kind == 'custom' else 'fc'}_"- f"{uuid.uuid4().hex[:24]}",- call_id=_string_value(block.get("id")) or new_call_id(),- kind=identity.kind,- name=identity.name,- namespace=identity.namespace,- )- initial_input = block.get("input")- if (identity.kind == "custom" and initial_input not in (None, {}, "")) or (- isinstance(initial_input, dict) and initial_input- ):- state.argument_parts.append(json.dumps(initial_input))- self._active_blocks[index] = state- chunks.append(- format_response_sse_event(- "response.output_item.added",- {- "type": "response.output_item.added",- "output_index": state.output_index,- "item": self._tool_item(state, status="in_progress"),- },- )- )- return chunks-- def _emit_text_delta(self, state: _TextBlockState, text: str) -> list[str]:- if not text:- return []- state.text_parts.append(text)- return [- format_response_sse_event(- "response.output_text.delta",- {- "type": "response.output_text.delta",- "item_id": state.item_id,- "output_index": state.output_index,- "content_index": 0,- "delta": text,- },- )- ]-- def _emit_reasoning_delta(- self, state: _ReasoningBlockState, text: str- ) -> list[str]:- if not text:- return []- state.text_parts.append(text)- return [- format_response_sse_event(- "response.reasoning_text.delta",- {- "type": "response.reasoning_text.delta",- "item_id": state.item_id,- "output_index": state.output_index,- "content_index": 0,- "delta": text,- },- )- ]-- def _complete_existing_block(self, index: int) -> list[str]:- existing = self._active_blocks.pop(index, None)- if existing is None:- return []- return self._complete_block(existing)-- def _complete_block(self, state: _BlockState) -> list[str]:- if isinstance(state, _TextBlockState):- return self._complete_text_block(state)- if isinstance(state, _ReasoningBlockState):- return self._complete_reasoning_block(state)- return self._complete_tool_block(state)-- def _complete_text_block(self, state: _TextBlockState) -> list[str]:- text = "".join(state.text_parts)- item = message_item(state.item_id, text, "completed")- self._commit_output(state.output_index, item)- return [- format_response_sse_event(- "response.output_text.done",- {- "type": "response.output_text.done",- "item_id": state.item_id,- "output_index": state.output_index,- "content_index": 0,- "text": text,- },- ),- format_response_sse_event(- "response.content_part.done",- {- "type": "response.content_part.done",- "item_id": state.item_id,- "output_index": state.output_index,- "content_index": 0,- "part": {"type": "output_text", "text": text, "annotations": []},- },- ),- format_response_sse_event(- "response.output_item.done",- {- "type": "response.output_item.done",- "output_index": state.output_index,- "item": item,- },- ),- ]-- def _complete_reasoning_block(self, state: _ReasoningBlockState) -> list[str]:- item = _reasoning_output_item(state, status="completed")- self._commit_output(state.output_index, item)- chunks: list[str] = []- text = "".join(state.text_parts)- if text:- self._reasoning_tokens_estimate += estimate_text_tokens(text)- chunks.append(- format_response_sse_event(- "response.reasoning_text.done",- {- "type": "response.reasoning_text.done",- "item_id": state.item_id,- "output_index": state.output_index,- "content_index": 0,- "text": text,- },- )- )- chunks.append(- format_response_sse_event(- "response.output_item.done",- {- "type": "response.output_item.done",- "output_index": state.output_index,- "item": item,- },- )- )- return chunks-- def _complete_tool_block(self, state: _ToolBlockState) -> list[str]:- if state.kind == "custom":- return self._complete_custom_tool_block(state)- raw_arguments = "".join(state.argument_parts) or "{}"- try:- arguments = normalized_function_call_arguments(raw_arguments)- except ResponsesConversionError as exc:- return self._fail_invalid_function_call(state, exc)- item = self._tool_item(state, status="completed", arguments=arguments)- self._commit_output(state.output_index, item)- chunks: list[str] = []- if arguments:- chunks.append(- format_response_sse_event(- "response.function_call_arguments.delta",- {- "type": "response.function_call_arguments.delta",- "item_id": state.item_id,- "output_index": state.output_index,- "delta": arguments,- },- )- )- chunks.extend(- [- format_response_sse_event(- "response.function_call_arguments.done",- {- "type": "response.function_call_arguments.done",- "item_id": state.item_id,- "output_index": state.output_index,- "arguments": arguments,- },- ),- format_response_sse_event(- "response.output_item.done",- {- "type": "response.output_item.done",- "output_index": state.output_index,- "item": item,- },- ),- ]- )- return chunks-- def _fail_invalid_function_call(- self, state: _ToolBlockState, exc: ResponsesConversionError- ) -> list[str]:- trace_event(- stage="responses",- event="responses.output.function_call_invalid_arguments",- source="openai_responses",- call_id=state.call_id,- tool_name=state.name,- error_type=type(exc).__name__,- )- error = {- "message": (- "Upstream function_call arguments were not a valid JSON object; "- "refusing to emit replay-unsafe Responses output."- ),- "type": "api_error",- "param": None,- "code": None,- }- self.final_response = self.response_payload(status="failed", error=error)- self.terminal = True- return [- format_response_sse_event(- "response.failed",- {"type": "response.failed", "response": self.final_response},- )- ]-- def _complete_custom_tool_block(self, state: _ToolBlockState) -> list[str]:- input_text = custom_tool_input_text_from_arguments(- "".join(state.argument_parts)- )- item = self._tool_item(state, status="completed", input_text=input_text)- self._commit_output(state.output_index, item)- chunks: list[str] = []- if input_text:- chunks.append(- format_response_sse_event(- "response.custom_tool_call_input.delta",- {- "type": "response.custom_tool_call_input.delta",- "item_id": state.item_id,- "output_index": state.output_index,- "delta": input_text,- },- )- )- chunks.extend(- [- format_response_sse_event(- "response.custom_tool_call_input.done",- {- "type": "response.custom_tool_call_input.done",- "item_id": state.item_id,- "output_index": state.output_index,- "input": input_text,- },- ),- format_response_sse_event(- "response.output_item.done",- {- "type": "response.output_item.done",- "output_index": state.output_index,- "item": item,- },- ),- ]- )- return chunks-- def _tool_item(- self,- state: _ToolBlockState,- *,- status: str,- arguments: str = "",- input_text: str = "",- ) -> dict[str, Any]:- if state.kind == "custom":- item = {- "id": state.item_id,- "type": "custom_tool_call",- "status": status,- "call_id": state.call_id,- "name": state.name,- "input": input_text,- }- else:- item = {- "id": state.item_id,- "type": "function_call",- "status": status,- "call_id": state.call_id,- "name": state.name,- "arguments": arguments,- }- if state.namespace:- item["namespace"] = state.namespace- return item-- def _flush_active_blocks(self) -> list[str]:- chunks: list[str] = []- states = sorted(- self._active_blocks.values(), key=lambda state: state.output_index- )- self._active_blocks.clear()- for state in states:- if self.terminal:- break- chunks.extend(self._complete_block(state))- return chunks-- def _reserve_output_slot(self) -> int:- output_index = len(self._output_slots)- self._output_slots.append(None)- return output_index-- def _commit_output(self, output_index: int, item: dict[str, Any]) -> None:- while output_index >= len(self._output_slots):- self._output_slots.append(None)- self._output_slots[output_index] = item-- def _output(self) -> list[dict[str, Any]]:- return [item for item in self._output_slots if item is not None]-- def _usage(self) -> dict[str, Any] | None:- if self._input_tokens is None and self._output_tokens is None:- return None- input_tokens = self._input_tokens or 0- output_tokens = self._output_tokens or 0- usage: dict[str, Any] = {- "input_tokens": input_tokens,- "output_tokens": output_tokens,- "total_tokens": input_tokens + output_tokens,- }- capped_reasoning_tokens = min(self._reasoning_tokens_estimate, output_tokens)- if capped_reasoning_tokens:- usage["output_tokens_details"] = {- "reasoning_tokens": capped_reasoning_tokens- }- return usage-- def _safe_index(self, index: int | None) -> int:- if index is not None:- return index- value = self._fallback_text_index- self._fallback_text_index -= 1- return value---def _event_index(data: Mapping[str, Any]) -> int | None:- value = data.get("index")- return value if isinstance(value, int) else None---def _reasoning_output_item(- state: _ReasoningBlockState, *, status: str-) -> dict[str, Any]:- if state.encrypted_content is not None:- return encrypted_reasoning_item(state.item_id, state.encrypted_content, status)- return reasoning_item(state.item_id, "".join(state.text_parts), status)---def _openai_error_from_anthropic_error(data: Mapping[str, Any]) -> dict[str, Any]:- error = data.get("error")- if not isinstance(error, dict):- error = {"type": "api_error", "message": str(data)}- return {- "message": str(error.get("message", "")),- "type": str(error.get("type", "api_error")),- "param": None,- "code": None,- }---def _string_value(value: Any) -> str:- if value is None:- return ""- return value if isinstance(value, str) else str(value)diff --git a/core/openai_responses/streaming/__init__.py b/core/openai_responses/streaming/__init__.pynew file mode 100644index 00000000..fc3056aa--- /dev/null+++ b/core/openai_responses/streaming/__init__.py@@ -0,0 +1,5 @@+"""OpenAI Responses streaming assembly internals."""++from .assembler import ResponsesStreamAssembler++__all__ = ["ResponsesStreamAssembler"]diff --git a/core/openai_responses/streaming/assembler.py b/core/openai_responses/streaming/assembler.pynew file mode 100644index 00000000..c707b673--- /dev/null+++ b/core/openai_responses/streaming/assembler.py@@ -0,0 +1,330 @@+"""Anthropic SSE to OpenAI Responses stream assembly."""++from __future__ import annotations++import json+import time+import uuid+from collections.abc import Mapping+from typing import Any++from core.trace import trace_event++from ..anthropic_sse import AnthropicSseEvent+from ..errors import ResponsesConversionError+from ..ids import (+ new_call_id,+ new_message_item_id,+ new_reasoning_item_id,+ new_response_id,+)+from ..tools import responses_tool_identity_from_anthropic_name+from . import event_builders as events+from .blocks import ReasoningBlockState, TextBlockState, ToolBlockState+from .completion import ResponseBlockCompleter, reasoning_output_item, tool_item+from .error_mapping import (+ openai_error_from_anthropic_error,+ replay_unsafe_function_call_error,+)+from .ledger import ResponsesOutputLedger+++class ResponsesStreamAssembler:+ """Assemble Responses SSE events from indexed Anthropic content blocks."""++ def __init__(self, request: Mapping[str, Any]) -> None:+ self._request = request+ self._response_id = new_response_id()+ self._created_at = int(time.time())+ self._ledger = ResponsesOutputLedger()+ self._completer = ResponseBlockCompleter(+ self._ledger,+ on_invalid_function_call=self._fail_invalid_function_call,+ )+ self._started = False+ self.terminal = False+ self.final_response: dict[str, Any] | None = None++ def process_anthropic_event(self, event: AnthropicSseEvent) -> list[str]:+ if self.terminal:+ return []++ chunks = self._ensure_started()+ if event.event == "content_block_start":+ chunks.extend(self._handle_content_block_start(event.data))+ elif event.event == "content_block_delta":+ chunks.extend(self._handle_content_block_delta(event.data))+ elif event.event == "content_block_stop":+ chunks.extend(self._handle_content_block_stop(event.data))+ elif event.event == "message_delta":+ self._ledger.record_usage_delta(event.data)+ elif event.event == "message_stop":+ chunks.extend(self.complete_response())+ elif event.event == "error":+ chunks.extend(self.fail_response(event.data))+ return chunks++ def finish_if_needed(self) -> list[str]:+ if self.terminal:+ return []+ chunks = self._ensure_started()+ chunks.extend(self.complete_response())+ return chunks++ def response_payload(+ self, *, status: str, error: dict[str, Any] | None = None+ ) -> dict[str, Any]:+ return {+ "id": self._response_id,+ "object": "response",+ "created_at": self._created_at,+ "status": status,+ "model": str(self._request.get("model", "")),+ "output": self._ledger.output(),+ "parallel_tool_calls": bool(self._request.get("parallel_tool_calls", True)),+ "tool_choice": self._request.get("tool_choice", "auto"),+ "temperature": self._request.get("temperature"),+ "top_p": self._request.get("top_p"),+ "max_output_tokens": self._request.get("max_output_tokens"),+ "usage": self._ledger.usage(),+ "error": error,+ }++ def complete_response(self) -> list[str]:+ chunks = self._flush_active_blocks()+ if self.terminal:+ return chunks+ self.final_response = self.response_payload(status="completed")+ chunks.append(events.response_completed(self.final_response))+ self.terminal = True+ return chunks++ def fail_response(self, data: Mapping[str, Any]) -> list[str]:+ chunks = self._flush_active_blocks()+ if self.terminal:+ return chunks+ error = openai_error_from_anthropic_error(data)+ self.final_response = self.response_payload(status="failed", error=error)+ chunks.append(events.response_failed(self.final_response))+ self.terminal = True+ return chunks++ def _ensure_started(self) -> list[str]:+ if self._started:+ return []+ self._started = True+ return [events.response_created(self.response_payload(status="in_progress"))]++ def _handle_content_block_start(self, data: Mapping[str, Any]) -> list[str]:+ block = data.get("content_block")+ if not isinstance(block, dict):+ return []+ block_type = block.get("type")+ index = _event_index(data)+ if block_type == "text":+ index = self._ledger.safe_text_index(index)+ chunks, state = self._start_text_block(index)+ if state is None:+ return chunks+ if text := _string_value(block.get("text")):+ chunks.extend(self._emit_text_delta(state, text))+ return chunks+ if block_type == "thinking":+ if index is None:+ return []+ chunks, state = self._start_reasoning_block(index)+ if state is None:+ return chunks+ if text := _string_value(block.get("thinking")):+ chunks.extend(self._emit_reasoning_delta(state, text))+ return chunks+ if block_type == "redacted_thinking":+ if index is None:+ return []+ chunks, _state = self._start_reasoning_block(+ index, encrypted_content=_string_value(block.get("data"))+ )+ return chunks+ if block_type == "tool_use":+ if index is None:+ return []+ return self._start_tool_block(index, block)+ return []++ def _handle_content_block_delta(self, data: Mapping[str, Any]) -> list[str]:+ delta = data.get("delta")+ if not isinstance(delta, dict):+ return []+ delta_type = delta.get("type")+ index = _event_index(data)+ if delta_type == "text_delta":+ index = self._ledger.safe_text_index(index)+ state = self._ledger.active_block(index)+ chunks: list[str] = []+ if not isinstance(state, TextBlockState):+ chunks, state = self._start_text_block(index)+ if state is None:+ return chunks+ chunks.extend(+ self._emit_text_delta(state, _string_value(delta.get("text")))+ )+ return chunks+ if delta_type == "thinking_delta":+ if index is None:+ return []+ state = self._ledger.active_block(index)+ chunks = []+ if not isinstance(state, ReasoningBlockState):+ chunks, state = self._start_reasoning_block(index)+ if state is None:+ return chunks+ chunks.extend(+ self._emit_reasoning_delta(state, _string_value(delta.get("thinking")))+ )+ return chunks+ if delta_type == "input_json_delta":+ state = self._ledger.active_block(index) if index is not None else None+ if isinstance(state, ToolBlockState):+ state.argument_parts.append(_string_value(delta.get("partial_json")))+ return []++ def _handle_content_block_stop(self, data: Mapping[str, Any]) -> list[str]:+ index = _event_index(data)+ if index is None:+ return []+ state = self._ledger.pop_active_block(index)+ if state is None:+ return []+ return self._completer.complete_block(state)++ def _start_text_block(self, index: int) -> tuple[list[str], TextBlockState | None]:+ chunks = self._complete_existing_block(index)+ if self.terminal:+ return chunks, None+ output_index = self._ledger.reserve_output_slot()+ state = TextBlockState(+ index=index,+ output_index=output_index,+ item_id=new_message_item_id(),+ )+ self._ledger.set_active_block(state)+ item = {+ "id": state.item_id,+ "type": "message",+ "status": "in_progress",+ "role": "assistant",+ "content": [],+ }+ chunks.extend(+ [+ events.output_item_added(output_index, item),+ events.content_part_added(state.item_id, output_index),+ ]+ )+ return chunks, state++ def _start_reasoning_block(+ self, index: int, *, encrypted_content: str | None = None+ ) -> tuple[list[str], ReasoningBlockState | None]:+ chunks = self._complete_existing_block(index)+ if self.terminal:+ return chunks, None+ output_index = self._ledger.reserve_output_slot()+ state = ReasoningBlockState(+ index=index,+ output_index=output_index,+ item_id=new_reasoning_item_id(),+ encrypted_content=encrypted_content,+ )+ self._ledger.set_active_block(state)+ chunks.append(+ events.output_item_added(+ output_index,+ reasoning_output_item(state, status="in_progress"),+ )+ )+ return chunks, state++ def _start_tool_block(self, index: int, block: Mapping[str, Any]) -> list[str]:+ chunks = self._complete_existing_block(index)+ if self.terminal:+ return chunks+ identity = responses_tool_identity_from_anthropic_name(+ self._request, _string_value(block.get("name"))+ )+ state = ToolBlockState(+ index=index,+ output_index=self._ledger.reserve_output_slot(),+ item_id=f"{'ctc' if identity.kind == 'custom' else 'fc'}_"+ f"{uuid.uuid4().hex[:24]}",+ call_id=_string_value(block.get("id")) or new_call_id(),+ kind=identity.kind,+ name=identity.name,+ namespace=identity.namespace,+ )+ initial_input = block.get("input")+ if (identity.kind == "custom" and initial_input not in (None, {}, "")) or (+ isinstance(initial_input, dict) and initial_input+ ):+ state.argument_parts.append(json.dumps(initial_input))+ self._ledger.set_active_block(state)+ chunks.append(+ events.output_item_added(+ state.output_index,+ tool_item(state, status="in_progress"),+ )+ )+ return chunks++ def _emit_text_delta(self, state: TextBlockState, text: str) -> list[str]:+ if not text:+ return []+ state.text_parts.append(text)+ return [events.output_text_delta(state.item_id, state.output_index, text)]++ def _emit_reasoning_delta(self, state: ReasoningBlockState, text: str) -> list[str]:+ if not text:+ return []+ state.text_parts.append(text)+ return [events.reasoning_text_delta(state.item_id, state.output_index, text)]++ def _complete_existing_block(self, index: int) -> list[str]:+ existing = self._ledger.pop_active_block(index)+ if existing is None:+ return []+ return self._completer.complete_block(existing)++ def _flush_active_blocks(self) -> list[str]:+ chunks: list[str] = []+ for state in self._ledger.pop_active_blocks_by_output_order():+ if self.terminal:+ break+ chunks.extend(self._completer.complete_block(state))+ return chunks++ def _fail_invalid_function_call(+ self, state: ToolBlockState, exc: ResponsesConversionError+ ) -> list[str]:+ trace_event(+ stage="responses",+ event="responses.output.function_call_invalid_arguments",+ source="openai_responses",+ call_id=state.call_id,+ tool_name=state.name,+ error_type=type(exc).__name__,+ )+ error = replay_unsafe_function_call_error()+ self.final_response = self.response_payload(status="failed", error=error)+ self.terminal = True+ return [events.response_failed(self.final_response)]+++def _event_index(data: Mapping[str, Any]) -> int | None:+ value = data.get("index")+ return value if isinstance(value, int) else None+++def _string_value(value: Any) -> str:+ if value is None:+ return ""+ return value if isinstance(value, str) else str(value)diff --git a/core/openai_responses/streaming/blocks.py b/core/openai_responses/streaming/blocks.pynew file mode 100644index 00000000..3226b48e--- /dev/null+++ b/core/openai_responses/streaming/blocks.py@@ -0,0 +1,38 @@+"""Block state for OpenAI Responses streaming assembly."""++from __future__ import annotations++from dataclasses import dataclass, field+from typing import Literal+++@dataclass(slots=True)+class TextBlockState:+ index: int+ output_index: int+ item_id: str+ text_parts: list[str] = field(default_factory=list)+++@dataclass(slots=True)+class ReasoningBlockState:+ index: int+ output_index: int+ item_id: str+ text_parts: list[str] = field(default_factory=list)+ encrypted_content: str | None = None+++@dataclass(slots=True)+class ToolBlockState:+ index: int+ output_index: int+ item_id: str+ call_id: str+ kind: Literal["function", "custom"]+ name: str+ namespace: str | None = None+ argument_parts: list[str] = field(default_factory=list)+++BlockState = TextBlockState | ReasoningBlockState | ToolBlockStatediff --git a/core/openai_responses/streaming/completion.py b/core/openai_responses/streaming/completion.pynew file mode 100644index 00000000..0165d1aa--- /dev/null+++ b/core/openai_responses/streaming/completion.py@@ -0,0 +1,156 @@+"""Block finalization for OpenAI Responses streams."""++from __future__ import annotations++from collections.abc import Callable++from ..errors import ResponsesConversionError+from ..items import encrypted_reasoning_item, message_item, reasoning_item+from ..tools import (+ custom_tool_input_text_from_arguments,+ normalized_function_call_arguments,+)+from . import event_builders as events+from .blocks import BlockState, ReasoningBlockState, TextBlockState, ToolBlockState+from .ledger import ResponsesOutputLedger++InvalidFunctionCallHandler = Callable[+ [ToolBlockState, ResponsesConversionError], list[str]+]+++class ResponseBlockCompleter:+ """Finalize active Responses output blocks."""++ def __init__(+ self,+ ledger: ResponsesOutputLedger,+ *,+ on_invalid_function_call: InvalidFunctionCallHandler,+ ) -> None:+ self._ledger = ledger+ self._on_invalid_function_call = on_invalid_function_call++ def complete_block(self, state: BlockState) -> list[str]:+ if isinstance(state, TextBlockState):+ return self._complete_text_block(state)+ if isinstance(state, ReasoningBlockState):+ return self._complete_reasoning_block(state)+ return self._complete_tool_block(state)++ def _complete_text_block(self, state: TextBlockState) -> list[str]:+ text = "".join(state.text_parts)+ item = message_item(state.item_id, text, "completed")+ self._ledger.commit_output(state.output_index, item)+ return [+ events.output_text_done(state.item_id, state.output_index, text),+ events.content_part_done(state.item_id, state.output_index, text),+ events.output_item_done(state.output_index, item),+ ]++ def _complete_reasoning_block(self, state: ReasoningBlockState) -> list[str]:+ item = _reasoning_output_item(state, status="completed")+ self._ledger.commit_output(state.output_index, item)+ chunks: list[str] = []+ text = "".join(state.text_parts)+ if text:+ self._ledger.add_reasoning_text(text)+ chunks.append(+ events.reasoning_text_done(state.item_id, state.output_index, text)+ )+ chunks.append(events.output_item_done(state.output_index, item))+ return chunks++ def _complete_tool_block(self, state: ToolBlockState) -> list[str]:+ if state.kind == "custom":+ return self._complete_custom_tool_block(state)+ raw_arguments = "".join(state.argument_parts) or "{}"+ try:+ arguments = normalized_function_call_arguments(raw_arguments)+ except ResponsesConversionError as exc:+ return self._on_invalid_function_call(state, exc)+ item = tool_item(state, status="completed", arguments=arguments)+ self._ledger.commit_output(state.output_index, item)+ chunks: list[str] = []+ if arguments:+ chunks.append(+ events.function_call_arguments_delta(+ state.item_id, state.output_index, arguments+ )+ )+ chunks.extend(+ [+ events.function_call_arguments_done(+ state.item_id, state.output_index, arguments+ ),+ events.output_item_done(state.output_index, item),+ ]+ )+ return chunks++ def _complete_custom_tool_block(self, state: ToolBlockState) -> list[str]:+ input_text = custom_tool_input_text_from_arguments(+ "".join(state.argument_parts)+ )+ item = tool_item(state, status="completed", input_text=input_text)+ self._ledger.commit_output(state.output_index, item)+ chunks: list[str] = []+ if input_text:+ chunks.append(+ events.custom_tool_call_input_delta(+ state.item_id, state.output_index, input_text+ )+ )+ chunks.extend(+ [+ events.custom_tool_call_input_done(+ state.item_id, state.output_index, input_text+ ),+ events.output_item_done(state.output_index, item),+ ]+ )+ return chunks+++def tool_item(+ state: ToolBlockState,+ *,+ status: str,+ arguments: str = "",+ input_text: str = "",+) -> dict[str, object]:+ if state.kind == "custom":+ item: dict[str, object] = {+ "id": state.item_id,+ "type": "custom_tool_call",+ "status": status,+ "call_id": state.call_id,+ "name": state.name,+ "input": input_text,+ }+ else:+ item = {+ "id": state.item_id,+ "type": "function_call",+ "status": status,+ "call_id": state.call_id,+ "name": state.name,+ "arguments": arguments,+ }+ if state.namespace:+ item["namespace"] = state.namespace+ return item+++def reasoning_output_item(+ state: ReasoningBlockState, *, status: str+) -> dict[str, object]:+ if state.encrypted_content is not None:+ return encrypted_reasoning_item(state.item_id, state.encrypted_content, status)+ return reasoning_item(state.item_id, "".join(state.text_parts), status)+++def _reasoning_output_item(+ state: ReasoningBlockState, *, status: str+) -> dict[str, object]:+ return reasoning_output_item(state, status=status)diff --git a/core/openai_responses/streaming/error_mapping.py b/core/openai_responses/streaming/error_mapping.pynew file mode 100644index 00000000..fcf71fdf--- /dev/null+++ b/core/openai_responses/streaming/error_mapping.py@@ -0,0 +1,30 @@+"""Responses stream error mapping."""++from __future__ import annotations++from collections.abc import Mapping+from typing import Any+++def openai_error_from_anthropic_error(data: Mapping[str, Any]) -> dict[str, Any]:+ error = data.get("error")+ if not isinstance(error, dict):+ error = {"type": "api_error", "message": str(data)}+ return {+ "message": str(error.get("message", "")),+ "type": str(error.get("type", "api_error")),+ "param": None,+ "code": None,+ }+++def replay_unsafe_function_call_error() -> dict[str, Any]:+ return {+ "message": (+ "Upstream function_call arguments were not a valid JSON object; "+ "refusing to emit replay-unsafe Responses output."+ ),+ "type": "api_error",+ "param": None,+ "code": None,+ }diff --git a/core/openai_responses/streaming/event_builders.py b/core/openai_responses/streaming/event_builders.pynew file mode 100644index 00000000..4fcb8233--- /dev/null+++ b/core/openai_responses/streaming/event_builders.py@@ -0,0 +1,184 @@+"""OpenAI Responses SSE event builders."""++from __future__ import annotations++from typing import Any++from ..events import format_response_sse_event+++def response_created(response: dict[str, Any]) -> str:+ return format_response_sse_event(+ "response.created",+ {"type": "response.created", "response": response},+ )+++def response_completed(response: dict[str, Any]) -> str:+ return format_response_sse_event(+ "response.completed",+ {"type": "response.completed", "response": response},+ )+++def response_failed(response: dict[str, Any]) -> str:+ return format_response_sse_event(+ "response.failed",+ {"type": "response.failed", "response": response},+ )+++def output_item_added(output_index: int, item: dict[str, Any]) -> str:+ return format_response_sse_event(+ "response.output_item.added",+ {+ "type": "response.output_item.added",+ "output_index": output_index,+ "item": item,+ },+ )+++def output_item_done(output_index: int, item: dict[str, Any]) -> str:+ return format_response_sse_event(+ "response.output_item.done",+ {+ "type": "response.output_item.done",+ "output_index": output_index,+ "item": item,+ },+ )+++def content_part_added(item_id: str, output_index: int) -> str:+ return format_response_sse_event(+ "response.content_part.added",+ {+ "type": "response.content_part.added",+ "item_id": item_id,+ "output_index": output_index,+ "content_index": 0,+ "part": {"type": "output_text", "text": "", "annotations": []},+ },+ )+++def output_text_delta(item_id: str, output_index: int, text: str) -> str:+ return format_response_sse_event(+ "response.output_text.delta",+ {+ "type": "response.output_text.delta",+ "item_id": item_id,+ "output_index": output_index,+ "content_index": 0,+ "delta": text,+ },+ )+++def output_text_done(item_id: str, output_index: int, text: str) -> str:+ return format_response_sse_event(+ "response.output_text.done",+ {+ "type": "response.output_text.done",+ "item_id": item_id,+ "output_index": output_index,+ "content_index": 0,+ "text": text,+ },+ )+++def content_part_done(item_id: str, output_index: int, text: str) -> str:+ return format_response_sse_event(+ "response.content_part.done",+ {+ "type": "response.content_part.done",+ "item_id": item_id,+ "output_index": output_index,+ "content_index": 0,+ "part": {"type": "output_text", "text": text, "annotations": []},+ },+ )+++def reasoning_text_delta(item_id: str, output_index: int, text: str) -> str:+ return format_response_sse_event(+ "response.reasoning_text.delta",+ {+ "type": "response.reasoning_text.delta",+ "item_id": item_id,+ "output_index": output_index,+ "content_index": 0,+ "delta": text,+ },+ )+++def reasoning_text_done(item_id: str, output_index: int, text: str) -> str:+ return format_response_sse_event(+ "response.reasoning_text.done",+ {+ "type": "response.reasoning_text.done",+ "item_id": item_id,+ "output_index": output_index,+ "content_index": 0,+ "text": text,+ },+ )+++def function_call_arguments_delta(+ item_id: str, output_index: int, arguments: str+) -> str:+ return format_response_sse_event(+ "response.function_call_arguments.delta",+ {+ "type": "response.function_call_arguments.delta",+ "item_id": item_id,+ "output_index": output_index,+ "delta": arguments,+ },+ )+++def function_call_arguments_done(+ item_id: str, output_index: int, arguments: str+) -> str:+ return format_response_sse_event(+ "response.function_call_arguments.done",+ {+ "type": "response.function_call_arguments.done",+ "item_id": item_id,+ "output_index": output_index,+ "arguments": arguments,+ },+ )+++def custom_tool_call_input_delta(+ item_id: str, output_index: int, input_text: str+) -> str:+ return format_response_sse_event(+ "response.custom_tool_call_input.delta",+ {+ "type": "response.custom_tool_call_input.delta",+ "item_id": item_id,+ "output_index": output_index,+ "delta": input_text,+ },+ )+++def custom_tool_call_input_done(+ item_id: str, output_index: int, input_text: str+) -> str:+ return format_response_sse_event(+ "response.custom_tool_call_input.done",+ {+ "type": "response.custom_tool_call_input.done",+ "item_id": item_id,+ "output_index": output_index,+ "input": input_text,+ },+ )diff --git a/core/openai_responses/streaming/ledger.py b/core/openai_responses/streaming/ledger.pynew file mode 100644index 00000000..c468f9cc--- /dev/null+++ b/core/openai_responses/streaming/ledger.py@@ -0,0 +1,86 @@+"""Output ledger for OpenAI Responses streaming assembly."""++from __future__ import annotations++from collections.abc import Mapping+from typing import Any++from ..usage import estimate_text_tokens+from .blocks import BlockState+++class ResponsesOutputLedger:+ """Track active blocks, reserved output slots, and accumulated usage."""++ def __init__(self) -> None:+ self._output_slots: list[dict[str, Any] | None] = []+ self._active_blocks: dict[int, BlockState] = {}+ self._fallback_text_index = -1+ self._input_tokens: int | None = None+ self._output_tokens: int | None = None+ self._reasoning_tokens_estimate = 0++ def active_block(self, index: int) -> BlockState | None:+ return self._active_blocks.get(index)++ def set_active_block(self, state: BlockState) -> None:+ self._active_blocks[state.index] = state++ def pop_active_block(self, index: int) -> BlockState | None:+ return self._active_blocks.pop(index, None)++ def pop_active_blocks_by_output_order(self) -> list[BlockState]:+ states = sorted(+ self._active_blocks.values(), key=lambda state: state.output_index+ )+ self._active_blocks.clear()+ return states++ def reserve_output_slot(self) -> int:+ output_index = len(self._output_slots)+ self._output_slots.append(None)+ return output_index++ def commit_output(self, output_index: int, item: dict[str, Any]) -> None:+ while output_index >= len(self._output_slots):+ self._output_slots.append(None)+ self._output_slots[output_index] = item++ def output(self) -> list[dict[str, Any]]:+ return [item for item in self._output_slots if item is not None]++ def record_usage_delta(self, data: Mapping[str, Any]) -> None:+ usage = data.get("usage")+ if not isinstance(usage, dict):+ return+ if isinstance(usage.get("input_tokens"), int):+ self._input_tokens = usage["input_tokens"]+ if isinstance(usage.get("output_tokens"), int):+ self._output_tokens = usage["output_tokens"]++ def add_reasoning_text(self, text: str) -> None:+ self._reasoning_tokens_estimate += estimate_text_tokens(text)++ def usage(self) -> dict[str, Any] | None:+ if self._input_tokens is None and self._output_tokens is None:+ return None+ input_tokens = self._input_tokens or 0+ output_tokens = self._output_tokens or 0+ usage: dict[str, Any] = {+ "input_tokens": input_tokens,+ "output_tokens": output_tokens,+ "total_tokens": input_tokens + output_tokens,+ }+ capped_reasoning_tokens = min(self._reasoning_tokens_estimate, output_tokens)+ if capped_reasoning_tokens:+ usage["output_tokens_details"] = {+ "reasoning_tokens": capped_reasoning_tokens+ }+ return usage++ def safe_text_index(self, index: int | None) -> int:+ if index is not None:+ return index+ value = self._fallback_text_index+ self._fallback_text_index -= 1+ return valuediff --git a/pyproject.toml b/pyproject.tomlindex a033e445..2dc4830f 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -4,7 +4,7 @@ build-backend = "hatchling.build"[project]name = "free-claude-code"-version = "2.3.22"+version = "2.3.23"description = "Middleware between Claude Code CLI (Anthropic API) and NVIDIA NIM"readme = "README.md"requires-python = ">=3.14.0"diff --git a/tests/contracts/test_import_boundaries.py b/tests/contracts/test_import_boundaries.pyindex 21a248db..8bbc95af 100644--- a/tests/contracts/test_import_boundaries.py+++ b/tests/contracts/test_import_boundaries.py@@ -278,6 +278,7 @@ def test_anthropic_stream_engine_owns_provider_stream_state() -> None:def test_openai_responses_uses_adapter_boundary() -> None:repo_root = Path(__file__).resolve().parents[2]responses_root = repo_root / "core" / "openai_responses"+ responses_streaming_root = responses_root / "streaming"api_root = repo_root / "api"handlers_root = api_root / "handlers"@@ -286,6 +287,7 @@ def test_openai_responses_uses_adapter_boundary() -> None:assert not (responses_root / "conversion.py").exists()assert not (responses_root / "sse.py").exists()assert not (responses_root / "output.py").exists()+ assert not (responses_root / "stream_state.py").exists()for filename in {"adapter.py","anthropic_sse.py",@@ -296,10 +298,22 @@ def test_openai_responses_uses_adapter_boundary() -> None:"items.py","reasoning.py","stream.py",- "stream_state.py","tools.py",}:assert (responses_root / filename).exists()+ for filename in {+ "__init__.py",+ "assembler.py",+ "blocks.py",+ "completion.py",+ "error_mapping.py",+ "event_builders.py",+ "ledger.py",+ }:+ assert (responses_streaming_root / filename).exists()++ stream_text = (responses_root / "stream.py").read_text(encoding="utf-8")+ assert "from .streaming import ResponsesStreamAssembler" in stream_textresponses_handler = handlers_root / "responses.py"responses_handler_text = responses_handler.read_text(encoding="utf-8")diff --git a/uv.lock b/uv.lockindex 03bf8455..048ab67d 100644--- a/uv.lock+++ b/uv.lock@@ -561,7 +561,7 @@ wheels = [[[package]]name = "free-claude-code"-version = "2.3.22"+version = "2.3.23"source = { editable = "." }dependencies = [{ name = "aiohttp" },