Skip to content

armgit / avibe

Public Imported from GitHub
0

Make your computer a home for your AI partner. Avibe is the local-first Agent OS: Vibey, its built-in AI partner, works out of the box, and Claude Code, Codex & OpenCode run unchanged beside it — reach them from your browser, phone, or any chat app.

feat(agent-core): add native provider adapters (#2339)

Call Whited768a9e23e79
diff --git a/core/agent_core/agent/loop.py b/core/agent_core/agent/loop.py
index 3182a303a..f6f8d1429 100644
--- a/core/agent_core/agent/loop.py
+++ b/core/agent_core/agent/loop.py
@@ -486,6 +486,19 @@ class Agent:
close = getattr(stream, "aclose", None)
if close is not None:
await self._cleanup(close, stream=True)
+ if terminal.partial is not None and terminal.partial.usage is not None and not terminal.partial.content:
+ row = await self._response(terminal.partial, final=False)
+ if not self._consumer_closed:
+ await emit(
+ MessageCommitted,
+ message_id=row.row_id,
+ context_seq=row.context_seq,
+ final=False,
+ )
+ # This attempt has already been durably announced. Keep the
+ # retry decision, but do not carry the same partial through a
+ # later expiry path where _loop would commit it again.
+ terminal = replace(terminal, partial=None)
retry_error = terminal
retries += 1
await self._scope.call(lambda: asyncio.sleep(delay))
@@ -520,6 +533,7 @@ class Agent:
async def _loop(self, system: str, emit: Callable[..., Awaitable[None]], selected: ModelSelection) -> RunEndReason:
first_selection: Optional[ModelSelection] = selected
+ length_tool_retries = 0
while True:
async with self._model(system, emit, first_selection) as (terminal, tools):
first_selection = None
@@ -542,6 +556,8 @@ class Agent:
message = terminal.message
self._validate_response(message)
failed = message.stop_reason in {"error", "aborted"}
+ if not (message.tool_calls and message.stop_reason == "length"):
+ length_tool_retries = 0
if failed:
self._outcome.primary("aborted" if message.stop_reason == "aborted" else "error")
await emit(
@@ -570,6 +586,48 @@ class Agent:
end = True
break
skip = skip or isinstance(decision, SkipTools)
+ if message.tool_calls and message.stop_reason != "tool_use":
+ reason = message.stop_reason
+ skip_reason = (
+ "Tool call was truncated by the output limit; re-issue it with complete arguments."
+ if reason == "length"
+ else f"Tool call not executed because the model stopped with {reason}."
+ )
+ for call in message.tool_calls:
+ self._scope.check()
+ await self._tool(
+ call,
+ tools,
+ True,
+ emit,
+ skip_reason=skip_reason,
+ )
+ if reason == "length":
+ if end:
+ return "ended_by_hook"
+ length_tool_retries += 1
+ # Reuse the bounded loop retry budget so an impossible
+ # tool call cannot spin forever after repeated truncation.
+ if length_tool_retries > self.retry.max_retries:
+ self._open = False
+ self._outcome.primary("error")
+ await emit(
+ AgentError,
+ kind="length",
+ message="The model repeatedly exceeded its output limit while emitting a tool call.",
+ )
+ return "error"
+ await self._drain_steers(emit)
+ continue
+ self._open = False
+ if not failed:
+ self._outcome.primary("error")
+ await emit(
+ AgentError,
+ kind=reason,
+ message=message.error_message or f"Model stopped with {reason}.",
+ )
+ return "aborted" if message.stop_reason == "aborted" else "error"
if failed:
return "aborted" if message.stop_reason == "aborted" else "error"
if not message.tool_calls:
@@ -592,18 +650,21 @@ class Agent:
return "ended_by_hook"
if terminate:
return "completed"
- applied = []
- try:
- async with self._lock:
- while self._steers:
- item = self._steers[0]
- await self._consume(item)
- self._steers.popleft()
- applied.append(item)
- finally:
- if not self._consumer_closed:
- for item in applied:
- await emit(SteerApplied, message_id=item.message_id)
+ await self._drain_steers(emit)
+
+ async def _drain_steers(self, emit: Callable[..., Awaitable[None]]) -> None:
+ applied = []
+ try:
+ async with self._lock:
+ while self._steers:
+ item = self._steers[0]
+ await self._consume(item)
+ self._steers.popleft()
+ applied.append(item)
+ finally:
+ if not self._consumer_closed:
+ for item in applied:
+ await emit(SteerApplied, message_id=item.message_id)
async def _tool(
self,
@@ -611,12 +672,14 @@ class Agent:
tools: Mapping[str, Tool],
skip: bool,
emit: Callable[..., Awaitable[None]],
+ *,
+ skip_reason: str | None = None,
) -> tuple[ToolResult, bool]:
call = deepcopy(original)
end = False
result = None
if skip:
- result = ToolResult((text("[skipped by policy]"),), is_error=True)
+ result = ToolResult((text(skip_reason or "[skipped by policy]"),), is_error=True)
else:
for hook in self.hooks:
decision = await self._hook(lambda: hook.before_tool(call, self._ctx))
diff --git a/core/agent_core/agent/models.py b/core/agent_core/agent/models.py
index c8f13d558..358b0770e 100644
--- a/core/agent_core/agent/models.py
+++ b/core/agent_core/agent/models.py
@@ -7,7 +7,6 @@ from math import isfinite
from typing import Optional, Protocol
from core.agent_core.ai.provider import (
- RETRYABLE_ERROR_KINDS,
ModelCapabilities,
ModelEndpoint,
ProviderAdapter,
@@ -68,12 +67,13 @@ class RetryPolicy:
def delay(self, error: ProviderError, *, retries: int, streamed: bool, elapsed_s: float = 0) -> Optional[float]:
if (
retries >= self.max_retries
- or streamed
- or error.partial is not None
or not error.retryable
- or error.kind not in RETRYABLE_ERROR_KINDS
):
return None
+ # ``ProviderError.retryable`` is the provider boundary decision. The
+ # loop only applies the bounded count/time budget; it must not infer a
+ # second retry boundary from a partial message or its own event count.
+ del streamed
backoff = min(self.max_delay_s, self.initial_delay_s * 2**retries)
delay = max(backoff, error.retry_after_s or 0.0)
return delay if elapsed_s + delay < self.max_elapsed_s else None
diff --git a/core/agent_core/ai/_common.py b/core/agent_core/ai/_common.py
new file mode 100644
index 000000000..bb55f9787
--- /dev/null
+++ b/core/agent_core/ai/_common.py
@@ -0,0 +1,1860 @@
+"""Shared HTTP, origin, and wire-content helpers for native adapters."""
+
+from __future__ import annotations
+
+import asyncio
+import base64
+import io
+import inspect
+import json
+import re
+from collections.abc import AsyncIterator, Awaitable, Callable, Hashable, Mapping
+from dataclasses import dataclass, replace
+from typing import Any, TypeVar
+from urllib.parse import parse_qsl, unquote, unquote_to_bytes, urlencode, urlsplit, urlunsplit
+
+import httpx
+
+from core.agent_core.ai.errors import (
+ _is_sensitive_key,
+ classify_error,
+ parse_retry_after,
+ redact_provider_error,
+)
+from core.agent_core.ai.sse import SSEEvent, SSEParseError, SSEParser
+from core.agent_core.cancel import CancelToken
+from core.agent_core.messages import (
+ AssistantContent,
+ AssistantMessage,
+ ImageBlock,
+ Origin,
+ TextBlock,
+ ThinkingBlock,
+ ToolCallBlock,
+ ToolResultMessage,
+ UserContent,
+)
+from core.agent_core.ai.provider import (
+ BlockEnd,
+ Done,
+ MediaLoader,
+ ModelEndpoint,
+ ProviderError,
+ TextDelta,
+ ThinkingDelta,
+ ToolCallDelta,
+ ToolCallStart,
+)
+
+ServedHopResolver = Callable[
+ [Mapping[str, str]], Origin | None | Awaitable[Origin | None]
+]
+_T = TypeVar("_T")
+WireTranslator = Callable[[AsyncIterator[SSEEvent]], AsyncIterator[Any]]
+
+
+@dataclass(frozen=True)
+class WireField:
+ """Declarative JSON field shape used at native protocol boundaries."""
+
+ name: str
+ expected: type | tuple[type, ...]
+ required: bool = False
+ nullable: bool = True
+ children: tuple["WireField", ...] = ()
+ item_children: tuple["WireField", ...] = ()
+
+# A provider that never produces headers or pauses forever between chunks must
+# not hold an agent turn indefinitely. These bounds are deliberately shared by
+# every native adapter; the loop may retry the resulting network error only
+# when no model output has been emitted.
+CONNECT_TIMEOUT_S = 10.0
+TIME_TO_FIRST_BYTE_TIMEOUT_S = 30.0
+IDLE_CHUNK_TIMEOUT_S = 30.0
+CLEANUP_TIMEOUT_S = 10.0
+MAX_CUMULATIVE_OUTPUT_CHARS = 32 * 1024 * 1024
+# Conservative structural allowances, not a one-byte item counter. These cover
+# block/tool objects and their indexing sets/maps in addition to payload bytes.
+BLOCK_SLOT_OVERHEAD_BYTES = 2048
+TOOL_ALIAS_OVERHEAD_BYTES = 512
+# Only late response closes are detached; retain them until bounded cleanup
+# completes. The driver registers their ownership in its single finally.
+_response_cleanup_tasks: set[asyncio.Task[None]] = set()
+
+
+class OutputBudgetExceeded(ValueError):
+ """A provider exceeded the shared cumulative assembled-output budget."""
+
+
+class WireDispatchError(ValueError):
+ """A known wire frame has an invalid or missing type discriminator."""
+
+
+class ToolIdentityError(ValueError):
+ """A wire frame attempts to rebind an open tool slot to another call."""
+
+
+def _string_buffer(value: str = "") -> io.StringIO:
+ buffer = io.StringIO()
+ buffer.write(value)
+ return buffer
+
+
+def usage_counter_error(
+ value: Any,
+ *,
+ label: str,
+ fields: tuple[str, ...],
+ nested_fields: Mapping[str, tuple[str, ...]] | None = None,
+) -> str | None:
+ """Return an error for present usage counters with the wrong JSON shape."""
+
+ if value is None:
+ return None
+ if not isinstance(value, Mapping):
+ return f"{label} must be an object"
+ for field in fields:
+ raw = value.get(field)
+ if raw is not None and (not isinstance(raw, int) or isinstance(raw, bool) or raw < 0):
+ return f"{label} {field} must be a non-negative integer"
+ for parent, child_fields in (nested_fields or {}).items():
+ nested = value.get(parent)
+ if nested is None:
+ continue
+ if not isinstance(nested, Mapping):
+ return f"{label} {parent} must be an object"
+ for field in child_fields:
+ raw = nested.get(field)
+ if raw is not None and (not isinstance(raw, int) or isinstance(raw, bool) or raw < 0):
+ return f"{label} {parent}.{field} must be a non-negative integer"
+ return None
+
+
+class StreamAssembler:
+ """Own canonical stream state shared by every native protocol adapter.
+
+ Adapter modules translate wire events into these operations. This class
+ owns visible-output accounting, tool-call identity, partial construction,
+ and the exactly-one-terminal invariant.
+ """
+
+ def __init__(
+ self,
+ *,
+ origin: Origin,
+ protocol: str,
+ verified_origin: bool = True,
+ endpoint_url: str | None = None,
+ sensitive_values: tuple[str, ...] = (),
+ ) -> None:
+ self.origin = origin
+ self.protocol = protocol
+ self.verified_origin = verified_origin
+ self._endpoint_url = endpoint_url
+ self._sensitive_values = tuple(value for value in sensitive_values if value)
+ self.content: list[AssistantContent] = []
+ self.usage: Any = None
+ self._terminal_seen = False
+ self._emitted_output = False
+ self._closed_indices: set[int] = set()
+ self._slots: dict[tuple[str, Hashable], int] = {}
+ self._block_kinds: dict[Hashable, str] = {}
+ self._thinking_key_by_index: dict[int, Hashable] = {}
+ self._visible_blocks: set[int] = set()
+ self._tools: dict[Hashable, dict[str, Any]] = {}
+ self._tool_order: list[Hashable] = []
+ self._tool_order_set: set[Hashable] = set()
+ self._tool_id_owners: dict[str, set[Hashable]] = {}
+ self._allocated_tool_ids: set[str] = set()
+ self._next_tool_id = 0
+ self._tool_keys_by_native_id: dict[str, Hashable] = {}
+ self._charged_native_ids: set[str] = set()
+ self._fallback_tool_sequence = 0
+ self._latest_fallback_tool_key: Hashable | None = None
+ self._driver_mode = False
+ self._output_chars = 0
+ self._text_buffers: dict[int, io.StringIO] = {}
+ self._thinking_buffers: dict[int, io.StringIO] = {}
+ self._thinking_signature_buffers: dict[int, io.StringIO] = {}
+ self._thinking_details: dict[Hashable, list[dict[str, Any]]] = {}
+ self._thinking_detail_buffers: dict[tuple[Hashable, int, str], io.StringIO] = {}
+ self._reasoning_items: dict[Hashable, dict[str, Any]] = {}
+ self._reasoning_key_by_id: dict[str, Hashable] = {}
+ self._closed_reasoning_keys: set[Hashable] = set()
+ self._tool_argument_buffers: dict[Hashable, io.StringIO] = {}
+
+ @property
+ def streamed(self) -> bool:
+ """Whether a non-empty model output was exposed to the loop."""
+
+ return self._emitted_output
+
+ def set_origin(self, origin: Origin, verified_origin: bool) -> None:
+ self.origin = origin
+ self.verified_origin = verified_origin
+
+ def begin_driver(self) -> None:
+ """Defer terminal marking while the shared lifecycle driver runs."""
+
+ self._driver_mode = True
+
+ def end_driver(self) -> None:
+ self._driver_mode = False
+
+ def set_usage(self, usage: Any) -> None:
+ if usage is not None:
+ self.usage = usage
+
+ def _account_output(self, value: str | bytes | int) -> None:
+ """Account every byte retained by the canonical stream state."""
+
+ if isinstance(value, int):
+ size = value
+ elif isinstance(value, bytes):
+ size = len(value)
+ else:
+ size = len(value.encode("utf-8"))
+ if size <= 0:
+ return
+ if self._output_chars + size > MAX_CUMULATIVE_OUTPUT_CHARS:
+ raise OutputBudgetExceeded(
+ "provider cumulative output budget exceeded "
+ f"({MAX_CUMULATIVE_OUTPUT_CHARS} bytes)"
+ )
+ self._output_chars += size
+
+ def _account_replacement(self, previous: str, value: str) -> None:
+ """Charge the bytes newly retained by a snapshot replacement."""
+
+ if value.startswith(previous):
+ self._account_output(value[len(previous) :])
+ else:
+ self._account_output(value)
+
+ def _text_value(self, index: int) -> str:
+ buffer = self._text_buffers.get(index)
+ if buffer is not None:
+ return buffer.getvalue()
+ block = self.content[index]
+ return block.text or "" if isinstance(block, TextBlock) else ""
+
+ def _thinking_value(self, index: int) -> str:
+ buffer = self._thinking_buffers.get(index)
+ if buffer is not None:
+ return buffer.getvalue()
+ block = self.content[index]
+ return block.text if isinstance(block, ThinkingBlock) else ""
+
+ def _thinking_signature_value(self, index: int) -> str:
+ key = self._thinking_key_by_index.get(index)
+ if key is not None:
+ self._materialize_thinking_details(key)
+ buffer = self._thinking_signature_buffers.get(index)
+ if buffer is not None:
+ return buffer.getvalue()
+ block = self.content[index]
+ return block.signature or "" if isinstance(block, ThinkingBlock) else ""
+
+ def _tool_arguments_value(self, key: Hashable) -> str:
+ buffer = self._tool_argument_buffers.get(key)
+ return buffer.getvalue() if buffer is not None else ""
+
+ def _materialize_thinking_details(self, key: Hashable) -> None:
+ details = self._thinking_details.get(key)
+ if details is None:
+ return
+ index = self._slots.get(("thinking", key))
+ if index is None:
+ return
+ values = [dict(item) for item in details]
+ for (owner, item_index, field), buffer in self._thinking_detail_buffers.items():
+ if owner == key and item_index < len(values):
+ values[item_index][field] = buffer.getvalue()
+ signature = json.dumps(values, ensure_ascii=False, separators=(",", ":"))
+ block = self.content[index]
+ if isinstance(block, ThinkingBlock):
+ self._thinking_signature_buffers[index] = _string_buffer(signature)
+ self.content[index] = ThinkingBlock(
+ text=self._thinking_value(index),
+ signature=signature,
+ redacted=block.redacted,
+ )
+ self._thinking_details.pop(key, None)
+ for detail_key in tuple(self._thinking_detail_buffers):
+ if detail_key[0] == key:
+ del self._thinking_detail_buffers[detail_key]
+
+ def _materialize_content(self) -> None:
+ """Publish buffered fragments into canonical blocks at a stream boundary."""
+
+ for key in tuple(self._thinking_details):
+ self._materialize_thinking_details(key)
+ for index, block in enumerate(self.content):
+ if isinstance(block, TextBlock):
+ self.content[index] = TextBlock(text=self._text_value(index))
+ elif isinstance(block, ThinkingBlock):
+ self.content[index] = ThinkingBlock(
+ text=self._thinking_value(index),
+ signature=self._thinking_signature_value(index) or None,
+ redacted=block.redacted,
+ )
+
+ def text_delta(self, key: Hashable, value: str) -> TextDelta | None:
+ if not value:
+ return None
+ index = self._ensure_slot("text", key, TextBlock(text=""))
+ if index in self._closed_indices:
+ return None
+ block = self.content[index]
+ if not isinstance(block, TextBlock):
+ return None
+ self._account_output(value)
+ buffer = self._text_buffers.setdefault(index, _string_buffer(block.text or ""))
+ buffer.write(value)
+ self._visible_blocks.add(index)
+ self._emitted_output = True
+ return TextDelta(index=index, delta=value)
+
+ def ensure_text_slot(self, key: Hashable) -> int:
+ return self._ensure_slot("text", key, TextBlock(text=""))
+
+ def merge_text_snapshot(self, key: Hashable, value: str) -> TextDelta | None:
+ if not value:
+ return None
+ index = self._ensure_slot("text", key, TextBlock(text=""))
+ if index in self._closed_indices:
+ return None
+ block = self.content[index]
+ if not isinstance(block, TextBlock):
+ return None
+ previous = self._text_value(index)
+ self._account_replacement(previous, value)
+ self._text_buffers[index] = _string_buffer(value)
+ self._visible_blocks.add(index)
+ self._emitted_output = True
+ suffix = value[len(previous) :] if value.startswith(previous) else ""
+ return TextDelta(index=index, delta=suffix) if suffix else None
+
+ def thinking_delta(
+ self,
+ key: Hashable,
+ value: str,
+ *,
+ signature: str | None = None,
+ ) -> ThinkingDelta | None:
+ if not value:
+ return None
+ if ("thinking", key) not in self._slots and signature:
+ self._account_output(signature)
+ index = self._ensure_slot(
+ "thinking",
+ key,
+ ThinkingBlock(text="", signature=signature),
+ )
+ block = self.content[index]
+ if index in self._closed_indices:
+ return None
+ if not isinstance(block, ThinkingBlock):
+ return None
+ self._account_output(value)
+ buffer = self._thinking_buffers.setdefault(index, _string_buffer(block.text))
+ buffer.write(value)
+ self._visible_blocks.add(index)
+ self._emitted_output = True
+ return ThinkingDelta(index=index, delta=value)
+
+ def replace_thinking(self, key: Hashable, value: str) -> ThinkingDelta | None:
+ index = self._slots.get(("thinking", key))
+ if index is None:
+ index = self._ensure_slot("thinking", key, ThinkingBlock(text=""))
+ if index in self._closed_indices:
+ return None
+ block = self.content[index]
+ if isinstance(block, ThinkingBlock):
+ previous = self._thinking_value(index)
+ self._account_replacement(previous, value)
+ self._thinking_buffers[index] = _string_buffer(value)
+ if value:
+ self._visible_blocks.add(index)
+ self._emitted_output = True
+ suffix = value[len(previous) :] if value.startswith(previous) else ""
+ return ThinkingDelta(index=index, delta=suffix) if suffix else None
+ return None
+
+ def ensure_thinking_slot(
+ self,
+ key: Hashable,
+ *,
+ signature: str | None = None,
+ redacted: bool = False,
+ ) -> int:
+ if ("thinking", key) not in self._slots and signature:
+ self._account_output(signature)
+ return self._ensure_slot(
+ "thinking",
+ key,
+ ThinkingBlock(text="", signature=signature, redacted=redacted),
+ )
+
+ def redacted_thinking(self, key: Hashable, signature: str) -> int | None:
+ # C-1 removes unverifiable opaque blocks. Do so before allocating an
+ # index, otherwise final sanitization shifts already-published deltas.
+ if not self.verified_origin:
+ return None
+ index = self.ensure_thinking_slot(key, signature=signature, redacted=True)
+ block = self.content[index]
+ if isinstance(block, ThinkingBlock):
+ previous = self._thinking_signature_value(index)
+ if signature != previous:
+ self._account_replacement(previous, signature)
+ self._thinking_buffers.pop(index, None)
+ self._thinking_signature_buffers[index] = _string_buffer(signature)
+ self.content[index] = ThinkingBlock(text="", signature=signature, redacted=True)
+ return index
+
+ def set_thinking_signature(self, key: Hashable, signature: str) -> None:
+ index = self._slots.get(("thinking", key))
+ if index is None:
+ index = self._ensure_slot("thinking", key, ThinkingBlock(text=""))
+ self._materialize_thinking_details(key)
+ block = self.content[index]
+ if isinstance(block, ThinkingBlock):
+ previous_signature = self._thinking_signature_value(index)
+ self._account_replacement(previous_signature, signature)
+ self._thinking_signature_buffers[index] = _string_buffer(signature)
+
+ def append_thinking_signature(self, key: Hashable, value: str) -> None:
+ if not value:
+ return
+ index = self._slots.get(("thinking", key))
+ if index is None:
+ index = self._ensure_slot("thinking", key, ThinkingBlock(text=""))
+ self._materialize_thinking_details(key)
+ block = self.content[index]
+ if isinstance(block, ThinkingBlock):
+ self._account_output(value)
+ buffer = self._thinking_signature_buffers.get(index)
+ if buffer is None:
+ buffer = _string_buffer(block.signature or "")
+ self._thinking_signature_buffers[index] = buffer
+ buffer.write(value)
+
+ def merge_thinking_details(self, key: Hashable, details: list[Any]) -> None:
+ valid = [detail for detail in details if isinstance(detail, Mapping)]
+ if not valid:
+ return
+ index = self._ensure_slot("thinking", key, ThinkingBlock(text=""))
+ accumulated = self._thinking_details.get(key)
+ if accumulated is None:
+ block = self.content[index]
+ accumulated = []
+ existing_signature = self._thinking_signature_value(index)
+ if isinstance(block, ThinkingBlock) and existing_signature:
+ try:
+ previous = json.loads(existing_signature)
+ except (TypeError, ValueError):
+ previous = []
+ if isinstance(previous, list):
+ accumulated.extend(item for item in previous if isinstance(item, Mapping))
+ self._thinking_details[key] = accumulated
+ if accumulated is None:
+ return
+ for detail in valid:
+ item = dict(detail)
+ previous = accumulated[-1] if accumulated else None
+ if (
+ isinstance(previous, dict)
+ and previous.get("type") == item.get("type")
+ and item.get("type") in {"reasoning.text", "reasoning.summary"}
+ and isinstance(previous.get("text" if item["type"] == "reasoning.text" else "summary"), str)
+ and isinstance(item.get("text" if item["type"] == "reasoning.text" else "summary"), str)
+ ):
+ field = "text" if item["type"] == "reasoning.text" else "summary"
+ detail_index = len(accumulated) - 1
+ buffer = self._thinking_detail_buffers.setdefault(
+ (key, detail_index, field),
+ _string_buffer(str(previous[field])),
+ )
+ self._account_output(
+ json.dumps(item, ensure_ascii=False, separators=(",", ":"))
+ )
+ buffer.write(item[field])
+ previous[field] = ""
+ for name in ("id", "format", "index", "signature"):
+ if previous.get(name) in (None, "") and name in item:
+ previous[name] = item[name]
+ continue
+ self._account_output(
+ json.dumps(item, ensure_ascii=False, separators=(",", ":"))
+ )
+ accumulated.append(item)
+
+ def merge_reasoning_item(
+ self, key: Hashable, item: Mapping[str, Any], *, terminal_backfill: bool = False,
+ ) -> None:
+ """Budget and serialize changed reasoning once, including terminal backfill."""
+
+ if key in self._closed_reasoning_keys and not terminal_backfill:
+ return
+ state = self._reasoning_items.get(key, {"type": "reasoning", "id": "", "encrypted_content": ""})
+ changed = key not in self._reasoning_items
+ for name, value in item.items():
+ if name == "encrypted_content" and not value:
+ continue
+ if state.get(name) != value:
+ changed = True
+ break
+ if not changed:
+ return
+ merged = dict(state)
+ for name, value in item.items():
+ if name == "encrypted_content" and not value:
+ continue
+ merged[name] = value
+ merged["type"] = "reasoning"
+ after = json.dumps(merged, ensure_ascii=False, separators=(",", ":"))
+ self._account_output(after)
+ previous_id = state.get("id")
+ state = merged
+ self._reasoning_items[key] = state
+ if isinstance(previous_id, str) and previous_id and self._reasoning_key_by_id.get(previous_id) == key:
+ del self._reasoning_key_by_id[previous_id]
+ item_id = state.get("id")
+ if isinstance(item_id, str) and item_id:
+ self._reasoning_key_by_id[item_id] = key
+ self.ensure_thinking_slot(key)
+ if state["encrypted_content"]:
+ self.set_thinking_signature(key, after)
+
+ def reasoning_key_for_id(self, item_id: str | None) -> Hashable | None:
+ if not item_id:
+ return None
+ return self._reasoning_key_by_id.get(item_id)
+
+ def has_tools(self) -> bool:
+ return any(isinstance(block, ToolCallBlock) for block in self.content)
+
+ def has_content(self) -> bool:
+ return bool(self.content)
+
+ def has_text_slot(self, key: Hashable) -> bool:
+ return ("text", key) in self._slots
+
+ def set_block_kind(self, key: Hashable, kind: str) -> None:
+ if key not in self._block_kinds:
+ self._account_output(BLOCK_SLOT_OVERHEAD_BYTES)
+ self._block_kinds[key] = kind
+
+ def block_kind(self, key: Hashable) -> str | None:
+ return self._block_kinds.get(key)
+
+ def tool_count(self) -> int:
+ return len(self._tool_order)
+
+ def tool_start(
+ self,
+ key: Hashable,
+ *,
+ name: str | None = None,
+ call_id: str | None = None,
+ native_id: str | None = None,
+ signature: str | None = None,
+ defer_start: bool = False,
+ ) -> ToolCallStart | None:
+ state = self.tool_state(key)
+ if "content_index" in state and state["content_index"] in self._closed_indices:
+ return None
+ self.bind_tool_identity(key, native_id)
+ if call_id:
+ # Canonical identity is immutable after ToolCallStart. A late wire
+ # ID is an alias, never a new allocated canonical ID.
+ if "content_index" not in state:
+ self._set_tool_id(key, state, call_id)
+ self.bind_tool_alias(key, call_id)
+ if name and not state["name"]:
+ self._account_pending_tool_identity(state, "name", name)
+ state["name"] = name
+ native_id = state["native_id"]
+ owners = self._tool_id_owners.get(native_id or "", set())
+ native_is_unique = bool(native_id) and (not owners or (len(owners) == 1 and key in owners))
+ if "content_index" not in state and not state["id"] and native_is_unique:
+ self._set_tool_id(key, state, state["native_id"])
+ if signature and signature != state.get("signature"):
+ previous_signature = state.get("signature") or ""
+ self._account_replacement(previous_signature, signature)
+ state["signature"] = signature
+ if not state["name"] or defer_start:
+ return None
+ if "content_index" not in state:
+ if not state["id"]:
+ self._set_tool_id(key, state, self._new_tool_id())
+ native = state["native_id"]
+ state["content_index"] = len(self.content)
+ self.content.append(
+ ToolCallBlock(
+ id=state["id"],
+ native_id=native,
+ name=state["name"],
+ arguments={},
+ signature=state["signature"],
+ )
+ )
+ self._visible_blocks.add(state["content_index"])
+ self._emitted_output = True
+ self._account_output(BLOCK_SLOT_OVERHEAD_BYTES)
+ self._account_tool_identity_block(state)
+ if native:
+ self.bind_tool_alias(key, native)
+ return ToolCallStart(
+ index=state["content_index"],
+ id=state["id"],
+ name=state["name"],
+ )
+ index = state["content_index"]
+ if index in self._closed_indices:
+ return None
+ block = self.content[index]
+ if isinstance(block, ToolCallBlock):
+ self.content[index] = ToolCallBlock(
+ id=block.id,
+ native_id=state["native_id"] or block.native_id,
+ name=state["name"] or block.name,
+ arguments=dict(block.arguments),
+ signature=state["signature"] or block.signature,
+ )
+ return None
+
+ def _account_pending_tool_identity(
+ self,
+ state: dict[str, Any],
+ field: str,
+ value: str,
+ ) -> None:
+ charged = state.setdefault("_charged_identity", set())
+ previous = str(state.get(field) or "")
+ if field not in charged:
+ self._account_output(value)
+ charged.add(field)
+ elif previous != value:
+ self._account_replacement(previous, value)
+
+ def _account_tool_identity_block(self, state: dict[str, Any]) -> None:
+ for field in ("id", "name", "native_id"):
+ value = state.get(field)
+ if value:
+ self._account_pending_tool_identity(state, field, str(value))
+
+ def bind_tool_identity(self, key: Hashable, native_id: str | None) -> None:
+ """Bind once to the stream slot; aliases never override an explicit index."""
+
+ if not native_id:
+ return
+ state = self.tool_state(key)
+ if "content_index" in state and state["content_index"] in self._closed_indices:
+ return
+ previous = state["native_id"]
+ if previous and previous != native_id:
+ raise ToolIdentityError("tool slot received a conflicting native ID")
+ if not previous:
+ self._account_pending_tool_identity(state, "native_id", native_id)
+ state["native_id"] = native_id
+ self.bind_tool_alias(key, native_id)
+
+ def bind_tool_alias(self, key: Hashable, native_id: str | None) -> None:
+ if native_id:
+ if native_id not in self._charged_native_ids:
+ self._account_output(native_id)
+ self._account_output(TOOL_ALIAS_OVERHEAD_BYTES)
+ self._charged_native_ids.add(native_id)
+ self._tool_keys_by_native_id[native_id] = key
+
+ def fallback_tool_key(
+ self,
+ *,
+ native_id: str | None = None,
+ allocate: bool,
+ ) -> Hashable | None:
+ if native_id:
+ existing = self._tool_keys_by_native_id.get(native_id)
+ if existing is not None:
+ self._latest_fallback_tool_key = existing
+ return existing
+ if not allocate:
+ key = self._latest_fallback_tool_key
+ if key is None:
+ return None
+ state = self._tools.get(key)
+ if (
+ state is not None
+ and not state.get("finished")
+ and (
+ "content_index" not in state
+ or state["content_index"] not in self._closed_indices
+ )
+ ):
+ return key
+ return None
+ key = ("tool-fallback", self._fallback_tool_sequence)
+ self._fallback_tool_sequence += 1
+ self._latest_fallback_tool_key = key
+ self.bind_tool_alias(key, native_id)
+ return key
+
+ def tool_arguments(self, key: Hashable, value: str, *, replace: bool = False) -> ToolCallDelta | None:
+ state = self._tools.get(key)
+ if state is not None and "content_index" in state and state["content_index"] in self._closed_indices:
+ return None
+ if value:
+ state = self.tool_state(key)
+ if replace:
+ previous = self._tool_arguments_value(key)
+ self._account_replacement(previous, value)
+ self._tool_argument_buffers[key] = _string_buffer(value)
+ else:
+ self._account_output(value)
+ buffer = self._tool_argument_buffers.get(key)
+ if buffer is None:
+ buffer = _string_buffer()
+ self._tool_argument_buffers[key] = buffer
+ buffer.write(value)
+ state = self._tools.get(key)
+ if not value or state is None or "content_index" not in state:
+ return None
+ self._emitted_output = True
+ return ToolCallDelta(index=state["content_index"], arguments_delta=value)
+
+ def tool_arguments_snapshot(self, key: Hashable, value: str) -> ToolCallDelta | None:
+ """Replace a provider's final argument snapshot and emit only its suffix."""
+
+ state = self._tools.get(key)
+ if state is None:
+ return None
+ if "content_index" not in state:
+ self.tool_arguments(key, value, replace=True)
+ return None
+ if state["content_index"] in self._closed_indices:
+ return None
+ previous = self._tool_arguments_value(key)
+ if not value:
+ return None
+ if not value.startswith(previous):
+ self._account_replacement(previous, value)
+ self._tool_argument_buffers[key] = _string_buffer(value)
+ return None
+ self._account_replacement(previous, value)
+ self._tool_argument_buffers[key] = _string_buffer(value)
+ suffix = value[len(previous) :]
+ if not suffix:
+ return None
+ self._emitted_output = True
+ return ToolCallDelta(index=state["content_index"], arguments_delta=suffix)
+
+ def pending_tool_arguments(self, key: Hashable) -> ToolCallDelta | None:
+ state = self._tools.get(key)
+ if state is None or "content_index" not in state:
+ return None
+ if state["content_index"] in self._closed_indices:
+ return None
+ arguments = self._tool_arguments_value(key)
+ if not arguments:
+ return None
+ if state.get("arguments_emitted"):
+ return None
+ state["arguments_emitted"] = True
+ return ToolCallDelta(
+ index=state["content_index"],
+ arguments_delta=arguments,
+ )
+
+ def set_tool_arguments_object(self, key: Hashable, value: Mapping[str, Any]) -> None:
+ """Store an initial object without corrupting later JSON deltas."""
+
+ encoded = json.dumps(value, ensure_ascii=False, separators=(",", ":"))
+ self._account_output(encoded)
+ self.tool_state(key)["arguments_obj"] = dict(value)
+
+ def tool_state(self, key: Hashable) -> dict[str, Any]:
+ state = self._tools.get(key)
+ if state is None:
+ state = self._new_tool_state()
+ self._tools[key] = state
+ self._account_output(BLOCK_SLOT_OVERHEAD_BYTES)
+ if key not in self._tool_order_set:
+ self._tool_order_set.add(key)
+ self._tool_order.append(key)
+ return state
+
+ @staticmethod
+ def _new_tool_state() -> dict[str, Any]:
+ return {
+ "id": "",
+ "native_id": None,
+ "name": "",
+ "arguments": "",
+ "signature": None,
+ "_charged_identity": set(),
+ }
+
+ def tool_item_id(self, key: Hashable) -> str:
+ return str(self._tools.get(key, {}).get("native_id") or "")
+
+ def tool_name(self, key: Hashable) -> str:
+ return str(self._tools.get(key, {}).get("name", ""))
+
+ def has_tool(self, key: Hashable) -> bool:
+ state = self._tools.get(key)
+ return state is not None and "content_index" in state
+
+ def finish_tool(self, key: Hashable) -> None:
+ state = self._tools.get(key)
+ if state is not None and "content_index" in state:
+ state["finished"] = True
+
+ def unfinished_tool_calls(self) -> tuple[ToolCallBlock, ...]:
+ unfinished: list[ToolCallBlock] = []
+ for state in self._tools.values():
+ if "content_index" not in state or state.get("finished"):
+ continue
+ block = self.content[state["content_index"]]
+ if isinstance(block, ToolCallBlock):
+ unfinished.append(block)
+ return tuple(unfinished)
+
+ def interrupted_tool_events(self) -> tuple[ToolCallStart | ToolCallDelta, ...]:
+ """Expose pending calls for a non-tool stop so the loop can settle them."""
+
+ events: list[ToolCallStart | ToolCallDelta] = []
+ for key, state in self._tools.items():
+ if "content_index" in state or not state.get("name"):
+ continue
+ start = self.tool_start(key)
+ if start is not None:
+ events.append(start)
+ arguments = self.pending_tool_arguments(key)
+ if arguments is not None:
+ events.append(arguments)
+ return tuple(events)
+
+ def block_end_events(self) -> tuple[BlockEnd, ...]:
+ events: list[BlockEnd] = []
+ for index in sorted(self._visible_blocks):
+ if index in self._closed_indices:
+ continue
+ self._closed_indices.add(index)
+ key = self._thinking_key_by_index.get(index)
+ if key is not None:
+ self._closed_reasoning_keys.add(key)
+ events.append(BlockEnd(index=index))
+ return tuple(events)
+
+ def block_end(self, key: Hashable) -> BlockEnd | None:
+ for kind in ("text", "thinking"):
+ index = self._slots.get((kind, key))
+ if index is not None:
+ if index in self._closed_indices:
+ return None
+ if index not in self._visible_blocks:
+ self._closed_indices.add(index)
+ if kind == "thinking":
+ self._closed_reasoning_keys.add(key)
+ return None
+ self._closed_indices.add(index)
+ if kind == "thinking":
+ self._closed_reasoning_keys.add(key)
+ return BlockEnd(index=index)
+ state = self._tools.get(key)
+ if state is not None and "content_index" in state:
+ index = state["content_index"]
+ if index in self._closed_indices:
+ return None
+ self._closed_indices.add(index)
+ return BlockEnd(index=index)
+ return None
+
+ def finalize(self, stop_reason: str, *, error_message: str | None = None) -> AssistantMessage | ProviderError:
+ self._materialize_content()
+ for state in self._tools.values():
+ if not state.get("name"):
+ return self.error("tool call name is missing", kind="invalid_request")
+ if "content_index" not in state:
+ return self.error("tool call ended before its identity was complete", kind="invalid_request")
+ if stop_reason == "stop" and self.has_tools():
+ stop_reason = "tool_use"
+ final: list[AssistantContent] = []
+ state_by_index = {
+ state.get("content_index"): state
+ for state in self._tools.values()
+ if "content_index" in state
+ }
+ key_by_index = {
+ state.get("content_index"): key
+ for key, state in self._tools.items()
+ if "content_index" in state
+ }
+ for index, block in enumerate(self.content):
+ if not isinstance(block, ToolCallBlock):
+ final.append(block)
+ continue
+ state = state_by_index.get(index, {})
+ raw_arguments = self._tool_arguments_value(key_by_index[index])
+ if not raw_arguments and isinstance(state.get("arguments_obj"), Mapping):
+ arguments: dict[str, Any] | ProviderError = dict(state["arguments_obj"])
+ else:
+ arguments = parsed_arguments(raw_arguments, tool_name=block.name)
+ if isinstance(arguments, ProviderError):
+ if stop_reason == "tool_use":
+ return self.error(
+ arguments.message,
+ kind="invalid_request",
+ )
+ # A length, safety, refusal, or error stop must still carry
+ # every model-emitted call so the loop can settle it as an
+ # unsuccessful tool result. The arguments are incomplete and
+ # must not turn a provider stop into a malformed-request
+ # failure.
+ arguments = {}
+ final.append(
+ ToolCallBlock(
+ id=block.id,
+ native_id=state.get("native_id") or block.native_id,
+ name=block.name,
+ arguments=arguments,
+ signature=state.get("signature") or block.signature,
+ )
+ )
+ return assistant_message(
+ final,
+ origin=self.origin,
+ stop_reason=stop_reason,
+ usage=self.usage,
+ error_message=error_message,
+ verified_origin=self.verified_origin,
+ )
+
+ def partial(self, *, stop_reason: str = "error") -> AssistantMessage | None:
+ if self.usage is None and not self._emitted_output:
+ return None
+ self._materialize_content()
+ content = list(self.content)
+ if not self._emitted_output:
+ content = []
+ return partial_message(
+ content,
+ origin=self.origin,
+ usage=self.usage,
+ verified_origin=self.verified_origin,
+ stop_reason=stop_reason,
+ )
+
+ def error(
+ self,
+ message: str,
+ *,
+ kind: str | None = None,
+ code: str | None = None,
+ status: int | None = None,
+ headers: Mapping[str, str] | None = None,
+ ) -> ProviderError:
+ partial = (
+ self.partial()
+ if self.streamed or self.usage is not None
+ else None
+ )
+ if kind == "invalid_request":
+ error = ProviderError(
+ kind="invalid_request",
+ message=message,
+ retryable=False,
+ status=status,
+ partial=partial,
+ )
+ return error
+ if kind is not None:
+ error = ProviderError(
+ kind=kind,
+ message=message,
+ retryable=kind in {"rate_limit", "overloaded", "network", "server"} and not self.streamed,
+ retry_after_s=parse_retry_after((headers or {}).get("retry-after")),
+ status=status,
+ partial=partial,
+ )
+ return error
+ error = classify_error(
+ body=message,
+ code=code,
+ status=status,
+ headers=headers,
+ streamed=self.streamed,
+ partial=partial,
+ protocol=self.protocol,
+ )
+ return error
+
+ def exception(
+ self,
+ exc: BaseException,
+ *,
+ status: int | None = None,
+ headers: Mapping[str, str] | None = None,
+ ) -> ProviderError:
+ error = classify_error(
+ exc=exc,
+ status=status,
+ headers=headers,
+ streamed=self.streamed,
+ partial=self.partial() if self.streamed or self.usage is not None else None,
+ )
+ return error
+
+ def aborted(self, reason: str | None = None) -> ProviderError:
+ return ProviderError(
+ kind="aborted",
+ message=reason or "provider request aborted",
+ retryable=False,
+ partial=self.partial(stop_reason="aborted"),
+ )
+
+ def incomplete(self) -> ProviderError:
+ return self.error(
+ f"{self.protocol} stream ended before terminal event",
+ kind="network",
+ )
+
+ def terminal(self, event: Done | ProviderError) -> Done | ProviderError | None:
+ if self._driver_mode:
+ return event
+ if self._terminal_seen:
+ return None
+ if isinstance(event, ProviderError):
+ event = self._sanitize_error(event)
+ self._terminal_seen = True
+ return event
+
+ def _sanitize_error(self, error: ProviderError) -> ProviderError:
+ return redact_provider_error(
+ error,
+ literal_secrets=self._sensitive_values,
+ endpoint_url=self._endpoint_url,
+ )
+
+ def _ensure_slot(self, kind: str, key: Hashable, block: AssistantContent) -> int:
+ slot = (kind, key)
+ index = self._slots.get(slot)
+ if index is not None:
+ return index
+ self._account_output(BLOCK_SLOT_OVERHEAD_BYTES)
+ index = len(self.content)
+ self._slots[slot] = index
+ if kind == "thinking":
+ self._thinking_key_by_index[index] = key
+ self.content.append(block)
+ return index
+
+ def _new_tool_id(self) -> str:
+ self._next_tool_id = max(self._next_tool_id, len(self._tool_order) - 1)
+ candidate = f"call_{self._next_tool_id}"
+ while candidate in self._allocated_tool_ids:
+ self._next_tool_id += 1
+ candidate = f"call_{self._next_tool_id}"
+ self._next_tool_id += 1
+ return candidate
+
+ def _set_tool_id(
+ self,
+ key: Hashable,
+ state: dict[str, Any],
+ value: str | None,
+ ) -> None:
+ owners = self._tool_id_owners.get(value or "")
+ if owners and (len(owners) != 1 or key not in owners):
+ value = self._new_tool_id()
+ previous = state.get("id") or ""
+ if previous == (value or ""):
+ return
+ if value:
+ self._account_pending_tool_identity(state, "id", value)
+ if previous:
+ owners = self._tool_id_owners.get(previous)
+ if owners is not None:
+ owners.discard(key)
+ if not owners:
+ del self._tool_id_owners[previous]
+ self._allocated_tool_ids.discard(previous)
+ state["id"] = value or ""
+ if value:
+ self._tool_id_owners.setdefault(value, set()).add(key)
+ self._allocated_tool_ids.add(value)
+
+
+def endpoint_origin(endpoint: ModelEndpoint) -> Origin:
+ provider = endpoint.provider or f"endpoint:{credential_free_endpoint_identity(endpoint.base_url)}"
+ if provider == "endpoint:":
+ provider = f"endpoint:{endpoint.protocol}:{endpoint.model_id}"
+ return Origin(
+ provider=provider,
+ api=endpoint.protocol,
+ model=endpoint.model_id,
+ )
+
+
+def credential_free_endpoint_identity(base_url: str) -> str:
+ """Return the endpoint location without userinfo, query, or fragment data."""
+
+ try:
+ parsed = urlsplit(base_url)
+ except ValueError:
+ return _fallback_endpoint_identity(base_url)
+ if parsed.scheme and parsed.hostname:
+ host = parsed.hostname
+ if ":" in host and not host.startswith("["):
+ host = f"[{host}]"
+ try:
+ port = parsed.port
+ except ValueError:
+ port = None
+ if port is not None:
+ host = f"{host}:{port}"
+ path = parsed.path or "/"
+ return f"{parsed.scheme}://{host}{path.rstrip('/') or '/'}"
+ return _fallback_endpoint_identity(base_url)
+
+
+def join_endpoint_url(base_url: str, suffix: str) -> str:
+ """Append a protocol path while preserving the endpoint's query string.
+
+ The endpoint may already be a complete protocol URL (useful for custom
+ gateways), and the protocol suffix may add its own query parameters, as
+ Some protocols add query parameters to their stream endpoint. URL parsing
+ keeps credentials out of this operation's string manipulation and prevents
+ a base query from becoming part of the request path.
+ """
+
+ base = urlsplit(base_url)
+ extra = urlsplit(suffix)
+ base_path = base.path.rstrip("/")
+ suffix_path = extra.path.strip("/")
+ base_leaf = base_path.rsplit("/", 1)[-1]
+ suffix_leaf = suffix_path.rsplit("/", 1)[-1]
+ same_operation = (
+ ":" in base_leaf
+ and ":" in suffix_leaf
+ and base_leaf.split(":", 1)[1] == suffix_leaf.split(":", 1)[1]
+ )
+ already_joined = suffix_path and (
+ base_path == suffix_path
+ or base_path.endswith(f"/{suffix_path}")
+ or same_operation
+ )
+ if suffix_path and not already_joined:
+ path = f"{base_path}/{suffix_path}" if base_path else f"/{suffix_path}"
+ else:
+ path = base_path or "/"
+ query = list(parse_qsl(base.query, keep_blank_values=True))
+ query_keys = {key for key, _ in query}
+ for key, value in parse_qsl(extra.query, keep_blank_values=True):
+ if key in query_keys:
+ continue
+ query.append((key, value))
+ query_keys.add(key)
+ return urlunsplit((base.scheme, base.netloc, path, urlencode(query), ""))
+
+
+def _fallback_endpoint_identity(base_url: str) -> str:
+ value = base_url.split("?", 1)[0].split("#", 1)[0]
+ scheme, separator, rest = value.partition("://")
+ if not separator:
+ return value.rstrip("/") or "unknown"
+ authority, slash, path = rest.partition("/")
+ authority = authority.rsplit("@", 1)[-1]
+ return f"{scheme}://{authority}{('/' + path) if slash else '/'}"
+
+
+def dispatch_wire_event(
+ event: Any,
+ *,
+ known: frozenset[str],
+ event_name: str | None = None,
+ default: str | None = None,
+ aliases: Mapping[str, str] | None = None,
+) -> str | None:
+ """Return a normalized known event type, ignoring unknown wire events like Pi.
+
+ Native adapters use this at the protocol boundary before validating the
+ shape of a known event. A missing ``type`` is allowed only for protocols
+ whose stream frames are implicitly typed (Chat Completions).
+ """
+
+ if not isinstance(event, Mapping):
+ return None
+ named_type = (aliases or {}).get(event_name, event_name)
+ if "type" in event:
+ raw_type = event["type"]
+ if not isinstance(raw_type, str):
+ if named_type not in known:
+ return None
+ raise WireDispatchError(f"{event_name}.type must be a string")
+ elif named_type in known:
+ raise WireDispatchError(f"{event_name}.type is required")
+ else:
+ raw_type = default
+ if not isinstance(raw_type, str):
+ return None
+ normalized = (aliases or {}).get(raw_type, raw_type)
+ return normalized if normalized in known else None
+
+
+def validate_wire_shape(
+ event: Mapping[str, Any],
+ event_type: str,
+ table: Mapping[str, tuple[WireField, ...]],
+) -> str | None:
+ """Validate one known event against its declarative protocol row."""
+
+ fields = table.get(event_type)
+ if fields is None:
+ return None
+ return _validate_wire_fields(event, fields, event_type)
+
+
+def _validate_wire_fields(
+ value: Mapping[str, Any],
+ fields: tuple[WireField, ...],
+ path: str,
+) -> str | None:
+ for field in fields:
+ field_path = f"{path}.{field.name}"
+ if field.name not in value:
+ if field.required:
+ return f"{field_path} is required"
+ continue
+ current = value[field.name]
+ if current is None:
+ if field.nullable:
+ continue
+ return f"{field_path} must not be null"
+ if not _wire_value_matches(current, field.expected):
+ return f"{field_path} must be {_wire_type_name(field.expected)}"
+ if field.children:
+ child_error = _validate_wire_fields(current, field.children, field_path)
+ if child_error is not None:
+ return child_error
+ if field.item_children:
+ for index, item in enumerate(current):
+ item_path = f"{field_path}[{index}]"
+ if not isinstance(item, Mapping):
+ return f"{item_path} must be an object"
+ item_error = _validate_wire_fields(item, field.item_children, item_path)
+ if item_error is not None:
+ return item_error
+ return None
+
+
+def _wire_value_matches(value: Any, expected: type | tuple[type, ...]) -> bool:
+ expected_types = expected if isinstance(expected, tuple) else (expected,)
+ for expected_type in expected_types:
+ if expected_type is int:
+ if isinstance(value, int) and not isinstance(value, bool):
+ return True
+ elif expected_type is Mapping:
+ if isinstance(value, Mapping):
+ return True
+ elif isinstance(value, expected_type):
+ return True
+ return False
+
+
+def _wire_type_name(expected: type | tuple[type, ...]) -> str:
+ expected_types = expected if isinstance(expected, tuple) else (expected,)
+ names = [
+ "object" if item is Mapping else "integer" if item is int else item.__name__
+ for item in expected_types
+ ]
+ return " or ".join(names)
+
+
+async def resolve_served_origin(
+ endpoint: ModelEndpoint,
+ headers: Mapping[str, str],
+ resolver: ServedHopResolver | None,
+ *,
+ gateway: bool,
+ cancel: CancelToken,
+) -> tuple[Origin, bool] | None:
+ """Return the served origin and whether its signature data is verified."""
+
+ direct = endpoint_origin(endpoint)
+ if not gateway:
+ return direct, True
+ candidate = resolver(headers) if resolver is not None else default_served_hop_resolver(headers)
+ if inspect.isawaitable(candidate):
+ try:
+ served = await _await_injected(candidate, cancel)
+ except _CancelledDependency:
+ return None
+ else:
+ served = candidate
+ if cancel.cancelled:
+ return None
+ return served or direct, served is not None
+
+
+def default_served_hop_resolver(headers: Mapping[str, str]) -> Origin | None:
+ """Read the exact C-6 served-hop header."""
+
+ normalized = {key.lower(): value for key, value in headers.items()}
+ report = normalized.get("x-avibe-served-hop")
+ if not report or not report.isascii():
+ return None
+ try:
+ value = json.loads(report, object_pairs_hook=_unique_json_object)
+ except (TypeError, ValueError):
+ return None
+ if not isinstance(value, Mapping):
+ return None
+ if set(value) != {"provider", "api", "model"} or any(not isinstance(value[key], str) for key in value):
+ return None
+ try:
+ return Origin(provider=value["provider"], api=value["api"], model=value["model"])
+ except (KeyError, TypeError, ValueError):
+ return None
+
+
+def _unique_json_object(pairs: list[tuple[str, Any]]) -> dict[str, Any]:
+ value = dict(pairs)
+ if len(value) != len(pairs):
+ raise ValueError("served-hop report contains duplicate keys")
+ return value
+
+
+def auth_headers(endpoint: ModelEndpoint, *, provider: str, gateway: bool) -> dict[str, str]:
+ headers = {str(key): str(value) for key, value in endpoint.request_headers.items()}
+ if any(key.lower() in {"authorization", "x-api-key", "x-goog-api-key"} for key in headers):
+ return headers
+ if gateway or provider in {"openai", "openai_chat", "openai_responses"}:
+ headers["Authorization"] = f"Bearer {endpoint.token}"
+ elif provider == "anthropic":
+ headers["x-api-key"] = endpoint.token
+ else:
+ headers["Authorization"] = f"Bearer {endpoint.token}"
+ return headers
+
+
+def request_credential_values(endpoint: ModelEndpoint) -> tuple[str, ...]:
+ """Return endpoint credentials that may appear in transport diagnostics."""
+
+ values = [endpoint.token] if endpoint.token else []
+ for name, value in endpoint.request_headers.items():
+ if _is_sensitive_key(str(name)):
+ values.append(str(value))
+ try:
+ parsed = urlsplit(endpoint.base_url)
+ except ValueError:
+ parsed = None
+ if parsed is not None:
+ values.extend(unquote(value) for value in (parsed.username, parsed.password) if value)
+ values.extend(
+ value for name, value in parse_qsl(parsed.query)
+ if _is_sensitive_key(name)
+ )
+ return tuple(dict.fromkeys(values))
+
+
+async def iter_sse_events(
+ response: httpx.Response,
+ cancel: CancelToken,
+) -> AsyncIterator[SSEEvent]:
+ """Yield SSE events while allowing a CancelToken to interrupt a stalled read."""
+
+ parser = SSEParser()
+ iterator = response.aiter_bytes().__aiter__()
+ first_chunk = True
+ while True:
+ if cancel.cancelled:
+ return
+ try:
+ chunk = await _await_network(
+ iterator.__anext__(),
+ cancel,
+ timeout_s=(
+ TIME_TO_FIRST_BYTE_TIMEOUT_S
+ if first_chunk
+ else IDLE_CHUNK_TIMEOUT_S
+ ),
+ )
+ except StopAsyncIteration:
+ break
+ if chunk is None:
+ return
+ first_chunk = False
+ for event in parser.feed(chunk):
+ yield event
+ for event in parser.finish():
+ yield event
+
+
+async def drive_sse_stream(
+ client: httpx.AsyncClient,
+ *,
+ method: str,
+ url: str,
+ json_body: Any,
+ headers: Mapping[str, str],
+ cancel: CancelToken,
+ assembler: StreamAssembler,
+ endpoint: ModelEndpoint,
+ resolver: ServedHopResolver | None,
+ gateway: bool,
+ translate: WireTranslator,
+) -> AsyncIterator[Any]:
+ """Own the complete request/stream/terminal/cleanup lifecycle.
+
+ Protocol adapters provide only ``translate``. It receives the shared SSE
+ iterator and yields canonical deltas or a candidate ``Done``/
+ ``ProviderError``. The driver commits exactly one terminal event before
+ closing the response, including when the transport raises while reading.
+ """
+
+ response: httpx.Response | None = None
+ opening: asyncio.Task[httpx.Response] | None = None
+ candidate: Done | ProviderError | None = None
+ assembler.begin_driver()
+ try:
+ try:
+ if cancel.cancelled:
+ candidate = assembler.aborted(cancel.reason)
+ else:
+ request = client.build_request(method, url, json=json_body, headers=headers)
+ # Retain the opening task even if cancellation wins the await:
+ # its successful result still belongs to this driver's finally.
+ opening = asyncio.create_task(client.send(request, stream=True))
+ response = await _await_network(
+ opening,
+ cancel,
+ timeout_s=CONNECT_TIMEOUT_S,
+ )
+ if response is None:
+ candidate = assembler.aborted(cancel.reason)
+ elif not 200 <= response.status_code < 300:
+ # HTTP errors already identify their outcome. Resolving a
+ # served hop first could mask auth/rate limits (or stall).
+ try:
+ body = await read_response_body(response, cancel)
+ except (GeneratorExit, asyncio.CancelledError):
+ raise
+ except Exception as exc:
+ candidate = assembler.exception(
+ exc,
+ status=response.status_code,
+ headers=response.headers,
+ )
+ else:
+ if body is None:
+ candidate = assembler.aborted(cancel.reason)
+ else:
+ candidate = assembler.error(
+ body or f"provider endpoint returned HTTP {response.status_code}",
+ status=response.status_code,
+ headers=response.headers,
+ )
+ else:
+ resolved_origin = await resolve_served_origin(
+ endpoint,
+ response.headers,
+ resolver,
+ gateway=gateway,
+ cancel=cancel,
+ )
+ if resolved_origin is None:
+ candidate = assembler.aborted(cancel.reason)
+ else:
+ assembler.set_origin(*resolved_origin)
+ async for item in translate(iter_sse_events(response, cancel)):
+ if isinstance(item, (Done, ProviderError)):
+ candidate = item
+ break
+ yield item
+ if candidate is None:
+ candidate = (
+ assembler.aborted(cancel.reason)
+ if cancel.cancelled
+ else assembler.incomplete()
+ )
+ except (GeneratorExit, asyncio.CancelledError):
+ raise
+ except (OutputBudgetExceeded, SSEParseError, ToolIdentityError) as exc:
+ candidate = assembler.error(str(exc), kind="invalid_request")
+ except Exception as exc:
+ candidate = assembler.exception(exc)
+
+ if candidate is not None:
+ # Translator terminals are candidates, not public errors. Commit
+ # and sanitize exactly once at the shared driver boundary.
+ assembler.end_driver()
+ terminal = assembler.terminal(candidate)
+ if terminal is not None:
+ yield terminal
+ finally:
+ assembler.end_driver()
+ async def close_opened_response() -> None:
+ if opening is None:
+ return
+ try:
+ opened_response = opening.result()
+ except BaseException:
+ # A failed/cancelled open did not transfer a response to us.
+ return
+ try:
+ await _await_network(
+ opened_response.aclose(),
+ CancelToken(),
+ timeout_s=CLEANUP_TIMEOUT_S,
+ )
+ except Exception:
+ # The terminal event has already been delivered. Cleanup is
+ # diagnostic only and must never create a second outcome.
+ # asyncio.CancelledError remains a BaseException so consumer
+ # and task cancellation continues through this cleanup path.
+ pass
+ if opening is not None:
+ if opening.done():
+ await close_opened_response()
+ else:
+ # Non-cooperative opening tasks may outlive the bounded cancel
+ # join. Attach disposal here without delaying the terminal.
+ def close_late_response(_: asyncio.Future[httpx.Response]) -> None:
+ cleanup = asyncio.create_task(close_opened_response())
+ _response_cleanup_tasks.add(cleanup)
+ cleanup.add_done_callback(_response_cleanup_tasks.discard)
+ cleanup.add_done_callback(_consume_task_result)
+
+ opening.add_done_callback(close_late_response)
+
+
+async def _await_network(
+ awaitable: Awaitable[_T],
+ cancel: CancelToken,
+ *,
+ timeout_s: float | None = None,
+) -> _T | None:
+ """Own one cancellable network await for opening, reads, and body reads."""
+
+ if cancel.cancelled:
+ close = getattr(awaitable, "close", None)
+ if close is not None:
+ close()
+ return None
+ operation = asyncio.ensure_future(awaitable)
+ cancellation = asyncio.create_task(cancel.wait())
+ try:
+ done, _ = await asyncio.wait(
+ {operation, cancellation},
+ timeout=timeout_s,
+ return_when=asyncio.FIRST_COMPLETED,
+ )
+ if not done:
+ await _cancel_and_join(operation)
+ raise TimeoutError(
+ f"provider network operation timed out after {timeout_s:.1f}s"
+ )
+ if cancellation in done and cancel.cancelled:
+ await _cancel_and_join(operation)
+ return None
+ return operation.result()
+ except TimeoutError:
+ raise
+ except BaseException:
+ await _cancel_and_join(operation)
+ raise
+ finally:
+ if not cancellation.done():
+ cancellation.cancel()
+ with _suppress_cancelled():
+ await cancellation
+
+
+async def _cancel_and_join(operation: asyncio.Future[Any]) -> None:
+ """Cancel an I/O task without hanging on a non-cooperative awaitable."""
+
+ if operation.done():
+ _consume_task_result(operation)
+ return
+ operation.cancel()
+ try:
+ done, _ = await asyncio.wait({operation}, timeout=CLEANUP_TIMEOUT_S)
+ except asyncio.CancelledError:
+ if not operation.done():
+ operation.add_done_callback(_consume_task_result)
+ raise
+ if operation not in done:
+ operation.add_done_callback(_consume_task_result)
+ else:
+ _consume_task_result(operation)
+
+
+def _consume_task_result(operation: asyncio.Future[Any]) -> None:
+ try:
+ operation.result()
+ except BaseException:
+ pass
+
+
+class _CancelledDependency(Exception):
+ """Internal marker for cancellation while loading or resolving injected data."""
+
+
+async def _await_injected(awaitable: Awaitable[_T], cancel: CancelToken) -> _T:
+ """Await a loader or resolver through the shared cancellation owner."""
+
+ result = await _await_network(awaitable, cancel)
+ if result is None and cancel.cancelled:
+ raise _CancelledDependency
+ return result # type: ignore[return-value]
+
+
+async def read_response_body(
+ response: httpx.Response,
+ cancel: CancelToken,
+ *,
+ max_bytes: int = 64 * 1024,
+) -> str | None:
+ """Read an error body through the shared cancellation owner with a byte cap."""
+
+ iterator = response.aiter_bytes().__aiter__()
+ first_chunk = True
+ chunks: list[bytes] = []
+ size = 0
+ while size < max_bytes:
+ try:
+ chunk = await _await_network(
+ iterator.__anext__(),
+ cancel,
+ timeout_s=(
+ TIME_TO_FIRST_BYTE_TIMEOUT_S
+ if first_chunk
+ else IDLE_CHUNK_TIMEOUT_S
+ ),
+ )
+ except StopAsyncIteration:
+ break
+ if chunk is None:
+ return None
+ first_chunk = False
+ if not chunk:
+ continue
+ remaining = max_bytes - size
+ piece = bytes(chunk[:remaining])
+ chunks.append(piece)
+ size += len(piece)
+ if len(piece) < len(chunk):
+ break
+ return b"".join(chunks).decode("utf-8", errors="replace")
+
+
+async def prepare_messages(
+ messages: tuple[Any, ...],
+ *,
+ target: Any,
+ supports_images: bool,
+ protocol: str,
+ media_loader: MediaLoader | None,
+ cancel: CancelToken,
+) -> tuple[tuple[Any, ...], dict[str, tuple[str, str]]] | ProviderError:
+ """Transform history and resolve immutable media snapshots as one safe boundary."""
+
+ try:
+ from core.agent_core.ai.transform import transform_messages
+
+ transformed = transform_messages(
+ messages,
+ target=target,
+ supports_images=supports_images,
+ protocol=protocol,
+ )
+ loaded_images = await load_images(transformed.messages, media_loader, cancel)
+ except _CancelledDependency:
+ return ProviderError(
+ kind="aborted",
+ message=cancel.reason or "provider request aborted",
+ retryable=False,
+ )
+ except Exception as exc:
+ return classify_error(
+ body=f"request preparation failed: {type(exc).__name__}: {exc}",
+ )
+ return transformed.messages, loaded_images
+
+
+class _suppress_cancelled:
+ def __enter__(self) -> None:
+ return None
+
+ def __exit__(self, exception_type: type[BaseException] | None, exception: BaseException | None, traceback: Any) -> bool:
+ return exception_type is asyncio.CancelledError
+
+
+def json_object(data: str) -> dict[str, Any] | None:
+ try:
+ value = json.loads(data)
+ except (TypeError, ValueError):
+ return None
+ return value if isinstance(value, dict) else None
+
+
+def image_data(block: ImageBlock) -> str:
+ """Resolve the in-memory media token form used by hermetic adapter tests."""
+
+ token = block.media_token
+ if token.startswith("data:") and ";base64," in token:
+ return token.split(";base64,", 1)[1]
+ if token.startswith("data:,"):
+ return base64.b64encode(unquote_to_bytes(token[6:])).decode("ascii")
+ return token
+
+
+async def load_image_data(
+ block: ImageBlock,
+ media_loader: MediaLoader | None,
+ cancel: CancelToken | None = None,
+) -> tuple[str, str]:
+ """Resolve a media token just before the request is sent."""
+
+ if media_loader is not None:
+ if cancel is None:
+ raw, mime_type = await media_loader.load(block.media_token)
+ else:
+ raw, mime_type = await _await_injected(media_loader.load(block.media_token), cancel)
+ return base64.b64encode(raw).decode("ascii"), mime_type
+ return image_data(block), block.mime_type
+
+
+async def load_images(
+ messages: tuple[Any, ...],
+ media_loader: MediaLoader | None,
+ cancel: CancelToken,
+) -> dict[str, tuple[str, str]]:
+ """Load every image token once for a request."""
+
+ if media_loader is None:
+ return {}
+ tokens: list[str] = []
+ for message in messages:
+ content = getattr(message, "content", ())
+ for block in content:
+ if isinstance(block, ImageBlock) and block.media_token not in tokens:
+ tokens.append(block.media_token)
+ loaded: dict[str, tuple[str, str]] = {}
+ for token in tokens:
+ raw, mime_type = await _await_injected(media_loader.load(token), cancel)
+ loaded[token] = (base64.b64encode(raw).decode("ascii"), mime_type)
+ return loaded
+
+
+def text_from_content(content: tuple[UserContent, ...]) -> str:
+ parts: list[str] = []
+ for block in content:
+ if isinstance(block, TextBlock):
+ parts.append(block.text or "")
+ return "\n".join(part for part in parts if part)
+
+
+def content_parts(
+ content: tuple[UserContent, ...],
+ *,
+ include_images: bool = True,
+ loaded_images: Mapping[str, tuple[str, str]] | None = None,
+) -> list[dict[str, Any]]:
+ result: list[dict[str, Any]] = []
+ for block in content:
+ if isinstance(block, TextBlock):
+ if block.text:
+ result.append({"type": "text", "text": block.text})
+ elif isinstance(block, ImageBlock) and include_images:
+ data, mime_type = (loaded_images or {}).get(block.media_token, (image_data(block), block.mime_type))
+ result.append({"type": "image", "mime_type": mime_type, "data": data, "media_token": block.media_token})
+ return result
+
+
+def tool_schema(tool: Any) -> dict[str, Any]:
+ return {
+ "name": tool.name,
+ "description": tool.description,
+ "input_schema": dict(tool.input_schema),
+ }
+
+
+def parsed_arguments(raw: str, *, tool_name: str = "") -> dict[str, Any] | ProviderError:
+ if not raw:
+ return {}
+ try:
+ value = json.loads(raw)
+ except (TypeError, ValueError):
+ return _malformed_arguments(tool_name)
+ if not isinstance(value, dict):
+ return _malformed_arguments(tool_name)
+ return value
+
+
+def _malformed_arguments(tool_name: str) -> ProviderError:
+ suffix = f" for tool {tool_name}" if tool_name else ""
+ return ProviderError(
+ kind="invalid_request",
+ message=f"malformed tool arguments{suffix}: expected a JSON object",
+ retryable=False,
+ )
+
+
+def assistant_message(
+ content: list[AssistantContent],
+ *,
+ origin: Origin,
+ stop_reason: str,
+ usage: Any = None,
+ error_message: str | None = None,
+ verified_origin: bool = True,
+) -> AssistantMessage:
+ if not verified_origin:
+ sanitized: list[AssistantContent] = []
+ for block in content:
+ if isinstance(block, ThinkingBlock):
+ if block.redacted:
+ continue
+ sanitized.append(replace(block, signature=None))
+ elif isinstance(block, ToolCallBlock):
+ sanitized.append(replace(block, signature=None))
+ else:
+ sanitized.append(block)
+ content = sanitized
+ return AssistantMessage(
+ content=tuple(content),
+ origin=origin,
+ stop_reason=stop_reason, # type: ignore[arg-type]
+ usage=usage,
+ error_message=error_message,
+ )
+
+
+def partial_message(
+ content: list[AssistantContent],
+ *,
+ origin: Origin,
+ usage: Any = None,
+ verified_origin: bool = True,
+ stop_reason: str = "aborted",
+) -> AssistantMessage:
+ if stop_reason in {"aborted", "error"}:
+ content = [block for block in content if not isinstance(block, ToolCallBlock)]
+ return assistant_message(
+ content,
+ origin=origin,
+ stop_reason=stop_reason,
+ usage=usage,
+ verified_origin=verified_origin,
+ )
+
+
+def _default_provider(protocol: str) -> str:
+ return {
+ "anthropic": "anthropic",
+ "openai_chat": "openai",
+ "openai_responses": "openai",
+ }.get(protocol, protocol)
diff --git a/core/agent_core/ai/anthropic.py b/core/agent_core/ai/anthropic.py
new file mode 100644
index 000000000..db9719d58
--- /dev/null
+++ b/core/agent_core/ai/anthropic.py
@@ -0,0 +1,1017 @@
+"""Anthropic Messages streaming adapter.
+
+Payload and stream rules are ported from tau's ``tau_ai/anthropic.py`` (MIT)
+and Pi's ``packages/ai/src/api/anthropic-messages.ts`` (MIT). This module uses
+httpx directly so Model Hub remains the only gateway boundary.
+"""
+
+from __future__ import annotations
+
+import json
+from collections.abc import AsyncIterator, Mapping
+from typing import Any
+
+import httpx
+
+from core.agent_core.ai._common import (
+ ServedHopResolver,
+ auth_headers,
+ content_parts,
+ drive_sse_stream,
+ dispatch_wire_event,
+ endpoint_origin,
+ join_endpoint_url,
+ json_object,
+ prepare_messages,
+ request_credential_values,
+ StreamAssembler,
+ WireField,
+ WireDispatchError,
+ usage_counter_error,
+ validate_wire_shape,
+)
+from core.agent_core.ai.provider import (
+ Done,
+ ModelRequest,
+ ProviderAdapter,
+ ProviderError,
+ MediaLoader,
+)
+from core.agent_core.cancel import CancelToken
+from core.agent_core.messages import (
+ AssistantMessage,
+ ImageBlock,
+ TextBlock,
+ ThinkingBlock,
+ ToolCallBlock,
+ ToolResultMessage,
+ UserMessage,
+)
+
+ANTHROPIC_VERSION = "2023-06-01"
+_MAX_CACHE_BREAKPOINTS = 4
+_LEGACY_THINKING_BUDGETS = {
+ "minimal": 1024,
+ "low": 2048,
+ "medium": 8192,
+ "high": 16384,
+ "xhigh": 16384,
+ "max": 16384,
+}
+_KNOWN_STREAM_EVENTS = frozenset(
+ {
+ "message_start",
+ "content_block_start",
+ "content_block_delta",
+ "content_block_stop",
+ "message_delta",
+ "error",
+ "message_stop",
+ "ping",
+ }
+)
+_ANTHROPIC_USAGE_FIELDS = (
+ WireField("input_tokens", int),
+ WireField("output_tokens", int),
+ WireField("cache_read_input_tokens", int),
+ WireField("cache_creation_input_tokens", int),
+ WireField(
+ "cache_creation",
+ Mapping,
+ children=(
+ WireField("ephemeral_5m_input_tokens", int),
+ WireField("ephemeral_1h_input_tokens", int),
+ ),
+ ),
+ WireField(
+ "output_tokens_details",
+ Mapping,
+ children=(WireField("thinking_tokens", int),),
+ ),
+)
+_ANTHROPIC_WIRE_SHAPES = {
+ "message_start": (
+ WireField(
+ "message",
+ Mapping,
+ required=True,
+ nullable=False,
+ children=(
+ WireField("usage", Mapping, children=_ANTHROPIC_USAGE_FIELDS),
+ ),
+ ),
+ ),
+ "content_block_start": (
+ WireField("index", int, required=True, nullable=False),
+ WireField(
+ "content_block",
+ Mapping,
+ required=True,
+ nullable=False,
+ children=(
+ WireField("type", str, required=True, nullable=False),
+ WireField("id", str),
+ WireField("name", str),
+ WireField("signature", str),
+ WireField("data", str),
+ WireField("text", str),
+ WireField("thinking", str),
+ WireField("input", Mapping),
+ ),
+ ),
+ ),
+ "content_block_delta": (
+ WireField("index", int, required=True, nullable=False),
+ WireField(
+ "delta",
+ Mapping,
+ required=True,
+ nullable=False,
+ children=(
+ WireField("type", str, required=True, nullable=False),
+ WireField("text", str),
+ WireField("thinking", str),
+ WireField("signature", str),
+ WireField("partial_json", str),
+ ),
+ ),
+ ),
+ "content_block_stop": (
+ WireField("index", int, required=True, nullable=False),
+ ),
+ "message_delta": (
+ WireField(
+ "delta",
+ Mapping,
+ children=(WireField("stop_reason", str),),
+ ),
+ WireField("usage", Mapping, children=_ANTHROPIC_USAGE_FIELDS),
+ ),
+ "error": (
+ WireField(
+ "error",
+ Mapping,
+ children=(
+ WireField("type", str),
+ WireField("message", str),
+ ),
+ ),
+ ),
+ "message_stop": (),
+ "ping": (),
+}
+
+
+class AnthropicAdapter(ProviderAdapter):
+ """Adapter for the native Anthropic Messages protocol."""
+
+ protocol = "anthropic"
+
+ def __init__(
+ self,
+ client: httpx.AsyncClient | None = None,
+ *,
+ media_loader: MediaLoader | None = None,
+ served_hop_resolver: ServedHopResolver | None = None,
+ gateway: bool = False,
+ ) -> None:
+ self._client = client or httpx.AsyncClient(timeout=None)
+ self._owns_client = client is None
+ self._media_loader = media_loader
+ self._served_hop_resolver = served_hop_resolver
+ self._gateway = gateway
+
+ async def aclose(self) -> None:
+ if self._owns_client:
+ await self._client.aclose()
+
+ def stream(self, request: ModelRequest, cancel: CancelToken) -> AsyncIterator[Any]:
+ return self._stream(request, cancel)
+
+ async def _stream(self, request: ModelRequest, cancel: CancelToken) -> AsyncIterator[Any]:
+ origin = endpoint_origin(request.endpoint)
+ assembler = StreamAssembler(
+ origin=origin,
+ protocol=self.protocol,
+ verified_origin=not self._gateway,
+ endpoint_url=request.endpoint.base_url,
+ sensitive_values=request_credential_values(request.endpoint),
+ )
+ if cancel.cancelled:
+ terminal = assembler.terminal(assembler.aborted(cancel.reason))
+ if terminal is not None:
+ yield terminal
+ return
+ target = origin
+ prepared = await prepare_messages(
+ request.messages,
+ target=target,
+ supports_images=request.supports_images,
+ protocol=self.protocol,
+ media_loader=self._media_loader,
+ cancel=cancel,
+ )
+ if isinstance(prepared, ProviderError):
+ terminal = assembler.terminal(prepared)
+ if terminal is not None:
+ yield terminal
+ return
+ transformed_messages, loaded_images = prepared
+ if cancel.cancelled:
+ terminal = assembler.terminal(assembler.aborted(cancel.reason))
+ if terminal is not None:
+ yield terminal
+ return
+ stop_reason: str | None = None
+ message_started = False
+ message_stopped = False
+ try:
+ payload = build_messages_payload(request, transformed_messages, loaded_images=loaded_images)
+ headers = auth_headers(request.endpoint, provider="anthropic", gateway=self._gateway)
+ headers.update({"anthropic-version": ANTHROPIC_VERSION, "content-type": "application/json"})
+ url = join_endpoint_url(request.endpoint.base_url, "/messages")
+ async def translate(events: AsyncIterator[Any]) -> AsyncIterator[Any]:
+ nonlocal message_started, message_stopped, stop_reason
+ async for event in events:
+ if cancel.cancelled:
+ terminal = assembler.terminal(assembler.aborted(cancel.reason))
+ if terminal is not None:
+ yield terminal
+ return
+ if event.data == "[DONE]" or not event.data:
+ continue
+ if event.event == "ping":
+ continue
+ if event.event == "error":
+ # Pi 7fbbd5f iterateAnthropicEvents handles named
+ # errors before JSON parsing; these may be plain text.
+ terminal = assembler.terminal(assembler.error(event.data))
+ if terminal is not None:
+ yield terminal
+ return
+ if event.event is not None and event.event not in _KNOWN_STREAM_EVENTS:
+ # Pi filters by the SSE event name before parsing its
+ # JSON payload, so unknown event names are ignored
+ # even when their data is malformed.
+ continue
+ chunk = json_object(event.data)
+ if chunk is None:
+ # Pi ignores data-only frames because Anthropic event
+ # dispatch is keyed by the SSE event name. Avibe
+ # accepts valid data-only JSON for gateway
+ # compatibility, but malformed data-only frames are
+ # still ignored rather than misclassified as provider
+ # payload errors.
+ if event.event is None:
+ continue
+ terminal = assembler.terminal(
+ assembler.error("Provider returned invalid Anthropic JSON", kind="invalid_request")
+ )
+ if terminal is not None:
+ yield terminal
+ return
+ try:
+ event_type = dispatch_wire_event(
+ chunk,
+ known=_KNOWN_STREAM_EVENTS,
+ event_name=event.event,
+ )
+ except WireDispatchError as exc:
+ terminal = assembler.terminal(
+ assembler.error(str(exc), kind="invalid_request")
+ )
+ if terminal is not None:
+ yield terminal
+ return
+ if event_type is None:
+ continue
+ shape_error = validate_wire_shape(
+ chunk,
+ event_type,
+ _ANTHROPIC_WIRE_SHAPES,
+ )
+ if shape_error is not None:
+ terminal = assembler.terminal(
+ assembler.error(shape_error, kind="invalid_request")
+ )
+ if terminal is not None:
+ yield terminal
+ return
+ if event_type == "message_start":
+ message_started = True
+ message = chunk.get("message")
+ if not isinstance(message, Mapping):
+ terminal = assembler.terminal(
+ assembler.error("message_start message must be an object", kind="invalid_request")
+ )
+ if terminal is not None:
+ yield terminal
+ return
+ if "usage" in message and not isinstance(message.get("usage"), Mapping):
+ terminal = assembler.terminal(
+ assembler.error("message_start usage must be an object", kind="invalid_request")
+ )
+ if terminal is not None:
+ yield terminal
+ return
+ usage_error = usage_counter_error(
+ message.get("usage"),
+ label="message_start usage",
+ fields=(
+ "input_tokens",
+ "output_tokens",
+ "cache_read_input_tokens",
+ "cache_creation_input_tokens",
+ ),
+ nested_fields={
+ "cache_creation": ("ephemeral_5m_input_tokens", "ephemeral_1h_input_tokens"),
+ "output_tokens_details": ("thinking_tokens",),
+ },
+ )
+ if usage_error is not None:
+ terminal = assembler.terminal(assembler.error(usage_error, kind="invalid_request"))
+ if terminal is not None:
+ yield terminal
+ return
+ assembler.set_usage(
+ _anthropic_usage(message.get("usage"))
+ )
+ elif event_type == "content_block_start":
+ index = _stream_index(chunk)
+ if index is None:
+ terminal = assembler.terminal(
+ assembler.error("content_block_start index must be an integer", kind="invalid_request")
+ )
+ if terminal is not None:
+ yield terminal
+ return
+ block = chunk.get("content_block")
+ if not isinstance(block, Mapping):
+ terminal = assembler.terminal(
+ assembler.error("content_block must be an object", kind="invalid_request")
+ )
+ if terminal is not None:
+ yield terminal
+ return
+ kind = block.get("type")
+ if not isinstance(kind, str):
+ terminal = assembler.terminal(
+ assembler.error(
+ "content_block type must be a string",
+ kind="invalid_request",
+ )
+ )
+ if terminal is not None:
+ yield terminal
+ return
+ if kind == "fallback":
+ if assembler.has_content():
+ terminal = assembler.terminal(
+ assembler.exception(
+ RuntimeError(
+ "Anthropic performed an unsupported mid-output model fallback"
+ )
+ )
+ )
+ if terminal is not None:
+ yield terminal
+ return
+ continue
+ if kind == "text":
+ assembler.set_block_kind(index, "text")
+ assembler.ensure_text_slot(index)
+ initial = block.get("text")
+ if initial is not None and not isinstance(initial, str):
+ terminal = assembler.terminal(
+ assembler.error(
+ "text content must be a string",
+ kind="invalid_request",
+ )
+ )
+ if terminal is not None:
+ yield terminal
+ return
+ if initial:
+ emitted = assembler.text_delta(index, initial)
+ if emitted is not None:
+ yield emitted
+ elif kind == "thinking":
+ raw_signature = block.get("signature")
+ if raw_signature is not None and not isinstance(raw_signature, str):
+ terminal = assembler.terminal(
+ assembler.error(
+ "thinking signature must be a string",
+ kind="invalid_request",
+ )
+ )
+ if terminal is not None:
+ yield terminal
+ return
+ signature = raw_signature
+ signature = signature if isinstance(signature, str) and signature else None
+ assembler.set_block_kind(index, "thinking")
+ assembler.ensure_thinking_slot(index, signature=signature)
+ initial = block.get("thinking")
+ if initial is not None and not isinstance(initial, str):
+ terminal = assembler.terminal(
+ assembler.error(
+ "thinking content must be a string",
+ kind="invalid_request",
+ )
+ )
+ if terminal is not None:
+ yield terminal
+ return
+ if initial:
+ emitted = assembler.thinking_delta(index, initial)
+ if emitted is not None:
+ yield emitted
+ elif kind == "redacted_thinking":
+ signature = block.get("data")
+ if not isinstance(signature, str) or not signature:
+ terminal = assembler.terminal(
+ assembler.error(
+ "redacted_thinking data must be a non-empty string",
+ kind="invalid_request",
+ )
+ )
+ if terminal is not None:
+ yield terminal
+ return
+ assembler.redacted_thinking(index, signature)
+ assembler.set_block_kind(index, "redacted")
+ elif kind == "tool_use":
+ raw_id = block.get("id")
+ if raw_id is not None and not isinstance(raw_id, str):
+ terminal = assembler.terminal(
+ assembler.error(
+ "tool_use id must be a string",
+ kind="invalid_request",
+ )
+ )
+ if terminal is not None:
+ yield terminal
+ return
+ raw_name = block.get("name")
+ if raw_name is not None and not isinstance(raw_name, str):
+ terminal = assembler.terminal(
+ assembler.error(
+ "tool_use name must be a string",
+ kind="invalid_request",
+ )
+ )
+ if terminal is not None:
+ yield terminal
+ return
+ native_id = _string(raw_id) or None
+ name = _string(raw_name)
+ if not name:
+ terminal = assembler.terminal(
+ assembler.error("tool_use name must not be empty", kind="invalid_request")
+ )
+ if terminal is not None:
+ yield terminal
+ return
+ assembler.set_block_kind(index, "tool")
+ start = assembler.tool_start(index, name=name, native_id=native_id)
+ if start is not None:
+ yield start
+ initial_input = block.get("input")
+ if initial_input is not None and not isinstance(initial_input, Mapping):
+ terminal = assembler.terminal(
+ assembler.error(
+ "tool_use input must be an object",
+ kind="invalid_request",
+ )
+ )
+ if terminal is not None:
+ yield terminal
+ return
+ if isinstance(initial_input, Mapping):
+ assembler.set_tool_arguments_object(index, initial_input)
+ elif event_type == "content_block_delta":
+ index = _stream_index(chunk)
+ if index is None:
+ terminal = assembler.terminal(
+ assembler.error("content_block_delta index must be an integer", kind="invalid_request")
+ )
+ if terminal is not None:
+ yield terminal
+ return
+ delta = chunk.get("delta")
+ if not isinstance(delta, Mapping):
+ terminal = assembler.terminal(
+ assembler.error("content_block_delta delta must be an object", kind="invalid_request")
+ )
+ if terminal is not None:
+ yield terminal
+ return
+ delta_type = delta.get("type")
+ if not isinstance(delta_type, str):
+ terminal = assembler.terminal(
+ assembler.error(
+ "content_block_delta type must be a string",
+ kind="invalid_request",
+ )
+ )
+ if terminal is not None:
+ yield terminal
+ return
+ block_kind = assembler.block_kind(index)
+ if block_kind is None:
+ # Pi ignores content deltas for block kinds it
+ # does not know yet; preserve that forward-
+ # compatible policy instead of inventing text.
+ continue
+ if delta_type == "text_delta":
+ if block_kind != "text":
+ continue
+ raw_text = delta.get("text")
+ if "text" in delta and not isinstance(raw_text, str):
+ terminal = assembler.terminal(
+ assembler.error(
+ "text_delta text must be a string",
+ kind="invalid_request",
+ )
+ )
+ if terminal is not None:
+ yield terminal
+ return
+ value = _string(raw_text)
+ if value:
+ emitted = assembler.text_delta(index, value)
+ if emitted is not None:
+ yield emitted
+ elif delta_type == "thinking_delta":
+ if block_kind != "thinking":
+ continue
+ raw_thinking = delta.get("thinking")
+ if "thinking" in delta and not isinstance(raw_thinking, str):
+ terminal = assembler.terminal(
+ assembler.error(
+ "thinking_delta thinking must be a string",
+ kind="invalid_request",
+ )
+ )
+ if terminal is not None:
+ yield terminal
+ return
+ value = _string(raw_thinking)
+ if value:
+ emitted = assembler.thinking_delta(index, value)
+ if emitted is not None:
+ yield emitted
+ elif delta_type == "signature_delta":
+ if block_kind != "thinking":
+ continue
+ raw_signature = delta.get("signature")
+ if "signature" in delta and not isinstance(raw_signature, str):
+ terminal = assembler.terminal(
+ assembler.error(
+ "signature_delta signature must be a string",
+ kind="invalid_request",
+ )
+ )
+ if terminal is not None:
+ yield terminal
+ return
+ value = _string(raw_signature)
+ if value:
+ assembler.append_thinking_signature(index, value)
+ elif delta_type == "input_json_delta":
+ if block_kind != "tool":
+ continue
+ raw_partial_json = delta.get("partial_json")
+ if "partial_json" in delta and not isinstance(raw_partial_json, str):
+ terminal = assembler.terminal(
+ assembler.error(
+ "input_json_delta partial_json must be a string",
+ kind="invalid_request",
+ )
+ )
+ if terminal is not None:
+ yield terminal
+ return
+ value = _string(raw_partial_json)
+ emitted = assembler.tool_arguments(index, value)
+ if emitted is not None:
+ yield emitted
+ # Pi ignores delta variants it does not know yet.
+ # Known event shape has already been validated above.
+ elif event_type == "content_block_stop":
+ index = _stream_index(chunk)
+ if index is None:
+ terminal = assembler.terminal(
+ assembler.error("content_block_stop index must be an integer", kind="invalid_request")
+ )
+ if terminal is not None:
+ yield terminal
+ return
+ end = assembler.block_end(index)
+ if end is not None:
+ yield end
+ elif event_type == "message_delta":
+ delta = chunk.get("delta")
+ if "delta" in chunk and not isinstance(delta, Mapping):
+ terminal = assembler.terminal(
+ assembler.error("message_delta delta must be an object", kind="invalid_request")
+ )
+ if terminal is not None:
+ yield terminal
+ return
+ usage = chunk.get("usage")
+ if usage is not None and not isinstance(usage, Mapping):
+ terminal = assembler.terminal(
+ assembler.error(
+ "message_delta usage must be an object",
+ kind="invalid_request",
+ )
+ )
+ if terminal is not None:
+ yield terminal
+ return
+ usage_error = usage_counter_error(
+ usage,
+ label="message_delta usage",
+ fields=(
+ "input_tokens",
+ "output_tokens",
+ "cache_read_input_tokens",
+ "cache_creation_input_tokens",
+ ),
+ nested_fields={
+ "cache_creation": ("ephemeral_5m_input_tokens", "ephemeral_1h_input_tokens"),
+ "output_tokens_details": ("thinking_tokens",),
+ },
+ )
+ if usage_error is not None:
+ terminal = assembler.terminal(assembler.error(usage_error, kind="invalid_request"))
+ if terminal is not None:
+ yield terminal
+ return
+ if isinstance(delta, Mapping):
+ if delta.get("stop_reason") is not None:
+ if not isinstance(delta.get("stop_reason"), str):
+ terminal = assembler.terminal(
+ assembler.error(
+ "message_delta stop_reason must be a string",
+ kind="invalid_request",
+ )
+ )
+ if terminal is not None:
+ yield terminal
+ return
+ stop_reason = _normalize_stop_reason(delta.get("stop_reason"))
+ assembler.set_usage(_anthropic_usage(usage, current=assembler.usage))
+ elif event_type == "error":
+ shape_error = _error_event_shape_error(chunk)
+ if shape_error is not None:
+ terminal = assembler.terminal(
+ assembler.error(shape_error, kind="invalid_request")
+ )
+ if terminal is not None:
+ yield terminal
+ return
+ terminal = assembler.terminal(
+ assembler.error(
+ json.dumps(dict(chunk), ensure_ascii=False),
+ )
+ )
+ if terminal is not None:
+ yield terminal
+ return
+ elif event_type == "message_stop":
+ message_stopped = True
+ if stop_reason is None:
+ terminal = assembler.terminal(
+ assembler.error(
+ "Anthropic stream ended without a stop reason",
+ kind="invalid_request",
+ )
+ )
+ if terminal is not None:
+ yield terminal
+ return
+ final = assembler.finalize(
+ stop_reason or ("tool_use" if assembler.has_tools() else "stop")
+ )
+ terminal = assembler.terminal(final if isinstance(final, ProviderError) else Done(final))
+ if terminal is not None:
+ yield terminal
+ return
+ elif event_type == "ping":
+ continue
+ if cancel.cancelled:
+ terminal = assembler.terminal(assembler.aborted(cancel.reason))
+ if terminal is not None:
+ yield terminal
+ return
+ if message_started and not message_stopped:
+ terminal = assembler.terminal(assembler.incomplete())
+ if terminal is not None:
+ yield terminal
+ return
+ if stop_reason is not None:
+ final = assembler.finalize(stop_reason)
+ terminal = assembler.terminal(
+ final if isinstance(final, ProviderError) else Done(final)
+ )
+ if terminal is not None:
+ yield terminal
+ return
+ terminal = assembler.terminal(assembler.incomplete())
+ if terminal is not None:
+ yield terminal
+ driver = drive_sse_stream(
+ self._client,
+ method="POST",
+ url=url,
+ json_body=payload,
+ headers=headers,
+ cancel=cancel,
+ assembler=assembler,
+ endpoint=request.endpoint,
+ resolver=self._served_hop_resolver,
+ gateway=self._gateway,
+ translate=translate,
+ )
+ try:
+ async for event in driver:
+ yield event
+ finally:
+ await driver.aclose()
+ except Exception as exc:
+ terminal = assembler.terminal(assembler.exception(exc))
+ if terminal is not None:
+ yield terminal
+
+
+def build_messages_payload(
+ request: ModelRequest,
+ messages: tuple[Any, ...],
+ *,
+ loaded_images: Mapping[str, tuple[str, str]] | None = None,
+) -> dict[str, Any]:
+ """Build the Anthropic Messages request body."""
+
+ payload_messages: list[dict[str, Any]] = []
+ for message in messages:
+ converted = _message_to_anthropic(message, request.supports_images, loaded_images)
+ if converted is None:
+ continue
+ if converted["role"] == "assistant" and not converted["content"]:
+ continue
+ payload_messages.append(converted)
+
+ system: Any = request.system
+ if request.cache == "default" and request.system:
+ system = [{"type": "text", "text": request.system, "cache_control": {"type": "ephemeral"}}]
+ if request.cache == "default":
+ _mark_message_breakpoints(payload_messages)
+ payload: dict[str, Any] = {
+ "model": request.endpoint.model_id,
+ "max_tokens": request.max_tokens,
+ "stream": True,
+ "system": system,
+ "messages": payload_messages,
+ }
+ if request.tools:
+ payload["tools"] = [
+ {
+ "name": tool.name,
+ "description": tool.description,
+ "input_schema": dict(tool.input_schema),
+ **(
+ {"cache_control": {"type": "ephemeral"}}
+ if request.cache == "default" and index == len(request.tools) - 1
+ else {}
+ ),
+ }
+ for index, tool in enumerate(request.tools)
+ ]
+ effort = (request.reasoning_effort or "").lower()
+ if effort in {"none", "off", "disabled"}:
+ payload["thinking"] = {"type": "disabled"}
+ elif effort:
+ if _uses_adaptive_thinking(request.endpoint.model_id):
+ payload["thinking"] = {"type": "adaptive"}
+ payload["output_config"] = {"effort": _anthropic_effort(effort)}
+ else:
+ # Pi's Anthropic adapter uses legacy budget thinking for Claude
+ # 4.5 and older families. The API requires room for the thinking
+ # budget and a response, so expand the request ceiling exactly as
+ # Pi's adjustMaxTokensForThinking helper does.
+ budget = _LEGACY_THINKING_BUDGETS.get(effort, _LEGACY_THINKING_BUDGETS["high"])
+ payload["max_tokens"] = max(payload["max_tokens"], budget + 1024)
+ payload["thinking"] = {
+ "type": "enabled",
+ "budget_tokens": budget,
+ }
+ return payload
+
+
+def _message_to_anthropic(
+ message: Any,
+ supports_images: bool,
+ loaded_images: Mapping[str, tuple[str, str]] | None = None,
+) -> dict[str, Any] | None:
+ if isinstance(message, UserMessage):
+ content = _anthropic_user_content(message.content, supports_images, loaded_images)
+ return {"role": "user", "content": content if len(content) != 1 or content[0]["type"] != "text" else content[0]["text"]}
+ if isinstance(message, AssistantMessage):
+ content: list[dict[str, Any]] = []
+ for block in message.content:
+ if isinstance(block, TextBlock) and block.text:
+ content.append({"type": "text", "text": block.text})
+ elif isinstance(block, ThinkingBlock):
+ if block.redacted:
+ if block.signature:
+ content.append({"type": "redacted_thinking", "data": block.signature})
+ elif block.signature is not None:
+ content.append({"type": "thinking", "thinking": block.text, "signature": block.signature})
+ elif block.text:
+ content.append({"type": "text", "text": block.text})
+ elif isinstance(block, ToolCallBlock):
+ content.append({"type": "tool_use", "id": block.id, "name": block.name, "input": dict(block.arguments)})
+ return {"role": "assistant", "content": content}
+ if isinstance(message, ToolResultMessage):
+ result = _anthropic_user_content(message.content, supports_images, loaded_images)
+ return {
+ "role": "user",
+ "content": [
+ {
+ "type": "tool_result",
+ "tool_use_id": message.tool_call_id,
+ "content": result,
+ "is_error": message.is_error,
+ }
+ ],
+ }
+ return None
+
+
+def _anthropic_user_content(
+ content: tuple[Any, ...],
+ supports_images: bool,
+ loaded_images: Mapping[str, tuple[str, str]] | None = None,
+) -> list[dict[str, Any]]:
+ parts = content_parts(content, include_images=supports_images, loaded_images=loaded_images)
+ result: list[dict[str, Any]] = []
+ for part in parts:
+ if part["type"] == "text":
+ result.append({"type": "text", "text": part["text"]})
+ else:
+ result.append(
+ {
+ "type": "image",
+ "source": {
+ "type": "base64",
+ "media_type": part["mime_type"],
+ "data": part["data"],
+ },
+ }
+ )
+ if not result:
+ result.append({"type": "text", "text": "(no content)"})
+ return result
+
+
+def _mark_message_breakpoints(messages: list[dict[str, Any]]) -> None:
+ candidates = [
+ index
+ for index, message in enumerate(messages)
+ if message.get("role") == "user" and isinstance(message.get("content"), (str, list))
+ ]
+ for index in candidates[-2:]:
+ content = messages[index]["content"]
+ if isinstance(content, str):
+ messages[index]["content"] = [{"type": "text", "text": content, "cache_control": {"type": "ephemeral"}}]
+ elif content:
+ last = content[-1]
+ if isinstance(last, dict) and last.get("type") in {"text", "image", "tool_result"}:
+ last["cache_control"] = {"type": "ephemeral"}
+
+
+def _error_event_shape_error(chunk: Mapping[str, Any]) -> str | None:
+ error = chunk.get("error")
+ if error is not None and not isinstance(error, Mapping):
+ return "Anthropic error must be an object"
+ if isinstance(error, Mapping):
+ for field in ("type", "message"):
+ value = error.get(field)
+ if value is not None and not isinstance(value, str):
+ return f"Anthropic error {field} must be a string"
+ return None
+
+
+def _anthropic_usage(value: Any, *, current: Any = None) -> Any:
+ """Normalize start/delta with the field policy in conversion-tables.md.
+
+ Tool request counts, tier and geography are not canonical token counters.
+ Output already includes thinking; TTLs decompose, never add to, cache writes.
+ """
+
+ if not isinstance(value, Mapping):
+ return current
+ if current is None:
+ current = _usage()
+ return _usage(
+ _pick(value, "input_tokens", current.input_tokens),
+ _pick(value, "output_tokens", current.output_tokens),
+ _pick(value, "cache_read_input_tokens", current.cache_read_tokens),
+ _anthropic_cache_write_tokens(value, current.cache_write_tokens),
+ _pick_nested(value, "output_tokens_details", "thinking_tokens", current.reasoning_tokens),
+ )
+
+
+def _anthropic_cache_write_tokens(value: Mapping[str, Any], fallback: int = 0) -> int:
+ """Keep Anthropic's aggregate cache count, falling back only when absent."""
+
+ aggregate = value.get("cache_creation_input_tokens")
+ if "cache_creation_input_tokens" in value and aggregate is not None:
+ return _nonnegative(aggregate)
+ breakdown = value.get("cache_creation")
+ if isinstance(breakdown, Mapping):
+ counters = [
+ breakdown[key]
+ for key in ("ephemeral_5m_input_tokens", "ephemeral_1h_input_tokens")
+ if breakdown.get(key) is not None
+ ]
+ if counters:
+ return sum(_nonnegative(counter) for counter in counters)
+ return fallback
+
+
+def _usage(input_tokens: int = 0, output_tokens: int = 0, cache_read: int = 0, cache_write: int = 0, reasoning: int | None = None) -> Any:
+ from core.agent_core.messages import Usage
+
+ return Usage(
+ input_tokens=input_tokens,
+ output_tokens=output_tokens,
+ cache_read_tokens=cache_read,
+ cache_write_tokens=cache_write,
+ reasoning_tokens=reasoning,
+ )
+
+
+def _normalize_stop_reason(value: Any) -> str:
+ normalized = {
+ "end_turn": "stop",
+ "stop_sequence": "stop",
+ "pause_turn": "stop",
+ "max_tokens": "length",
+ "tool_use": "tool_use",
+ "refusal": "refusal",
+ "safety": "safety",
+ }.get(str(value))
+ return normalized or "error"
+
+
+def _anthropic_effort(effort: str) -> str:
+ return {"minimal": "low", "xhigh": "max"}.get(effort, effort)
+
+
+def _uses_adaptive_thinking(model_id: str) -> bool:
+ normalized = model_id.lower().replace(".", "-")
+ return any(
+ family in normalized
+ for family in (
+ "claude-opus-4-6",
+ "claude-opus-4-7",
+ "claude-opus-4-8",
+ "claude-sonnet-4-6",
+ "claude-sonnet-5",
+ "claude-opus-5",
+ "claude-fable-5",
+ "claude-mythos-5",
+ )
+ )
+
+
+def _string(value: Any) -> str:
+ return value if isinstance(value, str) else ""
+
+
+def _stream_index(chunk: Mapping[str, Any]) -> int | None:
+ value = chunk.get("index")
+ return value if isinstance(value, int) and not isinstance(value, bool) and value >= 0 else None
+
+
+def _nonnegative(value: Any) -> int:
+ return value if isinstance(value, int) and not isinstance(value, bool) and value >= 0 else 0
+
+
+def _pick(value: Mapping[str, Any], key: str, default: int) -> int:
+ candidate = value.get(key)
+ return default if candidate is None else _nonnegative(candidate)
+
+
+def _pick_nested(value: Mapping[str, Any], parent: str, key: str, default: int | None) -> int | None:
+ nested = value.get(parent)
+ if not isinstance(nested, Mapping):
+ return default
+ candidate = nested.get(key)
+ return default if candidate is None else _nonnegative(candidate)
+
+
+AnthropicProvider = AnthropicAdapter
diff --git a/core/agent_core/ai/errors.py b/core/agent_core/ai/errors.py
new file mode 100644
index 000000000..019af301e
--- /dev/null
+++ b/core/agent_core/ai/errors.py
@@ -0,0 +1,612 @@
+"""Provider error classification.
+
+Overflow expressions are ported from Pi's ``packages/ai/src/utils/overflow.ts``
+(MIT, revision 7fbbd5f). The adapter layer adds HTTP and transport semantics
+from C-2.
+"""
+
+from __future__ import annotations
+
+import json
+import re
+from dataclasses import replace
+from datetime import datetime, timezone
+from email.utils import parsedate_to_datetime
+from typing import Any, Mapping
+from urllib.parse import urlsplit
+
+import httpx
+
+from core.agent_core.messages import AssistantMessage
+from core.agent_core.ai.provider import ProviderError
+
+_OVERFLOW_PATTERNS = (
+ r"prompt (?:is )?too long",
+ r"prompt exceeds max length",
+ r"request_too_large",
+ r"input is too long for requested model",
+ r"exceeds the context window",
+ r"exceeds (?:the )?(?:model'?s )?maximum context length(?: of [\d,]+ tokens?|\s*\([\d,]+\))",
+ r"input token count.*exceeds the maximum",
+ r"maximum prompt length is \d+",
+ r"reduce the length of the messages",
+ r"maximum context length is \d+ tokens",
+ r"exceeds (?:the )?maximum allowed input length of [\d,]+ tokens?",
+ r"input \(\d+ tokens\) is longer than the model'?s context length \d+ tokens",
+ r"exceeds the limit of \d+",
+ r"exceeds the available context size",
+ r"greater than the context length",
+ r"context window exceeds limit",
+ r"exceeded model token limit",
+ r"too large for model with \d+ maximum context length",
+ r"prompt has [\d,]+ tokens?, but the configured context size is [\d,]+ tokens?",
+ r"model_context_window_exceeded",
+ r"prompt too long; exceeded (?:max )?context length",
+ r"range of input length should be",
+ r"context[_ ]length[_ ]exceeded",
+ r"too many tokens",
+ r"token limit exceeded",
+ r"4(?:00|13)\s*(?:status code)?\s*\(no body\)",
+)
+_OVERFLOW_RE = tuple(re.compile(pattern, re.IGNORECASE) for pattern in _OVERFLOW_PATTERNS)
+_NON_OVERFLOW_RE = (
+ re.compile(r"^(?:throttling error|service unavailable):", re.IGNORECASE),
+ re.compile(r"rate limit", re.IGNORECASE),
+ re.compile(r"too many requests", re.IGNORECASE),
+)
+_BEARER_RE = re.compile(
+ r"(?ix)\bBearer\s+"
+ r"(?=[A-Za-z0-9._~+/=-]{8,}(?:\b|$))"
+ r"(?=[A-Za-z0-9._~+/=-]*\d)"
+ r"[A-Za-z0-9._~+/=-]+"
+)
+# Syntax only: the predicate below owns the vocabulary for JSON, free text,
+# and configured headers alike. Scan prefixes only: a non-sensitive key never
+# rescans or copies the remainder of the line.
+_CREDENTIAL_KEY_RE = re.compile(
+ r"""(?ix)
+ (?<![a-z0-9_.-])
+ (?P<key>["']?[a-z][a-z0-9_.-]*(?:[ \t]+[a-z][a-z0-9_.-]*){0,3}["']?)
+ (?P<separator>[ \t]*[:=][ \t]*)
+ """
+)
+_QUOTED_CREDENTIAL_VALUE_RE = re.compile(r""""(?:\\.|[^"\\\r\n])*"|'(?:\\.|[^'\\\r\n])*'""")
+_LINE_END_RE = re.compile(r"[\r\n]")
+_AUTH_SCHEME_RE = re.compile(r"(?i)(Bearer|Basic|Digest|Token|AWS4-HMAC-SHA256)[ \t]+\S")
+_DIAGNOSTIC_URL_RE = re.compile(r"""https?://[^\s"'<>\\]+""", re.IGNORECASE)
+_TOKEN_SHAPE_RE = re.compile(
+ r"(?ix)(?<![A-Za-z0-9_-])(?:"
+ r"sk-[A-Za-z0-9][A-Za-z0-9._~+/=-]*|"
+ r"AIza[A-Za-z0-9_-]+|"
+ r"gsk_[A-Za-z0-9_-]+|"
+ r"gh[pousr]_[A-Za-z0-9_-]+|"
+ r"eyJ[A-Za-z0-9_-]{3,}\.[A-Za-z0-9_-]{3,}\.[A-Za-z0-9_-]{3,}"
+ r")(?![A-Za-z0-9_-])"
+)
+_SENSITIVE_KEYS = {
+ "authorization",
+ "proxy_authorization",
+ "api_key",
+ "key",
+ "apikey",
+ "x-api-key",
+ "x_api_key",
+ "x-goog-api-key",
+ "x_goog_api_key",
+ "ocp_apim_subscription_key",
+ "token",
+ "secret",
+ "password",
+ "cookie",
+ "set_cookie",
+ "credential",
+ "credentials",
+ "private_key",
+ "client_secret",
+ "access_token",
+ "refresh_token",
+ "oauth_token",
+ "auth",
+ "auth_key",
+ "access_key",
+ "client_key",
+ "refresh_key",
+ "oauth_key",
+}
+
+
+def classify_error(
+ *,
+ status: int | None = None,
+ body: str = "",
+ headers: Mapping[str, str] | None = None,
+ streamed: bool = False,
+ partial: AssistantMessage | None = None,
+ exc: BaseException | None = None,
+ code: str | None = None,
+ protocol: str | None = None,
+) -> ProviderError:
+ """Classify one HTTP, provider-body, or network failure."""
+
+ message = _error_message(body, exc)
+ retry_after = parse_retry_after(_header_value(headers, "retry-after"))
+ extracted_code = _extract_code(body, protocol=protocol)
+ effective_code = code
+ if not effective_code or _is_generic_code(effective_code):
+ effective_code = extracted_code or effective_code
+ kind = _classify_kind(
+ status=status,
+ message=f"{body}\n{message}",
+ exc=exc,
+ code=effective_code,
+ )
+ retryable = kind in {"rate_limit", "overloaded", "network", "server"} and not streamed
+ return ProviderError(
+ kind=kind,
+ message=message,
+ retryable=retryable,
+ retry_after_s=retry_after,
+ status=status,
+ partial=partial,
+ )
+
+
+def classify_http_error(
+ status: int,
+ body: str = "",
+ *,
+ headers: Mapping[str, str] | None = None,
+ streamed: bool = False,
+ partial: AssistantMessage | None = None,
+) -> ProviderError:
+ return classify_error(
+ status=status,
+ body=body,
+ headers=headers,
+ streamed=streamed,
+ partial=partial,
+ )
+
+
+def classify_network_error(
+ exc: BaseException,
+ *,
+ streamed: bool = False,
+ partial: AssistantMessage | None = None,
+) -> ProviderError:
+ return classify_error(exc=exc, streamed=streamed, partial=partial)
+
+
+def parse_retry_after(value: str | None) -> float | None:
+ if not value:
+ return None
+ try:
+ return max(0.0, float(value.strip()))
+ except ValueError:
+ pass
+ try:
+ target = parsedate_to_datetime(value)
+ if target.tzinfo is None:
+ target = target.replace(tzinfo=timezone.utc)
+ return max(0.0, (target - datetime.now(timezone.utc)).total_seconds())
+ except (TypeError, ValueError, OverflowError):
+ return None
+
+
+def is_overflow_message(message: str, *, status: int | None = None) -> bool:
+ if status == 413:
+ return True
+ if any(pattern.search(message) for pattern in _NON_OVERFLOW_RE):
+ return False
+ return any(pattern.search(message) for pattern in _OVERFLOW_RE)
+
+
+def _classify_kind(
+ *,
+ status: int | None,
+ message: str,
+ exc: BaseException | None,
+ code: str | None = None,
+) -> str:
+ if status == 413:
+ return "overflow"
+ if status in {401, 403}:
+ return "auth"
+ if status == 429:
+ return "rate_limit"
+ if status is not None and 300 <= status < 400:
+ return "invalid_request"
+ if status is not None and status >= 500:
+ if status in {529} or "overloaded" in message.lower():
+ return "overloaded"
+ return "server"
+ if status in {408, 409, 425}:
+ return "server"
+ normalized_code = (code or "").lower().replace("-", "_")
+ if normalized_code in {
+ "authentication_error",
+ "authentication",
+ "auth_error",
+ "invalid_api_key",
+ "invalid_api_key_error",
+ "api_key_invalid",
+ "api_key_invalid_error",
+ "permission",
+ "permission_error",
+ "permission_denied",
+ "unauthenticated",
+ "unauthorized",
+ "forbidden",
+ }:
+ return "auth"
+ if normalized_code in {
+ "rate_limit",
+ "rate_limited",
+ "rate_limit_error",
+ "too_many_requests",
+ "resource_exhausted",
+ }:
+ return "rate_limit"
+ if normalized_code in {"overloaded", "overload", "overloaded_error"}:
+ return "overloaded"
+ if normalized_code in {
+ "server_error",
+ "internal_server_error",
+ "bad_gateway",
+ "service_unavailable",
+ "internal",
+ "api_error",
+ "unavailable",
+ "deadline_exceeded",
+ "aborted",
+ }:
+ return "server"
+ if normalized_code in {"context_length_exceeded", "request_too_large"}:
+ return "overflow"
+ if is_overflow_message(message, status=status):
+ return "overflow"
+ if exc is not None:
+ if isinstance(
+ exc,
+ (
+ TimeoutError,
+ httpx.TimeoutException,
+ httpx.NetworkError,
+ httpx.TransportError,
+ OSError,
+ ),
+ ):
+ return "network"
+ return "unknown"
+ lowered = message.lower()
+ if "rate limit" in lowered or "too many requests" in lowered or "rate_limit" in lowered:
+ return "rate_limit"
+ if "overloaded" in lowered or "overload" in lowered:
+ return "overloaded"
+ if any(token in lowered for token in ("service unavailable", "internal server", "bad gateway", "server error")):
+ return "server"
+ if "unauthorized" in lowered or "forbidden" in lowered:
+ return "auth"
+ if status is not None and 400 <= status < 500:
+ return "invalid_request"
+ return "unknown"
+
+
+def _error_message(body: str, exc: BaseException | None) -> str:
+ if body:
+ try:
+ value = json.loads(body)
+ except (TypeError, ValueError):
+ return body.strip() or "provider request failed"
+ extracted = _extract_message(value)
+ if extracted:
+ return extracted
+ return json.dumps(
+ value,
+ ensure_ascii=False,
+ separators=(",", ":"),
+ )
+ if exc is not None:
+ return str(exc) or type(exc).__name__
+ return "provider request failed"
+
+
+def redact_provider_text(
+ value: str,
+ *,
+ literal_secrets: tuple[str, ...] = (),
+ endpoint_url: str | None = None,
+) -> str:
+ """Redact credentials from any provider diagnostic text."""
+
+ # Parse first so URL punctuation and escaped quotes cannot corrupt JSON.
+ try:
+ parsed = json.loads(value)
+ except (TypeError, ValueError):
+ parsed = None
+ if isinstance(parsed, (Mapping, list)):
+ return json.dumps(
+ _redact_json(parsed, literal_secrets=literal_secrets, endpoint_url=endpoint_url),
+ ensure_ascii=False,
+ separators=(",", ":"),
+ )
+ return _redact_free_text(value, literal_secrets=literal_secrets, endpoint_url=endpoint_url)
+
+
+def _redact_free_text(
+ value: str,
+ *,
+ literal_secrets: tuple[str, ...] = (),
+ endpoint_url: str | None = None,
+) -> str:
+ value = sanitize_endpoint_text(value, endpoint_url)
+ # Decide key sensitivity before replacing literals so a configured
+ # placeholder cannot destroy a credential key in a diagnostic.
+ value = _redact_credential_pairs(value)
+ for secret in _literal_secret_variants(literal_secrets):
+ value = value.replace(secret, "[redacted]")
+ value = _BEARER_RE.sub("Bearer [redacted]", value)
+ return _TOKEN_SHAPE_RE.sub("[redacted]", value)
+
+
+def redact_provider_error(
+ error: ProviderError,
+ *,
+ literal_secrets: tuple[str, ...] = (),
+ endpoint_url: str | None = None,
+) -> ProviderError:
+ """Apply the single provider-diagnostic redaction boundary."""
+
+ partial = error.partial
+ if partial is not None and partial.error_message is not None:
+ partial = replace(
+ partial,
+ error_message=redact_provider_text(
+ partial.error_message,
+ literal_secrets=literal_secrets,
+ endpoint_url=endpoint_url,
+ ),
+ )
+ return replace(
+ error,
+ message=redact_provider_text(
+ error.message,
+ literal_secrets=literal_secrets,
+ endpoint_url=endpoint_url,
+ ),
+ partial=partial,
+ )
+
+
+def _redact_credential_pairs(value: str) -> str:
+ pieces: list[str] = []
+ position = copied = 0
+ while match := _CREDENTIAL_KEY_RE.search(value, position):
+ position = match.end()
+ key = match.group("key").strip("\"'")
+ if not _is_sensitive_key(key):
+ continue
+ quoted = _QUOTED_CREDENTIAL_VALUE_RE.match(value, position)
+ quote = value[position] if quoted else ""
+ if quoted is not None:
+ end = quoted.end()
+ else:
+ newline = _LINE_END_RE.search(value, position)
+ end = newline.start() if newline else len(value)
+ raw_start = position + bool(quote)
+ scheme = _AUTH_SCHEME_RE.match(value, raw_start, end)
+ replacement = "[redacted]"
+ if key.lower().endswith("authorization") and scheme:
+ replacement = f"{scheme.group(1)} [redacted]"
+ pieces.extend((value[copied:position], quote, replacement, quote))
+ position = copied = end
+ pieces.append(value[copied:])
+ return "".join(pieces)
+
+
+def _literal_secret_variants(literal_secrets: tuple[str, ...]) -> tuple[str, ...]:
+ variants: set[str] = set()
+ for secret in literal_secrets:
+ if not secret:
+ continue
+ escaped = secret.encode("unicode_escape").decode("ascii")
+ for candidate in (secret, secret.strip(), escaped, escaped.strip()):
+ if len(candidate) >= 8:
+ variants.add(candidate)
+ return tuple(sorted(variants, key=len, reverse=True))
+
+
+def _credential_free_url(raw: str) -> str:
+ try:
+ parsed = urlsplit(raw)
+ except ValueError:
+ return "[redacted-url]"
+ if not parsed.scheme:
+ return "[redacted-url]"
+ host = parsed.hostname
+ if host is None:
+ authority = parsed.netloc.rsplit("@", 1)[-1]
+ return f"{parsed.scheme}://{authority}{parsed.path or '/'}"
+ if ":" in host and not host.startswith("["):
+ host = f"[{host}]"
+ try:
+ port = parsed.port
+ except ValueError:
+ port = None
+ if port is not None:
+ host = f"{host}:{port}"
+ identity = f"{parsed.scheme}://{host}{parsed.path or '/'}"
+ return identity
+
+
+def sanitize_endpoint_text(text: str, endpoint_url: str | None = None) -> str:
+ """Strip URL credentials without consuming surrounding diagnostic syntax."""
+
+ if endpoint_url:
+ text = text.replace(endpoint_url, _credential_free_url(endpoint_url))
+
+ def sanitize(match: re.Match[str]) -> str:
+ raw = match.group(0)
+ url = raw.rstrip(".,;:!?)]}")
+ return _credential_free_url(url) + raw[len(url):]
+
+ return _DIAGNOSTIC_URL_RE.sub(sanitize, text)
+
+
+def _extract_message(value: Any) -> str | None:
+ if isinstance(value, str):
+ return value
+ if isinstance(value, Mapping):
+ for key in ("message", "error", "detail", "description", "status"):
+ if key not in value:
+ continue
+ nested = _extract_message(value[key])
+ if nested:
+ return nested
+ if isinstance(value, list):
+ for item in value:
+ nested = _extract_message(item)
+ if nested:
+ return nested
+ return None
+
+
+def _extract_code(body: str, *, protocol: str | None = None) -> str | None:
+ """Extract the provider's standard code from any common error envelope."""
+
+ try:
+ value = json.loads(body)
+ except (TypeError, ValueError):
+ return None
+ return _find_code(value, protocol=protocol)
+
+
+def _is_generic_code(code: str) -> bool:
+ return code.lower().replace("-", "_") in {
+ "error",
+ "provider_error",
+ "invalid_argument",
+ "invalid_request",
+ "bad_request",
+ }
+
+
+def _find_code(value: Any, *, protocol: str | None = None) -> str | None:
+ if isinstance(value, Mapping):
+ # Prefer a specific code on the current envelope. Generic wrapper
+ # statuses such as INVALID_ARGUMENT still defer to nested provider
+ # details from provider-specific nested error metadata.
+ key_order = {
+ "anthropic": ("type", "status"),
+ "openai_chat": ("code", "type"),
+ "openai_responses": ("code", "type"),
+ }.get(protocol, ("code", "status", "type"))
+ for key in key_order:
+ candidate = value.get(key)
+ if (
+ isinstance(candidate, str)
+ and not _is_generic_code(candidate)
+ and not candidate.lstrip("-").isdigit()
+ ):
+ return candidate
+ for key in ("error", "details", "cause"):
+ if key in value:
+ nested = _find_code(value[key], protocol=protocol)
+ if nested:
+ return nested
+ for key in key_order:
+ candidate = value.get(key)
+ if isinstance(candidate, str) and not candidate.lstrip("-").isdigit():
+ return candidate
+ candidate = value.get("reason")
+ if isinstance(candidate, str):
+ return candidate
+ elif isinstance(value, list):
+ for item in value:
+ nested = _find_code(item, protocol=protocol)
+ if nested:
+ return nested
+ return None
+
+
+def _redact_json(
+ value: Any,
+ *,
+ key: str | None = None,
+ literal_secrets: tuple[str, ...] = (),
+ endpoint_url: str | None = None,
+) -> Any:
+ if key is not None and _is_sensitive_key(key):
+ return "[redacted]"
+ if isinstance(value, Mapping):
+ return {
+ str(item_key): _redact_json(
+ item_value,
+ key=str(item_key),
+ literal_secrets=literal_secrets,
+ endpoint_url=endpoint_url,
+ )
+ for item_key, item_value in value.items()
+ }
+ if isinstance(value, list):
+ return [
+ _redact_json(item, literal_secrets=literal_secrets, endpoint_url=endpoint_url)
+ for item in value
+ ]
+ if isinstance(value, str):
+ return redact_provider_text(value, literal_secrets=literal_secrets, endpoint_url=endpoint_url)
+ return value
+
+
+def _is_sensitive_key(key: str) -> bool:
+ camel_case = re.sub(r"(?<=[a-z0-9])(?=[A-Z])", "_", key)
+ normalized = re.sub(r"[^a-z0-9]+", "_", camel_case.lower()).strip("_")
+ if normalized in _SENSITIVE_KEYS:
+ return True
+ if normalized in {"tokenizer", "tokens", "token_count", "token_limit"} or normalized.endswith(
+ ("_tokens", "_token_count", "_token_limit")
+ ) or normalized in {
+ "max_tokens",
+ "budget_tokens",
+ "context_tokens",
+ }:
+ return False
+ parts = set(normalized.split("_"))
+ if any(word in normalized for word in ("secret", "credential", "password")):
+ return True
+ if parts & {
+ "authorization",
+ "auth",
+ "apikey",
+ "password",
+ "cookie",
+ "credential",
+ "credentials",
+ "private",
+ "secret",
+ "token",
+ }:
+ return True
+ return len(parts) >= 2 and (
+ parts.intersection({"access", "client", "refresh", "oauth", "private", "auth", "api"})
+ and parts.intersection({"key", "secret", "token"})
+ )
+
+
+def _header_value(headers: Mapping[str, str] | None, name: str) -> str | None:
+ if headers is None:
+ return None
+ for key, value in headers.items():
+ if key.lower() == name:
+ return value
+ return None
+
+
+class ProviderErrorClassifier:
+ """Small callable wrapper useful to tests and adapter integrations."""
+
+ def __call__(self, **kwargs: Any) -> ProviderError:
+ return classify_error(**kwargs)
+
+
+classify_provider_error = classify_error
diff --git a/core/agent_core/ai/openai_chat.py b/core/agent_core/ai/openai_chat.py
new file mode 100644
index 000000000..a98cafcdd
--- /dev/null
+++ b/core/agent_core/ai/openai_chat.py
@@ -0,0 +1,875 @@
+"""OpenAI Chat Completions streaming adapter.
+
+Payload and stream rules are ported from tau's ``tau_ai/openai_compatible.py``
+(MIT) and Pi's ``packages/ai/src/api/openai-completions.ts`` (MIT).
+"""
+
+from __future__ import annotations
+
+import json
+from collections.abc import AsyncIterator, Mapping
+from itertools import groupby
+from typing import Any
+
+import httpx
+
+from core.agent_core.ai._common import (
+ ServedHopResolver,
+ auth_headers,
+ content_parts,
+ drive_sse_stream,
+ endpoint_origin,
+ join_endpoint_url,
+ json_object,
+ prepare_messages,
+ request_credential_values,
+ StreamAssembler,
+ validate_wire_shape,
+ WireField,
+ usage_counter_error,
+)
+from core.agent_core.ai.provider import (
+ Done,
+ MediaLoader,
+ ModelRequest,
+ ProviderAdapter,
+ ProviderError,
+)
+from core.agent_core.cancel import CancelToken
+from core.agent_core.messages import (
+ AssistantMessage,
+ ImageBlock,
+ TextBlock,
+ ThinkingBlock,
+ ToolCallBlock,
+ ToolResultMessage,
+ UserMessage,
+)
+
+
+_CHAT_USAGE_FIELDS = (
+ WireField("prompt_tokens", int),
+ WireField("completion_tokens", int),
+ WireField("prompt_cache_hit_tokens", int),
+ WireField("cached_tokens", int),
+ WireField(
+ "prompt_tokens_details",
+ Mapping,
+ children=(
+ WireField("cached_tokens", int),
+ WireField("cache_write_tokens", int),
+ ),
+ ),
+ WireField(
+ "completion_tokens_details",
+ Mapping,
+ children=(WireField("reasoning_tokens", int),),
+ ),
+)
+_CHAT_REASONING_DETAIL_FIELDS = (
+ WireField("type", str),
+ WireField("text", str),
+ WireField("summary", str),
+ WireField("id", str),
+ WireField("format", str),
+ WireField("index", int),
+ WireField("signature", str),
+ WireField("data", str),
+ WireField("encrypted_content", str),
+)
+_CHAT_TOOL_CALL_FIELDS = (
+ WireField("id", str),
+ WireField("index", int),
+ WireField(
+ "function",
+ Mapping,
+ children=(
+ WireField("name", str),
+ WireField("arguments", str),
+ ),
+ ),
+)
+_CHAT_DELTA_FIELDS = (
+ WireField("content", str),
+ WireField("reasoning_content", str),
+ WireField("reasoning", str),
+ WireField("reasoning_text", str),
+ WireField("refusal", str),
+ WireField(
+ "reasoning_details",
+ list,
+ item_children=_CHAT_REASONING_DETAIL_FIELDS,
+ ),
+ WireField(
+ "tool_calls",
+ list,
+ item_children=_CHAT_TOOL_CALL_FIELDS,
+ ),
+ WireField(
+ "function_call",
+ Mapping,
+ children=(
+ WireField("name", str),
+ WireField("arguments", str),
+ ),
+ ),
+)
+_CHAT_WIRE_SHAPES = {
+ "chunk": (
+ WireField("usage", Mapping, children=_CHAT_USAGE_FIELDS),
+ WireField(
+ "error",
+ Mapping,
+ children=(
+ WireField("type", str),
+ WireField("code", (str, int)),
+ WireField("message", str),
+ ),
+ ),
+ WireField(
+ "choices",
+ list,
+ item_children=(
+ WireField("finish_reason", str),
+ WireField("native_finish_reason", str),
+ WireField("usage", Mapping, children=_CHAT_USAGE_FIELDS),
+ WireField(
+ "delta",
+ Mapping,
+ children=_CHAT_DELTA_FIELDS,
+ ),
+ ),
+ ),
+ ),
+}
+
+
+class OpenAIChatAdapter(ProviderAdapter):
+ """Adapter for OpenAI-compatible ``/chat/completions`` endpoints."""
+
+ protocol = "openai_chat"
+
+ def __init__(
+ self,
+ client: httpx.AsyncClient | None = None,
+ *,
+ media_loader: MediaLoader | None = None,
+ served_hop_resolver: ServedHopResolver | None = None,
+ gateway: bool = False,
+ ) -> None:
+ self._client = client or httpx.AsyncClient(timeout=None)
+ self._owns_client = client is None
+ self._media_loader = media_loader
+ self._served_hop_resolver = served_hop_resolver
+ self._gateway = gateway
+
+ async def aclose(self) -> None:
+ if self._owns_client:
+ await self._client.aclose()
+
+ def stream(self, request: ModelRequest, cancel: CancelToken) -> AsyncIterator[Any]:
+ return self._stream(request, cancel)
+
+ async def _stream(self, request: ModelRequest, cancel: CancelToken) -> AsyncIterator[Any]:
+ target = endpoint_origin(request.endpoint)
+ assembler = StreamAssembler(
+ origin=target,
+ protocol=self.protocol,
+ verified_origin=not self._gateway,
+ endpoint_url=request.endpoint.base_url,
+ sensitive_values=request_credential_values(request.endpoint),
+ )
+ if cancel.cancelled:
+ terminal = assembler.terminal(assembler.aborted(cancel.reason))
+ if terminal is not None:
+ yield terminal
+ return
+ prepared = await prepare_messages(
+ request.messages,
+ target=target,
+ supports_images=request.supports_images,
+ protocol=self.protocol,
+ media_loader=self._media_loader,
+ cancel=cancel,
+ )
+ if isinstance(prepared, ProviderError):
+ terminal = assembler.terminal(prepared)
+ if terminal is not None:
+ yield terminal
+ return
+ transformed_messages, loaded_images = prepared
+ if cancel.cancelled:
+ terminal = assembler.terminal(assembler.aborted(cancel.reason))
+ if terminal is not None:
+ yield terminal
+ return
+ finish_reason: str | None = None
+ native_finish_reason: str | None = None
+ refusal_seen = False
+ protocol_terminal = False
+ try:
+ payload = build_chat_payload(request, transformed_messages, loaded_images=loaded_images)
+ headers = auth_headers(request.endpoint, provider="openai", gateway=self._gateway)
+ headers.setdefault("content-type", "application/json")
+ url = join_endpoint_url(request.endpoint.base_url, "/chat/completions")
+ async def translate(events: AsyncIterator[Any]) -> AsyncIterator[Any]:
+ nonlocal finish_reason, native_finish_reason, refusal_seen, protocol_terminal
+ async for event in events:
+ if cancel.cancelled:
+ terminal = assembler.terminal(assembler.aborted(cancel.reason))
+ if terminal is not None:
+ yield terminal
+ return
+ if not event.data:
+ continue
+ if event.data == "[DONE]":
+ break
+ chunk = json_object(event.data)
+ if chunk is None:
+ terminal = assembler.terminal(
+ assembler.error("Provider returned invalid OpenAI Chat JSON", kind="invalid_request")
+ )
+ if terminal is not None:
+ yield terminal
+ return
+ shape_error = validate_wire_shape(chunk, "chunk", _CHAT_WIRE_SHAPES)
+ if shape_error is not None:
+ terminal = assembler.terminal(
+ assembler.error(shape_error, kind="invalid_request")
+ )
+ if terminal is not None:
+ yield terminal
+ return
+ if "usage" in chunk and chunk.get("usage") is not None and not isinstance(chunk.get("usage"), Mapping):
+ terminal = assembler.terminal(
+ assembler.error("OpenAI Chat usage must be an object", kind="invalid_request")
+ )
+ if terminal is not None:
+ yield terminal
+ return
+ usage_error = usage_counter_error(
+ chunk.get("usage"),
+ label="OpenAI Chat usage",
+ fields=("prompt_tokens", "completion_tokens", "prompt_cache_hit_tokens", "cached_tokens"),
+ nested_fields={
+ "prompt_tokens_details": ("cached_tokens", "cache_write_tokens"),
+ "completion_tokens_details": ("reasoning_tokens",),
+ },
+ )
+ if usage_error is not None:
+ terminal = assembler.terminal(assembler.error(usage_error, kind="invalid_request"))
+ if terminal is not None:
+ yield terminal
+ return
+ if isinstance(chunk.get("usage"), Mapping):
+ assembler.set_usage(_openai_usage(chunk["usage"]))
+ top_level_error = chunk.get("error")
+ if top_level_error is not None and not isinstance(top_level_error, Mapping):
+ terminal = assembler.terminal(
+ assembler.error("OpenAI Chat error must be an object", kind="invalid_request")
+ )
+ if terminal is not None:
+ yield terminal
+ return
+ if isinstance(top_level_error, Mapping):
+ for field in ("type", "code", "message"):
+ value = top_level_error.get(field)
+ if field == "code" and isinstance(value, int) and not isinstance(value, bool):
+ continue
+ if value is not None and not isinstance(value, str):
+ terminal = assembler.terminal(
+ assembler.error(
+ f"OpenAI Chat error {field} must be a string",
+ kind="invalid_request",
+ )
+ )
+ if terminal is not None:
+ yield terminal
+ return
+ terminal = assembler.terminal(
+ assembler.error(
+ json.dumps(dict(chunk), ensure_ascii=False),
+ )
+ )
+ if terminal is not None:
+ yield terminal
+ return
+ choices = chunk.get("choices")
+ if choices is not None and not isinstance(choices, list):
+ terminal = assembler.terminal(
+ assembler.error("OpenAI Chat choices must be an array", kind="invalid_request")
+ )
+ if terminal is not None:
+ yield terminal
+ return
+ if choices is None or not choices:
+ continue
+ choice = choices[0]
+ if not isinstance(choice, Mapping):
+ terminal = assembler.terminal(
+ assembler.error("OpenAI Chat choice must be an object", kind="invalid_request")
+ )
+ if terminal is not None:
+ yield terminal
+ return
+ choice_usage = choice.get("usage")
+ if choice_usage is not None and not isinstance(choice_usage, Mapping):
+ terminal = assembler.terminal(
+ assembler.error("OpenAI Chat choice usage must be an object", kind="invalid_request")
+ )
+ if terminal is not None:
+ yield terminal
+ return
+ usage_error = usage_counter_error(
+ choice_usage,
+ label="OpenAI Chat choice usage",
+ fields=("prompt_tokens", "completion_tokens", "prompt_cache_hit_tokens", "cached_tokens"),
+ nested_fields={
+ "prompt_tokens_details": ("cached_tokens", "cache_write_tokens"),
+ "completion_tokens_details": ("reasoning_tokens",),
+ },
+ )
+ if usage_error is not None:
+ terminal = assembler.terminal(assembler.error(usage_error, kind="invalid_request"))
+ if terminal is not None:
+ yield terminal
+ return
+ if not isinstance(chunk.get("usage"), Mapping) and isinstance(choice_usage, Mapping):
+ assembler.set_usage(_openai_usage(choice_usage))
+ if choice.get("finish_reason") is not None:
+ if not isinstance(choice.get("finish_reason"), str):
+ terminal = assembler.terminal(
+ assembler.error(
+ "OpenAI Chat finish_reason must be a string",
+ kind="invalid_request",
+ )
+ )
+ if terminal is not None:
+ yield terminal
+ return
+ finish_reason = _string(choice.get("finish_reason"))
+ raw_native_finish_reason = choice.get("native_finish_reason")
+ if raw_native_finish_reason is not None and not isinstance(
+ raw_native_finish_reason, str
+ ):
+ terminal = assembler.terminal(
+ assembler.error(
+ "OpenAI Chat native_finish_reason must be a string",
+ kind="invalid_request",
+ )
+ )
+ if terminal is not None:
+ yield terminal
+ return
+ if raw_native_finish_reason is not None:
+ native_finish_reason = _string(raw_native_finish_reason)
+ delta = choice.get("delta")
+ if delta is None or not isinstance(delta, Mapping):
+ if delta is None:
+ continue
+ terminal = assembler.terminal(
+ assembler.error("OpenAI Chat delta must be an object", kind="invalid_request")
+ )
+ if terminal is not None:
+ yield terminal
+ return
+ raw_content = delta.get("content")
+ if raw_content is not None and not isinstance(raw_content, str):
+ terminal = assembler.terminal(
+ assembler.error(
+ "OpenAI Chat content must be a string",
+ kind="invalid_request",
+ )
+ )
+ if terminal is not None:
+ yield terminal
+ return
+ value = _string(raw_content)
+ if value:
+ emitted = assembler.text_delta("chat-text", value)
+ if emitted is not None:
+ yield emitted
+ reasoning_field, reasoning = _first_reasoning_delta(delta)
+ for field in ("reasoning_content", "reasoning", "reasoning_text"):
+ raw_reasoning = delta.get(field)
+ if raw_reasoning is not None and not isinstance(raw_reasoning, str):
+ terminal = assembler.terminal(
+ assembler.error(
+ f"OpenAI Chat {field} must be a string",
+ kind="invalid_request",
+ )
+ )
+ if terminal is not None:
+ yield terminal
+ return
+ if reasoning:
+ emitted = assembler.thinking_delta("chat-thinking", reasoning, signature=reasoning_field)
+ if emitted is not None:
+ yield emitted
+ raw_refusal = delta.get("refusal")
+ if raw_refusal is not None and not isinstance(raw_refusal, str):
+ terminal = assembler.terminal(
+ assembler.error(
+ "OpenAI Chat refusal must be a string",
+ kind="invalid_request",
+ )
+ )
+ if terminal is not None:
+ yield terminal
+ return
+ refusal = _string(raw_refusal)
+ if refusal:
+ refusal_seen = True
+ emitted = assembler.text_delta("chat-text", refusal)
+ if emitted is not None:
+ yield emitted
+ details = delta.get("reasoning_details")
+ if details is not None and not isinstance(details, list):
+ terminal = assembler.terminal(
+ assembler.error(
+ "OpenAI Chat reasoning_details must be an array",
+ kind="invalid_request",
+ )
+ )
+ if terminal is not None:
+ yield terminal
+ return
+ if isinstance(details, list):
+ if any(not isinstance(detail, Mapping) for detail in details):
+ terminal = assembler.terminal(
+ assembler.error(
+ "OpenAI Chat reasoning_details entries must be objects",
+ kind="invalid_request",
+ )
+ )
+ if terminal is not None:
+ yield terminal
+ return
+ assembler.merge_thinking_details("chat-thinking", details)
+ raw_tool_calls = delta.get("tool_calls")
+ if raw_tool_calls is not None and not isinstance(raw_tool_calls, list):
+ terminal = assembler.terminal(
+ assembler.error("OpenAI Chat tool_calls must be an array", kind="invalid_request")
+ )
+ if terminal is not None:
+ yield terminal
+ return
+ if isinstance(raw_tool_calls, list):
+ for raw in raw_tool_calls:
+ if not isinstance(raw, Mapping):
+ terminal = assembler.terminal(
+ assembler.error("tool_calls entry must be an object", kind="invalid_request")
+ )
+ if terminal is not None:
+ yield terminal
+ return
+ raw_id = _string(raw.get("id"))
+ if raw.get("id") is not None and not isinstance(raw.get("id"), str):
+ terminal = assembler.terminal(
+ assembler.error(
+ "OpenAI Chat tool call id must be a string",
+ kind="invalid_request",
+ )
+ )
+ if terminal is not None:
+ yield terminal
+ return
+ index_value = raw.get("index")
+ if index_value is not None and (
+ not isinstance(index_value, int) or isinstance(index_value, bool)
+ ):
+ terminal = assembler.terminal(
+ assembler.error(
+ "OpenAI Chat tool call index must be an integer",
+ kind="invalid_request",
+ )
+ )
+ if terminal is not None:
+ yield terminal
+ return
+ if isinstance(index_value, int) and not isinstance(index_value, bool):
+ key = ("chat-tool", index_value)
+ else:
+ function = raw.get("function")
+ has_new_identity = bool(raw_id) or (
+ isinstance(function, Mapping) and function.get("name") is not None
+ )
+ key = assembler.fallback_tool_key(
+ native_id=raw_id or None,
+ allocate=has_new_identity,
+ )
+ if key is None:
+ terminal = assembler.terminal(
+ assembler.error(
+ "OpenAI Chat tool call could not allocate a slot",
+ kind="invalid_request",
+ )
+ )
+ if terminal is not None:
+ yield terminal
+ return
+ function = raw.get("function")
+ if function is not None and not isinstance(function, Mapping):
+ terminal = assembler.terminal(
+ assembler.error(
+ "OpenAI Chat tool call function must be an object",
+ kind="invalid_request",
+ )
+ )
+ if terminal is not None:
+ yield terminal
+ return
+ if isinstance(function, Mapping):
+ raw_name = function.get("name")
+ if raw_name is not None and not isinstance(raw_name, str):
+ terminal = assembler.terminal(
+ assembler.error("tool call name must not be empty", kind="invalid_request")
+ )
+ if terminal is not None:
+ yield terminal
+ return
+ if raw_name == "":
+ terminal = assembler.terminal(
+ assembler.error("tool call name must not be empty", kind="invalid_request")
+ )
+ if terminal is not None:
+ yield terminal
+ return
+ name = _string(raw_name)
+ start = assembler.tool_start(key, name=name or None, native_id=raw_id or None)
+ if start is not None:
+ yield start
+ pending = assembler.pending_tool_arguments(key)
+ if pending is not None:
+ yield pending
+ arguments = _string(function.get("arguments"))
+ raw_arguments = function.get("arguments")
+ if raw_arguments is not None and not isinstance(raw_arguments, str):
+ terminal = assembler.terminal(
+ assembler.error(
+ "OpenAI Chat tool arguments must be a string",
+ kind="invalid_request",
+ )
+ )
+ if terminal is not None:
+ yield terminal
+ return
+ emitted = assembler.tool_arguments(key, arguments)
+ if emitted is not None:
+ yield emitted
+ elif raw_id:
+ assembler.tool_start(key, native_id=raw_id)
+ legacy_function = delta.get("function_call")
+ if legacy_function is not None:
+ if not isinstance(legacy_function, Mapping):
+ terminal = assembler.terminal(
+ assembler.error("legacy function_call must be an object", kind="invalid_request")
+ )
+ if terminal is not None:
+ yield terminal
+ return
+ key = ("legacy-tool", 0)
+ raw_name = legacy_function.get("name")
+ if raw_name is not None and not isinstance(raw_name, str):
+ terminal = assembler.terminal(
+ assembler.error("legacy function_call name must not be empty", kind="invalid_request")
+ )
+ if terminal is not None:
+ yield terminal
+ return
+ if raw_name == "":
+ terminal = assembler.terminal(
+ assembler.error("legacy function_call name must not be empty", kind="invalid_request")
+ )
+ if terminal is not None:
+ yield terminal
+ return
+ name = _string(raw_name)
+ start = assembler.tool_start(key, name=name or None, native_id=None)
+ if start is not None:
+ yield start
+ pending = assembler.pending_tool_arguments(key)
+ if pending is not None:
+ yield pending
+ arguments = _string(legacy_function.get("arguments"))
+ raw_arguments = legacy_function.get("arguments")
+ if raw_arguments is not None and not isinstance(raw_arguments, str):
+ terminal = assembler.terminal(
+ assembler.error(
+ "legacy function_call arguments must be a string",
+ kind="invalid_request",
+ )
+ )
+ if terminal is not None:
+ yield terminal
+ return
+ emitted = assembler.tool_arguments(key, arguments)
+ if emitted is not None:
+ yield emitted
+ if cancel.cancelled:
+ terminal = assembler.terminal(assembler.aborted(cancel.reason))
+ if terminal is not None:
+ yield terminal
+ return
+ if finish_reason is not None:
+ protocol_terminal = True
+ if not protocol_terminal:
+ terminal = assembler.terminal(assembler.incomplete())
+ if terminal is not None:
+ yield terminal
+ return
+ for event in assembler.block_end_events():
+ yield event
+ final = assembler.finalize(
+ "refusal"
+ if refusal_seen
+ else _normalize_stop(
+ finish_reason,
+ assembler.has_tools(),
+ native_finish_reason=native_finish_reason,
+ )
+ )
+ terminal = assembler.terminal(final if isinstance(final, ProviderError) else Done(final))
+ if terminal is not None:
+ yield terminal
+ driver = drive_sse_stream(
+ self._client,
+ method="POST",
+ url=url,
+ json_body=payload,
+ headers=headers,
+ cancel=cancel,
+ assembler=assembler,
+ endpoint=request.endpoint,
+ resolver=self._served_hop_resolver,
+ gateway=self._gateway,
+ translate=translate,
+ )
+ try:
+ async for event in driver:
+ yield event
+ finally:
+ await driver.aclose()
+ except Exception as exc:
+ terminal = assembler.terminal(assembler.exception(exc))
+ if terminal is not None:
+ yield terminal
+
+
+def build_chat_payload(
+ request: ModelRequest,
+ messages: tuple[Any, ...],
+ *,
+ loaded_images: Mapping[str, tuple[str, str]] | None = None,
+) -> dict[str, Any]:
+ payload_messages: list[dict[str, Any]] = [{"role": "system", "content": request.system}]
+ # Pi keeps every correlated text tool result adjacent, then sends images
+ # from that complete group in one supported multimodal user continuation.
+ for tool_group, group in groupby(messages, key=lambda message: isinstance(message, ToolResultMessage)):
+ image_parts: list[dict[str, Any]] = []
+ for message in group:
+ payload_messages.append(_message_to_chat(message, request.supports_images, loaded_images))
+ if tool_group and request.supports_images:
+ images = tuple(block for block in message.content if isinstance(block, ImageBlock))
+ if images:
+ image_parts.extend(_chat_content(images, True, loaded_images))
+ if image_parts:
+ payload_messages.append({
+ "role": "user",
+ "content": [{"type": "text", "text": "Attached image(s) from tool result:"}, *image_parts],
+ })
+ payload: dict[str, Any] = {
+ "model": request.endpoint.model_id,
+ "messages": payload_messages,
+ "stream": True,
+ "stream_options": {"include_usage": True},
+ }
+ if _uses_completion_tokens(request.endpoint.model_id, request.reasoning_effort):
+ payload["max_completion_tokens"] = request.max_tokens
+ else:
+ payload["max_tokens"] = request.max_tokens
+ if request.tools:
+ payload["tools"] = [
+ {
+ "type": "function",
+ "function": {
+ "name": tool.name,
+ "description": tool.description,
+ "parameters": dict(tool.input_schema),
+ },
+ }
+ for tool in request.tools
+ ]
+ if request.reasoning_effort and request.reasoning_effort.lower() not in {"off", "disabled"}:
+ payload["reasoning_effort"] = _openai_effort(request.reasoning_effort)
+ return payload
+
+
+def _message_to_chat(
+ message: Any,
+ supports_images: bool,
+ loaded_images: Mapping[str, tuple[str, str]] | None = None,
+) -> dict[str, Any]:
+ if isinstance(message, UserMessage):
+ parts = _chat_content(message.content, supports_images, loaded_images)
+ return {"role": "user", "content": parts[0]["text"] if len(parts) == 1 and parts[0]["type"] == "text" else parts}
+ if isinstance(message, AssistantMessage):
+ output: dict[str, Any] = {"role": "assistant", "content": None}
+ text_parts = [block.text for block in message.content if isinstance(block, TextBlock) and block.text]
+ if text_parts:
+ output["content"] = "".join(text_parts)
+ thinking = [block for block in message.content if isinstance(block, ThinkingBlock)]
+ for block in thinking:
+ if block.signature is None:
+ continue
+ details = _signature_details(block.signature)
+ if details is not None:
+ output["reasoning_details"] = details
+ elif block.signature in {"reasoning", "reasoning_content", "reasoning_text"}:
+ output[block.signature] = block.text
+ else:
+ output["reasoning_content"] = block.text
+ calls = [block for block in message.content if isinstance(block, ToolCallBlock)]
+ if calls:
+ output["tool_calls"] = [
+ {
+ "id": call.id,
+ "type": "function",
+ "function": {"name": call.name, "arguments": json.dumps(dict(call.arguments), ensure_ascii=False)},
+ }
+ for call in calls
+ ]
+ if output["content"] is None and "tool_calls" not in output:
+ output["content"] = ""
+ return output
+ if isinstance(message, ToolResultMessage):
+ text = "\n".join(block.text for block in message.content if isinstance(block, TextBlock) and block.text is not None)
+ has_images = any(isinstance(block, ImageBlock) for block in message.content)
+ content = text or ("(see attached image)" if has_images else "(no tool output)")
+ return {"role": "tool", "tool_call_id": message.tool_call_id, "content": content}
+ raise TypeError(f"unsupported message {type(message).__name__}")
+
+
+def _chat_content(
+ content: tuple[Any, ...],
+ supports_images: bool,
+ loaded_images: Mapping[str, tuple[str, str]] | None = None,
+) -> list[dict[str, Any]]:
+ result: list[dict[str, Any]] = []
+ for part in content_parts(content, include_images=supports_images, loaded_images=loaded_images):
+ if part["type"] == "text":
+ result.append({"type": "text", "text": part["text"]})
+ else:
+ result.append(
+ {
+ "type": "image_url",
+ "image_url": {"url": f"data:{part['mime_type']};base64,{part['data']}"},
+ }
+ )
+ return result or [{"type": "text", "text": "(no content)"}]
+
+
+def _normalize_stop(
+ reason: str | None,
+ has_tools: bool,
+ *,
+ native_finish_reason: str | None = None,
+) -> str:
+ if reason == "stop" and native_finish_reason:
+ native = native_finish_reason.lower()
+ if native not in {"stop", "end_turn", "tool_calls", "function_call"}:
+ reason = native
+ normalized = {
+ "length": "length",
+ "max_tokens": "length",
+ "content_filter": "safety",
+ "recitation": "safety",
+ "refusal": "refusal",
+ "safety": "safety",
+ "tool_calls": "tool_use",
+ "function_call": "tool_use",
+ "stop": "stop",
+ "end": "stop",
+ None: "stop",
+ }.get(reason)
+ if normalized is not None:
+ return normalized
+ return "error"
+
+
+def _openai_usage(value: Mapping[str, Any]) -> Any:
+ """Project CompletionUsage according to conversion-tables.md's field ledger.
+
+ Audio/image/text and prediction details are subsets of inclusive totals;
+ they and the redundant total_tokens must not be counted a second time.
+ """
+
+ from core.agent_core.messages import Usage
+
+ prompt_details = value.get("prompt_tokens_details")
+ completion_details = value.get("completion_tokens_details")
+ # Pi uses nullish precedence per counter, not truthiness or the presence
+ # of its containing object. An explicit zero must stop the fallback.
+ cache_read = prompt_details.get("cached_tokens") if isinstance(prompt_details, Mapping) else None
+ if cache_read is None:
+ cache_read = value.get("prompt_cache_hit_tokens")
+ if cache_read is None:
+ cache_read = value.get("cached_tokens")
+ cache_read_tokens = _nonnegative(cache_read)
+ cache_write_tokens = (
+ _nonnegative(prompt_details.get("cache_write_tokens"))
+ if isinstance(prompt_details, Mapping)
+ else 0
+ )
+ return Usage(
+ input_tokens=max(0, _nonnegative(value.get("prompt_tokens")) - cache_read_tokens - cache_write_tokens),
+ output_tokens=_nonnegative(value.get("completion_tokens")),
+ cache_read_tokens=cache_read_tokens,
+ cache_write_tokens=cache_write_tokens,
+ reasoning_tokens=(
+ _nonnegative(completion_details.get("reasoning_tokens"))
+ if isinstance(completion_details, Mapping) and "reasoning_tokens" in completion_details
+ else None
+ ),
+ )
+
+
+def _first_reasoning_delta(delta: Mapping[str, Any]) -> tuple[str | None, str]:
+ for key in ("reasoning_content", "reasoning", "reasoning_text"):
+ value = delta.get(key)
+ if isinstance(value, str) and value:
+ return key, value
+ return None, ""
+
+
+def _signature_details(signature: str) -> Any:
+ try:
+ value = json.loads(signature)
+ except (TypeError, ValueError):
+ return None
+ return value if isinstance(value, (list, dict)) else None
+
+
+def _openai_effort(value: str) -> str:
+ # Pi preserves extended tiers when the resolved model advertises them;
+ # the loop has already filtered ``reasoning_effort`` through
+ # ModelCapabilities.reasoning_efforts.
+ return value.lower()
+
+
+def _uses_completion_tokens(model: str, effort: str | None) -> bool:
+ normalized = model.lower()
+ if any(normalized.startswith(prefix) for prefix in ("o1", "o3", "o4", "gpt-5")):
+ return True
+ return effort is not None and effort.lower() not in {"none", "off", "disabled"} and "reasoning" in normalized
+
+
+def _string(value: Any) -> str:
+ return value if isinstance(value, str) else ""
+
+
+def _nonnegative(value: Any) -> int:
+ return value if isinstance(value, int) and not isinstance(value, bool) and value >= 0 else 0
+
+
+OpenAIChatProvider = OpenAIChatAdapter
diff --git a/core/agent_core/ai/openai_responses.py b/core/agent_core/ai/openai_responses.py
new file mode 100644
index 000000000..40f0ee602
--- /dev/null
+++ b/core/agent_core/ai/openai_responses.py
@@ -0,0 +1,1609 @@
+"""OpenAI Responses API streaming adapter.
+
+The client-side transcript is authoritative: every request sets ``store`` to
+false and never sends ``previous_response_id``.
+
+Payload and stream rules are ported from tau's ``tau_ai/openai_compatible.py``
+(MIT) and Pi's ``packages/ai/src/api/openai-responses-shared.ts`` (MIT).
+"""
+
+from __future__ import annotations
+
+import json
+from collections.abc import AsyncIterator, Mapping
+from typing import Any
+
+import httpx
+
+from core.agent_core.ai._common import (
+ ServedHopResolver,
+ auth_headers,
+ content_parts,
+ drive_sse_stream,
+ dispatch_wire_event,
+ endpoint_origin,
+ join_endpoint_url,
+ json_object,
+ prepare_messages,
+ request_credential_values,
+ StreamAssembler,
+ validate_wire_shape,
+ WireField,
+ WireDispatchError,
+ usage_counter_error,
+)
+from core.agent_core.ai.provider import (
+ Done,
+ MediaLoader,
+ ModelRequest,
+ ProviderAdapter,
+ ProviderError,
+ TextDelta,
+)
+from core.agent_core.cancel import CancelToken
+from core.agent_core.messages import (
+ AssistantMessage,
+ TextBlock,
+ ThinkingBlock,
+ ToolCallBlock,
+ ToolResultMessage,
+ UserMessage,
+)
+
+_KNOWN_RESPONSE_EVENTS = frozenset(
+ {
+ "response.created",
+ "response.in_progress",
+ "response.queued",
+ "response.output_text.delta",
+ "response.output_text.done",
+ "response.refusal.delta",
+ "response.reasoning_summary_text.delta",
+ "response.reasoning_summary_text.done",
+ "response.reasoning_summary_part.added",
+ "response.reasoning_summary_part.done",
+ "response.reasoning_text.delta",
+ "response.reasoning_text.done",
+ "response.output_item.added",
+ "response.output_item.done",
+ "response.function_call_arguments.delta",
+ "response.function_call_arguments.done",
+ "response.custom_tool_call_input.delta",
+ "response.custom_tool_call_input.done",
+ "response.content_part.added",
+ "response.content_part.done",
+ "response.completed",
+ "response.incomplete",
+ "response.failed",
+ "error",
+ }
+)
+_RESPONSES_USAGE_FIELDS = (
+ WireField("input_tokens", int),
+ WireField("output_tokens", int),
+ WireField(
+ "input_tokens_details",
+ Mapping,
+ children=(
+ WireField("cached_tokens", int),
+ WireField("cache_write_tokens", int),
+ ),
+ ),
+ WireField(
+ "output_tokens_details",
+ Mapping,
+ children=(WireField("reasoning_tokens", int),),
+ ),
+)
+_RESPONSES_ERROR_FIELDS = (
+ WireField("type", str),
+ WireField("code", (str, int)),
+ WireField("message", str),
+)
+_RESPONSES_CONTENT_PART_FIELDS = (
+ WireField("type", str),
+ WireField("text", str),
+ WireField("refusal", str),
+)
+_RESPONSES_ITEM_FIELDS = (
+ WireField("type", str, required=True, nullable=False),
+ WireField("id", str),
+ WireField("call_id", str),
+ WireField("name", str),
+ WireField("arguments", (str, Mapping)),
+ WireField("input", str),
+ WireField("encrypted_content", str),
+ WireField(
+ "summary",
+ list,
+ item_children=(
+ WireField("type", str),
+ WireField("text", str),
+ WireField("summary", str),
+ ),
+ ),
+ WireField(
+ "content",
+ list,
+ item_children=_RESPONSES_CONTENT_PART_FIELDS,
+ ),
+)
+_RESPONSES_RESPONSE_FIELDS = (
+ WireField("status", str),
+ WireField(
+ "incomplete_details",
+ Mapping,
+ children=(WireField("reason", str),),
+ ),
+ WireField(
+ "usage",
+ Mapping,
+ children=_RESPONSES_USAGE_FIELDS,
+ ),
+ WireField(
+ "error",
+ Mapping,
+ children=_RESPONSES_ERROR_FIELDS,
+ ),
+ WireField(
+ "output",
+ list,
+ item_children=_RESPONSES_ITEM_FIELDS,
+ ),
+)
+_RESPONSES_WIRE_SHAPES = {
+ "response.created": (
+ WireField("response", Mapping, children=_RESPONSES_RESPONSE_FIELDS),
+ ),
+ "response.in_progress": (
+ WireField("response", Mapping, children=_RESPONSES_RESPONSE_FIELDS),
+ ),
+ "response.queued": (
+ WireField("response", Mapping, children=_RESPONSES_RESPONSE_FIELDS),
+ ),
+ "response.output_text.delta": (
+ WireField("delta", str, required=True, nullable=False),
+ WireField("output_index", int),
+ ),
+ "response.refusal.delta": (
+ WireField("delta", str, required=True, nullable=False),
+ WireField("output_index", int),
+ ),
+ "response.reasoning_summary_text.delta": (
+ WireField("delta", str, required=True, nullable=False),
+ WireField("output_index", int),
+ ),
+ "response.reasoning_text.delta": (
+ WireField("delta", str, required=True, nullable=False),
+ WireField("output_index", int),
+ ),
+ "response.reasoning_summary_part.added": (
+ WireField("output_index", int),
+ WireField("part", Mapping),
+ ),
+ "response.reasoning_summary_part.done": (
+ WireField("output_index", int),
+ ),
+ "response.output_item.added": (
+ WireField("output_index", int),
+ WireField("item", Mapping, required=True, nullable=False, children=_RESPONSES_ITEM_FIELDS),
+ ),
+ "response.output_item.done": (
+ WireField("output_index", int),
+ WireField("item", Mapping, required=True, nullable=False, children=_RESPONSES_ITEM_FIELDS),
+ ),
+ "response.function_call_arguments.delta": (
+ WireField("delta", str, required=True, nullable=False),
+ WireField("item_id", str),
+ WireField("output_index", int),
+ ),
+ "response.function_call_arguments.done": (
+ WireField("arguments", str),
+ WireField("item_id", str),
+ WireField("output_index", int),
+ ),
+ "response.custom_tool_call_input.delta": (
+ WireField("delta", str, required=True, nullable=False),
+ WireField("item_id", str),
+ WireField("output_index", int),
+ ),
+ "response.custom_tool_call_input.done": (
+ WireField("item_id", str),
+ WireField("output_index", int),
+ ),
+ "response.output_text.done": (
+ WireField("output_index", int),
+ ),
+ "response.reasoning_summary_text.done": (
+ WireField("output_index", int),
+ ),
+ "response.reasoning_text.done": (
+ WireField("output_index", int),
+ ),
+ "response.content_part.added": (
+ WireField("output_index", int),
+ WireField("part", Mapping),
+ ),
+ "response.content_part.done": (
+ WireField("output_index", int),
+ WireField("part", Mapping),
+ ),
+ "response.completed": (
+ WireField(
+ "response",
+ Mapping,
+ required=True,
+ nullable=False,
+ children=_RESPONSES_RESPONSE_FIELDS,
+ ),
+ ),
+ "response.incomplete": (
+ WireField(
+ "response",
+ Mapping,
+ required=True,
+ nullable=False,
+ children=_RESPONSES_RESPONSE_FIELDS,
+ ),
+ ),
+ "response.failed": (
+ WireField("response", Mapping, children=_RESPONSES_RESPONSE_FIELDS),
+ WireField("error", Mapping, children=_RESPONSES_ERROR_FIELDS),
+ ),
+ "error": (
+ WireField("error", Mapping, children=_RESPONSES_ERROR_FIELDS),
+ WireField("type", str),
+ WireField("code", (str, int)),
+ WireField("message", str),
+ ),
+}
+
+
+class OpenAIResponsesAdapter(ProviderAdapter):
+ """Adapter for the native OpenAI Responses protocol."""
+
+ protocol = "openai_responses"
+
+ def __init__(
+ self,
+ client: httpx.AsyncClient | None = None,
+ *,
+ media_loader: MediaLoader | None = None,
+ served_hop_resolver: ServedHopResolver | None = None,
+ gateway: bool = False,
+ ) -> None:
+ self._client = client or httpx.AsyncClient(timeout=None)
+ self._owns_client = client is None
+ self._media_loader = media_loader
+ self._served_hop_resolver = served_hop_resolver
+ self._gateway = gateway
+
+ async def aclose(self) -> None:
+ if self._owns_client:
+ await self._client.aclose()
+
+ def stream(self, request: ModelRequest, cancel: CancelToken) -> AsyncIterator[Any]:
+ return self._stream(request, cancel)
+
+ async def _stream(self, request: ModelRequest, cancel: CancelToken) -> AsyncIterator[Any]:
+ target = endpoint_origin(request.endpoint)
+ assembler = StreamAssembler(
+ origin=target,
+ protocol=self.protocol,
+ verified_origin=not self._gateway,
+ endpoint_url=request.endpoint.base_url,
+ sensitive_values=request_credential_values(request.endpoint),
+ )
+ if cancel.cancelled:
+ terminal = assembler.terminal(assembler.aborted(cancel.reason))
+ if terminal is not None:
+ yield terminal
+ return
+ prepared = await prepare_messages(
+ request.messages,
+ target=target,
+ supports_images=request.supports_images,
+ protocol=self.protocol,
+ media_loader=self._media_loader,
+ cancel=cancel,
+ )
+ if isinstance(prepared, ProviderError):
+ terminal = assembler.terminal(prepared)
+ if terminal is not None:
+ yield terminal
+ return
+ transformed_messages, loaded_images = prepared
+ if cancel.cancelled:
+ terminal = assembler.terminal(assembler.aborted(cancel.reason))
+ if terminal is not None:
+ yield terminal
+ return
+ reasoning: set[int] = set()
+ status: str | None = None
+ incomplete_reason: str | None = None
+ refusal = False
+
+ try:
+ payload = build_responses_payload(request, transformed_messages, loaded_images=loaded_images)
+ headers = auth_headers(request.endpoint, provider="openai", gateway=self._gateway)
+ headers.setdefault("content-type", "application/json")
+ url = join_endpoint_url(request.endpoint.base_url, "/responses")
+ async def translate(events: AsyncIterator[Any]) -> AsyncIterator[Any]:
+ nonlocal status, incomplete_reason, refusal
+ async for event in events:
+ if cancel.cancelled:
+ terminal = assembler.terminal(assembler.aborted(cancel.reason))
+ if terminal is not None:
+ yield terminal
+ return
+ if not event.data or event.data == "[DONE]":
+ continue
+ chunk = json_object(event.data)
+ if chunk is None:
+ terminal = assembler.terminal(
+ assembler.error(
+ "Provider returned invalid OpenAI Responses JSON",
+ kind="invalid_request",
+ )
+ )
+ if terminal is not None:
+ yield terminal
+ return
+ try:
+ event_type = dispatch_wire_event(
+ chunk,
+ known=_KNOWN_RESPONSE_EVENTS,
+ event_name=event.event,
+ aliases={"response.done": "response.completed"},
+ )
+ except WireDispatchError as exc:
+ terminal = assembler.terminal(
+ assembler.error(str(exc), kind="invalid_request")
+ )
+ if terminal is not None:
+ yield terminal
+ return
+ if event_type is None:
+ continue
+ shape_error = validate_wire_shape(
+ chunk,
+ event_type,
+ _RESPONSES_WIRE_SHAPES,
+ )
+ if shape_error is not None:
+ terminal = assembler.terminal(
+ assembler.error(shape_error, kind="invalid_request")
+ )
+ if terminal is not None:
+ yield terminal
+ return
+ if event_type in {"response.created", "response.in_progress"}:
+ response_body = chunk.get("response")
+ if "response" in chunk and not isinstance(response_body, Mapping):
+ terminal = assembler.terminal(
+ assembler.error(
+ f"{event_type} response must be an object",
+ kind="invalid_request",
+ )
+ )
+ if terminal is not None:
+ yield terminal
+ return
+ if isinstance(response_body, Mapping):
+ response_status = response_body.get("status")
+ if response_status is not None and not isinstance(response_status, str):
+ terminal = assembler.terminal(
+ assembler.error(
+ f"{event_type} response status must be a string",
+ kind="invalid_request",
+ )
+ )
+ if terminal is not None:
+ yield terminal
+ return
+ status = response_status or status
+ elif event_type == "response.output_text.delta":
+ if "delta" in chunk and not isinstance(chunk.get("delta"), str):
+ terminal = assembler.terminal(
+ assembler.error(
+ "response.output_text.delta delta must be a string",
+ kind="invalid_request",
+ )
+ )
+ if terminal is not None:
+ yield terminal
+ return
+ value = _string(chunk.get("delta"))
+ if value:
+ output_index = _output_index(chunk)
+ if output_index is None:
+ terminal = assembler.terminal(
+ assembler.error(
+ "response.output_text.delta output_index must be an integer",
+ kind="invalid_request",
+ )
+ )
+ if terminal is not None:
+ yield terminal
+ return
+ if not assembler.has_text_slot(output_index):
+ # Pi creates output slots only from
+ # response.output_item.added. Deltas for an
+ # unknown slot are ignored, preserving
+ # arrival order and avoiding invented blocks.
+ continue
+ emitted = assembler.text_delta(output_index, value)
+ if emitted is not None:
+ yield emitted
+ elif event_type == "response.refusal.delta":
+ if "delta" in chunk and not isinstance(chunk.get("delta"), str):
+ terminal = assembler.terminal(
+ assembler.error(
+ "response.refusal.delta delta must be a string",
+ kind="invalid_request",
+ )
+ )
+ if terminal is not None:
+ yield terminal
+ return
+ value = _string(chunk.get("delta"))
+ if value:
+ output_index = _output_index(chunk)
+ if output_index is None:
+ terminal = assembler.terminal(
+ assembler.error(
+ "response.refusal.delta output_index must be an integer",
+ kind="invalid_request",
+ )
+ )
+ if terminal is not None:
+ yield terminal
+ return
+ if not assembler.has_text_slot(output_index):
+ continue
+ refusal = True
+ emitted = assembler.text_delta(output_index, value)
+ if emitted is not None:
+ yield emitted
+ elif event_type in {"response.reasoning_summary_text.delta", "response.reasoning_text.delta"}:
+ if "delta" in chunk and not isinstance(chunk.get("delta"), str):
+ terminal = assembler.terminal(
+ assembler.error(
+ f"{event_type} delta must be a string",
+ kind="invalid_request",
+ )
+ )
+ if terminal is not None:
+ yield terminal
+ return
+ value = _string(chunk.get("delta"))
+ if value:
+ output_index = _output_index(chunk)
+ if output_index is None:
+ terminal = assembler.terminal(
+ assembler.error(
+ f"{event_type} output_index must be an integer",
+ kind="invalid_request",
+ )
+ )
+ if terminal is not None:
+ yield terminal
+ return
+ if output_index not in reasoning:
+ continue
+ emitted = assembler.thinking_delta(output_index, value)
+ if emitted is not None:
+ yield emitted
+ elif event_type == "response.output_item.added":
+ item = chunk.get("item")
+ output_index = _output_index(chunk)
+ if output_index is None:
+ terminal = assembler.terminal(
+ assembler.error(
+ "response.output_item.added output_index must be an integer",
+ kind="invalid_request",
+ )
+ )
+ if terminal is not None:
+ yield terminal
+ return
+ if not isinstance(item, Mapping):
+ terminal = assembler.terminal(
+ assembler.error(
+ "response.output_item.added item must be an object",
+ kind="invalid_request",
+ )
+ )
+ if terminal is not None:
+ yield terminal
+ return
+ item_type_value = item.get("type")
+ if not isinstance(item_type_value, str):
+ terminal = assembler.terminal(
+ assembler.error(
+ "response.output_item.added item type must be a string",
+ kind="invalid_request",
+ )
+ )
+ if terminal is not None:
+ yield terminal
+ return
+ raw_id = item.get("id")
+ if raw_id is not None and not isinstance(raw_id, str):
+ terminal = assembler.terminal(
+ assembler.error(
+ "response.output_item.added id must be a string",
+ kind="invalid_request",
+ )
+ )
+ if terminal is not None:
+ yield terminal
+ return
+ item_type = item_type_value
+ if item_type == "function_call":
+ for field in ("call_id", "name", "arguments"):
+ value = item.get(field)
+ if value is not None and not isinstance(value, str):
+ terminal = assembler.terminal(
+ assembler.error(
+ f"response.output_item.added {field} must be a string",
+ kind="invalid_request",
+ )
+ )
+ if terminal is not None:
+ yield terminal
+ return
+ raw_arguments = item.get("arguments")
+ if raw_arguments is not None and not isinstance(raw_arguments, str):
+ terminal = assembler.terminal(
+ assembler.error(
+ "function_call arguments must be a JSON string",
+ kind="invalid_request",
+ )
+ )
+ if terminal is not None:
+ yield terminal
+ return
+ call_id = _string(item.get("call_id")) or None
+ name = _string(item.get("name"))
+ if not name:
+ terminal = assembler.terminal(
+ assembler.error(
+ "function_call name must not be empty",
+ kind="invalid_request",
+ )
+ )
+ if terminal is not None:
+ yield terminal
+ return
+ item_id = _string(item.get("id"))
+ if "output_index" in chunk:
+ key_index = _output_index(chunk)
+ if key_index is None:
+ terminal = assembler.terminal(
+ assembler.error(
+ "response.output_item.added output_index must be an integer",
+ kind="invalid_request",
+ )
+ )
+ if terminal is not None:
+ yield terminal
+ return
+ key = ("responses-tool", key_index)
+ else:
+ key = assembler.fallback_tool_key(
+ native_id=item_id or call_id,
+ allocate=True,
+ )
+ if key is None:
+ terminal = assembler.terminal(
+ assembler.error(
+ "response.output_item.added could not allocate a tool slot",
+ kind="invalid_request",
+ )
+ )
+ if terminal is not None:
+ yield terminal
+ return
+ start = assembler.tool_start(
+ key,
+ call_id=call_id,
+ native_id=item_id or None,
+ name=name,
+ defer_start=not call_id,
+ )
+ if start is not None:
+ yield start
+ emitted = assembler.tool_arguments_snapshot(key, _string(item.get("arguments")))
+ if emitted is not None:
+ yield emitted
+ elif item_type == "reasoning":
+ reasoning.add(output_index)
+ assembler.merge_reasoning_item(output_index, item)
+ elif item_type == "message":
+ assembler.ensure_text_slot(output_index)
+ elif event_type == "response.reasoning_summary_text.done":
+ continue
+ elif event_type == "response.reasoning_summary_part.done":
+ if "output_index" in chunk:
+ output_index = _output_index(chunk)
+ if output_index is None:
+ terminal = assembler.terminal(
+ assembler.error(
+ "response.reasoning_summary_part.done output_index must be an integer",
+ kind="invalid_request",
+ )
+ )
+ if terminal is not None:
+ yield terminal
+ return
+ else:
+ output_index = 0
+ if output_index in reasoning:
+ emitted = assembler.thinking_delta(output_index, "\n\n")
+ if emitted is not None:
+ yield emitted
+ elif event_type == "response.function_call_arguments.delta":
+ if "delta" in chunk and not isinstance(chunk.get("delta"), str):
+ terminal = assembler.terminal(
+ assembler.error(
+ "response.function_call_arguments.delta delta must be a string",
+ kind="invalid_request",
+ )
+ )
+ if terminal is not None:
+ yield terminal
+ return
+ raw_item_id = chunk.get("item_id")
+ if raw_item_id is not None and not isinstance(raw_item_id, str):
+ terminal = assembler.terminal(
+ assembler.error(
+ "response.function_call_arguments.delta item_id must be a string",
+ kind="invalid_request",
+ )
+ )
+ if terminal is not None:
+ yield terminal
+ return
+ item_id = _string(raw_item_id) or None
+ if "output_index" in chunk:
+ output_index = _output_index(chunk)
+ if output_index is None:
+ terminal = assembler.terminal(
+ assembler.error(
+ "response.function_call_arguments.delta output_index must be an integer",
+ kind="invalid_request",
+ )
+ )
+ if terminal is not None:
+ yield terminal
+ return
+ key = ("responses-tool", output_index)
+ else:
+ key = assembler.fallback_tool_key(native_id=item_id, allocate=False)
+ if key is None:
+ continue
+ if not assembler.tool_name(key):
+ continue
+ assembler.bind_tool_identity(key, item_id)
+ value = _string(chunk.get("delta"))
+ emitted = assembler.tool_arguments(key, value)
+ if emitted is not None:
+ yield emitted
+ elif event_type == "response.function_call_arguments.done":
+ raw_item_id = chunk.get("item_id")
+ if raw_item_id is not None and not isinstance(raw_item_id, str):
+ terminal = assembler.terminal(
+ assembler.error(
+ "response.function_call_arguments.done item_id must be a string",
+ kind="invalid_request",
+ )
+ )
+ if terminal is not None:
+ yield terminal
+ return
+ item_id = _string(raw_item_id) or None
+ if "output_index" in chunk:
+ output_index = _output_index(chunk)
+ if output_index is None:
+ terminal = assembler.terminal(
+ assembler.error(
+ "response.function_call_arguments.done output_index must be an integer",
+ kind="invalid_request",
+ )
+ )
+ if terminal is not None:
+ yield terminal
+ return
+ key = ("responses-tool", output_index)
+ else:
+ key = assembler.fallback_tool_key(native_id=item_id, allocate=False)
+ if key is None:
+ continue
+ if not assembler.tool_name(key):
+ continue
+ assembler.bind_tool_identity(key, item_id)
+ if "arguments" in chunk:
+ complete_arguments = chunk.get("arguments")
+ if not isinstance(complete_arguments, str):
+ terminal = assembler.terminal(
+ assembler.error(
+ "function-call arguments must be a JSON string",
+ kind="invalid_request",
+ )
+ )
+ if terminal is not None:
+ yield terminal
+ return
+ emitted = assembler.tool_arguments_snapshot(key, complete_arguments)
+ if emitted is not None:
+ yield emitted
+ elif event_type in {
+ "response.custom_tool_call_input.delta",
+ "response.custom_tool_call_input.done",
+ }:
+ # Avibe's canonical tool model has no custom-tool
+ # input slot. Pi supports these events conditionally;
+ # ignoring them preserves the canonical history shape.
+ continue
+ elif event_type == "response.output_item.done":
+ item = chunk.get("item")
+ if "item" in chunk and not isinstance(item, Mapping):
+ terminal = assembler.terminal(
+ assembler.error(
+ "response.output_item.done item must be an object",
+ kind="invalid_request",
+ )
+ )
+ if terminal is not None:
+ yield terminal
+ return
+ if isinstance(item, Mapping):
+ if "type" not in item or not isinstance(item.get("type"), str):
+ terminal = assembler.terminal(
+ assembler.error(
+ "response.output_item.done item type must be a string",
+ kind="invalid_request",
+ )
+ )
+ if terminal is not None:
+ yield terminal
+ return
+ if item.get("id") is not None and not isinstance(item.get("id"), str):
+ terminal = assembler.terminal(
+ assembler.error(
+ "response.output_item.done item id must be a string",
+ kind="invalid_request",
+ )
+ )
+ if terminal is not None:
+ yield terminal
+ return
+ item_id = _string(item.get("id"))
+ if item.get("type") == "function_call":
+ for field in ("call_id", "name", "arguments"):
+ value = item.get(field)
+ if value is not None and not isinstance(value, str):
+ terminal = assembler.terminal(
+ assembler.error(
+ f"response.output_item.done {field} must be a string",
+ kind="invalid_request",
+ )
+ )
+ if terminal is not None:
+ yield terminal
+ return
+ if item.get("type") == "function_call" and "output_index" not in chunk:
+ call_id = _string(item.get("call_id")) or None
+ key = assembler.fallback_tool_key(
+ native_id=item_id or call_id,
+ allocate=False,
+ )
+ if key is None:
+ key = assembler.fallback_tool_key(
+ native_id=item_id or call_id,
+ allocate=True,
+ )
+ if key is None:
+ terminal = assembler.terminal(
+ assembler.error(
+ "response.output_item.done could not allocate a tool slot",
+ kind="invalid_request",
+ )
+ )
+ if terminal is not None:
+ yield terminal
+ return
+ else:
+ output_index = _output_index(chunk)
+ if output_index is None:
+ terminal = assembler.terminal(
+ assembler.error(
+ "response.output_item.done output_index must be an integer",
+ kind="invalid_request",
+ )
+ )
+ if terminal is not None:
+ yield terminal
+ return
+ key = (
+ ("responses-tool", output_index)
+ if item.get("type") == "function_call"
+ else output_index
+ )
+ if item.get("type") == "reasoning":
+ reasoning.add(output_index)
+ assembler.merge_reasoning_item(output_index, item)
+ summary_text = _reasoning_summary_text(item)
+ if summary_text is not None:
+ emitted = assembler.replace_thinking(output_index, summary_text)
+ if emitted is not None:
+ yield emitted
+ end = assembler.block_end(output_index)
+ if end is not None:
+ yield end
+ elif item.get("type") == "function_call":
+ name = _string(item.get("name")) or assembler.tool_name(key)
+ if not name:
+ terminal = assembler.terminal(
+ assembler.error(
+ "function_call name must not be empty",
+ kind="invalid_request",
+ )
+ )
+ if terminal is not None:
+ yield terminal
+ return
+ item_id = _string(item.get("id")) or assembler.tool_item_id(key)
+ call_id = _string(item.get("call_id")) or None
+ raw_arguments = item.get("arguments")
+ if raw_arguments is not None and not isinstance(raw_arguments, str):
+ terminal = assembler.terminal(
+ assembler.error(
+ "function_call arguments must be a JSON string",
+ kind="invalid_request",
+ )
+ )
+ if terminal is not None:
+ yield terminal
+ return
+ start = assembler.tool_start(
+ key,
+ call_id=call_id or None,
+ native_id=item_id or None,
+ name=name,
+ )
+ if start is not None:
+ yield start
+ pending = assembler.pending_tool_arguments(key)
+ if pending is not None:
+ yield pending
+ if raw_arguments is not None:
+ emitted = assembler.tool_arguments_snapshot(key, raw_arguments)
+ if emitted is not None:
+ yield emitted
+ assembler.finish_tool(key)
+ end = assembler.block_end(key)
+ if end is not None:
+ yield end
+ elif item.get("type") == "message":
+ content_error = _message_content_error(item)
+ if content_error is not None:
+ terminal = assembler.terminal(
+ assembler.error(
+ f"response.output_item.done {content_error}",
+ kind="invalid_request",
+ )
+ )
+ if terminal is not None:
+ yield terminal
+ return
+ assembler.ensure_text_slot(output_index)
+ message_refusal, emitted = _append_message_text(
+ assembler,
+ output_index,
+ item,
+ )
+ if emitted is not None:
+ yield emitted
+ refusal = refusal or message_refusal
+ end = assembler.block_end(output_index)
+ if end is not None:
+ yield end
+ elif event_type in {"response.completed", "response.incomplete"}:
+ response_body = chunk.get("response")
+ if not isinstance(response_body, Mapping):
+ terminal = assembler.terminal(
+ assembler.error(f"{event_type} response must be an object", kind="invalid_request")
+ )
+ if terminal is not None:
+ yield terminal
+ return
+ response_error: Mapping[str, Any] | None = None
+ response_status = response_body.get("status")
+ if response_status is not None and not isinstance(response_status, str):
+ terminal = assembler.terminal(
+ assembler.error(
+ f"{event_type} response status must be a string",
+ kind="invalid_request",
+ )
+ )
+ if terminal is not None:
+ yield terminal
+ return
+ if response_status is not None:
+ status = response_status
+ incomplete = response_body.get("incomplete_details")
+ if incomplete is not None and not isinstance(incomplete, Mapping):
+ terminal = assembler.terminal(
+ assembler.error(
+ f"{event_type} incomplete_details must be an object",
+ kind="invalid_request",
+ )
+ )
+ if terminal is not None:
+ yield terminal
+ return
+ if isinstance(incomplete, Mapping):
+ if incomplete.get("reason") is not None and not isinstance(
+ incomplete.get("reason"), str
+ ):
+ terminal = assembler.terminal(
+ assembler.error(
+ f"{event_type} incomplete_details reason must be a string",
+ kind="invalid_request",
+ )
+ )
+ if terminal is not None:
+ yield terminal
+ return
+ incomplete_reason = _string(incomplete.get("reason")) or incomplete_reason
+ if "usage" in response_body and response_body.get("usage") is not None and not isinstance(
+ response_body.get("usage"), Mapping
+ ):
+ terminal = assembler.terminal(
+ assembler.error(
+ f"{event_type} response usage must be an object",
+ kind="invalid_request",
+ )
+ )
+ if terminal is not None:
+ yield terminal
+ return
+ usage_error = usage_counter_error(
+ response_body.get("usage"),
+ label=f"{event_type} response usage",
+ fields=("input_tokens", "output_tokens"),
+ nested_fields={
+ "input_tokens_details": ("cached_tokens", "cache_write_tokens"),
+ "output_tokens_details": ("reasoning_tokens",),
+ },
+ )
+ if usage_error is not None:
+ terminal = assembler.terminal(assembler.error(usage_error, kind="invalid_request"))
+ if terminal is not None:
+ yield terminal
+ return
+ usage = _responses_usage(response_body.get("usage"))
+ assembler.set_usage(usage)
+ response_value = response_body.get("error")
+ if response_value is not None and not isinstance(response_value, Mapping):
+ terminal = assembler.terminal(
+ assembler.error(
+ f"{event_type} response error must be an object",
+ kind="invalid_request",
+ )
+ )
+ if terminal is not None:
+ yield terminal
+ return
+ if isinstance(response_value, Mapping):
+ shape_error = _responses_error_shape_error(
+ response_value,
+ f"{event_type} response error",
+ )
+ if shape_error is not None:
+ terminal = assembler.terminal(
+ assembler.error(shape_error, kind="invalid_request")
+ )
+ if terminal is not None:
+ yield terminal
+ return
+ response_error = response_value
+ output = response_body.get("output")
+ if output is not None and not isinstance(output, list):
+ terminal = assembler.terminal(
+ assembler.error(
+ f"{event_type} response output must be an array",
+ kind="invalid_request",
+ )
+ )
+ if terminal is not None:
+ yield terminal
+ return
+ terminal_output_error, terminal_refusal = _apply_terminal_output_items(
+ output,
+ assembler,
+ reasoning,
+ )
+ refusal = refusal or terminal_refusal
+ if terminal_output_error is not None:
+ terminal = assembler.terminal(terminal_output_error)
+ if terminal is not None:
+ yield terminal
+ return
+ if response_error is not None:
+ terminal = assembler.terminal(
+ assembler.error(
+ _responses_error_body(response_error),
+ )
+ )
+ if terminal is not None:
+ yield terminal
+ return
+ if status in {"failed", "cancelled"}:
+ terminal = assembler.terminal(
+ assembler.error(
+ f"OpenAI Responses response {status}",
+ kind="unknown",
+ )
+ )
+ elif (
+ event_type == "response.incomplete" or status == "incomplete"
+ ) and incomplete_reason not in {
+ "max_output_tokens",
+ "length",
+ "content_filter",
+ "safety",
+ }:
+ terminal = assembler.terminal(
+ assembler.error(
+ f"OpenAI Responses response incomplete: {incomplete_reason or 'unknown'}",
+ )
+ )
+ else:
+ stop = (
+ "refusal"
+ if refusal
+ else "safety"
+ if incomplete_reason in {"content_filter", "safety"}
+ else "length"
+ if incomplete_reason in {"max_output_tokens", "length"}
+ else "tool_use"
+ if assembler.has_tools()
+ else "stop"
+ )
+ if stop == "tool_use":
+ unfinished = assembler.unfinished_tool_calls()
+ if unfinished:
+ names = ", ".join(block.name for block in unfinished)
+ terminal = assembler.terminal(
+ assembler.error(
+ "OpenAI Responses stream completed with unfinished tool call"
+ + (f": {names}" if names else ""),
+ kind="invalid_request",
+ )
+ )
+ if terminal is not None:
+ yield terminal
+ return
+ elif stop in {"length", "safety", "refusal", "error"}:
+ for pending in assembler.interrupted_tool_events():
+ yield pending
+ final = assembler.finalize(stop)
+ terminal = assembler.terminal(
+ final if isinstance(final, ProviderError) else Done(final)
+ )
+ if terminal is not None:
+ yield terminal
+ return
+ elif event_type == "response.failed":
+ response_body = chunk.get("response")
+ if "response" in chunk and not isinstance(response_body, Mapping):
+ terminal = assembler.terminal(
+ assembler.error(
+ "response.failed response must be an object",
+ kind="invalid_request",
+ )
+ )
+ if terminal is not None:
+ yield terminal
+ return
+ error = response_body.get("error") if isinstance(response_body, Mapping) else chunk.get("error")
+ if isinstance(response_body, Mapping):
+ response_status = response_body.get("status")
+ if response_status is not None and not isinstance(response_status, str):
+ terminal = assembler.terminal(
+ assembler.error(
+ "response.failed response status must be a string",
+ kind="invalid_request",
+ )
+ )
+ if terminal is not None:
+ yield terminal
+ return
+ error_value = response_body.get("error")
+ if error_value is not None and not isinstance(error_value, Mapping):
+ terminal = assembler.terminal(
+ assembler.error(
+ "response.failed error must be an object",
+ kind="invalid_request",
+ )
+ )
+ if terminal is not None:
+ yield terminal
+ return
+ if isinstance(error_value, Mapping):
+ shape_error = _responses_error_shape_error(
+ error_value,
+ "response.failed error",
+ )
+ if shape_error is not None:
+ terminal = assembler.terminal(
+ assembler.error(shape_error, kind="invalid_request")
+ )
+ if terminal is not None:
+ yield terminal
+ return
+ usage_value = response_body.get("usage")
+ if usage_value is not None and not isinstance(usage_value, Mapping):
+ terminal = assembler.terminal(
+ assembler.error(
+ "response.failed usage must be an object",
+ kind="invalid_request",
+ )
+ )
+ if terminal is not None:
+ yield terminal
+ return
+ usage_error = usage_counter_error(
+ usage_value,
+ label="response.failed usage",
+ fields=("input_tokens", "output_tokens"),
+ nested_fields={
+ "input_tokens_details": ("cached_tokens", "cache_write_tokens"),
+ "output_tokens_details": ("reasoning_tokens",),
+ },
+ )
+ if usage_error is not None:
+ terminal = assembler.terminal(assembler.error(usage_error, kind="invalid_request"))
+ if terminal is not None:
+ yield terminal
+ return
+ assembler.set_usage(_responses_usage(response_body.get("usage")))
+ elif "error" in chunk and chunk.get("error") is not None and not isinstance(
+ chunk.get("error"), Mapping
+ ):
+ terminal = assembler.terminal(
+ assembler.error("response.failed error must be an object", kind="invalid_request")
+ )
+ if terminal is not None:
+ yield terminal
+ return
+ if isinstance(error, Mapping):
+ shape_error = _responses_error_shape_error(error, "response.failed error")
+ if shape_error is not None:
+ terminal = assembler.terminal(
+ assembler.error(shape_error, kind="invalid_request")
+ )
+ if terminal is not None:
+ yield terminal
+ return
+ if isinstance(error, Mapping):
+ message = _responses_error_body(error)
+ else:
+ incomplete_details = (
+ response_body.get("incomplete_details")
+ if isinstance(response_body, Mapping)
+ else None
+ )
+ reason = (
+ incomplete_details.get("reason")
+ if isinstance(incomplete_details, Mapping)
+ else None
+ )
+ message = (
+ f"OpenAI Responses response failed: {reason}"
+ if isinstance(reason, str) and reason
+ else "OpenAI Responses response failed"
+ )
+ terminal = assembler.terminal(
+ assembler.error(
+ message,
+ )
+ )
+ if terminal is not None:
+ yield terminal
+ return
+ elif event_type == "error":
+ nested_error = chunk.get("error")
+ if nested_error is not None and not isinstance(nested_error, Mapping):
+ terminal = assembler.terminal(
+ assembler.error("OpenAI Responses error must be an object", kind="invalid_request")
+ )
+ if terminal is not None:
+ yield terminal
+ return
+ if isinstance(nested_error, Mapping):
+ shape_error = _responses_error_shape_error(nested_error, "OpenAI Responses error")
+ else:
+ shape_error = _responses_error_shape_error(chunk, "OpenAI Responses error")
+ if shape_error is not None:
+ terminal = assembler.terminal(
+ assembler.error(shape_error, kind="invalid_request")
+ )
+ if terminal is not None:
+ yield terminal
+ return
+ terminal = assembler.terminal(
+ assembler.error(
+ json.dumps(dict(chunk), ensure_ascii=False),
+ )
+ )
+ if terminal is not None:
+ yield terminal
+ return
+ elif event_type in {
+ "response.queued",
+ "response.content_part.added",
+ "response.content_part.done",
+ "response.output_text.done",
+ "response.reasoning_text.done",
+ }:
+ continue
+ else:
+ # Unknown frames are filtered by dispatch_wire_event
+ # above, but keep this fallthrough for future aliases.
+ continue
+ if cancel.cancelled:
+ terminal = assembler.terminal(assembler.aborted(cancel.reason))
+ if terminal is not None:
+ yield terminal
+ return
+ terminal = assembler.terminal(assembler.incomplete())
+ if terminal is not None:
+ yield terminal
+ driver = drive_sse_stream(
+ self._client,
+ method="POST",
+ url=url,
+ json_body=payload,
+ headers=headers,
+ cancel=cancel,
+ assembler=assembler,
+ endpoint=request.endpoint,
+ resolver=self._served_hop_resolver,
+ gateway=self._gateway,
+ translate=translate,
+ )
+ try:
+ async for event in driver:
+ yield event
+ finally:
+ await driver.aclose()
+ except Exception as exc:
+ terminal = assembler.terminal(assembler.exception(exc))
+ if terminal is not None:
+ yield terminal
+
+
+def build_responses_payload(
+ request: ModelRequest,
+ messages: tuple[Any, ...],
+ *,
+ loaded_images: Mapping[str, tuple[str, str]] | None = None,
+) -> dict[str, Any]:
+ payload: dict[str, Any] = {
+ "model": request.endpoint.model_id,
+ "instructions": request.system,
+ "input": [
+ item
+ for message in messages
+ for item in _message_to_response(message, request.supports_images, loaded_images)
+ ],
+ "max_output_tokens": request.max_tokens,
+ "stream": True,
+ "store": False,
+ }
+ if request.tools:
+ payload["tools"] = [
+ {
+ "type": "function",
+ "name": tool.name,
+ "description": tool.description,
+ "parameters": dict(tool.input_schema),
+ }
+ for tool in request.tools
+ ]
+ if request.reasoning_effort and request.reasoning_effort.lower() not in {"off", "disabled"}:
+ payload["reasoning"] = {"effort": _openai_effort(request.reasoning_effort), "summary": "auto"}
+ if request.reasoning_effort.lower() != "none":
+ payload["include"] = ["reasoning.encrypted_content"]
+ return payload
+
+
+def _message_to_response(
+ message: Any,
+ supports_images: bool,
+ loaded_images: Mapping[str, tuple[str, str]] | None = None,
+) -> list[dict[str, Any]]:
+ if isinstance(message, UserMessage):
+ return [{"role": "user", "content": _response_content(message.content, supports_images, input_text=True, loaded_images=loaded_images)}]
+ if isinstance(message, AssistantMessage):
+ items: list[dict[str, Any]] = []
+ for block in message.content:
+ if isinstance(block, TextBlock) and block.text:
+ items.append(
+ {
+ "role": "assistant",
+ "content": [{"type": "output_text", "text": block.text}],
+ }
+ )
+ elif isinstance(block, ThinkingBlock):
+ if block.signature is not None:
+ details = _reasoning_signature(block.signature)
+ if details is not None:
+ items.append({"type": "reasoning", **details})
+ elif block.text:
+ items.append(
+ {
+ "role": "assistant",
+ "content": [{"type": "output_text", "text": block.text}],
+ }
+ )
+ elif isinstance(block, ToolCallBlock):
+ items.append(
+ {
+ "type": "function_call",
+ "id": block.native_id or block.id,
+ "call_id": block.id,
+ "name": block.name,
+ "arguments": json.dumps(dict(block.arguments), ensure_ascii=False),
+ }
+ )
+ return items or [{"role": "assistant", "content": ""}]
+ if isinstance(message, ToolResultMessage):
+ values = content_parts(message.content, include_images=supports_images, loaded_images=loaded_images)
+ text = "\n".join(part["text"] for part in values if part["type"] == "text")
+ if any(part["type"] == "image" for part in values):
+ output: Any = [
+ (
+ {"type": "input_text", "text": part["text"]}
+ if part["type"] == "text"
+ else {
+ "type": "input_image",
+ "image_url": f"data:{part['mime_type']};base64,{part['data']}",
+ }
+ )
+ for part in values
+ ]
+ else:
+ output = text or "(no tool output)"
+ return [{"type": "function_call_output", "call_id": message.tool_call_id, "output": output}]
+ raise TypeError(f"unsupported message {type(message).__name__}")
+
+
+def _response_content(
+ content: tuple[Any, ...],
+ supports_images: bool,
+ *,
+ input_text: bool,
+ loaded_images: Mapping[str, tuple[str, str]] | None = None,
+) -> list[dict[str, Any]]:
+ result: list[dict[str, Any]] = []
+ for part in content_parts(content, include_images=supports_images, loaded_images=loaded_images):
+ if part["type"] == "text":
+ result.append({"type": "input_text" if input_text else "output_text", "text": part["text"]})
+ else:
+ result.append({"type": "input_image", "image_url": f"data:{part['mime_type']};base64,{part['data']}"})
+ return result or [{"type": "input_text", "text": "(no content)"}]
+
+
+def _reasoning_signature(signature: str) -> dict[str, Any] | None:
+ try:
+ value = json.loads(signature)
+ except (TypeError, ValueError):
+ return None
+ if isinstance(value, Mapping):
+ output = dict(value)
+ output.pop("type", None)
+ if not isinstance(output.get("id"), str) or not isinstance(output.get("encrypted_content"), str):
+ return None
+ return output if output["encrypted_content"] else None
+ return None
+
+
+def _apply_terminal_output_items(
+ items: Any,
+ assembler: StreamAssembler,
+ reasoning: set[int],
+) -> tuple[ProviderError | None, bool]:
+ if not isinstance(items, list):
+ return None, False
+ refusal = False
+ for index, item in enumerate(items):
+ if not isinstance(item, Mapping):
+ return assembler.error("response output item must be an object", kind="invalid_request"), refusal
+ item_type = item.get("type")
+ if not isinstance(item_type, str):
+ return assembler.error(
+ "response output item type must be a string",
+ kind="invalid_request",
+ ), refusal
+ if item_type == "reasoning":
+ item_id = _string(item.get("id"))
+ state_index = assembler.reasoning_key_for_id(item_id)
+ if state_index is None and index in reasoning:
+ state_index = index
+ if state_index is None:
+ continue
+ assembler.merge_reasoning_item(state_index, item, terminal_backfill=True)
+ elif item_type == "message":
+ content_error = _message_content_error(item)
+ if content_error is not None:
+ return assembler.error(
+ f"response output message {content_error}",
+ kind="invalid_request",
+ ), refusal
+ message_refusal = _message_has_refusal(item)
+ refusal = refusal or message_refusal
+ if message_refusal and assembler.has_text_slot(index):
+ _append_message_refusal(assembler, index, item)
+ return None, refusal
+
+
+def _message_has_refusal(item: Mapping[str, Any]) -> bool:
+ value = item.get("content")
+ if not isinstance(value, list):
+ return False
+ return any(
+ isinstance(part, Mapping) and bool(_string(part.get("refusal")))
+ for part in value
+ )
+
+
+def _message_content_error(item: Mapping[str, Any]) -> str | None:
+ value = item.get("content")
+ if value is None:
+ return None
+ if not isinstance(value, list):
+ return "message content must be an array"
+ for index, part in enumerate(value):
+ if not isinstance(part, Mapping):
+ return f"message content part {index} must be an object"
+ for field in ("type", "text", "refusal"):
+ raw = part.get(field)
+ if raw is not None and not isinstance(raw, str):
+ return f"message content part {index} {field} must be a string"
+ return None
+
+
+def _append_message_refusal(assembler: StreamAssembler, index: int, item: Mapping[str, Any]) -> None:
+ value = item.get("content")
+ if not isinstance(value, list):
+ return
+ refusal_parts = [
+ _string(part.get("refusal"))
+ for part in value
+ if isinstance(part, Mapping) and _string(part.get("refusal"))
+ ]
+ if refusal_parts:
+ assembler.merge_text_snapshot(index, "".join(refusal_parts))
+
+
+def _append_message_text(
+ assembler: StreamAssembler,
+ index: int,
+ item: Mapping[str, Any],
+) -> tuple[bool, TextDelta | None]:
+ value = item.get("content")
+ if not isinstance(value, list):
+ return False, None
+ snapshot_parts: list[str] = []
+ refusal = False
+ for part in value:
+ if not isinstance(part, Mapping):
+ continue
+ if _string(part.get("refusal")):
+ refusal = True
+ text = _string(part.get("text")) or _string(part.get("refusal"))
+ if text:
+ snapshot_parts.append(text)
+ emitted = None
+ if snapshot_parts:
+ emitted = assembler.merge_text_snapshot(index, "".join(snapshot_parts))
+ return refusal, emitted
+
+
+def _responses_usage(value: Any) -> Any:
+ """Project ResponseUsage once; inclusive totals own the ignored breakdowns.
+
+ See the full documented field inventory in conversion-tables.md. Total
+ tokens are redundant with the canonical components, not another counter.
+ """
+
+ if not isinstance(value, Mapping):
+ return None
+ from core.agent_core.messages import Usage
+
+ input_details = value.get("input_tokens_details")
+ output_details = value.get("output_tokens_details")
+ cache_read_tokens = (
+ _nonnegative(input_details.get("cached_tokens"))
+ if isinstance(input_details, Mapping)
+ else 0
+ )
+ cache_write_tokens = (
+ _nonnegative(input_details.get("cache_write_tokens"))
+ if isinstance(input_details, Mapping)
+ else 0
+ )
+ return Usage(
+ input_tokens=max(0, _nonnegative(value.get("input_tokens")) - cache_read_tokens - cache_write_tokens),
+ output_tokens=_nonnegative(value.get("output_tokens")),
+ cache_read_tokens=cache_read_tokens,
+ cache_write_tokens=cache_write_tokens,
+ reasoning_tokens=_nonnegative(output_details.get("reasoning_tokens")) if isinstance(output_details, Mapping) and "reasoning_tokens" in output_details else None,
+ )
+
+
+def _responses_error_shape_error(value: Any, label: str) -> str | None:
+ if not isinstance(value, Mapping):
+ return f"{label} must be an object"
+ for field in ("type", "code", "message"):
+ raw = value.get(field)
+ if field == "code":
+ if raw is not None and (
+ isinstance(raw, str)
+ or (isinstance(raw, int) and not isinstance(raw, bool))
+ ):
+ continue
+ if raw is not None:
+ return f"{label} code must be a string or integer"
+ elif raw is not None and not isinstance(raw, str):
+ return f"{label} {field} must be a string"
+ return None
+
+
+def _responses_error_body(error: Mapping[str, Any]) -> str:
+ return json.dumps({"error": dict(error)}, ensure_ascii=False)
+
+
+def _reasoning_summary_text(item: Mapping[str, Any]) -> str | None:
+ summary = item.get("summary")
+ if summary is None:
+ summary = item.get("content")
+ if not isinstance(summary, list):
+ return None
+ parts: list[str] = []
+ for part in summary:
+ if isinstance(part, Mapping):
+ text = _string(part.get("text"))
+ if text:
+ parts.append(text)
+ return "\n\n".join(parts) if parts else None
+
+
+def _openai_effort(value: str) -> str:
+ # Pi preserves extended tiers when the resolved model advertises them;
+ # the loop has already filtered ``reasoning_effort`` through
+ # ModelCapabilities.reasoning_efforts.
+ return value.lower()
+
+
+def _string(value: Any) -> str:
+ return value if isinstance(value, str) else ""
+
+
+def _output_index(chunk: Mapping[str, Any]) -> int | None:
+ if "output_index" not in chunk:
+ return 0
+ value = chunk.get("output_index")
+ return value if isinstance(value, int) and not isinstance(value, bool) and value >= 0 else None
+
+
+def _nonnegative(value: Any) -> int:
+ return value if isinstance(value, int) and not isinstance(value, bool) and value >= 0 else 0
+
+
+OpenAIResponsesProvider = OpenAIResponsesAdapter
diff --git a/core/agent_core/ai/registry.py b/core/agent_core/ai/registry.py
new file mode 100644
index 000000000..77008a91b
--- /dev/null
+++ b/core/agent_core/ai/registry.py
@@ -0,0 +1,33 @@
+"""Native protocol adapter registry."""
+
+from __future__ import annotations
+
+from typing import Any
+
+from core.agent_core.ai.anthropic import AnthropicAdapter
+from core.agent_core.ai.openai_chat import OpenAIChatAdapter
+from core.agent_core.ai.openai_responses import OpenAIResponsesAdapter
+from core.agent_core.ai.provider import ProviderAdapter
+from core.agent_core.messages import ProtocolName
+
+ADAPTERS: dict[ProtocolName, type[ProviderAdapter]] = {
+ "anthropic": AnthropicAdapter,
+ "openai_chat": OpenAIChatAdapter,
+ "openai_responses": OpenAIResponsesAdapter,
+}
+
+
+def adapter_class(protocol: ProtocolName) -> type[ProviderAdapter]:
+ try:
+ return ADAPTERS[protocol]
+ except KeyError as exc:
+ raise ValueError(f"unsupported provider protocol: {protocol}") from exc
+
+
+def create_adapter(protocol: ProtocolName, **kwargs: Any) -> ProviderAdapter:
+ """Construct the adapter registered for ``protocol``."""
+
+ return adapter_class(protocol)(**kwargs) # type: ignore[call-arg]
+
+
+get_adapter = create_adapter
diff --git a/core/agent_core/ai/sse.py b/core/agent_core/ai/sse.py
new file mode 100644
index 000000000..5fa039664
--- /dev/null
+++ b/core/agent_core/ai/sse.py
@@ -0,0 +1,228 @@
+"""Incremental Server-Sent Events parsing.
+
+The parser follows the event-stream grammar from the W3C/WHATWG SSE
+specification. It deliberately accepts bytes because an HTTP transport may
+split a UTF-8 code point, a CRLF pair, or a ``data:`` field at any boundary.
+"""
+
+from __future__ import annotations
+
+import codecs
+import re
+from dataclasses import dataclass
+from typing import Iterable
+
+
+DEFAULT_MAX_PENDING_LINE_SIZE = 8 * 1024 * 1024
+DEFAULT_MAX_PENDING_EVENT_SIZE = 32 * 1024 * 1024
+_LINE_END_RE = re.compile(r"[\r\n]")
+
+
+class SSEParseError(ValueError):
+ """A provider sent an event-stream frame larger than the safety budget."""
+
+
+@dataclass(frozen=True)
+class SSEEvent:
+ """One dispatched SSE event."""
+
+ data: str
+ event: str | None = None
+ event_id: str | None = None
+ retry: int | None = None
+
+ @property
+ def id(self) -> str | None:
+ """Compatibility alias for callers using the SSE field name."""
+
+ return self.event_id
+
+
+class SSEParser:
+ """Parse an SSE byte or text stream incrementally."""
+
+ def __init__(
+ self,
+ *,
+ max_line_size: int | None = None,
+ max_event_size: int | None = None,
+ ) -> None:
+ self.max_line_size = (
+ DEFAULT_MAX_PENDING_LINE_SIZE if max_line_size is None else max_line_size
+ )
+ self.max_event_size = (
+ DEFAULT_MAX_PENDING_EVENT_SIZE if max_event_size is None else max_event_size
+ )
+ if self.max_line_size <= 0 or self.max_event_size <= 0:
+ raise ValueError("SSE parser limits must be positive")
+ self._buffer = ""
+ self._decoder = codecs.getincrementaldecoder("utf-8")("replace")
+ self._data: list[str] = []
+ self._data_size = 0
+ self._event: str | None = None
+ self._event_id: str | None = None
+ self._retry: int | None = None
+ self._at_stream_start = True
+ self._line_start = 0
+ self._scan_position = 0
+
+ def feed(self, chunk: bytes | bytearray | memoryview | str) -> list[SSEEvent]:
+ """Consume an arbitrary chunk and return complete events."""
+
+ text = self._decode(chunk)
+ if not text:
+ return []
+ self._buffer += text
+ events: list[SSEEvent] = []
+ while True:
+ line = self._take_line()
+ if line is None:
+ break
+ if line == "":
+ event = self._dispatch()
+ if event is not None:
+ events.append(event)
+ continue
+ self._check_line_size(line)
+ self._parse_line(line)
+ self._compact_buffer()
+ self._check_pending_line_size()
+ return events
+
+ def finish(self) -> list[SSEEvent]:
+ """Flush a final unterminated line and pending event."""
+
+ events: list[SSEEvent] = []
+ decoded_tail = self._decoder.decode(b"", final=True)
+ if decoded_tail:
+ self._buffer += decoded_tail
+ while True:
+ line = self._take_line()
+ if line is None:
+ break
+ if line == "":
+ event = self._dispatch()
+ if event is not None:
+ events.append(event)
+ continue
+ self._check_line_size(line)
+ self._parse_line(line)
+ self._compact_buffer()
+ if self._buffer:
+ self._check_pending_line_size()
+ line = self._buffer[:-1] if self._buffer.endswith("\r") else self._buffer
+ self._parse_line(line)
+ self._buffer = ""
+ self._line_start = 0
+ self._scan_position = 0
+ event = self._dispatch()
+ if event is not None:
+ events.append(event)
+ return events
+
+ def _decode(self, chunk: bytes | bytearray | memoryview | str) -> str:
+ if isinstance(chunk, (bytes, bytearray, memoryview)):
+ text = self._decoder.decode(bytes(chunk), final=False)
+ else:
+ pending, _ = self._decoder.getstate()
+ text = self._decoder.decode(b"", final=True) + chunk if pending else chunk
+ if self._at_stream_start and text:
+ self._at_stream_start = False
+ if text.startswith("\ufeff"):
+ text = text[1:]
+ return text
+
+ def _check_line_size(self, line: str) -> None:
+ if len(line) > self.max_line_size:
+ raise SSEParseError(
+ f"SSE pending line exceeds {self.max_line_size} characters"
+ )
+
+ def _check_pending_line_size(self) -> None:
+ if len(self._buffer) - self._line_start > self.max_line_size:
+ raise SSEParseError(
+ f"SSE pending line exceeds {self.max_line_size} characters"
+ )
+
+ def _take_line(self) -> str | None:
+ match = _LINE_END_RE.search(self._buffer, self._scan_position)
+ if match is None:
+ self._scan_position = len(self._buffer)
+ return None
+ index = match.start()
+ character = self._buffer[index]
+ # A CR may be the first half of a CRLF pair split across HTTP chunks.
+ # Wait for the next chunk so that the blank-line dispatch cannot happen
+ # one byte too early.
+ if character == "\r" and index + 1 == len(self._buffer):
+ self._scan_position = index
+ return None
+ line = self._buffer[self._line_start : index]
+ if character == "\r" and index + 1 < len(self._buffer) and self._buffer[index + 1] == "\n":
+ self._line_start = index + 2
+ else:
+ self._line_start = index + 1
+ self._scan_position = self._line_start
+ return line
+
+ def _compact_buffer(self) -> None:
+ if self._line_start:
+ self._buffer = self._buffer[self._line_start :]
+ self._line_start = 0
+ self._scan_position = 0
+
+ def _parse_line(self, line: str) -> None:
+ if line.startswith(":"):
+ return
+ if ":" in line:
+ field, value = line.split(":", 1)
+ if value.startswith(" "):
+ value = value[1:]
+ else:
+ field, value = line, ""
+ if field == "data":
+ new_size = self._data_size + len(value) + (1 if self._data else 0)
+ if new_size > self.max_event_size:
+ raise SSEParseError(
+ f"SSE pending event exceeds {self.max_event_size} characters"
+ )
+ self._data.append(value)
+ self._data_size = new_size
+ elif field == "event":
+ self._event = value
+ elif field == "id" and "\x00" not in value:
+ self._event_id = value
+ elif field == "retry" and value.isdigit():
+ self._retry = int(value)
+
+ def _dispatch(self) -> SSEEvent | None:
+ if not self._data:
+ self._event = None
+ self._retry = None
+ return None
+ event = SSEEvent(
+ data="\n".join(self._data),
+ event=self._event,
+ event_id=self._event_id,
+ retry=self._retry,
+ )
+ self._data.clear()
+ self._data_size = 0
+ self._event = None
+ self._retry = None
+ return event
+
+
+def parse_sse(chunks: Iterable[bytes | str]) -> list[SSEEvent]:
+ """Parse a finite iterable of chunks."""
+
+ parser = SSEParser()
+ events: list[SSEEvent] = []
+ for chunk in chunks:
+ events.extend(parser.feed(chunk))
+ events.extend(parser.finish())
+ return events
+
+
+IncrementalSSEParser = SSEParser
+SSEDecoder = SSEParser
diff --git a/core/agent_core/ai/transform.py b/core/agent_core/ai/transform.py
new file mode 100644
index 000000000..1bf37b2a2
--- /dev/null
+++ b/core/agent_core/ai/transform.py
@@ -0,0 +1,286 @@
+"""Canonical message transformation for provider requests.
+
+The portability rules are from Pi's ``transform-messages`` (MIT, revision
+7fbbd5f, ``packages/ai/src/api/transform-messages.ts``), with the canonical
+message shapes defined by Avibe's C-1 contract.
+"""
+
+from __future__ import annotations
+
+import hashlib
+import re
+from dataclasses import dataclass
+from typing import Any, Mapping
+
+from core.agent_core.messages import (
+ AssistantMessage,
+ AssistantContent,
+ ImageBlock,
+ Message,
+ Origin,
+ TextBlock,
+ ThinkingBlock,
+ ToolCallBlock,
+ ToolResultMessage,
+ UserMessage,
+)
+
+SYNTHETIC_TOOL_RESULT = "[tool call interrupted; no result recorded]"
+_SAFE_TOOL_ID = re.compile(r"^[A-Za-z0-9_-]+$")
+
+
+@dataclass(frozen=True)
+class TransformResult:
+ """Transformed messages and the canonical-to-wire tool id map."""
+
+ messages: tuple[Message, ...]
+ tool_call_id_map: Mapping[str, str]
+
+ @property
+ def id_map(self) -> Mapping[str, str]:
+ """Short alias used by adapter code."""
+
+ return self.tool_call_id_map
+
+ def __iter__(self):
+ return iter(self.messages)
+
+ def __len__(self) -> int:
+ return len(self.messages)
+
+ def __getitem__(self, index: int) -> Message:
+ return self.messages[index]
+
+
+def normalize_tool_call_id(tool_call_id: str, protocol: str = "anthropic") -> str:
+ """Return a deterministic id accepted by all supported native protocols."""
+
+ # Anthropic's documented alphabet is the strictest common subset. The
+ # The generated id is also accepted by OpenAI tool correlations.
+ del protocol
+ if _SAFE_TOOL_ID.fullmatch(tool_call_id) and len(tool_call_id) <= 64:
+ return tool_call_id
+ digest = hashlib.sha256(tool_call_id.encode("utf-8")).hexdigest()[:24]
+ return f"call_{digest}"
+
+
+def transform_messages(
+ messages: list[Message] | tuple[Message, ...],
+ target: Origin,
+ supports_images: bool = True,
+ protocol: str | None = None,
+) -> TransformResult:
+ """Compile canonical history for one target origin.
+
+ The returned map is per request. The transcript is never mutated.
+ """
+
+ target_protocol = protocol or target.api
+ id_map: dict[str, str] = {}
+ used_tool_ids: set[str] = set()
+ tool_id_occurrences: dict[str, int] = {}
+ pending_tool_ids: dict[str, list[str]] = {}
+ suppressed_tool_result_ids: set[str] = set()
+ transformed: list[Message] = []
+
+ for message in messages:
+ if isinstance(message, UserMessage):
+ pending_tool_ids.clear()
+ suppressed_tool_result_ids.clear()
+ transformed.append(_transform_user(message, supports_images=supports_images))
+ continue
+ if isinstance(message, ToolResultMessage):
+ if message.tool_call_id in suppressed_tool_result_ids:
+ continue
+ pending = pending_tool_ids.get(message.tool_call_id)
+ if pending:
+ wire_id = pending.pop(0)
+ if not pending:
+ pending_tool_ids.pop(message.tool_call_id, None)
+ else:
+ wire_id = id_map.get(
+ message.tool_call_id,
+ normalize_tool_call_id(message.tool_call_id, target_protocol),
+ )
+ transformed.append(
+ _transform_tool_result(
+ message,
+ tool_call_id=wire_id,
+ supports_images=supports_images,
+ )
+ )
+ continue
+ if not isinstance(message, AssistantMessage):
+ transformed.append(message)
+ continue
+
+ pending_tool_ids.clear()
+ same_origin = message.origin == target
+ content: list[AssistantContent] = []
+ turn_tool_ids: dict[str, list[str]] = {}
+ for block in message.content:
+ if isinstance(block, ThinkingBlock):
+ if block.redacted:
+ if same_origin:
+ content.append(block)
+ continue
+ if block.signature is None:
+ if block.text:
+ content.append(TextBlock(text=block.text))
+ elif same_origin:
+ content.append(block)
+ elif block.text:
+ content.append(TextBlock(text=block.text))
+ continue
+ if isinstance(block, TextBlock):
+ content.append(block)
+ continue
+ if isinstance(block, ToolCallBlock):
+ normalized = _claim_tool_call_id(
+ block.id,
+ normalize_tool_call_id(block.id, target_protocol),
+ used_tool_ids=used_tool_ids,
+ occurrences=tool_id_occurrences,
+ )
+ # Results are correlated to the pending calls in this turn.
+ # Keep the last occurrence in the public map for compatibility
+ # with callers that only have a stored id.
+ id_map[block.id] = normalized
+ turn_tool_ids.setdefault(block.id, []).append(normalized)
+ content.append(
+ ToolCallBlock(
+ id=normalized,
+ name=block.name,
+ arguments=dict(block.arguments),
+ native_id=block.native_id if same_origin else None,
+ signature=block.signature if same_origin else None,
+ )
+ )
+ continue
+ content.append(block)
+
+ # An aborted/error response is not a valid provider turn to replay.
+ if message.stop_reason in {"aborted", "error"}:
+ suppressed_tool_result_ids.update(turn_tool_ids)
+ continue
+ for source_id, wire_ids in turn_tool_ids.items():
+ pending_tool_ids.setdefault(source_id, []).extend(wire_ids)
+ transformed.append(
+ AssistantMessage(
+ content=tuple(content),
+ origin=message.origin,
+ stop_reason=message.stop_reason,
+ usage=message.usage,
+ error_message=message.error_message,
+ )
+ )
+
+ transformed = _insert_synthetic_results(transformed)
+ return TransformResult(messages=tuple(transformed), tool_call_id_map=dict(id_map))
+
+
+def transform_messages_for_target(
+ messages: list[Message] | tuple[Message, ...],
+ target: Origin,
+ *,
+ supports_images: bool = True,
+) -> TransformResult:
+ """Positional-argument convenience wrapper."""
+
+ return transform_messages(messages, target=target, supports_images=supports_images)
+
+
+portable_tool_call_id = normalize_tool_call_id
+
+
+def _transform_user(message: UserMessage, *, supports_images: bool) -> UserMessage:
+ if supports_images:
+ return message
+ return UserMessage(content=_replace_images(message.content, tool=False))
+
+
+def _claim_tool_call_id(
+ source_id: str,
+ base_id: str,
+ *,
+ used_tool_ids: set[str],
+ occurrences: dict[str, int],
+) -> str:
+ occurrence = occurrences.get(source_id, 0)
+ occurrences[source_id] = occurrence + 1
+ candidate = base_id
+ if candidate in used_tool_ids:
+ salt = occurrence
+ while candidate in used_tool_ids:
+ digest = hashlib.sha256(f"{source_id}\x00{salt}".encode("utf-8")).hexdigest()[:16]
+ prefix = base_id[: max(1, 64 - len(digest) - 1)]
+ candidate = f"{prefix}_{digest}"
+ salt += 1
+ used_tool_ids.add(candidate)
+ return candidate
+
+
+def _transform_tool_result(
+ message: ToolResultMessage,
+ *,
+ tool_call_id: str,
+ supports_images: bool,
+) -> ToolResultMessage:
+ return ToolResultMessage(
+ tool_call_id=tool_call_id,
+ tool_name=message.tool_name,
+ content=message.content if supports_images else _replace_images(message.content, tool=True),
+ is_error=message.is_error,
+ )
+
+
+def _replace_images(content: tuple[Any, ...], *, tool: bool) -> tuple[Any, ...]:
+ placeholder_template = "[image: {}]"
+ result: list[Any] = []
+ for block in content:
+ if isinstance(block, ImageBlock):
+ result.append(TextBlock(text=placeholder_template.format(block.name or block.mime_type)))
+ else:
+ result.append(block)
+ return tuple(result)
+
+
+def _insert_synthetic_results(messages: list[Message]) -> list[Message]:
+ result: list[Message] = []
+ pending: list[ToolCallBlock] = []
+ answered: set[str] = set()
+
+ def close_pending() -> None:
+ nonlocal pending, answered
+ for call in pending:
+ if call.id not in answered:
+ result.append(
+ ToolResultMessage(
+ tool_call_id=call.id,
+ tool_name=call.name,
+ content=(TextBlock(text=SYNTHETIC_TOOL_RESULT),),
+ is_error=True,
+ )
+ )
+ pending = []
+ answered = set()
+
+ for message in messages:
+ if isinstance(message, AssistantMessage):
+ close_pending()
+ calls = list(message.tool_calls)
+ if calls:
+ pending = calls
+ result.append(message)
+ elif isinstance(message, ToolResultMessage):
+ if message.tool_call_id in answered:
+ continue
+ answered.add(message.tool_call_id)
+ result.append(message)
+ elif isinstance(message, UserMessage):
+ close_pending()
+ result.append(message)
+ else:
+ result.append(message)
+ close_pending()
+ return result
diff --git a/docs/plans/agent-core-contracts/conversion-tables.md b/docs/plans/agent-core-contracts/conversion-tables.md
new file mode 100644
index 000000000..3a58432d6
--- /dev/null
+++ b/docs/plans/agent-core-contracts/conversion-tables.md
@@ -0,0 +1,629 @@
+# Native protocol conversion tables
+
+This file records the C-2 wire mappings implemented by the `ai` lane. The
+canonical types are the C-1 message and C-2 provider-event dataclasses. The
+adapters use `httpx.AsyncClient` directly and stream SSE frames incrementally.
+The protocol mappings are ported from tau (`tau_ai`, MIT) and Pi (`pi-ai`, MIT,
+revision `7fbbd5f`); the table records Avibe-specific normalization and origin
+rules on top of those mappings.
+
+## Shared rules
+
+| Concern | Rule |
+| --- | --- |
+| Request model | `ModelRequest.endpoint.model_id` is sent as the runtime model. The endpoint token is used only for request authentication. |
+| Request URL | `join_endpoint_url` parses the endpoint with `urllib.parse`, joins the protocol path before any existing query, preserves the base query, and appends protocol query fields only when that key is not already present. A complete protocol URL is reused by operation suffix. Adapters do not concatenate endpoint strings. |
+| System prompt | Sent from `ModelRequest.system`; it is never added to the persisted message history. |
+| Images | `ImageBlock.media_token` is resolved by `MediaLoader` immediately before the request. Unknown `supports_images` is false, so the cross-provider transform replaces each image with `[image: <name or mime>]`. |
+| Tool ids | A safe stored id is preserved when accepted by the target. Otherwise the per-request map uses `call_` plus the first 24 hex characters of SHA-256. The same map rewrites tool results. |
+| Missing tool results | The transform inserts `[tool call interrupted; no result recorded]` with `is_error=true`. |
+| Origin | Direct requests use the endpoint origin. Gateway requests parse only `x-avibe-served-hop`, whose JSON object must contain exactly `provider`, `api`, and `model`. A missing or invalid report makes the response unverified: thinking and tool-call signatures are nulled, and redacted thinking is dropped before allocating a canonical slot, so later event indexes still identify their final message blocks. |
+| Cancellation | `CancelToken` ends the HTTP stream and yields one non-retryable `ProviderError(kind="aborted")`. Opening, stream reads, error-body reads, media loads, and served-hop resolution all use the shared cancellation-aware await owner. |
+| Network timeouts | The shared lifecycle driver bounds connect/open at 10 seconds, time-to-first-byte at 30 seconds, and idle time between chunks at 30 seconds. Each timeout is a classified `ProviderError(kind="network")`, retryable only when no model output was emitted; a provider that never sends response headers cannot hang a turn. A bounded 10-second cancellation join detaches a non-cooperative transport task instead of extending the timeout indefinitely. |
+| HTTP response status | Only 2xx responses enter an SSE translator. Redirects (3xx) are terminal `invalid_request` errors and are never followed implicitly; 4xx/5xx bodies use the shared status-aware classifier. |
+| SSE memory and scan bounds | `SSEParser` caps an unfinished line at 8 MiB of decoded characters and an unfinished event's combined `data:` fields at 32 MiB of decoded characters. It scans each buffer with a cursor and compacts once per feed, so many short fields remain linear rather than repeatedly copying the suffix. Exceeding either bound is one terminal `invalid_request` provider error, with any assembled partial preserved. |
+| Cumulative assembled-output bound | `StreamAssembler._account_output` is the only byte-accounting function. It covers text, thinking, signatures, opaque/reasoning details, tool arguments, serialized initial tool inputs, tool-call identities and aliases. Each content slot, tool state, or Anthropic block-kind entry adds a conservative 2048-byte structure allowance; each alias adds 512 bytes, plus its string payload. The cumulative accounting budget is 32 MiB across the stream, not an exact process-RSS promise (transport/parser buffers and transient materialization have separate costs). An over-budget mutation raises one terminal `invalid_request` error, preserving the assembled partial. |
+| Error-body read failure | If a known HTTP error body raises or times out while being read, the shared driver classifies from the already-known status and headers, preserving `Retry-After`; the failure remains one terminal provider error with any partial. |
+| Response cleanup | The shared driver's single `finally` owns the opening task as well as its response. It closes successful results even when cancellation wins the same wait cycle or the bounded join; if opening is detached, that `finally` registers a late-result close callback. Cleanup follows terminal delivery and bounds `response.aclose()` at 10 seconds. A stalled close is cleanup-only and cannot replace or duplicate the terminal outcome. |
+| Retry boundary | `ProviderError.retryable` is false once any model content delta or tool-call start/delta was emitted. A Responses `ToolCallStart` therefore makes a later provider failure non-retryable. |
+| Partial and abort | The shared `partial_message` policy is used by all three adapters. Usage captured before the first visible delta is retained, and errors/abort carry an assembled `AssistantMessage` whenever visible content or usage exists; empty placeholder slots alone do not count as streamed output, while non-empty terminal snapshots do. Consumer/task cancellation is preserved even if response cleanup fails. |
+| Retry admission | `RetryPolicy.delay` in `core/agent_core/agent/models.py` applies only the bounded retry count/time budget and obeys `ProviderError.retryable`; it does not reject a usage-only partial or infer a second streamed-output boundary. A retry-admitted usage-only partial is committed as its own non-final model-response row, preserving per-attempt usage without adding prompt attempts together in one response. `test_retry_obeys_provider_flag_and_allows_usage_only_partial` and `test_retry_preserves_usage_only_partial_in_successful_response` are the loop proofs. |
+| Tool-call stop normalization | `StreamAssembler.finalize` changes only `stop` with one or more tool calls to canonical `tool_use`, following Pi. The loop admits execution only for `stop_reason="tool_use"`; calls attached to `length`, `safety`, `refusal`, or `error` are settled as `is_error` results explaining the stop reason. |
+
+## Shared stream assembler and dispatch ledger
+
+`StreamAssembler` in `core/agent_core/ai/_common.py` is the only owner of
+stream-boundary state, and `drive_sse_stream` is the only lifecycle owner.
+Adapter modules translate wire fields from the driver's shared SSE iterator into
+assembler calls; they do not open/close responses, classify retryability,
+construct partials, mark terminal state, or parse final tool arguments.
+
+| Concern | Single owner | Adapter call sites |
+| --- | --- | --- |
+| Content accumulation and visible-output flag | `StreamAssembler.text_delta`, `thinking_delta`, `tool_start`, `tool_arguments` | `anthropic.py` content-block branches; `openai_chat.py` delta branches; `openai_responses.py` output/reasoning/tool branches |
+| Stable tool id and native id map | `StreamAssembler.bind_tool_identity`, `tool_start` → `_set_tool_id` | The stream index owns the slot. A non-empty native ID binds once; a different ID on an open slot raises a terminal `invalid_request` before identity/argument mutation. Missing IDs use the unique monotonic allocator. Identical repeats and the first late ID are accepted; closed slots ignore late data. Explicit canonical IDs use the same ownership map and receive a fresh fallback on collision. Native aliases route only indexless frames, never override an explicit index; Responses argument delta/done use the same bind-once check as item added/done. |
+| Final JSON argument validation | `StreamAssembler.finalize` → `parsed_arguments` | The three adapters call `finalize` once after their protocol terminator; malformed arguments are a C-2 terminal `invalid_request` deviation from Pi's permissive partial parser |
+| Usage and early usage retention | `set_usage` | Anthropic `message_start`/`message_delta`; Chat usage chunks; Responses terminal response |
+| Per-protocol usage field normalization | `_anthropic_usage`, `_openai_usage`, `_responses_usage` | One normalizer per adapter. Anthropic start and delta share the same non-null merge; Chat chunk and choice usage share the same counter-level fallback order. See the field ledger below. |
+| Partial on every error and abort | `StreamAssembler.partial`, `error`, `exception`, `aborted`, `incomplete` | `drive_sse_stream` owns HTTP, transport-read, error-body, cancellation, and translator exceptions; protocol translators only request assembler errors |
+| Exactly one terminal event before response cleanup | `drive_sse_stream` → `StreamAssembler.terminal` | The driver commits the translator's candidate or its own transport/incomplete outcome before `response.aclose`; cleanup cannot replace a consumer/task cancellation |
+| HTTP status → served hop → streaming | `drive_sse_stream` | Classify non-2xx status/body first, retaining headers and `Retry-After` even if body reading fails. Only successful HTTP responses resolve/set the served origin and then translate SSE. Error responses never call the resolver; its failure/stall cannot replace a known auth/rate-limit/server error. |
+| Endpoint redaction | `errors.sanitize_endpoint_text`, called inside `redact_provider_text` | Includes preparation errors, HTTP error bodies, stream errors, network errors, and close failures. JSON is decoded before sanitizing its string values, so escaped quotes remain valid; URL userinfo, queries and fragments are removed before credential markers are inserted. Surrounding punctuation is preserved. |
+| Provider diagnostic redaction | `StreamAssembler.terminal` → `_sanitize_error` → `redact_provider_error` | Classification/preparation and translator candidates stay internal and unredacted; the driver sanitizes once when committing its terminal. `_is_sensitive_key` alone decides sensitivity for JSON keys, generic free-text key/value syntax and configured request headers/query keys. Prefix scanning is iterative, without rescanning the suffix after non-sensitive keys. Whole unquoted credential/header values are removed for both `:` and `=`; only recognizable Authorization scheme labels survive. Configured literals include endpoint userinfo and credential query values (original, stripped and escaped forms of at least eight characters), before token-shape redaction. Usage counters and partial error text are handled by the same boundary. |
+| Unknown wire event policy | `dispatch_wire_event` plus protocol frame validation | For data-bearing events, a known SSE name (including the `response.done` alias) requires a string payload `type`; missing/null/non-string discriminators are malformed. A valid payload type wins; unknown types are ignored. Anthropic's named `error` and `ping` are explicit Pi-parity control-frame exceptions: error data goes directly to classification and ping is ignored before parsing. Unknown Anthropic SSE names are also ignored before parsing. Valid data-only Anthropic JSON is accepted under rule (b) data-loss prevention because SSE `event` is optional. |
+| Cumulative output budget | `StreamAssembler._account_output`; `drive_sse_stream` catches `OutputBudgetExceeded` | One byte-accounting function covers text, thinking, opaque/reasoning details, tool arguments, tool-call signatures, serialized initial tool inputs, tool identities/aliases, and block/alias overhead; no adapter owns the limit or converts the overflow into a protocol-specific result |
+
+The shared dispatch helper only identifies a known event. Each adapter then
+validates the shape of that known event and emits exactly one terminal
+`invalid_request` error for malformed metadata. Thus a future event type is
+forward-compatible, while a known event with an invalid payload cannot become a
+successful response.
+
+## Wire-shape validation tables
+
+These tables enumerate every known event handled by each adapter. A required
+field is present in every valid frame. An optional field may be omitted or
+`null` only where the table says so. A present field with the wrong JSON type is
+a terminal `ProviderError(kind="invalid_request")`; unknown event types and
+unknown fields follow Pi and are ignored.
+For explicitly named known data events (after alias normalization), `type` is
+required and must be a non-null string. Otherwise, the frame is terminal
+malformed input. Unknown named events with a non-string discriminator remain
+ignored. When both discriminators are strings, the payload `type` wins.
+Anthropic named `error` and `ping` bypass data dispatch, as Pi does in
+`packages/ai/src/api/anthropic-messages.ts:543-549` at `7fbbd5f`:
+error data is classified without requiring JSON or a discriminator; ping is
+ignored without parsing.
+
+### Anthropic Messages
+
+| Event | Required fields and types | Optional fields and types |
+| --- | --- | --- |
+| `message_start` | `message: object` | `message.usage: object` |
+| `content_block_start` | `index: non-negative integer`, `content_block: object`, `content_block.type: string` | text/thinking `text`/`thinking`/`signature: string`; redacted `data: non-empty string`; tool `id`/`name: string`, `input: object` |
+| `content_block_delta` | `index: non-negative integer`, `delta: object`, `delta.type: string` | `text_delta.text`, `thinking_delta.thinking`, `signature_delta.signature`, `input_json_delta.partial_json: string`; present fields with a wrong type are terminal |
+| `content_block_stop` | `index: non-negative integer` | none |
+| `message_delta` | none | `delta: object`, `delta.stop_reason: string`, `usage: object` |
+| `message_stop` | none | none |
+| named SSE `error` | none: plain text or JSON error envelope accepted | classified before data-event dispatch, matching Pi |
+| data-only `error` | `error: object` when an envelope is present | `error.type`/`error.message: string`; provider extension fields such as `code` are ignored |
+| named SSE `ping` | none; payload not parsed | ignored before dispatch, matching Pi |
+
+### OpenAI Chat Completions
+
+| Wire frame | Required fields and types | Optional fields and types |
+| --- | --- | --- |
+| normal chunk | JSON object | `choices: array`, `usage: object`, `error: object` |
+| choice | `choice: object` | `delta: object`, `finish_reason: string`, `usage: object` |
+| delta text/refusal/reasoning | `content`/`refusal`/`reasoning_content`/`reasoning`/`reasoning_text: string` | each field may be omitted or `null` |
+| `reasoning_details` | array when present | entries are provider objects |
+| `tool_calls` | array when present | entries: `object`; `index: integer`, `id: string`, `function: object`; function `name`/`arguments: string` |
+| legacy `function_call` | object when present | `name`/`arguments: string` |
+| top-level `error` | object when present | `type`/`message: string`, `code: string or integer` (integer codes are ignored for classification) |
+| `[DONE]` | sentinel data | no JSON fields |
+
+### OpenAI Responses
+
+| Event | Required fields and types | Optional fields and types |
+| --- | --- | --- |
+| `response.created`, `response.in_progress` | `type: string` | `response: object`, `response.status: string` |
+| `response.queued` | `type: string` | none |
+| output/refusal/reasoning delta | `type: string`, `delta: string` | `output_index: non-negative integer` |
+| `response.output_item.added` | `item: object`; `item.type: string` | `output_index: non-negative integer`; function item `id`/`call_id`/`name`/`arguments: string` |
+| `response.output_item.done` | `item: object`; `item.type: string` | same function fields; `output_index: non-negative integer` |
+| `response.function_call_arguments.delta` | `delta: string` | `item_id: string`, `output_index: non-negative integer` |
+| `response.function_call_arguments.done` | none | `arguments: string`, `item_id: string`, `output_index: non-negative integer` |
+| `response.custom_tool_call_input.delta` | `delta: string` | `item_id: string`, `output_index: non-negative integer`; provider-specific fields are ignored |
+| `response.custom_tool_call_input.done` | none | `item_id: string`, `output_index: non-negative integer`; provider-specific fields are ignored |
+| `response.output_text.done`, `response.reasoning_summary_text.done`, `response.reasoning_text.done` | none | `output_index: non-negative integer` |
+| `response.content_part.added`, `response.content_part.done` | none | `output_index: non-negative integer`, `part: object` |
+| `response.completed`, `response.incomplete` | `response: object` | `response.status: string`, `output: array`, `usage: object`, `incomplete_details: object`, `error: object` |
+| `response.failed` | `type: string` | `response: object`, `response.error: object`, `response.usage: object` |
+| top-level `error` | `error: object` or `message: string` | `error.type`/`error.message: string`, `error.code: string or integer` |
+
+`response.output` is validated even when empty. If it is present and is not an
+array, the terminal is malformed rather than a successful empty response.
+
+### Provider error classification
+
+All three adapters route named error frames, data-only error frames, and HTTP
+error bodies through `StreamAssembler.error` and the shared `ProviderError`
+classifier. Each protocol translator supplies the provider-specific envelope
+or extracted message/code pair that its wire format makes available.
+
+| Protocol | Auth | Rate limit | Overload/server | Overflow/context |
+| --- | --- | --- | --- | --- |
+| Anthropic | `authentication_error`, `invalid_api_key`, `permission_error`, `permission` | `rate_limit_error` | `overloaded_error` → `overloaded`; `api_error` → `server` | `invalid_request_error` with context text; `context_length_exceeded` → `overflow` |
+| OpenAI Chat | `authentication_error`, `invalid_api_key`, `permission` | `rate_limit_error`, `too_many_requests` | `server_error`, `api_error` | `context_length_exceeded`, `request_too_large` |
+| OpenAI Responses | `unauthenticated`, `permission_denied`, `invalid_api_key` | `rate_limit`, `rate_limit_error` | `overloaded`, `server_error`, `service_unavailable` | `context_length_exceeded`, `request_too_large` |
+HTTP `401/403` always map to `auth`, `413` to `overflow`, `429` to
+`rate_limit` with `Retry-After`, and `5xx` to `server` or `overloaded`.
+Transport errors map to `network`. Every classification is non-retryable once
+the assembler has emitted visible content or a tool-call event.
+
+## Endpoint identity and redaction ledger
+
+Unnamed custom endpoints use `credential_free_endpoint_identity`: scheme,
+hostname, explicit port, and path only. Userinfo, query, and fragment are never
+part of `Origin.provider`; distinct endpoints remain distinct even when their
+provider field is empty.
+
+| Path that can carry endpoint text | Redaction owner | Proof |
+| --- | --- | --- |
+| Origin construction for an unnamed endpoint | `endpoint_origin` → `credential_free_endpoint_identity` | `test_unnamed_custom_endpoint_origin_is_credential_free` |
+| HTTP/provider error body | `StreamAssembler.error` classifies; `terminal` → `_sanitize_error` redacts once | `test_long_error_diagnostics_are_redacted_once_without_recursive_rescanning`, `test_adapter_error_redaction_preserves_json_classification` |
+| Network, cancellation, parser, and close exceptions | internal error candidate → `terminal` → `_sanitize_error` | `test_configured_literal_credentials_cross_the_real_adapter_boundary`, `test_close_failure_cannot_emit_a_second_terminal_event`, `test_all_adapters_cancel_at_every_http_lifecycle_phase` |
+| Extracted diagnostic credentials | `errors.redact_provider_text` plus `_redact_json` | One key predicate handles OAuth tokens, compound gateway API-key headers, cookies and Authorization. `request_credential_values` uses that predicate to include configured secrets, including escaped transport echoes. Shape rules cover `sk-`, `AIza`, GitHub tokens and JWTs; no internal classification/preparation path pre-redacts. |
+| Media preparation and served-hop resolver failures | adapter preflight plus `drive_sse_stream` | `test_media_loader_failure_is_a_provider_error` and cancellation lifecycle matrix |
+| Adapter logs | none: adapters do not log endpoint URLs | source audit of all three adapter modules |
+
+Retained output has one accounting owner, `StreamAssembler._account_output`.
+Reasoning items are serialized only when changed; the serialized snapshot is
+reused for the replay signature. Closed reasoning ignores later streamed
+snapshots but permits the documented terminal backfill. Thinking-signature
+fragments append without materializing thinking text. Tool IDs use a monotonic
+fallback cursor and constant-time owner checks; canonical IDs stop changing
+after `ToolCallStart`, and replaced pending IDs are not retained as history.
+Boundary regressions: `test_responses_reasoning_state_has_one_serialization_owner`,
+`test_signature_fragments_do_not_materialize_thinking_text`,
+`test_tool_id_allocation_has_linear_lookup_cost`,
+`test_shared_tool_id_uniqueness_does_not_copy_owners`, and
+`test_closed_tool_identity_does_not_retain_unused_history`.
+The table-driven budget test asserts that one actual content/argument delta
+was delivered before the next exceeds the cap; identity overhead cannot make
+an argument-accounting test pass early.
+
+### Final local pre-push review dispositions
+
+Per the owner's bounded-loop instruction, this was the last local review.
+Confirmed P1/P2 defects were reproduced test-first and fixed in one head; Codex
+is the reviewer of record after push. No P3 is silently treated as fixed.
+
+| Finding | Decision rule / disposition | Evidence |
+| --- | --- | --- |
+| P1 recursive/repeated diagnostic redaction | Hang harm + C-2 classification: iterative prefix scan, one terminal redaction | `test_long_error_diagnostics_are_redacted_once_without_recursive_rescanning` covers HTTP and stream errors through all three adapters; 1200 colons no longer lose HTTP 503/retry metadata |
+| P2 `authorization=Scheme credential` leak | Security harm: remove whole unquoted credential assignments, not one token | `test_adapter_diagnostics_redact_assignments_and_endpoint_credentials` |
+| P2 relative endpoint URL/query credential leak | Security harm: bare `key` is sensitive; configured URL userinfo/query credentials join the literal set | same three-adapter table, relative URL and schemeless password rows |
+| P2 pending Responses call masks length/safety | C-2 stop handling: emit a stable fallback start and buffered arguments for interrupted pending calls so the loop settles them without execution | `test_responses_interrupted_pending_identity_preserves_provider_stop` |
+| P2 Anthropic control-frame dispatch regression | Pi parity: named error classification and unparsed ping restored | Pi `7fbbd5f`, `anthropic-messages.ts:543-549`; `test_anthropic_named_error_uses_pi_name_first_handling`, `test_anthropic_ignores_named_ping_without_parsing_payload` |
+| P2 one-byte structural overhead | Hang/memory harm: 2048-byte state/slot/kind and 512-byte alias allowances; Anthropic kind state moves into the assembler | `test_empty_wire_states_consume_a_realistic_structural_budget` across all three adapters |
+| P3 complexity tests couple to private representations | Recorded/deferred test-strengthening limitation, not a runtime fix: these guards check the current cursor/set implementation but do not prove asymptotic cost for arbitrary alternative implementations. The current code retains its monotonic cursor and O(1) owner check; no current runtime defect was found here. Do not claim the prior mutation tests establish a general complexity bound. | Final local reviewer restored alternative linear scans and both guards passed; subsequent exact-head Codex review remains required |
+
+Sandboxed measurements for the P1/P2 fixes: 4,052,250 / 8,104,500-byte
+non-sensitive colon-rich diagnostics took 0.199 / 0.393 seconds to redact,
+with less than 50 KiB additional traced peak memory. At 1000 entries, empty
+tool states retained about 0.59 MB against 2.05 MB charged; empty text slots
+0.23 MB against 2.05 MB; started tools 1.20 MB against 4.64 MB. These are
+measurements of this runtime, not portable RSS guarantees.
+
+The driver call sites are exactly `AnthropicAdapter._stream`,
+`OpenAIChatAdapter._stream`, and `OpenAIResponsesAdapter._stream`. The delayed
+transport-read regression exercises all three call sites and proves terminal
+delivery precedes response cleanup.
+
+| Shared driver branch | Canonical outcome | Recorded proof |
+| --- | --- | --- |
+| non-2xx headers, with a throwing served-hop resolver and either readable or failing body | classify HTTP status/body without resolver invocation; preserve status, retryability and `Retry-After`, close response | `test_http_error_classification_precedes_served_hop_resolution`: all three adapters × 302/401/403/429/503 × readable/failing body |
+| transport read raises after a visible delta, while response close is observable | one non-retryable `ProviderError(kind="network", partial=...)`, delivered before `response.aclose`; no second terminal | `test_delayed_transport_read_emits_terminal_before_close` across all three adapters |
+
+### Round 13 exact-head Codex dispositions
+
+All three findings on `929aaf39e` are C-1/C-2 boundary defects, not new protocol
+policy. The new adapter regressions failed first (13 failing cases and one
+verified-origin control), then all 14 passed after the shared-owner fixes.
+No further local reviewer was launched; Codex remains the reviewer of record.
+
+| Finding | Decision rule / fix | Boundary evidence |
+| --- | --- | --- |
+| P2 response lost when cancellation wins header arrival | C-2 lifecycle / hang harm: retain the opening task in the driver and dispose its result from the single `finally`, including successful completion during join and after detach | `test_cancelled_header_arrival_disposes_the_unclaimed_response`: all three adapters × same-cycle, during-join, detached completion |
+| P2 duplicate explicit canonical tool-call IDs | C-2 per-message identity: `_set_tool_id` checks ownership, allocates a collision-free fallback, and charges the actual chosen ID before emission | `test_responses_parallel_calls_have_unique_explicit_canonical_ids`: duplicate IDs arriving at either added or done; distinct native item IDs, arguments, starts and final blocks |
+| P2 unverified redacted thinking shifts published indexes | C-1 opaque-origin stripping + C-2 stable content indexes: skip unverified redacted thinking before slot allocation, preserving verified opaque blocks | `test_gateway_origin_sanitization_preserves_streamed_block_indexes`: missing, invalid and verified served-hop reports with redacted thinking followed by thinking, text and a tool |
+
+### Round 14 usage and tool-image dispositions
+
+The repeated usage class had two local causes: Anthropic's initial and delta
+paths had separate field mappings, and Chat selected a cache source by object
+presence rather than counter presence. Both paths now have one normalizer
+per protocol. The image defect came from assuming one canonical message
+always maps to one Chat message; request conversion now handles a consecutive
+tool-result group as Pi does.
+
+| Finding | Decision rule / fix | Source and boundary evidence |
+| --- | --- | --- |
+| P2 Anthropic initial reasoning usage lost | C-2 usage/data preservation: the same non-null mapping normalizes start and delta, including already-admitted reasoning details. Missing/null delta fields preserve the initial count; explicit zero replaces it. | Pi `anthropic-messages.ts:680-688,829-854` supplies early usage plus non-null field merge. Pi itself omits reasoning at start; applying its delta mapping there is an explicit C-2 deviation. `test_anthropic_usage_fields_share_start_and_delta_normalization` and the usage-only abort fixture cover final and partial outcomes. |
+| P2 Chat cache fallback suppressed by a partial nested object | Pi parity: select nested `cached_tokens`, then `prompt_cache_hit_tokens`, then top-level `cached_tokens`, using nullish precedence at every step; zero is authoritative. | Pi `openai-completions.ts:1522-1546`; `test_chat_usage_fields_follow_pi_nullish_precedence` covers chunk and choice usage, empty/partial/null details and explicit zero. |
+| P1 Chat vision tool images replaced by media tokens | Pi parity + C-1/C-2 image capability: emit all correlated text tool results first, then one user continuation containing their loaded image data URLs. Image-only results say `(see attached image)`; empty results say `(no tool output)`. Non-vision transforms keep the existing named placeholders without loading bytes. | Pi `openai-completions.ts:1399-1457`; `test_chat_tool_result_images_follow_the_complete_tool_group` checks parallel calls, mixed text/images, distinct snapshot bytes/MIME types, end-of-history and following-user boundaries, and the capability gate. |
+
+The 32-case adapter selection failed first in 16 cases, with 16 controls
+passing, before the production fixes. A sandboxed, network-disabled probe
+then drove Pi's actual handlers at `7fbbd5f4a1d982bb02d63472dde0774fa639f99b`:
+20 Chat usage projections, seven Anthropic usage projections, two tool-image
+request projections, and one five-field Responses usage projection. The
+recorded fixture values are in `test_provider_adapters.py`; no provider call
+or credentials were used. The only difference in the seven Anthropic
+projections is the explicitly preserved initial reasoning count when later
+delta usage omits it. No local reviewer was launched.
+
+### Round 15 class-level dispositions
+
+All three P2s on `46740df49` belong to existing classes. The usage inventory
+below now enumerates provider fields, not just the five canonical destinations.
+Tool identity had competing routing owners (explicit stream index and native
+alias); explicit indexes now own their slots, with one bind-once check in the
+assembler. The driver admits served-hop resolution only after HTTP success.
+These are C-2 data integrity/classification fixes, not new model capabilities.
+No local reviewer was launched; exact-head Codex remains the reviewer of record.
+
+| Finding | Single-owner fix | Boundary regression |
+| --- | --- | --- |
+| P2 conflicting native IDs in an open tool slot | `bind_tool_identity` checks before mutation. Removed duplicate Responses item-ID state and alias-first indexed lookup. | `test_open_tool_slot_rejects_conflicting_native_identity`: Chat started/pending/id-only, Anthropic start, Responses added/done/argument delta/done, with identical-ID controls. `test_responses_explicit_indexes_override_shared_native_aliases` keeps two indexed calls separate. Existing late-ID, missing-ID, collision and closed-slot fixtures remain. |
+| P2 empty/null Anthropic TTL breakdown overwrites prior cache writes | `_anthropic_usage` keeps Pi's aggregate-first/non-null precedence; fallback sums a reported TTL snapshot only when at least one counter is non-null, otherwise preserves current. Explicit zero still updates. | Expanded `test_anthropic_usage_fields_share_start_and_delta_normalization`; all documented fields in `test_documented_usage_objects_map_totals_without_double_counting_breakdowns`. |
+| P2 served-hop failure masks HTTP classification | driver classifies non-2xx first; only 2xx proceeds to origin resolution and SSE | 30-case HTTP/resolver matrix in the driver ledger above |
+
+The initial test-first selection produced 43 failures and 15 passing controls
+before production changes. Every failure was at the asserted identity,
+cache-write preservation or status/classification boundary. Full usage fixtures
+reuse the round-14 pinned-Pi projections; additional documented decomposition
+fields prove that inclusive totals are not counted twice.
+
+### Complete documented usage field inventory
+
+Sources fetched on 2026-10-04:
+
+- [Anthropic Messages / Usage](https://platform.claude.com/docs/en/api/typescript/messages#usage)
+- [OpenAI Chat Completions / CompletionUsage](https://developers.openai.com/api/reference/resources/chat/subresources/completions/methods/create)
+- [OpenAI Responses / ResponseUsage](https://developers.openai.com/api/reference/resources/responses/methods/create)
+
+Every top-level and nested field in these usage objects has a row below.
+There is one normalizer per adapter, not separate initial/delta/choice mappers.
+Mapped counters are shape-validated before normalization. Ignored fields are
+not revalidated or retained: they do not influence canonical usage. The
+canonical schema deliberately has no per-modality, TTL, request-count, tier,
+geography, cost or redundant-total field. This inventory does not add any.
+Reasoning is already included in output, never added to it; a missing optional
+reasoning count remains `None`, unlike Pi's default zero.
+
+#### Anthropic: `_anthropic_usage`
+
+Pi `7fbbd5f`, `anthropic-messages.ts:680-688,829-854`: initial counters and
+non-null delta merge. Missing/null mapped fields preserve current values;
+initial numeric totals default to zero. TTL fallback and initial reasoning
+preservation are explicit existing C-2 data-preservation deviations from Pi.
+Pi's separate `cacheWrite1h` (`:840-847`) has no canonical counterpart.
+
+| Documented wire field | Canonical mapping or ignore policy |
+| --- | --- |
+| `input_tokens` | `input_tokens`, already excludes cache read/write; no subtraction |
+| `output_tokens` | `output_tokens`, inclusive of thinking |
+| `cache_read_input_tokens` | `cache_read_tokens` |
+| `cache_creation_input_tokens` | `cache_write_tokens`; non-null aggregate wins over every TTL value, including when aggregate is zero |
+| `cache_creation` | Nullable TTL breakdown container. If aggregate is missing/null, sum its non-null counters as the reported snapshot; missing/null/empty/all-null breakdown preserves current aggregate. Do not add a TTL snapshot to previous usage. |
+| `cache_creation.ephemeral_5m_input_tokens` | Part of fallback `cache_write_tokens` sum only; absent/null contributes nothing. Explicit zero is a reported value. No separate TTL field. |
+| `cache_creation.ephemeral_1h_input_tokens` | Same fallback policy as 5m; never added on top of an aggregate. No separate 1h billing field. |
+| `output_tokens_details` | Nullable decomposition container; not itself a count |
+| `output_tokens_details.thinking_tokens` | `reasoning_tokens`; non-null merge at both message start and delta. This observability subset does not increase `output_tokens`. |
+| `server_tool_use` | Ignored: server-side request-count metadata, not tokens or canonical tool calls |
+| `server_tool_use.web_fetch_requests` | Ignored: request count has no canonical usage field; cannot be added to token totals |
+| `server_tool_use.web_search_requests` | Ignored for the same unit/schema reason |
+| `inference_geo` | Ignored: geography metadata is not a usage counter or a verified served-hop identity |
+| `service_tier` | Ignored: tier/pricing metadata has no canonical usage field |
+
+Fixtures: the start/delta table protects `7/9/3/5/6`, non-null updates,
+missing/null/zero controls, each TTL alone, an empty/all-null TTL object, and
+zero aggregate overriding a nonzero TTL sum. Existing initial fixtures keep
+`15 + 10 = 25` without adding the aggregate again. The complete-object fixture
+adds both server request counts, geography and tier without changing usage.
+
+#### OpenAI Chat: `_openai_usage`
+
+Pi `7fbbd5f`, `openai-completions.ts:1522-1546`: nested cache-read value,
+then `prompt_cache_hit_tokens`, then top-level `cached_tokens`, using nullish
+precedence per counter. Explicit zero stops fallback. Missing numeric totals
+and cache values default to zero. Both chunk and choice usage use this mapper.
+
+| Documented wire field | Canonical mapping or ignore policy |
+| --- | --- |
+| `prompt_tokens` | `input_tokens = max(0, prompt_tokens - cache_read_tokens - cache_write_tokens)` |
+| `completion_tokens` | `output_tokens`, inclusive of reasoning and billed rejected prediction tokens |
+| `total_tokens` | Ignored: redundant prompt + completion total; canonical components already retain it without double counting |
+| `prompt_tokens_details` | Optional breakdown container; an empty/partial/null object does not suppress per-counter fallbacks |
+| `prompt_tokens_details.cached_tokens` | First-choice `cache_read_tokens` |
+| `prompt_tokens_details.cache_write_tokens` | `cache_write_tokens`, default zero; distinct from cache reads |
+| `prompt_tokens_details.audio_tokens` | Ignored: modality subset already in prompt total; no canonical audio count |
+| `prompt_tokens_details.image_tokens` | Ignored: modality subset already in prompt total; no canonical image count |
+| `prompt_tokens_details.text_tokens` | Ignored: modality subset already in prompt total; no canonical text count |
+| `completion_tokens_details` | Optional decomposition container; not itself a count |
+| `completion_tokens_details.reasoning_tokens` | `reasoning_tokens`; absent field is `None`. Accepted compatible null counter normalizes to zero, matching Pi. |
+| `completion_tokens_details.audio_tokens` | Ignored: output modality subset, already included in completion total |
+| `completion_tokens_details.text_tokens` | Ignored: output modality subset, already included in completion total |
+| `completion_tokens_details.accepted_prediction_tokens` | Ignored: accepted-prediction subset already accounted in completion total; no canonical prediction dimension |
+| `completion_tokens_details.rejected_prediction_tokens` | Ignored: billed rejected prediction tokens already included in completion total; neither add again nor subtract |
+
+Compatibility fields (not fields of the official OpenAI usage object):
+
+| Wire field | Mapping |
+| --- | --- |
+| `prompt_cache_hit_tokens` | Second-choice cache-read count, after a null/missing nested value |
+| `cached_tokens` | Third-choice cache-read count, then zero |
+
+Fixtures: pinned-Pi upstream `openai-completions-tool-choice.test.ts:1641-1760`
+projects `100 - 50 - 30 = 20`, output `33`, reasoning `21`. The recorded
+nullish-precedence matrix covers partial objects and zeros on both ingestion
+paths. The complete-object fixture adds every modality/prediction/total field
+without changing these canonical values.
+
+#### OpenAI Responses: `_responses_usage`
+
+Pi `7fbbd5f`, `openai-responses-shared.ts:560-575`: project the terminal
+response's usage once. Missing input/output/cache counts default to zero;
+reasoning follows the canonical optional-field rule.
+
+| Documented wire field | Canonical mapping or ignore policy |
+| --- | --- |
+| `input_tokens` | `input_tokens = max(0, input_tokens - cache_read_tokens - cache_write_tokens)` |
+| `input_tokens_details` | Input breakdown container; not itself a count |
+| `input_tokens_details.cached_tokens` | `cache_read_tokens`, default zero |
+| `input_tokens_details.cache_write_tokens` | `cache_write_tokens`, default zero; distinct from cache reads |
+| `output_tokens` | `output_tokens`, inclusive of reasoning |
+| `output_tokens_details` | Output decomposition container; not itself a count |
+| `output_tokens_details.reasoning_tokens` | `reasoning_tokens`; absent field is `None`. Accepted compatible null counter normalizes to zero, matching Pi. |
+| `total_tokens` | Ignored: redundant inclusive input + output; canonical components already preserve the total |
+
+Fixture: actual pinned-Pi projection `10 - 3 - 2 = 5`, output `4`, reasoning
+`2`; the full documented object also supplies `total_tokens: 14`. Pi's old
+Chat source comment calls cache writes a compatibility extension; the current
+official Chat and Responses schemas fetched above now document that counter.
+
+## Pi branch audit
+
+The following rows are the branch-by-branch audit against Pi revision
+`7fbbd5f`. “Same” means the Avibe handler preserves Pi's state-machine
+behavior. A stated deviation is limited to the C-1/C-2 canonical event,
+origin, retry, cancellation, media, or message-shape rules.
+
+| Protocol | Pi branch | Avibe handler | Result |
+| --- | --- | --- | --- |
+| Responses | `openai-responses-shared.ts:599-604` response id and output-item creation | `OpenAIResponsesAdapter._stream` → `response.output_item.added` | Same slot creation order; Avibe stores canonical blocks. |
+| Responses | `:605-634` reasoning summary/text deltas | `OpenAIResponsesAdapter._stream` → reasoning delta branches | Same; unknown slots are ignored. |
+| Responses | `:635-654` output/refusal deltas | `OpenAIResponsesAdapter._stream` → text/refusal branches | Same slot lookup; refusal is preserved as a canonical refusal stop for an existing message slot, while orphan refusal deltas are ignored like Pi. |
+| Responses | `:655-671` function-call argument delta/done | `OpenAIResponsesAdapter._stream` → argument branches | Same suffix and replacement rules; malformed metadata is canonical `invalid_request`. |
+| Responses | `:683-742` output-item finalization | `OpenAIResponsesAdapter._stream` and `_apply_terminal_output_items` | `output_item.done` follows Pi for arrival-order slots, argument finalization, and reasoning signatures; consecutive calls with omitted `output_index` are rebound by item id to prevent call loss (rule (b)); terminal `response.output` only backfills an existing reasoning signature, while refusal status is a C-2 deviation. |
+| Responses | `:743-744` completed/incomplete | `OpenAIResponsesAdapter._stream` → completed/incomplete branch | Same terminal response ownership; canonical stop reasons and usage, with cached read/write tokens excluded from `input_tokens`. |
+| Responses | terminal `response.output` shape | `OpenAIResponsesAdapter._stream` → terminal response validation | Same successful output-array contract; a present non-array output is a terminal malformed error, preventing a false empty success (rule (b), false information prevention). |
+| Responses | `:745-757` provider error/failed | `OpenAIResponsesAdapter._stream` → failed/error branches | Same classification, with Avibe's streamed retry boundary and partial message. |
+| Responses | `:759-777` missing terminal/unfinished call | `OpenAIResponsesAdapter._stream` → `StreamAssembler.unfinished_tool_calls` | Same terminal requirement; Avibe emits canonical `ProviderError`. |
+| Responses | unknown event fallthrough | `dispatch_wire_event` and `_KNOWN_RESPONSE_EVENTS` | Same: ignored for forward compatibility. |
+| Chat | `openai-completions.ts:553-565` chunk metadata and usage | `OpenAIChatAdapter._stream` → chunk metadata/usage | Same relevant metadata/usage behavior, including cache subtraction from `input_tokens`. |
+| Chat | `:567-585` choice finish reason | `OpenAIChatAdapter._stream` and `_normalize_stop` | Known mapping is the same, including `end -> stop`; unknown values become canonical `Done(stop_reason="error")` instead of Pi's provider error, as required by C-2 stop reasons. |
+| Chat | `:586-633` text and legacy reasoning fields | `OpenAIChatAdapter._stream` → content/reasoning branches | Same first non-empty reasoning field and visible deltas. |
+| Chat | `:635-661` tool-call state machine | `OpenAIChatAdapter._stream` and `StreamAssembler.tool_key` | Same index/id correlation; an id arriving before the name is retained and reused. |
+| Chat | `:665-675` reasoning-details accumulation | `OpenAIChatAdapter._stream` → `merge_thinking_details` | Same consecutive text/summary merge and opaque-entry preservation. |
+| Chat | `:680-701` finish blocks and terminal checks | `OpenAIChatAdapter._stream` → finish/EOF checks | Same terminal requirement; malformed final arguments are a C-2 `invalid_request` deviation from Pi's permissive parser. |
+| Chat | top-level provider error | `OpenAIChatAdapter._stream` → top-level error branch | Same classification, with canonical partial usage and streamed retry boundary. |
+| Chat | aborted/error cleanup | `openai-completions.ts:702-724` | Same assembled partial policy through `StreamAssembler`. |
+| Anthropic | `anthropic-messages.ts:665-690` message start | `AnthropicAdapter._stream` → `message_start` | Same early usage capture; cache-write total is retained. C-2 additionally preserves an admitted initial reasoning breakdown through the same normalizer used for deltas. |
+| Anthropic | `:691-738` block start | `AnthropicAdapter._stream` → `content_block_start` | Same supported text/thinking/redacted/tool blocks and initial content; non-empty initial `tool_use.input` is retained when no JSON delta follows (rule (b), preventing tool-argument loss); opaque payloads follow C-1 origin rules. |
+| Anthropic | `:739-784` content deltas | `AnthropicAdapter._stream` → `content_block_delta` | Same supported delta accumulation and signature append; malformed known fields are a C-2 terminal `invalid_request` deviation. |
+| Anthropic | `:785-816` block stop | `AnthropicAdapter._stream` → `content_block_stop` | Same block finalization. |
+| Anthropic | `:817-860` message delta and usage merge | `AnthropicAdapter._stream` → `message_delta` | Same non-null usage merge and stop normalization; explicit null fields do not erase earlier counts; malformed usage is terminal `invalid_request`, and unknown stop values become canonical `error` under C-2 stop-reason normalization. |
+| Anthropic | stream end after `message_start` | `AnthropicAdapter._stream` → post-loop finalization | Same as Pi: even a captured `message_delta.stop_reason` requires `message_stop`; EOF after `message_start` is incomplete and retains early usage. A stream with no `message_start` may complete from a captured stop reason, matching Pi's handler state. |
+| Anthropic | `:863-899` abort/error terminal path | `AnthropicAdapter._stream` → error/cleanup branches | Same assembled partial behavior; cancellation is the C-2 non-retryable `aborted` kind. |
+| Anthropic | unknown event/content block | `dispatch_wire_event` and `content_block_start` | Unknown named events and unknown content blocks follow Pi's ignore policy; a valid data-only SSE frame is accepted as a rule (b) data-loss prevention deviation. |
+| All | known event field shape | each adapter's dispatch branch and the wire-shape tables above | Present wrong-type fields are terminal `invalid_request`; optional fields may be absent or null; unknown event types remain ignored like Pi. |
+
+### Branch closure by protocol
+
+The rows below enumerate the state-machine branches in Pi `7fbbd5f`; the
+recorded fixture names point to the table-driven tests that exercise the
+canonical projection. “Ignore” is intentional Pi parity, not an unhandled
+case.
+
+| Protocol | Pi branch | Avibe outcome | Recorded proof |
+| --- | --- | --- | --- |
+| Responses | `response.created`, `response.in_progress`, `response.queued` | `created`/`in_progress` record state and validate an optional response object; `queued` is a no-op; unknown type is ignored | `test_responses_known_lifecycle_events_are_accounted_for`, `responses_unknown_event_is_ignored` |
+| Responses | `response.output_item.added` reasoning/message/function_call | create arrival-order slot; malformed item/name/arguments is terminal `invalid_request` | `responses_output_slots_arrive_in_order` |
+| Responses | missing `output_index` on output-item and argument events | non-tool items retain Pi's shared fallback; consecutive function calls allocate distinct internal fallback slots and rebind by `item_id` | `test_responses_missing_output_index_uses_one_shared_fallback_slot`, `test_responses_consecutive_missing_output_indexes_rebind_tool_slots` |
+| Responses | `response.reasoning_summary_text.delta`, `response.reasoning_text.delta` | thinking delta for an existing slot; unknown slot ignored | `responses_output_slots_arrive_in_order` |
+| Responses | `response.reasoning_summary_part.added` | ignore | `test_responses_known_lifecycle_events_are_accounted_for` |
+| Responses | `response.reasoning_summary_part.done` | append `"\n\n"` to the thinking block, matching Pi; a present non-integer `output_index` is terminal malformed metadata | `test_responses_summary_done_adds_separator`, `test_responses_summary_done_replaces_streaming_separator_after_late_delta`, `test_responses_summary_done_rejects_non_integer_output_index` |
+| Responses | `response.output_text.delta`, `response.refusal.delta` | text delta; refusal sets canonical `refusal` stop only for an existing message slot, while orphan refusal deltas are ignored | `responses_terminal_refusal_is_contract_deviation`, `responses_orphan_refusal_delta_is_ignored` |
+| Responses | `response.function_call_arguments.delta`, `.done` | accumulate and emit only the unseen suffix; orphan slots are ignored like Pi; malformed arguments for a known slot are terminal | `test_responses_argument_done_emits_only_the_unseen_suffix`, `test_responses_orphan_argument_events_are_ignored_like_pi` |
+| Responses | `response.custom_tool_call_input.delta`, `.done`; `custom_tool_call` output items | ignored because Avibe has no canonical custom-tool block; function-call events remain the only tool-call wire form | `test_responses_custom_tool_events_are_ignored_without_custom_tool_blocks` |
+| Responses | `response.output_item.done` reasoning/message/function_call | backfill reasoning signatures, replace the final message snapshot, create a missing function-call slot, emit final argument suffixes, close visible and empty slots before later deltas, or finish tool calls; malformed item is terminal | `test_responses_message_output_item_done_backfills_text`, `test_responses_output_item_done_can_create_a_function_call_slot`, `test_responses_output_item_done_closes_slot_before_late_delta`, `test_responses_empty_slots_close_before_late_deltas` |
+| Responses | message content parts in `response.output_item.done` and terminal `response.output` | content must be an array when present; every present part must be an object, and `type`, `text`, and `refusal` must be strings when present; malformed content is terminal `invalid_request` | `test_responses_rejects_malformed_message_content_parts` |
+| Responses | `response.done` alias | normalized to `response.completed` | `test_responses_done_alias_follows_terminal_response_state` |
+| Responses | `response.content_part.added/done`, `response.output_text.done`, `response.reasoning_text.done`, `response.reasoning_summary_text.done` | state/no-op | `test_responses_known_lifecycle_events_are_accounted_for` |
+| Responses | `response.completed`, `response.incomplete` | usage and terminal stop mapping; content filtering becomes `safety`, unsupported reasons are terminal errors; terminal message snapshots are not adopted, while refusal status is retained | `test_responses_incomplete_reasons_have_explicit_outcomes`, `test_responses_does_not_adopt_terminal_message_snapshot`, `test_responses_terminal_refusal_output_sets_refusal_stop_reason` |
+| Responses | `response.failed`, top-level `error` | classified provider error with partial and usage | `test_responses_top_level_error_frame_is_classified`, `_WIRE_EVENT_CASES` Responses rows |
+| Responses | missing terminal or unfinished tool call; final-only function calls in terminal `response.output` are ignored like Pi | terminal incomplete/invalid error with partial, or completed streamed tool call | `test_eof_without_protocol_terminal_is_not_success`, `test_responses_rejects_unfinished_tool_call_on_completed_response`, `test_responses_ignores_final_only_function_call_like_pi` |
+| Chat | chunk metadata, `usage`, and `choices[0].usage` fallback | retain usage fields; the choice-level fallback is used only when the chunk-level usage is absent | `test_chat_uses_choice_usage_fallback`, `chat_reasoning_details_merge` |
+| Chat | `choices[0].finish_reason` and `native_finish_reason` | canonical stop mapping, including `max_tokens -> length` and compatibility value `end -> stop`; a non-normal native reason overrides `stop`; unknown value becomes canonical `stop_reason="error"` | `test_chat_finish_reason_end_maps_to_stop`, `test_chat_max_tokens_maps_to_length`, `test_chat_native_safety_overrides_stop`, `test_chat_unknown_finish_reason_is_canonical_error`, `_WIRE_EVENT_CASES` Chat rows |
+| Chat | `delta.content` | text delta; wrong content/refusal field types are terminal malformed metadata | `chat_error_after_text_keeps_partial`, `test_chat_known_text_fields_reject_wrong_types` |
+| Chat | legacy reasoning fields | first non-empty field becomes thinking text/signature marker | `test_chat_reasoning_field_is_replayed_as_a_marker` |
+| Chat | `delta.tool_calls` | index/id/name correlation; late id binds to a stable canonical id; an absent index falls back to the native id alias | `chat_late_tool_id_uses_stable_canonical_id`, `test_chat_tool_call_without_integer_index_uses_native_id_alias` |
+| Chat | legacy `delta.function_call` | same single-tool state machine | `_WIRE_EVENT_CASES` legacy function-call row |
+| Chat | `delta.reasoning_details` | consecutive text/summary entries merge; opaque entries remain discrete | `chat_reasoning_details_merge` |
+| Chat | `delta.refusal` | preserve refusal text and canonical `refusal` stop reason; this is an Avibe C-2 deviation from Pi's text-only projection | `test_chat_refusal_stop_is_not_overwritten_by_later_stop_reason` |
+| Chat | top-level `error` | classified provider error with partial after deltas | `chat_error_after_text_keeps_partial` |
+| Chat | `[DONE]`, finish reason, missing terminal/close failure | `[DONE]` requires a finish reason; a finish reason may terminate at EOF; a prompt-level frame such as `promptFeedback` without candidates still has no finish reason and is incomplete; otherwise one retryable incomplete network error when no output was emitted | `test_chat_requires_finish_reason_before_done_marker`, `test_chat_prompt_feedback_without_candidates_is_incomplete`, `test_chat_finish_reason_can_terminate_at_eof_without_done_marker`, `test_close_failure_cannot_emit_a_second_terminal_event` |
+| Anthropic | `message_start` | capture usage before visible output; malformed message/usage is terminal | `anthropic_message_start_stop_reason_survives_eof` |
+| Anthropic | `content_block_start` text/thinking/redacted/tool_use/fallback | create canonical block; initial tool input is retained even without a later delta; unknown block type and pre-output fallback are ignored; a mid-output fallback is terminal like Pi | `test_anthropic_nonempty_initial_tool_input_is_preserved_without_deltas`, `test_anthropic_ignores_unknown_content_block_types_like_pi`, `test_anthropic_pre_output_fallback_is_ignored_like_pi`, `test_anthropic_mid_output_fallback_is_terminal_like_pi` |
+| Anthropic | content deltas text/thinking/signature/input JSON | corresponding delta/state; wrong field types are terminal malformed metadata; wrong-kind and unknown delta variants are ignored | `test_anthropic_malformed_delta_is_terminal_invalid_request`, `test_anthropic_known_delta_fields_reject_wrong_types`, `test_anthropic_wrong_kind_delta_is_ignored_like_pi`, `test_anthropic_ignores_unknown_delta_variants_like_pi` |
+| Anthropic | known event shape validation | malformed indexes, envelopes, or usage objects are terminal `invalid_request` | `test_wire_event_matrix_has_one_explicit_outcome` malformed Anthropic tuples plus the focused malformed-event tests |
+| Anthropic | `content_block_stop` | block end only for non-empty visible output; late deltas for a closed block are ignored | `test_anthropic_streams_thinking_tool_arguments_and_usage`, `test_anthropic_empty_block_end_does_not_count_as_streamed_output` |
+| Anthropic | `message_delta` | merge non-null usage and normalize stop reason; explicit `null` fields preserve earlier `message_start` counts; malformed usage is terminal | `test_anthropic_streams_thinking_tool_arguments_and_usage`, `test_anthropic_usage_fields_share_start_and_delta_normalization`, `test_anthropic_malformed_message_delta_usage_is_terminal_invalid_request` |
+| Anthropic | `message_stop` or EOF | `message_stop` completes only with a captured stop reason; after `message_start`, EOF without `message_stop` is incomplete even when a stop reason was captured; a no-`message_start` stream with a stop reason follows Pi's completion path | `test_anthropic_message_stop_without_reason_is_terminal_error`, `test_anthropic_message_start_requires_message_stop_even_with_stop_reason`, `test_anthropic_stop_reason_allows_eof_without_message_stop_like_pi` |
+| Anthropic | `error`/transport close | classified error with assembled partial and early usage; an empty placeholder block does not make the error non-retryable | `_WIRE_EVENT_CASES` Anthropic rows, `test_close_failure_cannot_emit_a_second_terminal_event` |
+| Anthropic | unknown top-level event | named unknown events are ignored before JSON parsing, matching Pi; valid data-only JSON frames are accepted under the documented rule (b) deviation, while malformed data-only frames are ignored like Pi | `test_anthropic_ignores_unknown_top_level_events_like_pi`, `test_anthropic_ignores_unknown_sse_event_before_parsing_like_pi`, `test_anthropic_malformed_data_only_frame_is_ignored_like_pi` |
+
+## Recorded Pi stream differential
+
+Pi was driven at revision `7fbbd5f` in an isolated temporary checkout with
+credential-free stub transports. The runner fed the same recorded wire
+sequences used by `tests/agent_core/ai/test_pi_stream_differential.py` to
+Pi's `processResponsesStream`, `openai-completions.stream`, and
+`anthropic-messages.stream`, then projected both outputs to:
+`outcome`, canonical stop reason, canonical blocks, usage, error kind, and
+partial blocks. The run covered Responses, Chat, and Anthropic. The Google
+adapter was not included because the owner deferred it from v1.
+
+| Fixture | Pi projection | Avibe projection | Difference |
+| --- | --- | --- | --- |
+| `responses_output_slots_arrive_in_order` | reasoning `plan` with signed item, then text `answer`; `stop`; usage `2/3/reasoning=1` | same | none |
+| `responses_unknown_event_is_ignored` | empty successful response; `stop`; Pi's initialized usage shape | empty successful response; `stop`; usage remains unknown when the provider omits it | canonical optional usage does not invent provider counts |
+| `responses_missing_output_index_shares_pi_slot` | one undefined output slot correlates the function-call argument delta; provider-native composite id; Pi's initialized usage shape | one fallback slot correlates the same delta; stable canonical id plus native id; optional usage remains absent | C-2 canonical id and optional usage |
+| `responses_terminal_message_snapshot_is_not_adopted` | terminal message output does not replace the empty slot created by `output_item.added`; `stop`; Pi's initialized usage shape | same; optional usage remains absent | canonical optional usage does not invent provider counts |
+| `chat_reasoning_details_merge` | one thinking block with signature `reasoning.text=ab`; `stop`; the usage parser fills missing reasoning details with `0` | same block and stop; canonical usage keeps unknown reasoning details as `None` | canonical optional usage fields |
+| `chat_error_after_text_keeps_partial` | server error with text partial and Pi's zero-initialized usage | server error with text partial and absent usage | canonical optional usage does not invent provider counts |
+| `anthropic_message_start_stop_reason_survives_eof` | error partial with input usage `7`, empty content | `network` error partial with the same usage; retryable because usage alone is not streamed output | C-2 retry boundary and shared incomplete classification |
+| `anthropic_unknown_event_is_ignored` | empty successful response with input usage `4` | same | none |
+| `responses_terminal_refusal_is_contract_deviation` | completed refusal projected as an empty text block with `stop` and zero-initialized usage | refusal text is retained with `refusal` and optional usage remains absent | C-2 canonical refusal stop reason; refusal is never folded into `stop` |
+| `chat_late_tool_id_uses_stable_canonical_id` | final provider id with Pi's initialized usage shape | stable id from `ToolCallStart` is retained, provider id is `native_id`, and optional usage remains absent | C-2 provider-event id stability |
+| `responses_consecutive_missing_output_indexes_rebind` | Pi's undefined slot is removed at each `output_item.done`, so both final calls survive with composite ids | item ids bind each call to a distinct internal fallback slot, preserving both streamed argument paths with canonical id/native id split | rule (b) data-loss prevention plus canonical ids |
+| `responses_empty_slots_ignore_late_deltas` | empty text and reasoning slots close on `output_item.done`; later deltas are ignored | same, with optional usage remaining absent | canonical optional usage |
+| `chat_finish_reason_end_maps_to_stop` | compatibility `finish_reason=end` maps to `stop`; no usage frame leaves Pi's initialized usage shape | same stop mapping; usage remains unknown | canonical optional usage |
+| `anthropic_null_delta_usage_preserves_message_start` | `message_start.input_tokens=7` survives null fields in `message_delta` | same | none |
+| `chat_malformed_tool_arguments` | Pi's permissive parser completes `read` with `{}` and `tool_use` | terminal `invalid_request` naming malformed arguments; partial has no tool block | C-2 canonical malformed-argument error |
+| `chat_eof_after_text_is_partial_abort` | missing finish reason becomes an error with text partial and Pi's initialized usage shape | `network` error with text partial and `retryable=false`; optional usage remains absent | C-2 retry boundary and canonical optional usage |
+| `anthropic_empty_block_end_then_error` | empty text block is ended before the overloaded error; Pi retains the empty block in partial and does not apply the empty-slot retry boundary | empty placeholder does not count as streamed output, so retry remains allowed and partial is omitted | C-2 retry boundary |
+| `anthropic_malformed_delta` | Pi's null delta raises a generic stream error with the empty text block in partial | known malformed metadata is terminal `invalid_request`; empty placeholder is omitted from partial | C-2 malformed-event classification and retry boundary |
+
+The isolated Pi run was successful for all 18 fixtures across the three handlers. The only setup
+limitation was the absent upstream `node_modules`; the runner used local
+credential-free stubs and did not alter the Pi source or Avibe dependencies.
+
+## Anthropic Messages
+
+| Canonical field | Request mapping |
+| --- | --- |
+| `system` | `system`, as a text string or one text block with `cache_control` when `cache="default"`. |
+| User text/image | `messages[].role="user"`; text blocks become `text`; images become `image` with a base64 `source`. |
+| Assistant text | `messages[].role="assistant"` with `text` blocks. |
+| Thinking | Same-origin signed thinking becomes `thinking` with `thinking` and `signature`; same-origin redacted thinking becomes `redacted_thinking` with `data`; unsigned thinking becomes text. |
+| Tool call | `tool_use` with `id`, `name`, and parsed `input`. |
+| Tool result | A user message containing `tool_result` with `tool_use_id`, `content`, and `is_error`. |
+| Tools | `tools[]` with `name`, `description`, and `input_schema`; the final tool receives a cache breakpoint for `cache="default"`. |
+| Reasoning effort | `none/off/disabled` → `thinking.type="disabled"`; other values → adaptive thinking and `output_config.effort` (`minimal` maps to `low`, `xhigh` to `max`). |
+| Cache | At most four breakpoints: system, final tool, and the two latest eligible user-message tails. |
+
+Anthropic stream events:
+
+| Wire event | Outcome | Provider event / state |
+| --- | --- | --- |
+| `message_start.message.usage` | delta/state | Initial `Usage` through the same normalizer as message delta, preserving all reported counters including `output_tokens_details.thinking_tokens`; `input_tokens` excludes cache reads and writes. |
+| `content_block_start` (`text`, `thinking`, `redacted_thinking`, `tool_use`) | delta/state | Creates the canonical block, preserves initial text/thinking/input, and `tool_use` emits `ToolCallStart`. Empty tool names are terminal `invalid_request`. |
+| `content_block_delta.text_delta` | delta | `TextDelta`. |
+| `content_block_delta.thinking_delta` | delta | `ThinkingDelta`. |
+| `content_block_delta.signature_delta` | state | Appends to the thinking signature. |
+| `content_block_delta.input_json_delta` | delta | `ToolCallDelta`; the complete JSON is parsed at `Done`. |
+| `content_block_stop` | delta | `BlockEnd`. |
+| `message_delta.stop_reason` | delta/state | Normalized stop reason; usage fields are merged. |
+| `message_delta.usage` with a non-object value | terminal `ProviderError` | `invalid_request`; malformed usage is never silently discarded. |
+| `message_stop` or clean EOF | Done or terminal `ProviderError` | `message_stop` yields `Done` when `message_delta.stop_reason` was present; after `message_start`, clean EOF without `message_stop` yields an incomplete error even when a stop reason was captured. A no-`message_start` stream with a stop reason follows Pi's clean-EOF completion path. |
+| `ping` | state | Ignored keepalive. |
+| SSE data-only frame with a known JSON event type | delta/state | Accepted because SSE `event` is optional; this is the documented rule (b) data-loss prevention deviation from Pi's event-name filter. |
+| `error` before deltas | retryable or terminal `ProviderError` | Provider error type selects the kind; `message_start` usage is retained in `partial` when present. |
+| `error` after deltas | terminal `ProviderError` | Partial content and usage are retained; `retryable=false`. |
+| unknown `content_block` type | state | Ignored like Pi; later deltas for an unknown block index are ignored. |
+| malformed JSON, block, delta, or redacted payload | terminal `ProviderError` | `invalid_request` for malformed provider metadata, otherwise `unknown`; never a successful `Done`. |
+| EOF without `message_stop` or response close failure | terminal `ProviderError` | After `message_start`, incomplete/transport failure preserves partial content and early usage regardless of a captured stop reason; close failures retain the same partial. |
+
+Anthropic stop reasons:
+
+| Wire value | Canonical |
+| --- | --- |
+| `end_turn`, `stop_sequence`, `pause_turn` | `stop` |
+| `max_tokens` | `length` |
+| `tool_use` | `tool_use` |
+| `refusal` | `refusal` |
+| `safety` | `safety` |
+
+## OpenAI Chat Completions
+
+| Canonical field | Request mapping |
+| --- | --- |
+| `system` | First `messages` item with `role="system"`. |
+| User text/image | `role="user"`; text is a string when alone, otherwise content parts; images use `image_url` data URLs. |
+| Assistant text | `role="assistant"`, string `content`. |
+| Thinking | Same-origin signed details are replayed as `reasoning_details` when the signature is structured; provider-compatible legacy signatures use `reasoning_content`, `reasoning`, or `reasoning_text`; unsigned thinking is text. |
+| Tool call | `tool_calls[].type="function"` with `id`, `function.name`, and JSON `function.arguments`. |
+| Tool result | `role="tool"` with `tool_call_id` and text content. Consecutive results stay adjacent; if `supports_images`, their loaded image bytes follow in one `role="user"` multimodal continuation after the complete group. Image-only tool text is `(see attached image)` and empty tool text is `(no tool output)`, matching Pi `openai-completions.ts:1399-1457`. Without image capability, C-1's named text placeholders remain. |
+| Tools | `tools[].type="function"` with `function.name`, `description`, and `parameters`. |
+| Reasoning effort | `reasoning_effort`; supported declared values, including explicit `none`, are forwarded unchanged, while `off`/`disabled` are omitted. |
+| Usage request | `stream_options.include_usage=true`. |
+
+Chat stream events:
+
+| Wire field | Outcome | Provider event / state |
+| --- | --- | --- |
+| `choices[0].delta.content` | delta | `TextDelta`. |
+| `choices[0].delta.reasoning_content/reasoning/reasoning_text` | delta | `ThinkingDelta`. |
+| `choices[0].delta.reasoning_details` | state | Stored as a structured thinking signature. |
+| `choices[0].delta.tool_calls[].id/function.name` | delta | `ToolCallStart`; missing/empty names are terminal `invalid_request`. |
+| `choices[0].delta.tool_calls[].function.arguments` | delta | `ToolCallDelta`; fragments are parsed at `Done`. |
+| `choices[0].delta.function_call.name/arguments` | delta | Legacy single-call form; normalized into the same tool-call state machine. |
+| `choices[0].finish_reason` | state | Stop reason. `max_tokens` becomes `length`; unknown values become terminal `error`, not `stop`. |
+| `choices[0].native_finish_reason` | state | A non-normal native reason such as `safety` or `recitation` overrides `finish_reason="stop"`; this prevents tool execution after a safety stop from a converted Gemini response. |
+| `usage` | state | One `_openai_usage` normalizer for chunk and choice usage. Cache reads use the first non-null nested `cached_tokens`, top-level `prompt_cache_hit_tokens`, or top-level `cached_tokens`; zero is authoritative. Cached read/write tokens are excluded from `input_tokens`; reasoning is already included in output. |
+| top-level `error` frame before deltas | retryable or terminal `ProviderError` | Classified from error type/code. |
+| top-level `error` frame after deltas | terminal `ProviderError` | Partial content and usage are retained; `retryable=false`. |
+| `data: [DONE]` | Done or terminal error | Completes the response only after a `finish_reason`; without one it is an incomplete `network` error, retryable only when no model output was emitted. A finish reason may also complete at clean EOF. |
+| malformed tool metadata, JSON, or EOF/close failure | terminal `ProviderError` | Invalid metadata is `invalid_request`; incomplete/transport failures retain partial state. |
+
+Chat stop reasons:
+
+| Wire value | Canonical |
+| --- | --- |
+| `stop` or absent | `stop` |
+| `length` | `length` |
+| `tool_calls`, `function_call` | `tool_use` |
+| `refusal` | `refusal` |
+| `content_filter`, `safety` | `safety` |
+
+## OpenAI Responses
+
+| Canonical field | Request mapping |
+| --- | --- |
+| System prompt | `instructions`. |
+| User text/image | `input` message with `role="user"`, `input_text`, and `input_image` parts. |
+| Assistant text | `input` message with `role="assistant"` and `output_text` parts. |
+| Thinking | Same-origin signed reasoning becomes an input `reasoning` item with its `id` and `encrypted_content`; unsigned thinking becomes assistant text. |
+| Tool call | Input `function_call` item with `id`, `call_id`, `name`, and JSON `arguments`. |
+| Tool result | Input `function_call_output` with `call_id` and `output`. |
+| Tools | `tools[]` with `type="function"`, `name`, `description`, and `parameters`. |
+| Reasoning effort | `reasoning.effort`, with supported declared values, including explicit `none`, forwarded unchanged, and `summary="auto"`; `off`/`disabled` are omitted. |
+| Client-side state | `store=false`; `previous_response_id` is never sent. |
+
+Responses stream events:
+
+| Wire event | Outcome | Provider event / state |
+| --- | --- | --- |
+| `response.created`, `response.in_progress`, `response.queued` | state | Records status; no visible delta. |
+| `response.output_text.delta` | delta | `TextDelta`. |
+| `response.refusal.delta` | delta/state | Refusal text delta and canonical `stop_reason="refusal"` only when its message slot exists; orphan deltas are ignored like Pi. |
+| `response.reasoning_summary_text.delta`, `response.reasoning_text.delta` | delta | `ThinkingDelta`. |
+| `response.reasoning_summary_part.added` | state | Recognized no-op lifecycle marker; future unknown event types remain ignored. |
+| `response.reasoning_summary_part.done` | delta | Adds the Pi-compatible `"\n\n"` separator to the current reasoning block. |
+| `response.output_item.added` (`reasoning`) | state | Captures reasoning item id and encrypted content; does not mark output streamed by itself. |
+| `response.output_item.added` (`function_call`) | delta/state | `ToolCallStart` when `call_id` is available; otherwise retains budgeted identity/argument state until `output_item.done` supplies the call ID, preserving C-2 ID stability and correct replay (rule (b)). Missing `output_index` uses a distinct internal fallback per consecutive call and later `item_id` events rebind to it. After a start, a later error is non-retryable under C-2. Proof: `test_responses_late_call_id_is_stable_and_replayable`. |
+| interrupted pending function call | delta/state before non-tool terminal | A length/safety/refusal/error stop exposes the pending call with a stable fallback ID and buffered arguments; it retains that stop reason instead of failing missing-identity validation. The loop settles, but never executes, the interrupted call. |
+| `response.function_call_arguments.delta` | delta/state | `ToolCallDelta`, or budgeted buffering while the call identity is pending. |
+| `response.function_call_arguments.done` | delta/state | Emits any suffix not already seen and replaces the final argument buffer. |
+| `response.output_item.done` | delta/state | Completes reasoning signatures, replaces the final message snapshot, emits unseen text/thinking and argument suffixes, and emits one `BlockEnd`; later streamed reasoning snapshots/deltas for the closed slot are ignored without re-serialization. Terminal `response.output` still backfills encrypted reasoning. |
+| `response.content_part.added/done`, `response.output_text.done`, reasoning `*.done` | state | Recognized no-op completion markers. |
+| `response.completed.response.usage` | Done | `Usage`; cached read/write tokens are excluded from `input_tokens`. Terminal status is normalized. Function calls and ordinary message/reasoning items listed only in terminal `response.output` are not adopted; existing reasoning signatures are backfilled and refusal status is detected. |
+| `response.incomplete.response.usage` without an error | Done or terminal `ProviderError` | The outer `response.incomplete` event always takes the incomplete path even when nested `response.status` is absent or stale. `max_output_tokens`/length becomes `length`; safety/content filtering becomes `safety`; other, missing, or unknown reasons become terminal `error`. |
+| `response.incomplete.response.error` | retryable or terminal `ProviderError` | Error code and usage are retained; after visible deltas `retryable=false`. |
+| `response.failed` / top-level `error` | retryable or terminal `ProviderError` | Error code classification with partial content and usage. |
+| malformed output item, tool metadata, JSON, or EOF/close failure | terminal `ProviderError` | Invalid metadata is `invalid_request`; transport/incomplete failures retain partial state. |
+
+Responses terminal states:
+
+| Wire state | Canonical |
+| --- | --- |
+| Completed with function calls | `tool_use` |
+| Completed without function calls | `stop` |
+| Refusal deltas | `refusal` |
+| `incomplete_details.reason=max_output_tokens` or `length` | `length` |
+| `incomplete_details.reason=content_filter` or `safety` | `safety` |
+| Failed/cancelled | terminal `ProviderError` (classified `unknown` when no provider error code is present) |
diff --git a/docs/plans/agent-core-contracts/provider.md b/docs/plans/agent-core-contracts/provider.md
index 034c6a4b7..a1ee4b6ef 100644
--- a/docs/plans/agent-core-contracts/provider.md
+++ b/docs/plans/agent-core-contracts/provider.md
@@ -5,7 +5,7 @@ about Model Hub routing.
```python
class ProviderAdapter(Protocol):
- protocol: Literal["anthropic", "openai_chat", "openai_responses", "google"]
+ protocol: Literal["anthropic", "openai_chat", "openai_responses"]
def stream(self, request: ModelRequest, cancel: CancelToken) -> AsyncIterator[ProviderEvent]: ...
diff --git a/tests/agent_core/agent/test_loop.py b/tests/agent_core/agent/test_loop.py
index b945c7f9d..44a3d820f 100644
--- a/tests/agent_core/agent/test_loop.py
+++ b/tests/agent_core/agent/test_loop.py
@@ -39,7 +39,7 @@ from core.agent_core.agent.models import RetryPolicy
from core.agent_core.ai.provider import Done, ModelCapabilities, ProviderError, TextDelta, ThinkingDelta, ToolCallStart
from core.agent_core.agent.models import ModelSelection
from core.agent_core.harness.projection import project
-from core.agent_core.messages import ThinkingBlock, ToolCallBlock, ToolResultMessage, UserMessage, text
+from core.agent_core.messages import AssistantMessage, ThinkingBlock, ToolCallBlock, ToolResultMessage, Usage, UserMessage, text
from core.agent_core.tools.base import ToolResult
from tests.agent_core.fakes import (
FakeJobHost,
@@ -256,6 +256,120 @@ async def test_C3_skip_tools_and_terminate_have_distinct_batch_semantics():
assert len([row for row in await agent.store.load("session") if row.kind == "tool_result"]) == 2
+ ("stop_reason", "run_reason"),
+ [("safety", "error"), ("error", "error"), ("aborted", "aborted")],
+)
+async def test_non_tool_stop_settles_calls_without_executing_tools(stop_reason, run_reason):
+ tool = FakeTool()
+ response = assistant(
+ calls=[ToolCallBlock("blocked-a", "echo"), ToolCallBlock("blocked-b", "echo")],
+ stop_reason=stop_reason,
+ )
+ agent = make_agent(ScriptedProvider([[Done(response)]]), tools=[tool])
+
+ events = await collect(agent)
+ rows = await agent.store.load("session")
+ results = [row.message for row in rows if row.kind == "tool_result"]
+
+ assert tool.calls == []
+ assert len(results) == 2
+ assert all(result.is_error for result in results)
+ assert all(stop_reason in result.content[0].text for result in results)
+ assert events[-1].reason == run_reason
+
+
+async def test_length_stop_settles_calls_and_retries_the_model_turn():
+ tool = FakeTool()
+ provider = ScriptedProvider(
+ [
+ [Done(assistant(calls=[ToolCallBlock("truncated", "echo", {"x": 1})], stop_reason="length"))],
+ [Done(assistant("reissued"))],
+ ]
+ )
+
+ events = await collect(make_agent(provider, tools=[tool]))
+
+ assert tool.calls == []
+ assert len(provider.requests) == 2
+ results = [message for message in provider.requests[1].messages if isinstance(message, ToolResultMessage)]
+ assert len(results) == 1
+ assert results[0].is_error is True
+ assert "re-issue" in results[0].content[0].text
+ assert events[-1].reason == "completed"
+
+
+async def test_length_stop_honors_end_hook_after_settling_calls():
+ class Stop(Hooks):
+ async def after_model(self, message, ctx):
+ return End()
+
+ tool = FakeTool()
+ provider = ScriptedProvider(
+ [[Done(assistant(calls=[ToolCallBlock("truncated", "echo", {"x": 1})], stop_reason="length"))]]
+ )
+ agent = make_agent(provider, tools=[tool], hooks=[Stop()])
+
+ events = await collect(agent)
+
+ assert tool.calls == []
+ assert len(provider.requests) == 1
+ assert events[-1].reason == "ended_by_hook"
+ assert len([row for row in await agent.store.load("session") if row.kind == "tool_result"]) == 1
+
+
+async def test_length_stop_applies_steer_before_reissued_model_call():
+ holder = {}
+
+ async def first(request, cancel):
+ assert await holder["agent"].steer(input_row("steer", "steered"))
+ yield Done(assistant(calls=[ToolCallBlock("truncated", "echo", {"x": 1})], stop_reason="length"))
+
+ provider = ScriptedProvider([first, [Done(assistant("done"))]])
+ holder["agent"] = make_agent(provider, tools=[FakeTool()])
+
+ events = await collect(holder["agent"])
+
+ assert len(provider.requests) == 2
+ assert user_texts(provider.requests[1]) == ["hello", "steered"]
+ assert events[-1].reason == "completed"
+
+
+async def test_length_stop_does_not_consume_steer_when_retry_budget_is_exhausted():
+ holder = {}
+
+ async def first(request, cancel):
+ del request, cancel
+ assert await holder["agent"].steer(input_row("steer", "preserve me"))
+ yield Done(assistant(calls=[ToolCallBlock("truncated", "echo", {"x": 1})], stop_reason="length"))
+
+ holder["agent"] = make_agent(
+ ScriptedProvider([first]),
+ tools=[FakeTool()],
+ retry=RetryPolicy(max_retries=0, initial_delay_s=0),
+ )
+ events = await collect(holder["agent"])
+
+ assert events[-1].reason == "error"
+ pending = await holder["agent"].take_pending_inputs()
+ assert [item.message.content[0].text for item in pending] == ["preserve me"]
+
+
+async def test_repeated_length_tool_stops_are_bounded():
+ tool = FakeTool()
+ response = Done(assistant(calls=[ToolCallBlock("truncated", "echo", {"x": 1})], stop_reason="length"))
+ provider = ScriptedProvider([[response], [response], [response]])
+
+ events = await collect(make_agent(provider, tools=[tool], retry=RetryPolicy(initial_delay_s=0)))
+
+ assert tool.calls == []
+ assert len(provider.requests) == 3
+ assert events[-1].reason == "error"
+ assert [(event.kind, event.message) for event in events if isinstance(event, AgentError)] == [
+ ("length", "The model repeatedly exceeded its output limit while emitting a tool call.")
+ ]
+
+
async def test_C4_steer_waits_for_the_batch_and_follow_up_waits_for_natural_end():
entered, release = asyncio.Event(), asyncio.Event()
@@ -465,7 +579,7 @@ async def test_C9_events_reference_committed_rows_and_progress_precedes_tool_fin
@pytest.mark.parametrize("streamed", [False, "text", "tool", "partial"])
-async def test_retry_only_before_output_and_re_resolves_the_route(streamed, monkeypatch):
+async def test_retry_obeys_provider_flag_and_allows_usage_only_partial(streamed, monkeypatch):
sleeps = []
real_sleep = asyncio.sleep
@@ -477,7 +591,7 @@ async def test_retry_only_before_output_and_re_resolves_the_route(streamed, monk
error = ProviderError(
"rate_limit",
"busy",
- True,
+ streamed not in {"text", "tool"},
retry_after_s=3.0,
partial=assistant("partial", stop_reason="error") if streamed == "partial" else None,
)
@@ -487,21 +601,92 @@ async def test_retry_only_before_output_and_re_resolves_the_route(streamed, monk
provider = ScriptedProvider([prefix + [error], [Done(assistant())]])
agent = make_agent(provider)
events = await collect(agent)
- if streamed:
+ if streamed in {"text", "tool"}:
assert len(provider.requests) == 1
assert events[-1].reason == "error"
assert sleeps == []
else:
+ # A usage-only partial is persisted as a non-final model response, not
+ # merged into the successful attempt. The provider owns retryability.
assert len(provider.requests) == agent.models.resolutions == 2
assert sleeps == [3.0]
assert events[-1].reason == "completed"
+async def test_retry_preserves_usage_only_partial_in_successful_response():
+ store = InMemoryTranscriptStore()
+ first_partial = AssistantMessage(
+ content=(),
+ origin=assistant().origin,
+ stop_reason="error",
+ usage=Usage(input_tokens=5, output_tokens=2, cache_write_tokens=1),
+ )
+ successful = AssistantMessage(
+ content=assistant("done").content,
+ origin=assistant().origin,
+ stop_reason="stop",
+ usage=Usage(input_tokens=7, output_tokens=3, cache_read_tokens=4),
+ )
+ provider = ScriptedProvider(
+ [
+ [ProviderError("rate_limit", "busy", True, partial=first_partial)],
+ [Done(successful)],
+ ]
+ )
+
+ events = await collect(
+ make_agent(provider, store=store, retry=RetryPolicy(initial_delay_s=0))
+ )
+
+ assert events[-1].reason == "completed"
+ responses = [row.message for row in await store.load("session") if row.kind == "response"]
+ assert len(responses) == 2
+ assert responses[0].usage == Usage(input_tokens=5, output_tokens=2, cache_write_tokens=1)
+ assert responses[1].usage == Usage(
+ input_tokens=7,
+ output_tokens=3,
+ cache_read_tokens=4,
+ )
+
+
+async def test_retry_usage_partial_is_not_committed_twice_when_budget_expires(monkeypatch):
+ real_sleep = asyncio.sleep
+
+ async def slow_sleep(delay):
+ del delay
+ await real_sleep(0.01)
+
+ monkeypatch.setattr("core.agent_core.agent.loop.asyncio.sleep", slow_sleep)
+ partial = AssistantMessage(
+ content=(),
+ origin=assistant().origin,
+ stop_reason="error",
+ usage=Usage(input_tokens=5),
+ )
+ provider = ScriptedProvider(
+ [[ProviderError("rate_limit", "busy", True, partial=partial)], [Done(assistant("done"))]]
+ )
+ store = InMemoryTranscriptStore()
+ agent = make_agent(
+ provider,
+ store=store,
+ retry=RetryPolicy(initial_delay_s=0, max_elapsed_s=0.005),
+ )
+
+ events = await collect(agent)
+
+ responses = [row.message for row in await store.load("session") if row.kind == "response"]
+ assert len(provider.requests) == 1
+ assert len(responses) == 1
+ assert responses[0].usage == Usage(input_tokens=5)
+ assert events[-1].reason == "error"
+
+
@pytest.mark.parametrize(
"kind,retryable,reason,count",
[
("server", True, "error", 3),
- ("unknown", True, "error", 1),
+ ("unknown", True, "error", 3),
("auth", False, "error", 1),
("overflow", False, "context_exhausted", 1),
("aborted", False, "aborted", 1),
diff --git a/tests/agent_core/ai/__init__.py b/tests/agent_core/ai/__init__.py
new file mode 100644
index 000000000..12ecaa543
--- /dev/null
+++ b/tests/agent_core/ai/__init__.py
@@ -0,0 +1 @@
+"""Provider adapter contract tests."""
diff --git a/tests/agent_core/ai/test_pi_stream_differential.py b/tests/agent_core/ai/test_pi_stream_differential.py
new file mode 100644
index 000000000..19070b554
--- /dev/null
+++ b/tests/agent_core/ai/test_pi_stream_differential.py
@@ -0,0 +1,891 @@
+"""Recorded stream projections compared with Pi 7fbbd5f.
+
+The expected Pi projections were produced by driving Pi's native handlers in
+an isolated temporary checkout with credential-free stub transports. This
+test keeps the recorded wire sequences and the canonical projection in the
+Avibe repository so adapter changes cannot silently drift from that audit.
+"""
+
+from __future__ import annotations
+
+import json
+from collections.abc import Mapping
+from typing import Any
+
+import httpx
+import pytest
+
+from core.agent_core.ai.anthropic import AnthropicAdapter
+from core.agent_core.ai.openai_chat import OpenAIChatAdapter
+from core.agent_core.ai.openai_responses import OpenAIResponsesAdapter
+from core.agent_core.ai.provider import Done, ModelEndpoint, ModelRequest, ProviderError
+from core.agent_core.cancel import CancelToken
+from core.agent_core.messages import (
+ AssistantMessage,
+ TextBlock,
+ ThinkingBlock,
+ ToolCallBlock,
+ Usage,
+ UserMessage,
+)
+
+
+def _request(protocol: str) -> ModelRequest:
+ provider = {
+ "anthropic": "anthropic",
+ "openai_chat": "openai",
+ "openai_responses": "openai",
+ }[protocol]
+ return ModelRequest(
+ endpoint=ModelEndpoint(
+ protocol=protocol, # type: ignore[arg-type]
+ base_url="https://model.test/v1",
+ model_id="model-x",
+ token="token",
+ provider=provider,
+ ),
+ system="system",
+ messages=(UserMessage((TextBlock(text="hello"),)),),
+ tools=(),
+ max_tokens=128,
+ reasoning_effort=None,
+ )
+
+
+def _sse(*events: Mapping[str, Any]) -> str:
+ return "".join(f"data: {json.dumps(dict(event), separators=(',', ':'))}\n\n" for event in events)
+
+
+def _anthropic_sse(*events: Mapping[str, Any]) -> str:
+ return "".join(
+ f"event: {event['type']}\ndata: {json.dumps(dict(event), separators=(',', ':'))}\n\n"
+ for event in events
+ )
+
+
+def _project_content(message: AssistantMessage) -> list[dict[str, Any]]:
+ projected: list[dict[str, Any]] = []
+ for block in message.content:
+ if isinstance(block, TextBlock):
+ projected.append({"type": "text", "text": block.text})
+ elif isinstance(block, ThinkingBlock):
+ projected.append(
+ {
+ "type": "thinking",
+ "text": block.text,
+ "signature": block.signature,
+ "redacted": block.redacted,
+ }
+ )
+ elif isinstance(block, ToolCallBlock):
+ projected.append(
+ {
+ "type": "tool",
+ "id": block.id,
+ "native_id": block.native_id,
+ "name": block.name,
+ "arguments": block.arguments,
+ "signature": block.signature,
+ }
+ )
+ return projected
+
+
+def _project_usage(usage: Usage | None) -> dict[str, Any] | None:
+ if usage is None:
+ return None
+ return {
+ "input": usage.input_tokens,
+ "output": usage.output_tokens,
+ "cache_read": usage.cache_read_tokens,
+ "cache_write": usage.cache_write_tokens,
+ "reasoning": usage.reasoning_tokens,
+ }
+
+
+def _project(events: list[Any]) -> dict[str, Any]:
+ terminal = events[-1]
+ if isinstance(terminal, Done):
+ return {
+ "outcome": "done",
+ "stop_reason": terminal.message.stop_reason,
+ "content": _project_content(terminal.message),
+ "usage": _project_usage(terminal.message.usage),
+ }
+ assert isinstance(terminal, ProviderError)
+ partial = terminal.partial
+ return {
+ "outcome": "error",
+ "kind": terminal.kind,
+ "retryable": terminal.retryable,
+ "partial": (
+ {
+ "stop_reason": partial.stop_reason,
+ "content": _project_content(partial),
+ "usage": _project_usage(partial.usage),
+ }
+ if partial is not None
+ else None
+ ),
+ }
+
+
+_CASES = (
+ {
+ "name": "responses_output_slots_arrive_in_order",
+ "adapter": OpenAIResponsesAdapter,
+ "protocol": "openai_responses",
+ "body": _sse(
+ {
+ "type": "response.output_item.added",
+ "output_index": 0,
+ "item": {"type": "reasoning", "id": "rs_1"},
+ },
+ {"type": "response.reasoning_text.delta", "output_index": 0, "delta": "plan"},
+ {
+ "type": "response.output_item.added",
+ "output_index": 1,
+ "item": {"type": "message", "id": "msg_1"},
+ },
+ {"type": "response.output_text.delta", "output_index": 1, "delta": "answer"},
+ {
+ "type": "response.output_item.done",
+ "output_index": 0,
+ "item": {
+ "type": "reasoning",
+ "id": "rs_1",
+ "encrypted_content": "enc",
+ "summary": [{"type": "summary_text", "text": "plan"}],
+ },
+ },
+ {
+ "type": "response.completed",
+ "response": {
+ "status": "completed",
+ "output": [
+ {
+ "type": "reasoning",
+ "id": "rs_1",
+ "encrypted_content": "enc",
+ "summary": [{"type": "summary_text", "text": "plan"}],
+ },
+ {"type": "message", "id": "msg_1", "content": [{"type": "output_text", "text": "answer"}]},
+ ],
+ "usage": {
+ "input_tokens": 2,
+ "output_tokens": 3,
+ "output_tokens_details": {"reasoning_tokens": 1},
+ },
+ },
+ },
+ ),
+ "pi": {
+ "outcome": "done",
+ "stop_reason": "stop",
+ "content": [
+ {
+ "type": "thinking",
+ "text": "plan",
+ "signature": '{"type":"reasoning","id":"rs_1","encrypted_content":"enc","summary":[{"type":"summary_text","text":"plan"}]}',
+ "redacted": False,
+ },
+ {"type": "text", "text": "answer"},
+ ],
+ "usage": {"input": 2, "output": 3, "cache_read": 0, "cache_write": 0, "reasoning": 1},
+ },
+ },
+ {
+ "name": "responses_unknown_event_is_ignored",
+ "adapter": OpenAIResponsesAdapter,
+ "protocol": "openai_responses",
+ "body": _sse(
+ {"type": "response.future_event", "new_field": True},
+ {"type": "response.completed", "response": {"status": "completed"}},
+ ),
+ "pi": {
+ "outcome": "done",
+ "stop_reason": "stop",
+ "content": [],
+ "usage": {"input": 0, "output": 0, "cache_read": 0, "cache_write": 0, "reasoning": None},
+ },
+ "avibe": {
+ "outcome": "done",
+ "stop_reason": "stop",
+ "content": [],
+ "usage": None,
+ },
+ },
+ {
+ "name": "responses_missing_output_index_shares_pi_slot",
+ "adapter": OpenAIResponsesAdapter,
+ "protocol": "openai_responses",
+ "body": _sse(
+ {"type": "response.output_item.added", "item": {"type": "reasoning", "id": "rs_1"}},
+ {
+ "type": "response.output_item.added",
+ "item": {
+ "type": "function_call",
+ "id": "fc_1",
+ "call_id": "call_1",
+ "name": "read",
+ },
+ },
+ {"type": "response.function_call_arguments.delta", "delta": '{"path":"x"}'},
+ {
+ "type": "response.output_item.done",
+ "item": {
+ "type": "function_call",
+ "id": "fc_1",
+ "call_id": "call_1",
+ "name": "read",
+ "arguments": '{"path":"x"}',
+ },
+ },
+ {"type": "response.completed", "response": {"status": "completed"}},
+ ),
+ "pi": {
+ "outcome": "done",
+ "stop_reason": "tool_use",
+ "content": [
+ {"type": "thinking", "text": "", "signature": None, "redacted": False},
+ {
+ "type": "tool",
+ "id": "call_1|fc_1",
+ "native_id": None,
+ "name": "read",
+ "arguments": {"path": "x"},
+ "signature": None,
+ },
+ ],
+ "usage": {"input": 0, "output": 0, "cache_read": 0, "cache_write": 0, "reasoning": None},
+ },
+ "avibe": {
+ "outcome": "done",
+ "stop_reason": "tool_use",
+ "content": [
+ {"type": "thinking", "text": "", "signature": None, "redacted": False},
+ {
+ "type": "tool",
+ "id": "call_1",
+ "native_id": "fc_1",
+ "name": "read",
+ "arguments": {"path": "x"},
+ "signature": None,
+ },
+ ],
+ "usage": None,
+ },
+ },
+ {
+ "name": "responses_terminal_message_snapshot_is_not_adopted",
+ "adapter": OpenAIResponsesAdapter,
+ "protocol": "openai_responses",
+ "body": _sse(
+ {"type": "response.output_item.added", "output_index": 0, "item": {"type": "message", "id": "msg_1"}},
+ {
+ "type": "response.completed",
+ "response": {
+ "status": "completed",
+ "output": [
+ {
+ "type": "message",
+ "id": "msg_1",
+ "content": [{"type": "output_text", "text": "terminal"}],
+ }
+ ],
+ },
+ },
+ ),
+ "pi": {
+ "outcome": "done",
+ "stop_reason": "stop",
+ "content": [{"type": "text", "text": ""}],
+ "usage": {"input": 0, "output": 0, "cache_read": 0, "cache_write": 0, "reasoning": None},
+ },
+ "avibe": {
+ "outcome": "done",
+ "stop_reason": "stop",
+ "content": [{"type": "text", "text": ""}],
+ "usage": None,
+ },
+ },
+ {
+ "name": "chat_reasoning_details_merge",
+ "adapter": OpenAIChatAdapter,
+ "protocol": "openai_chat",
+ "body": _sse(
+ {"choices": [{"delta": {"reasoning_details": [{"type": "reasoning.text", "text": "a"}]}}]},
+ {
+ "choices": [
+ {
+ "delta": {"reasoning_details": [{"type": "reasoning.text", "text": "b"}]},
+ "finish_reason": "stop",
+ }
+ ]
+ },
+ {"choices": []},
+ {"choices": [], "usage": {"prompt_tokens": 0, "completion_tokens": 0}},
+ )
+ + "data: [DONE]\n\n",
+ "pi": {
+ "outcome": "done",
+ "stop_reason": "stop",
+ "content": [
+ {
+ "type": "thinking",
+ "text": "",
+ "signature": '[{"type":"reasoning.text","text":"ab"}]',
+ "redacted": False,
+ }
+ ],
+ "usage": {"input": 0, "output": 0, "cache_read": 0, "cache_write": 0, "reasoning": 0},
+ },
+ "avibe": {
+ "outcome": "done",
+ "stop_reason": "stop",
+ "content": [
+ {
+ "type": "thinking",
+ "text": "",
+ "signature": '[{"type":"reasoning.text","text":"ab"}]',
+ "redacted": False,
+ }
+ ],
+ "usage": {"input": 0, "output": 0, "cache_read": 0, "cache_write": 0, "reasoning": None},
+ },
+ },
+ {
+ "name": "chat_error_after_text_keeps_partial",
+ "adapter": OpenAIChatAdapter,
+ "protocol": "openai_chat",
+ "body": _sse(
+ {"choices": [{"delta": {"content": "partial"}}]},
+ {"error": {"type": "server_error", "message": "failed"}},
+ ),
+ "pi": {
+ "outcome": "error",
+ "kind": "server",
+ "retryable": False,
+ "partial": {
+ "stop_reason": "error",
+ "content": [{"type": "text", "text": "partial"}],
+ "usage": {"input": 0, "output": 0, "cache_read": 0, "cache_write": 0, "reasoning": None},
+ },
+ },
+ "avibe": {
+ "outcome": "error",
+ "kind": "server",
+ "retryable": False,
+ "partial": {
+ "stop_reason": "error",
+ "content": [{"type": "text", "text": "partial"}],
+ "usage": None,
+ },
+ },
+ },
+ {
+ "name": "anthropic_message_start_stop_reason_survives_eof",
+ "adapter": AnthropicAdapter,
+ "protocol": "anthropic",
+ "body": _anthropic_sse(
+ {"type": "message_start", "message": {"usage": {"input_tokens": 7}}},
+ {"type": "message_delta", "delta": {"stop_reason": "end_turn"}},
+ ),
+ "pi": {
+ "outcome": "error",
+ "kind": "unknown",
+ "retryable": False,
+ "partial": {
+ "stop_reason": "error",
+ "content": [],
+ "usage": {"input": 7, "output": 0, "cache_read": 0, "cache_write": 0, "reasoning": None},
+ },
+ },
+ "avibe": {
+ "outcome": "error",
+ "kind": "network",
+ "retryable": True,
+ "partial": {
+ "stop_reason": "error",
+ "content": [],
+ "usage": {"input": 7, "output": 0, "cache_read": 0, "cache_write": 0, "reasoning": None},
+ },
+ },
+ },
+ {
+ "name": "anthropic_unknown_event_is_ignored",
+ "adapter": AnthropicAdapter,
+ "protocol": "anthropic",
+ "body": _anthropic_sse(
+ {"type": "message_start", "message": {"usage": {"input_tokens": 4}}},
+ {"type": "future_event", "payload": {"new": "field"}},
+ {"type": "message_delta", "delta": {"stop_reason": "end_turn"}},
+ {"type": "message_stop"},
+ ),
+ "pi": {
+ "outcome": "done",
+ "stop_reason": "stop",
+ "content": [],
+ "usage": {"input": 4, "output": 0, "cache_read": 0, "cache_write": 0, "reasoning": None},
+ },
+ },
+ {
+ "name": "responses_terminal_refusal_is_contract_deviation",
+ "adapter": OpenAIResponsesAdapter,
+ "protocol": "openai_responses",
+ "body": _sse(
+ {"type": "response.output_item.added", "output_index": 0, "item": {"type": "message", "id": "msg_1"}},
+ {
+ "type": "response.completed",
+ "response": {
+ "status": "completed",
+ "output": [
+ {
+ "type": "message",
+ "id": "msg_1",
+ "content": [{"type": "refusal", "refusal": "cannot help"}],
+ }
+ ],
+ },
+ },
+ ),
+ "pi": {
+ "outcome": "done",
+ "stop_reason": "stop",
+ "content": [{"type": "text", "text": ""}],
+ "usage": {"input": 0, "output": 0, "cache_read": 0, "cache_write": 0, "reasoning": None},
+ },
+ "avibe": {
+ "outcome": "done",
+ "stop_reason": "refusal",
+ "content": [{"type": "text", "text": "cannot help"}],
+ "usage": None,
+ },
+ },
+ {
+ "name": "responses_orphan_refusal_delta_is_ignored",
+ "adapter": OpenAIResponsesAdapter,
+ "protocol": "openai_responses",
+ "body": _sse(
+ {"type": "response.refusal.delta", "output_index": 3, "delta": "cannot help"},
+ {"type": "response.completed", "response": {"status": "completed"}},
+ ),
+ "pi": {
+ "outcome": "done",
+ "stop_reason": "stop",
+ "content": [],
+ "usage": {"input": 0, "output": 0, "cache_read": 0, "cache_write": 0, "reasoning": None},
+ },
+ "avibe": {
+ "outcome": "done",
+ "stop_reason": "stop",
+ "content": [],
+ "usage": None,
+ },
+ },
+ {
+ "name": "chat_late_tool_id_uses_stable_canonical_id",
+ "adapter": OpenAIChatAdapter,
+ "protocol": "openai_chat",
+ "body": _sse(
+ {"choices": [{"delta": {"tool_calls": [{"index": 0, "function": {"name": "read"}}]}}]},
+ {
+ "choices": [
+ {
+ "delta": {
+ "tool_calls": [
+ {"index": 0, "id": "provider-call", "function": {"arguments": '{"path":"x"}'}}
+ ]
+ },
+ "finish_reason": "tool_calls",
+ }
+ ]
+ },
+ )
+ + "data: [DONE]\n\n",
+ "pi": {
+ "outcome": "done",
+ "stop_reason": "tool_use",
+ "content": [
+ {
+ "type": "tool",
+ "id": "provider-call",
+ "native_id": None,
+ "name": "read",
+ "arguments": {"path": "x"},
+ "signature": None,
+ }
+ ],
+ "usage": {"input": 0, "output": 0, "cache_read": 0, "cache_write": 0, "reasoning": None},
+ },
+ "avibe": {
+ "outcome": "done",
+ "stop_reason": "tool_use",
+ "content": [
+ {
+ "type": "tool",
+ "id": "call_0",
+ "native_id": "provider-call",
+ "name": "read",
+ "arguments": {"path": "x"},
+ "signature": None,
+ }
+ ],
+ "usage": None,
+ },
+ },
+ {
+ "name": "responses_consecutive_missing_output_indexes_rebind",
+ "adapter": OpenAIResponsesAdapter,
+ "protocol": "openai_responses",
+ "body": _sse(
+ {
+ "type": "response.output_item.added",
+ "item": {"type": "function_call", "id": "fc_a", "call_id": "call_a", "name": "read"},
+ },
+ {
+ "type": "response.output_item.added",
+ "item": {"type": "function_call", "id": "fc_b", "call_id": "call_b", "name": "read"},
+ },
+ {
+ "type": "response.function_call_arguments.delta",
+ "item_id": "fc_a",
+ "delta": '{"path":"a"}',
+ },
+ {
+ "type": "response.function_call_arguments.delta",
+ "item_id": "fc_b",
+ "delta": '{"path":"b"}',
+ },
+ {
+ "type": "response.output_item.done",
+ "item": {
+ "type": "function_call",
+ "id": "fc_a",
+ "call_id": "call_a",
+ "name": "read",
+ "arguments": '{"path":"a"}',
+ },
+ },
+ {
+ "type": "response.output_item.done",
+ "item": {
+ "type": "function_call",
+ "id": "fc_b",
+ "call_id": "call_b",
+ "name": "read",
+ "arguments": '{"path":"b"}',
+ },
+ },
+ {"type": "response.completed", "response": {"status": "completed"}},
+ ),
+ "pi": {
+ "outcome": "done",
+ "stop_reason": "tool_use",
+ "content": [
+ {
+ "type": "tool",
+ "id": "call_a|fc_a",
+ "native_id": None,
+ "name": "read",
+ "arguments": {"path": "a"},
+ "signature": None,
+ },
+ {
+ "type": "tool",
+ "id": "call_b|fc_b",
+ "native_id": None,
+ "name": "read",
+ "arguments": {"path": "b"},
+ "signature": None,
+ },
+ ],
+ "usage": {"input": 0, "output": 0, "cache_read": 0, "cache_write": 0, "reasoning": None},
+ },
+ "avibe": {
+ "outcome": "done",
+ "stop_reason": "tool_use",
+ "content": [
+ {
+ "type": "tool",
+ "id": "call_a",
+ "native_id": "fc_a",
+ "name": "read",
+ "arguments": {"path": "a"},
+ "signature": None,
+ },
+ {
+ "type": "tool",
+ "id": "call_b",
+ "native_id": "fc_b",
+ "name": "read",
+ "arguments": {"path": "b"},
+ "signature": None,
+ },
+ ],
+ "usage": None,
+ },
+ },
+ {
+ "name": "responses_empty_slots_ignore_late_deltas",
+ "adapter": OpenAIResponsesAdapter,
+ "protocol": "openai_responses",
+ "body": _sse(
+ {
+ "type": "response.output_item.added",
+ "output_index": 0,
+ "item": {"type": "message", "id": "msg_1"},
+ },
+ {
+ "type": "response.output_item.added",
+ "output_index": 1,
+ "item": {"type": "reasoning", "id": "rs_1"},
+ },
+ {
+ "type": "response.output_item.done",
+ "output_index": 0,
+ "item": {"type": "message", "id": "msg_1", "content": []},
+ },
+ {
+ "type": "response.output_item.done",
+ "output_index": 1,
+ "item": {"type": "reasoning", "id": "rs_1", "summary": []},
+ },
+ {"type": "response.output_text.delta", "output_index": 0, "delta": "late text"},
+ {"type": "response.reasoning_text.delta", "output_index": 1, "delta": "late thinking"},
+ {"type": "response.completed", "response": {"status": "completed"}},
+ ),
+ "pi": {
+ "outcome": "done",
+ "stop_reason": "stop",
+ "content": [
+ {"type": "text", "text": ""},
+ {"type": "thinking", "text": "", "signature": None, "redacted": False},
+ ],
+ "usage": {"input": 0, "output": 0, "cache_read": 0, "cache_write": 0, "reasoning": None},
+ },
+ "avibe": {
+ "outcome": "done",
+ "stop_reason": "stop",
+ "content": [
+ {"type": "text", "text": ""},
+ {"type": "thinking", "text": "", "signature": None, "redacted": False},
+ ],
+ "usage": None,
+ },
+ },
+ {
+ "name": "chat_finish_reason_end_maps_to_stop",
+ "adapter": OpenAIChatAdapter,
+ "protocol": "openai_chat",
+ "body": _sse({"choices": [{"delta": {"content": "ok"}, "finish_reason": "end"}]})
+ + "data: [DONE]\n\n",
+ "pi": {
+ "outcome": "done",
+ "stop_reason": "stop",
+ "content": [{"type": "text", "text": "ok"}],
+ "usage": {"input": 0, "output": 0, "cache_read": 0, "cache_write": 0, "reasoning": None},
+ },
+ "avibe": {
+ "outcome": "done",
+ "stop_reason": "stop",
+ "content": [{"type": "text", "text": "ok"}],
+ "usage": None,
+ },
+ },
+ {
+ "name": "anthropic_null_delta_usage_preserves_message_start",
+ "adapter": AnthropicAdapter,
+ "protocol": "anthropic",
+ "body": _anthropic_sse(
+ {"type": "message_start", "message": {"usage": {"input_tokens": 7}}},
+ {
+ "type": "message_delta",
+ "delta": {"stop_reason": "end_turn"},
+ "usage": {"input_tokens": None, "output_tokens": None},
+ },
+ {"type": "message_stop"},
+ ),
+ "pi": {
+ "outcome": "done",
+ "stop_reason": "stop",
+ "content": [],
+ "usage": {"input": 7, "output": 0, "cache_read": 0, "cache_write": 0, "reasoning": None},
+ },
+ },
+ {
+ "name": "chat_malformed_tool_arguments",
+ "adapter": OpenAIChatAdapter,
+ "protocol": "openai_chat",
+ "body": _sse(
+ {
+ "choices": [
+ {
+ "delta": {
+ "tool_calls": [
+ {"index": 0, "id": "call_1", "function": {"name": "read", "arguments": "{"}}
+ ]
+ }
+ }
+ ]
+ },
+ {"choices": [{"delta": {}, "finish_reason": "tool_calls"}]},
+ )
+ + "data: [DONE]\n\n",
+ "pi": {
+ "outcome": "done",
+ "stop_reason": "tool_use",
+ "content": [
+ {
+ "type": "tool",
+ "id": "call_1",
+ "native_id": None,
+ "name": "read",
+ "arguments": {},
+ "signature": None,
+ }
+ ],
+ "usage": {"input": 0, "output": 0, "cache_read": 0, "cache_write": 0, "reasoning": None},
+ },
+ "avibe": {
+ "outcome": "error",
+ "kind": "invalid_request",
+ "retryable": False,
+ "partial": {"stop_reason": "error", "content": [], "usage": None},
+ },
+ },
+ {
+ "name": "chat_eof_after_text_is_partial_abort",
+ "adapter": OpenAIChatAdapter,
+ "protocol": "openai_chat",
+ "body": _sse({"choices": [{"delta": {"content": "partial"}}]}),
+ "pi": {
+ "outcome": "error",
+ "kind": "unknown",
+ "retryable": False,
+ "partial": {
+ "stop_reason": "error",
+ "content": [{"type": "text", "text": "partial"}],
+ "usage": {"input": 0, "output": 0, "cache_read": 0, "cache_write": 0, "reasoning": None},
+ },
+ },
+ "avibe": {
+ "outcome": "error",
+ "kind": "network",
+ "retryable": False,
+ "partial": {
+ "stop_reason": "error",
+ "content": [{"type": "text", "text": "partial"}],
+ "usage": None,
+ },
+ },
+ },
+ {
+ "name": "anthropic_empty_block_end_then_error",
+ "adapter": AnthropicAdapter,
+ "protocol": "anthropic",
+ "body": _anthropic_sse(
+ {"type": "content_block_start", "index": 0, "content_block": {"type": "text"}},
+ {"type": "content_block_stop", "index": 0},
+ {"type": "error", "error": {"type": "overloaded_error", "message": "busy"}},
+ ),
+ "pi": {
+ "outcome": "error",
+ "kind": "overloaded",
+ "retryable": False,
+ "partial": {
+ "stop_reason": "error",
+ "content": [{"type": "text", "text": ""}],
+ "usage": {"input": 0, "output": 0, "cache_read": 0, "cache_write": 0, "reasoning": None},
+ },
+ },
+ "avibe": {
+ "outcome": "error",
+ "kind": "overloaded",
+ "retryable": True,
+ "partial": None,
+ },
+ },
+ {
+ "name": "anthropic_malformed_delta",
+ "adapter": AnthropicAdapter,
+ "protocol": "anthropic",
+ "body": _anthropic_sse(
+ {"type": "content_block_start", "index": 0, "content_block": {"type": "text"}},
+ {"type": "content_block_delta", "index": 0, "delta": None},
+ ),
+ "pi": {
+ "outcome": "error",
+ "kind": "unknown",
+ "retryable": False,
+ "partial": {
+ "stop_reason": "error",
+ "content": [{"type": "text", "text": ""}],
+ "usage": {"input": 0, "output": 0, "cache_read": 0, "cache_write": 0, "reasoning": None},
+ },
+ },
+ "avibe": {
+ "outcome": "error",
+ "kind": "invalid_request",
+ "retryable": False,
+ "partial": None,
+ },
+ },
+)
+
+_CONTRACT_DEVIATIONS = {
+ "responses_unknown_event_is_ignored",
+ "responses_missing_output_index_shares_pi_slot",
+ "responses_terminal_message_snapshot_is_not_adopted",
+ "chat_reasoning_details_merge",
+ "chat_error_after_text_keeps_partial",
+ "responses_terminal_refusal_is_contract_deviation",
+ "responses_orphan_refusal_delta_is_ignored",
+ "chat_late_tool_id_uses_stable_canonical_id",
+ "responses_consecutive_missing_output_indexes_rebind",
+ "responses_empty_slots_ignore_late_deltas",
+ "chat_finish_reason_end_maps_to_stop",
+ "chat_malformed_tool_arguments",
+ "chat_eof_after_text_is_partial_abort",
+ "anthropic_message_start_stop_reason_survives_eof",
+ "anthropic_empty_block_end_then_error",
+ "anthropic_malformed_delta",
+}
+
+
+def _assert_projection_shape(projection: Mapping[str, Any]) -> None:
+ assert set(projection) >= {"outcome"}
+ if projection["outcome"] == "done":
+ assert set(projection) >= {"stop_reason", "content", "usage"}
+ usage = projection["usage"]
+ else:
+ assert set(projection) >= {"kind", "retryable", "partial"}
+ partial = projection["partial"]
+ usage = partial["usage"] if partial is not None else None
+ if usage is not None:
+ assert set(usage) == {"input", "output", "cache_read", "cache_write", "reasoning"}
+
+
[email protected]("case", _CASES, ids=lambda case: case["name"])
+async def test_recorded_pi_stream_projections(case: Mapping[str, Any]) -> None:
+ def handler(_: httpx.Request) -> httpx.Response:
+ return httpx.Response(
+ 200,
+ headers={"content-type": "text/event-stream"},
+ text=case["body"],
+ )
+
+ async with httpx.AsyncClient(transport=httpx.MockTransport(handler)) as client:
+ adapter = case["adapter"](client)
+ events = [
+ event async for event in adapter.stream(_request(case["protocol"]), CancelToken())
+ ]
+
+ _assert_projection_shape(case["pi"])
+ if "avibe" in case:
+ assert case["name"] in _CONTRACT_DEVIATIONS
+ _assert_projection_shape(case["avibe"])
+ assert case["avibe"] != case["pi"]
+ expected = case.get("avibe", case["pi"])
+ assert _project(events) == expected
diff --git a/tests/agent_core/ai/test_provider_adapters.py b/tests/agent_core/ai/test_provider_adapters.py
new file mode 100644
index 000000000..bec5e6326
--- /dev/null
+++ b/tests/agent_core/ai/test_provider_adapters.py
@@ -0,0 +1,5051 @@
+from __future__ import annotations
+
+import asyncio
+import base64
+import json
+from collections.abc import Mapping
+from dataclasses import replace
+from typing import Any
+
+import httpx
+import pytest
+
+import core.agent_core.ai._common as common_module
+import core.agent_core.ai.anthropic as anthropic_module
+import core.agent_core.ai.sse as sse_module
+import core.agent_core.ai.openai_responses as responses_module
+from core.agent_core.ai.anthropic import AnthropicAdapter, build_messages_payload
+from core.agent_core.ai._common import OutputBudgetExceeded, StreamAssembler, read_response_body
+from core.agent_core.ai.openai_chat import OpenAIChatAdapter, build_chat_payload
+from core.agent_core.ai.openai_responses import OpenAIResponsesAdapter, build_responses_payload
+from core.agent_core.ai.provider import (
+ BlockEnd,
+ Done,
+ MediaLoader,
+ ModelEndpoint,
+ ModelRequest,
+ ProviderError,
+ TextDelta,
+ ThinkingDelta,
+ ToolCallDelta,
+ ToolCallStart,
+)
+from core.agent_core.ai.registry import ADAPTERS, adapter_class
+from core.agent_core.cancel import CancelToken
+from core.agent_core.messages import (
+ AssistantMessage,
+ ImageBlock,
+ Origin,
+ TextBlock,
+ ThinkingBlock,
+ ToolCallBlock,
+ ToolResultMessage,
+ UserMessage,
+ Usage,
+)
+from core.agent_core.tools.base import ToolSpec
+
+
+def _request(
+ protocol: str,
+ *,
+ messages: tuple[Any, ...] = (),
+ supports_images: bool = False,
+ tools: tuple[ToolSpec, ...] = (),
+ model_id: str = "model-x",
+ base_url: str = "https://model.test/v1",
+ reasoning_effort: str | None = "high",
+) -> ModelRequest:
+ return ModelRequest(
+ endpoint=ModelEndpoint(
+ protocol,
+ base_url,
+ model_id,
+ "token",
+ provider={"anthropic": "anthropic", "openai_chat": "openai", "openai_responses": "openai"}[protocol],
+ ),
+ system="system",
+ messages=messages or (UserMessage((TextBlock(text="hello"),)),),
+ tools=tools,
+ max_tokens=128,
+ reasoning_effort=reasoning_effort,
+ supports_images=supports_images,
+ )
+
+
+def test_registry_exposes_only_v1_protocols() -> None:
+ assert set(ADAPTERS) == {"anthropic", "openai_chat", "openai_responses"}
+ with pytest.raises(ValueError, match="unsupported provider protocol: google"):
+ adapter_class("google")
+
+
+def test_each_known_wire_event_has_a_declarative_shape_row() -> None:
+ assert set(anthropic_module._KNOWN_STREAM_EVENTS) <= set(anthropic_module._ANTHROPIC_WIRE_SHAPES)
+ assert set(responses_module._KNOWN_RESPONSE_EVENTS) <= set(responses_module._RESPONSES_WIRE_SHAPES)
+
+
+async def _events(adapter: Any, request: ModelRequest, cancel: CancelToken | None = None) -> list[Any]:
+ return [event async for event in adapter.stream(request, cancel or CancelToken())]
+
+
[email protected]("protocol", ["anthropic", "openai_chat", "openai_responses"])
[email protected]("header", [None, "X-Portkey-Api-Key", "x-litellm-api-key"])
+async def test_configured_literal_credentials_cross_the_real_adapter_boundary(
+ protocol: str, header: str | None,
+) -> None:
+ # No recognizable key/scheme/shape in the exception: only configured literals
+ # can protect the diagnostic emitted by a rejecting transport.
+ secret = "opaque.private~value\n"
+ request = _request(protocol)
+ request = replace(request, endpoint=replace(
+ request.endpoint,
+ token=secret if header is None else "token",
+ request_headers={} if header is None else {header: secret},
+ ))
+
+ def handler(_: httpx.Request) -> httpx.Response:
+ raise httpx.LocalProtocolError(f"Illegal header value {secret.encode()!r}")
+
+ async with httpx.AsyncClient(transport=httpx.MockTransport(handler)) as client:
+ events = await _events(adapter_class(protocol)(client), request)
+ error = events[-1]
+ assert isinstance(error, ProviderError)
+ assert error.message == "Illegal header value b'[redacted]'"
+
+
[email protected]("stage", ["open", "closed", "terminal-backfill"])
+async def test_responses_reasoning_state_has_one_serialization_owner(
+ monkeypatch: pytest.MonkeyPatch, stage: str,
+) -> None:
+ item = {"type": "reasoning", "id": "rs", "encrypted_content": "ENC"}
+ initial = item if stage != "terminal-backfill" else {"type": "reasoning", "id": "rs"}
+ frames = [{"type": "response.output_item.added", "output_index": 0, "item": initial}]
+ if stage != "open":
+ frames.append({"type": "response.output_item.done", "output_index": 0, "item": initial})
+ if stage != "terminal-backfill":
+ frames.extend({
+ "type": "response.output_item.added" if stage == "open" else "response.output_item.done",
+ "output_index": 0,
+ # Closed items must ignore changes, not just identical snapshots.
+ "item": {"type": "reasoning", "id": "rs", **({"noise": str(i)} if stage == "closed" else {})},
+ } for i in range(20))
+ frames.append({"type": "response.completed", "response": {"status": "completed", "output": [item]}})
+ body = "".join(f"data: {json.dumps(frame)}\n\n" for frame in frames)
+ dumps = json.dumps
+ encoded_reasoning = []
+
+ def count_reasoning(value: Any, *args: Any, **kwargs: Any) -> str:
+ if isinstance(value, dict) and value.get("type") == "reasoning":
+ encoded_reasoning.append(value.copy())
+ return dumps(value, *args, **kwargs)
+
+ monkeypatch.setattr(json, "dumps", count_reasoning)
+ async with httpx.AsyncClient(transport=httpx.MockTransport(
+ lambda _: httpx.Response(200, text=body),
+ )) as client:
+ events = await _events(OpenAIResponsesAdapter(client), _request("openai_responses"))
+ assert isinstance(events[-1], Done)
+ block = events[-1].message.content[0]
+ assert isinstance(block, ThinkingBlock)
+ assert json.loads(block.signature)["encrypted_content"] == "ENC"
+ assert len(encoded_reasoning) == (2 if stage == "terminal-backfill" else 1)
+
+
+def test_signature_fragments_do_not_materialize_thinking_text(monkeypatch: pytest.MonkeyPatch) -> None:
+ assembler = StreamAssembler(origin=Origin("p", "anthropic", "m"), protocol="anthropic")
+ assembler.thinking_delta(0, "long thinking")
+
+ def unexpected(_: int) -> str:
+ pytest.fail("signature append copied unrelated thinking text")
+
+ with monkeypatch.context() as patch:
+ patch.setattr(assembler, "_thinking_value", unexpected)
+ for _ in range(20):
+ assembler.append_thinking_signature(0, "s")
+ message = assembler.finalize("stop")
+ assert message.content == (ThinkingBlock("long thinking", "s" * 20),)
+
+
+ ("event_name", "payload", "expected"),
+ [
+ ("response.done", {}, "malformed"),
+ ("response.done", {"type": None}, "malformed"),
+ ("response.output_text.delta", {"type": "response.completed"}, "response.completed"),
+ ("future", {"type": None}, None),
+ ("future", {"type": 5}, None),
+ ],
+)
+def test_dispatch_discriminator_contract(event_name: str, payload: dict, expected: str | None) -> None:
+ kwargs = dict(
+ known=responses_module._KNOWN_RESPONSE_EVENTS,
+ event_name=event_name,
+ aliases={"response.done": "response.completed"},
+ )
+ if expected == "malformed":
+ with pytest.raises(common_module.WireDispatchError):
+ common_module.dispatch_wire_event(payload, **kwargs)
+ else:
+ assert common_module.dispatch_wire_event(payload, **kwargs) == expected
+
+
+ "event: error\ndata: Overloaded\n\n",
+ 'event: error\ndata: {"error":{"type":"overloaded_error","message":"Overloaded"}}\n\n',
+ 'event: error\ndata: {"type":null,"error":{"type":"overloaded_error"}}\n\n',
+])
+async def test_anthropic_named_error_uses_pi_name_first_handling(body: str) -> None:
+ async with httpx.AsyncClient(transport=httpx.MockTransport(
+ lambda _: httpx.Response(200, text=body),
+ )) as client:
+ events = await _events(AnthropicAdapter(client), _request("anthropic"))
+ assert isinstance(events[-1], ProviderError)
+ assert events[-1].kind == "overloaded"
+ assert events[-1].retryable is True
+
+
+async def test_anthropic_ignores_named_ping_without_parsing_payload() -> None:
+ body = (
+ 'data: {"type":"content_block_start","index":0,"content_block":{"type":"text","text":"kept"}}\n\n'
+ 'event: ping\ndata: {}\n\n'
+ 'data: {"type":"message_delta","delta":{"stop_reason":"end_turn"}}\n\n'
+ 'data: {"type":"message_stop"}\n\n'
+ )
+ async with httpx.AsyncClient(transport=httpx.MockTransport(lambda _: httpx.Response(200, text=body))) as client:
+ events = await _events(AnthropicAdapter(client), _request("anthropic"))
+ assert isinstance(events[-1], Done)
+ assert events[-1].message.content == (TextBlock("kept"),)
+
+
[email protected]("protocol", ["anthropic", "openai_chat", "openai_responses"])
[email protected]("source", ["http", "stream"])
+async def test_long_error_diagnostics_are_redacted_once_without_recursive_rescanning(
+ monkeypatch: pytest.MonkeyPatch, protocol: str, source: str,
+) -> None:
+ diagnostic = "<html><style>" + "".join(f"a{i}:b;" for i in range(1200)) + "</style>Service Unavailable</html>"
+ calls = []
+ original = common_module.redact_provider_error
+
+ def record(error: ProviderError, **kwargs: Any) -> ProviderError:
+ calls.append(error)
+ return original(error, **kwargs)
+
+ monkeypatch.setattr(common_module, "redact_provider_error", record)
+ if source == "http":
+ status, body = 503, diagnostic
+ else:
+ status = 200
+ body = "data: " + json.dumps({
+ "type": "error", "error": {"type": "api_error", "message": diagnostic},
+ }) + "\n\n"
+ async with httpx.AsyncClient(transport=httpx.MockTransport(lambda _: httpx.Response(status, text=body))) as client:
+ events = await _events(adapter_class(protocol)(client), _request(protocol))
+ error = events[-1]
+ assert isinstance(error, ProviderError)
+ assert error.kind == "server"
+ assert error.retryable is True
+ assert error.status == (503 if source == "http" else None)
+ assert error.message == diagnostic
+ assert len(calls) == 1
+
+
[email protected]("protocol", ["anthropic", "openai_chat", "openai_responses"])
[email protected]("source", ["authorization_assignment", "relative_url", "bare_url_password"])
+async def test_adapter_diagnostics_redact_assignments_and_endpoint_credentials(
+ protocol: str, source: str,
+) -> None:
+ request = _request(protocol)
+ if source == "authorization_assignment":
+ secret = "dXNlcjpwYXNz"
+ request = replace(request, endpoint=replace(
+ request.endpoint, request_headers={"Authorization": "Basic " + secret},
+ ))
+ diagnostic = f"upstream proxy rejected {{Authorization=Basic {secret}}}"
+ elif source == "relative_url":
+ secret = "OPAQUEKEYVALUE9"
+ request = replace(request, endpoint=replace(request.endpoint, base_url=f"https://gw.example/v1?key={secret}"))
+ diagnostic = f"no route for /v1/chat/completions?key={secret}"
+ else:
+ secret = "opaquepassword9"
+ request = replace(request, endpoint=replace(request.endpoint, base_url=f"https://user:{secret}@gw.example/v1"))
+ diagnostic = f"connection failed for user:{secret}@gw.example"
+
+ def handler(_: httpx.Request) -> httpx.Response:
+ if source == "authorization_assignment":
+ raise httpx.LocalProtocolError(diagnostic)
+ return httpx.Response(404, text=diagnostic)
+
+ async with httpx.AsyncClient(transport=httpx.MockTransport(handler)) as client:
+ events = await _events(adapter_class(protocol)(client), request)
+ error = events[-1]
+ assert isinstance(error, ProviderError)
+ assert secret not in error.message
+ assert "[redacted]" in error.message
+
+
[email protected](("reason", "stop"), [("max_output_tokens", "length"), ("content_filter", "safety")])
+async def test_responses_interrupted_pending_identity_preserves_provider_stop(reason: str, stop: str) -> None:
+ frames = [
+ {"type": "response.output_item.added", "output_index": 0, "item": {"type": "message"}},
+ {"type": "response.output_text.delta", "output_index": 0, "delta": "kept"},
+ {"type": "response.output_item.added", "output_index": 1,
+ "item": {"type": "function_call", "id": "fc_1", "name": "read"}},
+ {"type": "response.function_call_arguments.delta", "output_index": 1, "delta": '{"path":'},
+ {"type": "response.incomplete", "response": {"incomplete_details": {"reason": reason}}},
+ ]
+ body = "".join(f"data: {json.dumps(frame)}\n\n" for frame in frames)
+ async with httpx.AsyncClient(transport=httpx.MockTransport(lambda _: httpx.Response(200, text=body))) as client:
+ events = await _events(OpenAIResponsesAdapter(client), _request("openai_responses"))
+ assert isinstance(events[-1], Done)
+ message = events[-1].message
+ assert message.stop_reason == stop
+ assert message.content[0] == TextBlock("kept")
+ assert message.tool_calls[0].id == next(event.id for event in events if isinstance(event, ToolCallStart))
+ assert message.tool_calls[0].name == "read"
+ assert message.tool_calls[0].arguments == {}
+
+
[email protected]("protocol", ["anthropic", "openai_chat", "openai_responses"])
+async def test_empty_wire_states_consume_a_realistic_structural_budget(monkeypatch: pytest.MonkeyPatch, protocol: str) -> None:
+ monkeypatch.setattr(common_module, "MAX_CUMULATIVE_OUTPUT_CHARS", 8192)
+ frames = []
+ for index in range(100):
+ if protocol == "anthropic":
+ frame = {"type": "content_block_start", "index": index, "content_block": {"type": "text"}}
+ elif protocol == "openai_chat":
+ frame = {"choices": [{"delta": {"tool_calls": [{"index": index, "function": {}}]}}]}
+ else:
+ frame = {"type": "response.output_item.added", "output_index": index, "item": {"type": "message"}}
+ frames.append(f"data: {json.dumps(frame)}\n\n")
+ body = "".join(frames)
+ async with httpx.AsyncClient(transport=httpx.MockTransport(lambda _: httpx.Response(200, text=body))) as client:
+ events = await _events(adapter_class(protocol)(client), _request(protocol))
+ assert isinstance(events[-1], ProviderError)
+ assert events[-1].kind == "invalid_request"
+ assert "output budget" in events[-1].message
+
+
+def test_tool_id_allocation_has_linear_lookup_cost() -> None:
+ class CountingSet(set):
+ lookups = 0
+
+ def __contains__(self, value: object) -> bool:
+ self.lookups += 1
+ return super().__contains__(value)
+
+ assembler = StreamAssembler(origin=Origin("p", "openai_chat", "m"), protocol="openai_chat")
+ allocated = CountingSet()
+ assembler._allocated_tool_ids = allocated
+ count = 100
+ for index in range(count):
+ assembler.tool_start(index, name="read", native_id=f"call_{count + index}")
+ for index in range(count, count * 2):
+ assembler.tool_start(index, name="read")
+ assert len(allocated) == count * 2
+ assert allocated.lookups <= count * 3
+
+
+def test_shared_tool_id_uniqueness_does_not_copy_owners() -> None:
+ class Owners(set):
+ def __sub__(self, _: object) -> set:
+ pytest.fail("tool uniqueness copied the complete owner set")
+
+ assembler = StreamAssembler(origin=Origin("p", "openai_responses", "m"), protocol="openai_responses")
+ assembler.tool_start(0, call_id="dup")
+ assembler._tool_id_owners["dup"] = Owners({0})
+ assembler.tool_start(1, name="read", native_id="dup")
+
+
[email protected]("indexed", [False, True])
[email protected]("item_id", ["fc_1", None])
+async def test_responses_late_call_id_is_stable_and_replayable(indexed: bool, item_id: str | None) -> None:
+ address = {"output_index": 0} if indexed else {}
+ identity = {"id": item_id} if item_id else {}
+ delta_identity = {"item_id": item_id} if item_id else {}
+ frames = [
+ {"type": "response.output_item.added", **address,
+ "item": {"type": "function_call", **identity, "name": "read"}},
+ {"type": "response.function_call_arguments.delta", **address,
+ **delta_identity, "delta": '{"path":"x"}'},
+ {"type": "response.output_item.done", **address,
+ "item": {"type": "function_call", **identity, "call_id": "call_1", "name": "read"}},
+ {"type": "response.completed", "response": {"status": "completed"}},
+ ]
+ body = "".join(f"data: {json.dumps(frame)}\n\n" for frame in frames)
+ async with httpx.AsyncClient(transport=httpx.MockTransport(lambda _: httpx.Response(200, text=body))) as client:
+ events = await _events(OpenAIResponsesAdapter(client), _request("openai_responses"))
+ assert isinstance(events[-1], Done)
+ message = events[-1].message
+ call = message.tool_calls[0]
+ start = next(event for event in events if isinstance(event, ToolCallStart))
+ assert start.id == call.id == "call_1"
+ assert call.native_id == item_id
+ assert call.arguments == {"path": "x"}
+ replay = build_responses_payload(_request("openai_responses", messages=(message,)), (message,))
+ assert replay["input"][0]["call_id"] == "call_1"
+
+
+def test_closed_tool_identity_does_not_retain_unused_history() -> None:
+ assembler = StreamAssembler(origin=Origin("p", "openai_responses", "m"), protocol="openai_responses")
+ assembler.tool_start(0, name="read", call_id="call", native_id="fc")
+ assembler.block_end(0)
+ for index in range(100):
+ assembler.tool_start(0, name="read", call_id="call" + "x" * index, native_id="fc")
+ assert assembler._allocated_tool_ids == {"call"}
+
+
[email protected]("conflicting", [True, False])
+ "chat-start", "chat-pending", "chat-id-only", "anthropic-start",
+ "responses-added", "responses-done", "responses-delta", "responses-arguments-done",
+])
+async def test_open_tool_slot_rejects_conflicting_native_identity(case: str, conflicting: bool) -> None:
+ # A second identity must not borrow the first call's name/arguments. Prior
+ # tests cover late/missing IDs, but not an index reused by a different call.
+ later_id = "second" if conflicting else "first"
+ if case.startswith("chat"):
+ protocol = "openai_chat"
+ first = {"name": "read", "arguments": "{}"} if case != "chat-pending" else {}
+ second = {"name": "read", "arguments": "{}" if case == "chat-pending" else " "}
+ if case == "chat-id-only":
+ second = None
+ frames = [
+ {"choices": [{"delta": {"tool_calls": [{"index": 0, "id": "first", "function": first}]}}]},
+ {"choices": [{"delta": {"tool_calls": [
+ {"index": 0, "id": later_id, **({"function": second} if second is not None else {})},
+ ]}, "finish_reason": "tool_calls"}]},
+ ]
+ elif case.startswith("anthropic"):
+ protocol = "anthropic"
+ frames = [
+ {"type": "content_block_start", "index": 0,
+ "content_block": {"type": "tool_use", "id": identity, "name": "read", "input": {}}}
+ for identity in ("first", later_id)
+ ] + [
+ {"type": "message_delta", "delta": {"stop_reason": "tool_use"}},
+ {"type": "message_stop"},
+ ]
+ else:
+ protocol = "openai_responses"
+ frames = [
+ {"type": "response.output_item.added", "output_index": 0, "item": {
+ "type": "function_call", "id": "first", "call_id": "call_first",
+ "name": "read", "arguments": "{}",
+ }},
+ ]
+ if case in {"responses-added", "responses-done"}:
+ frames.append({
+ "type": f"response.output_item.{case.removeprefix('responses-')}", "output_index": 0,
+ "item": {"type": "function_call", "id": later_id, "name": "read", "arguments": "{}"},
+ })
+ else:
+ # Already-known alias for another slot must not redirect index 0.
+ frames.append({"type": "response.output_item.added", "output_index": 1, "item": {
+ "type": "function_call", "id": later_id, "call_id": "call_second", "name": "read",
+ }})
+ is_delta = case == "responses-delta"
+ frames.append({
+ "type": f"response.function_call_arguments.{'delta' if is_delta else 'done'}",
+ "output_index": 0, "item_id": later_id, "delta" if is_delta else "arguments": " ",
+ })
+ for index in range(2 if case in {"responses-delta", "responses-arguments-done"} else 1):
+ frames.append({
+ "type": "response.output_item.done", "output_index": index,
+ "item": {"type": "function_call", "name": "read", "arguments": "{}"},
+ })
+ frames.append({"type": "response.completed", "response": {"status": "completed"}})
+ body = "".join(f"data: {json.dumps(frame)}\n\n" for frame in frames)
+ if protocol == "openai_chat":
+ body += "data: [DONE]\n\n"
+ async with httpx.AsyncClient(transport=httpx.MockTransport(lambda _: httpx.Response(200, text=body))) as client:
+ events = await _events(adapter_class(protocol)(client), _request(protocol))
+ if not conflicting:
+ assert isinstance(events[-1], Done)
+ assert events[-1].message.tool_calls[0].native_id == "first"
+ return
+ error = events[-1]
+ assert isinstance(error, ProviderError)
+ assert error.kind == "invalid_request"
+ assert "conflicting native ID" in error.message
+ assert error.retryable is False
+ assert len([event for event in events if isinstance(event, (Done, ProviderError))]) == 1
+ if error.partial and error.partial.tool_calls:
+ assert error.partial.tool_calls[0].native_id == "first"
+
+
+async def test_responses_explicit_indexes_override_shared_native_aliases() -> None:
+ # Duplicate provider IDs across distinct slots may be normalized; they must
+ # not cause indexed argument frames to merge into the alias's latest owner.
+ frames = [
+ {"type": "response.output_item.added", "output_index": index, "item": {
+ "type": "function_call", "id": "shared", "call_id": f"call_{index}", "name": "read",
+ }}
+ for index in range(2)
+ ]
+ for index in range(2):
+ frames.extend([
+ {"type": "response.function_call_arguments.delta", "output_index": index,
+ "item_id": "shared", "delta": json.dumps({"path": str(index)})},
+ {"type": "response.output_item.done", "output_index": index,
+ "item": {"type": "function_call", "id": "shared"}},
+ ])
+ frames.append({"type": "response.completed", "response": {"status": "completed"}})
+ body = "".join(f"data: {json.dumps(frame)}\n\n" for frame in frames)
+ async with httpx.AsyncClient(transport=httpx.MockTransport(lambda _: httpx.Response(200, text=body))) as client:
+ events = await _events(OpenAIResponsesAdapter(client), _request("openai_responses"))
+ assert isinstance(events[-1], Done)
+ assert [call.arguments for call in events[-1].message.tool_calls] == [{"path": "0"}, {"path": "1"}]
+ assert [call.id for call in events[-1].message.tool_calls] == ["call_0", "call_1"]
+
+
[email protected]("identity_at", ["added", "done"])
+async def test_responses_parallel_calls_have_unique_explicit_canonical_ids(identity_at: str) -> None:
+ frames = []
+ for index in range(2):
+ item = {"type": "function_call", "id": f"fc_{index}", "name": "read"}
+ if identity_at == "added":
+ item["call_id"] = "call_1"
+ frames.append({"type": "response.output_item.added", "output_index": index, "item": item})
+ for index in range(2):
+ frames.extend([
+ {"type": "response.function_call_arguments.delta", "output_index": index,
+ "item_id": f"fc_{index}", "delta": json.dumps({"path": str(index)})},
+ {"type": "response.output_item.done", "output_index": index, "item": {
+ "type": "function_call", "id": f"fc_{index}", "call_id": "call_1", "name": "read",
+ }},
+ ])
+ frames.append({"type": "response.completed", "response": {"status": "completed"}})
+ body = "".join(f"data: {json.dumps(frame)}\n\n" for frame in frames)
+ async with httpx.AsyncClient(transport=httpx.MockTransport(lambda _: httpx.Response(200, text=body))) as client:
+ events = await _events(OpenAIResponsesAdapter(client), _request("openai_responses"))
+ starts = [event for event in events if isinstance(event, ToolCallStart)]
+ assert len(starts) == 2
+ assert len({event.id for event in starts}) == 2
+ assert isinstance(events[-1], Done)
+ calls = events[-1].message.tool_calls
+ assert [call.id for call in calls] == [event.id for event in starts]
+ assert calls[0].id == "call_1"
+ assert [call.arguments for call in calls] == [{"path": "0"}, {"path": "1"}]
+ assert [call.native_id for call in calls] == ["fc_0", "fc_1"]
+
+
+async def test_anthropic_streams_thinking_tool_arguments_and_usage() -> None:
+ body = (
+ 'data: {"type":"message_start","message":{"usage":{"input_tokens":5}}}\r\n\r\n'
+ 'data: {"type":"content_block_start","index":0,"content_block":{"type":"thinking"}}\r\n\r\n'
+ 'data: {"type":"content_block_delta","index":0,"delta":{"type":"thinking_delta","thinking":"reason"}}\r\n\r\n'
+ 'data: {"type":"content_block_delta","index":0,"delta":{"type":"signature_delta","signature":"sig"}}\r\n\r\n'
+ 'data: {"type":"content_block_start","index":1,"content_block":{"type":"tool_use","id":"toolu_1","name":"read"}}\r\n\r\n'
+ 'data: {"type":"content_block_delta","index":1,"delta":{"type":"input_json_delta","partial_json":"{\\"path\\":\\"x\\"}"}}\r\n\r\n'
+ 'data: {"type":"content_block_stop","index":0}\r\n\r\n'
+ 'data: {"type":"content_block_stop","index":1}\r\n\r\n'
+ 'data: {"type":"message_delta","delta":{"stop_reason":"tool_use"},"usage":{"output_tokens":3}}\r\n\r\n'
+ 'data: {"type":"message_stop"}\r\n\r\n'
+ )
+
+ def handler(_: httpx.Request) -> httpx.Response:
+ return httpx.Response(200, headers={"content-type": "text/event-stream"}, text=body)
+
+ async with httpx.AsyncClient(transport=httpx.MockTransport(handler)) as client:
+ events = await _events(AnthropicAdapter(client), _request("anthropic"))
+
+ final = events[-1]
+ assert isinstance(final, Done)
+ assert final.message.stop_reason == "tool_use"
+ assert final.message.usage == Usage(input_tokens=5, output_tokens=3)
+ assert final.message.content == (
+ ThinkingBlock("reason", "sig"),
+ ToolCallBlock("toolu_1", "read", {"path": "x"}, native_id="toolu_1"),
+ )
+ assert [event.index for event in events if isinstance(event, BlockEnd)] == [0, 1]
+
+
+ ("adapter_type", "protocol", "body", "expected_path"),
+ [
+ (
+ AnthropicAdapter,
+ "anthropic",
+ 'data: {"type":"message_delta","delta":{"stop_reason":"end_turn"}}\n\n'
+ 'data: {"type":"message_stop"}\n\n',
+ "/v1/messages",
+ ),
+ (
+ OpenAIChatAdapter,
+ "openai_chat",
+ 'data: {"choices":[{"delta":{},"finish_reason":"stop"}]}\n\n'
+ "data: [DONE]\n\n",
+ "/v1/chat/completions",
+ ),
+ (
+ OpenAIResponsesAdapter,
+ "openai_responses",
+ 'data: {"type":"response.completed","response":{"status":"completed"}}\n\n',
+ "/v1/responses",
+ ),
+ ],
+)
+async def test_adapters_join_protocol_path_before_existing_query(
+ adapter_type: Any,
+ protocol: str,
+ body: str,
+ expected_path: str,
+) -> None:
+ seen: list[httpx.URL] = []
+
+ def handler(request: httpx.Request) -> httpx.Response:
+ seen.append(request.url)
+ return httpx.Response(200, headers={"content-type": "text/event-stream"}, text=body)
+
+ async with httpx.AsyncClient(transport=httpx.MockTransport(handler)) as client:
+ events = await _events(
+ adapter_type(client),
+ _request(protocol, base_url="https://model.test/v1?tenant=blue"),
+ )
+
+ assert isinstance(events[-1], Done)
+ assert seen[0].path == expected_path
+ assert seen[0].query == b"tenant=blue"
+
+
+ ("adapter_type", "protocol", "body"),
+ [
+ (
+ OpenAIChatAdapter,
+ "openai_chat",
+ (
+ 'data: {"choices":[{"delta":{"tool_calls":[{"index":0,"id":"call_1",'
+ '"function":{"name":"read","arguments":"{\\"path\\":\\"x"}}]}}]}\n\n'
+ 'data: {"choices":[{"delta":{},"finish_reason":"length"}]}\n\n'
+ "data: [DONE]\n\n"
+ ),
+ ),
+ (
+ AnthropicAdapter,
+ "anthropic",
+ (
+ 'data: {"type":"content_block_start","index":0,'
+ '"content_block":{"type":"tool_use","id":"toolu_1","name":"read"}}\n\n'
+ 'data: {"type":"content_block_delta","index":0,'
+ '"delta":{"type":"input_json_delta","partial_json":"{\\"path\\":\\"x"}}\n\n'
+ 'data: {"type":"message_delta","delta":{"stop_reason":"max_tokens"}}\n\n'
+ 'data: {"type":"message_stop"}\n\n'
+ ),
+ ),
+ (
+ OpenAIResponsesAdapter,
+ "openai_responses",
+ (
+ 'data: {"type":"response.output_item.added","output_index":0,'
+ '"item":{"type":"function_call","id":"fc_1","call_id":"call_1","name":"read"}}\n\n'
+ 'data: {"type":"response.function_call_arguments.delta","output_index":0,'
+ '"delta":"{\\"path\\":\\"x"}\n\n'
+ 'data: {"type":"response.incomplete","response":{"status":"incomplete",'
+ '"incomplete_details":{"reason":"max_output_tokens"}}}\n\n'
+ ),
+ ),
+ ],
+)
+async def test_non_tool_stop_preserves_truncated_tool_calls_for_settlement(
+ adapter_type: Any,
+ protocol: str,
+ body: str,
+) -> None:
+ def handler(_: httpx.Request) -> httpx.Response:
+ return httpx.Response(200, headers={"content-type": "text/event-stream"}, text=body)
+
+ async with httpx.AsyncClient(transport=httpx.MockTransport(handler)) as client:
+ events = await _events(adapter_type(client), _request(protocol))
+
+ terminal = events[-1]
+ assert isinstance(terminal, Done)
+ assert terminal.message.stop_reason == "length"
+ assert [call.arguments for call in terminal.message.tool_calls] == [{}]
+
+
+async def test_anthropic_empty_initial_tool_input_does_not_prefix_streamed_json() -> None:
+ body = (
+ 'data: {"type":"content_block_start","index":0,"content_block":{"type":"tool_use","id":"toolu_1","name":"read","input":{}}}\n\n'
+ 'data: {"type":"content_block_delta","index":0,"delta":{"type":"input_json_delta","partial_json":"{\\"path\\":\\"x\\"}"}}\n\n'
+ 'data: {"type":"message_delta","delta":{"stop_reason":"tool_use"}}\n\n'
+ 'data: {"type":"message_stop"}\n\n'
+ )
+
+ def handler(_: httpx.Request) -> httpx.Response:
+ return httpx.Response(200, headers={"content-type": "text/event-stream"}, text=body)
+
+ async with httpx.AsyncClient(transport=httpx.MockTransport(handler)) as client:
+ events = await _events(AnthropicAdapter(client), _request("anthropic"))
+
+ final = events[-1]
+ assert isinstance(final, Done)
+ assert final.message.tool_calls[0].arguments == {"path": "x"}
+
+
+async def test_anthropic_nonempty_initial_tool_input_is_preserved_without_deltas() -> None:
+ body = (
+ 'data: {"type":"content_block_start","index":0,"content_block":{"type":"tool_use","id":"toolu_1","name":"read","input":{"path":"x"}}}\n\n'
+ 'data: {"type":"message_delta","delta":{"stop_reason":"tool_use"}}\n\n'
+ 'data: {"type":"message_stop"}\n\n'
+ )
+
+ def handler(_: httpx.Request) -> httpx.Response:
+ return httpx.Response(200, headers={"content-type": "text/event-stream"}, text=body)
+
+ async with httpx.AsyncClient(transport=httpx.MockTransport(handler)) as client:
+ events = await _events(AnthropicAdapter(client), _request("anthropic"))
+
+ final = events[-1]
+ assert isinstance(final, Done)
+ assert final.message.tool_calls[0].arguments == {"path": "x"}
+
+
+async def test_anthropic_replays_redacted_thinking_payload_verbatim() -> None:
+ body = (
+ 'data: {"type":"content_block_start","index":0,"content_block":{"type":"redacted_thinking","data":"opaque-redacted"}}\n\n'
+ 'data: {"type":"message_delta","delta":{"stop_reason":"end_turn"}}\n\n'
+ 'data: {"type":"message_stop"}\n\n'
+ )
+ captured: dict[str, Any] = {}
+
+ def handler(request: httpx.Request) -> httpx.Response:
+ captured.update(json.loads(request.content))
+ return httpx.Response(200, headers={"content-type": "text/event-stream"}, text=body)
+
+ history = (
+ AssistantMessage(
+ content=(ThinkingBlock("", "opaque-redacted", redacted=True),),
+ origin=Origin("anthropic", "anthropic", "model-x"),
+ stop_reason="stop",
+ ),
+ UserMessage((TextBlock(text="continue"),)),
+ )
+ async with httpx.AsyncClient(transport=httpx.MockTransport(handler)) as client:
+ events = await _events(
+ AnthropicAdapter(client),
+ _request("anthropic", messages=history),
+ )
+
+ assistant = captured["messages"][0]
+ assert assistant["content"] == [{"type": "redacted_thinking", "data": "opaque-redacted"}]
+ final = events[-1]
+ assert isinstance(final, Done)
+ assert final.message.content == (ThinkingBlock("", "opaque-redacted", redacted=True),)
+
+
+async def test_anthropic_ignores_unknown_content_block_types_like_pi() -> None:
+ body = (
+ 'data: {"type":"content_block_start","index":0,"content_block":{"type":"future_block"}}\n\n'
+ 'data: {"type":"message_delta","delta":{"stop_reason":"end_turn"}}\n\n'
+ 'data: {"type":"message_stop"}\n\n'
+ )
+
+ def handler(_: httpx.Request) -> httpx.Response:
+ return httpx.Response(200, headers={"content-type": "text/event-stream"}, text=body)
+
+ async with httpx.AsyncClient(transport=httpx.MockTransport(handler)) as client:
+ events = await _events(AnthropicAdapter(client), _request("anthropic"))
+
+ assert isinstance(events[-1], Done)
+ assert events[-1].message.content == ()
+
+
+async def test_anthropic_mid_output_fallback_is_terminal_like_pi() -> None:
+ body = (
+ 'data: {"type":"content_block_start","index":0,"content_block":{"type":"text"}}\n\n'
+ 'data: {"type":"content_block_delta","index":0,"delta":{"type":"text_delta","text":"before"}}\n\n'
+ 'data: {"type":"content_block_start","index":1,"content_block":{"type":"fallback"}}\n\n'
+ )
+
+ def handler(_: httpx.Request) -> httpx.Response:
+ return httpx.Response(200, headers={"content-type": "text/event-stream"}, text=body)
+
+ async with httpx.AsyncClient(transport=httpx.MockTransport(handler)) as client:
+ events = await _events(AnthropicAdapter(client), _request("anthropic"))
+
+ assert isinstance(events[-1], ProviderError)
+ assert events[-1].kind == "unknown"
+ assert events[-1].retryable is False
+ assert events[-1].partial is not None
+
+
+async def test_anthropic_ignores_unknown_top_level_events_like_pi() -> None:
+ body = (
+ 'data: {"type":"future_event","payload":{"new":"field"}}\n\n'
+ 'data: {"type":"message_delta","delta":{"stop_reason":"end_turn"}}\n\n'
+ 'data: {"type":"message_stop"}\n\n'
+ )
+
+ def handler(_: httpx.Request) -> httpx.Response:
+ return httpx.Response(200, headers={"content-type": "text/event-stream"}, text=body)
+
+ async with httpx.AsyncClient(transport=httpx.MockTransport(handler)) as client:
+ events = await _events(AnthropicAdapter(client), _request("anthropic"))
+
+ assert isinstance(events[-1], Done)
+
+
+async def test_anthropic_ignores_unknown_sse_event_before_parsing_like_pi() -> None:
+ body = (
+ 'event: future_event\n'
+ 'data: not-json\n\n'
+ 'event: message_delta\n'
+ 'data: {"type":"message_delta","delta":{"stop_reason":"end_turn"}}\n\n'
+ 'event: message_stop\n'
+ 'data: {"type":"message_stop"}\n\n'
+ )
+
+ def handler(_: httpx.Request) -> httpx.Response:
+ return httpx.Response(200, headers={"content-type": "text/event-stream"}, text=body)
+
+ async with httpx.AsyncClient(transport=httpx.MockTransport(handler)) as client:
+ events = await _events(AnthropicAdapter(client), _request("anthropic"))
+
+ assert isinstance(events[-1], Done)
+
+
+async def test_anthropic_named_error_frame_uses_nested_error_code() -> None:
+ body = (
+ 'event: error\n'
+ 'data: {"type":"error","error":{"type":"api_error","message":"busy"}}\n\n'
+ )
+
+ def handler(_: httpx.Request) -> httpx.Response:
+ return httpx.Response(200, headers={"content-type": "text/event-stream"}, text=body)
+
+ async with httpx.AsyncClient(transport=httpx.MockTransport(handler)) as client:
+ events = await _events(AnthropicAdapter(client), _request("anthropic"))
+
+ error = events[-1]
+ assert isinstance(error, ProviderError)
+ assert error.kind == "server"
+ assert error.retryable is True
+
+
+async def test_anthropic_content_block_start_preserves_initial_content() -> None:
+ body = (
+ 'event: content_block_start\n'
+ 'data: {"type":"content_block_start","index":0,"content_block":{"type":"text","text":"initial"}}\n\n'
+ 'event: content_block_start\n'
+ 'data: {"type":"content_block_start","index":1,"content_block":{"type":"thinking","thinking":"plan","signature":"sig"}}\n\n'
+ 'event: message_delta\n'
+ 'data: {"type":"message_delta","delta":{"stop_reason":"end_turn"}}\n\n'
+ 'event: message_stop\n'
+ 'data: {"type":"message_stop"}\n\n'
+ )
+
+ def handler(_: httpx.Request) -> httpx.Response:
+ return httpx.Response(200, headers={"content-type": "text/event-stream"}, text=body)
+
+ async with httpx.AsyncClient(transport=httpx.MockTransport(handler)) as client:
+ events = await _events(AnthropicAdapter(client), _request("anthropic"))
+
+ assert isinstance(events[-1], Done)
+ assert events[-1].message.content == (TextBlock("initial"), ThinkingBlock("plan", "sig"))
+
+
+async def test_anthropic_malformed_delta_is_terminal_invalid_request() -> None:
+ body = (
+ 'data: {"type":"content_block_start","index":0,"content_block":{"type":"text"}}\n\n'
+ 'data: {"type":"content_block_delta","index":0,"delta":null}\n\n'
+ 'data: {"type":"message_stop"}\n\n'
+ )
+
+ def handler(_: httpx.Request) -> httpx.Response:
+ return httpx.Response(200, headers={"content-type": "text/event-stream"}, text=body)
+
+ async with httpx.AsyncClient(transport=httpx.MockTransport(handler)) as client:
+ events = await _events(AnthropicAdapter(client), _request("anthropic"))
+
+ error = events[-1]
+ assert isinstance(error, ProviderError)
+ assert error.kind == "invalid_request"
+
+
+ ("block", "delta"),
+ [
+ ("text", {"type": "text_delta", "text": 7}),
+ ("thinking", {"type": "thinking_delta", "thinking": []}),
+ ("thinking", {"type": "signature_delta", "signature": {}}),
+ ("tool", {"type": "input_json_delta", "partial_json": 7}),
+ ],
+)
+async def test_anthropic_known_delta_fields_reject_wrong_types(
+ block: str,
+ delta: dict[str, Any],
+) -> None:
+ content_block = {
+ "text": {"type": "text"},
+ "thinking": {"type": "thinking"},
+ "tool": {"type": "tool_use", "id": "toolu_1", "name": "read"},
+ }[block]
+ body = (
+ f'data: {json.dumps({"type": "content_block_start", "index": 0, "content_block": content_block})}\n\n'
+ f'data: {json.dumps({"type": "content_block_delta", "index": 0, "delta": delta})}\n\n'
+ )
+
+ def handler(_: httpx.Request) -> httpx.Response:
+ return httpx.Response(200, headers={"content-type": "text/event-stream"}, text=body)
+
+ async with httpx.AsyncClient(transport=httpx.MockTransport(handler)) as client:
+ events = await _events(AnthropicAdapter(client), _request("anthropic"))
+
+ error = events[-1]
+ assert isinstance(error, ProviderError)
+ assert error.kind == "invalid_request"
+
+
+async def test_anthropic_pre_output_fallback_is_ignored_like_pi() -> None:
+ body = (
+ 'data: {"type":"content_block_start","index":0,"content_block":{"type":"fallback"}}\n\n'
+ 'data: {"type":"message_delta","delta":{"stop_reason":"end_turn"}}\n\n'
+ 'data: {"type":"message_stop"}\n\n'
+ )
+
+ def handler(_: httpx.Request) -> httpx.Response:
+ return httpx.Response(200, headers={"content-type": "text/event-stream"}, text=body)
+
+ async with httpx.AsyncClient(transport=httpx.MockTransport(handler)) as client:
+ events = await _events(AnthropicAdapter(client), _request("anthropic"))
+
+ assert isinstance(events[-1], Done)
+ assert events[-1].message.content == ()
+
+
+async def test_anthropic_wrong_kind_delta_is_ignored_like_pi() -> None:
+ body = (
+ 'data: {"type":"content_block_start","index":0,"content_block":{"type":"text"}}\n\n'
+ 'data: {"type":"content_block_delta","index":0,"delta":{"type":"thinking_delta","thinking":"ignored"}}\n\n'
+ 'data: {"type":"message_delta","delta":{"stop_reason":"end_turn"}}\n\n'
+ 'data: {"type":"message_stop"}\n\n'
+ )
+
+ def handler(_: httpx.Request) -> httpx.Response:
+ return httpx.Response(200, headers={"content-type": "text/event-stream"}, text=body)
+
+ async with httpx.AsyncClient(transport=httpx.MockTransport(handler)) as client:
+ events = await _events(AnthropicAdapter(client), _request("anthropic"))
+
+ assert isinstance(events[-1], Done)
+ assert events[-1].message.content == (TextBlock(""),)
+
+
+async def test_anthropic_malformed_message_delta_usage_is_terminal_invalid_request() -> None:
+ body = (
+ 'data: {"type":"message_delta","delta":{"stop_reason":"end_turn"},"usage":[]}\n\n'
+ 'data: {"type":"message_stop"}\n\n'
+ )
+
+ def handler(_: httpx.Request) -> httpx.Response:
+ return httpx.Response(200, headers={"content-type": "text/event-stream"}, text=body)
+
+ async with httpx.AsyncClient(transport=httpx.MockTransport(handler)) as client:
+ events = await _events(AnthropicAdapter(client), _request("anthropic"))
+
+ error = events[-1]
+ assert isinstance(error, ProviderError)
+ assert error.kind == "invalid_request"
+
+
+async def test_anthropic_ignores_unknown_delta_variants_like_pi() -> None:
+ body = (
+ 'data: {"type":"content_block_start","index":0,"content_block":{"type":"text"}}\n\n'
+ 'data: {"type":"content_block_delta","index":0,"delta":{"type":"future_delta","value":"ignored"}}\n\n'
+ 'data: {"type":"message_delta","delta":{"stop_reason":"end_turn"}}\n\n'
+ 'data: {"type":"message_stop"}\n\n'
+ )
+
+ def handler(_: httpx.Request) -> httpx.Response:
+ return httpx.Response(200, headers={"content-type": "text/event-stream"}, text=body)
+
+ async with httpx.AsyncClient(transport=httpx.MockTransport(handler)) as client:
+ events = await _events(AnthropicAdapter(client), _request("anthropic"))
+
+ assert isinstance(events[-1], Done)
+ assert events[-1].message.content == (TextBlock(""),)
+
+
+async def test_anthropic_empty_block_end_does_not_count_as_streamed_output() -> None:
+ body = (
+ 'data: {"type":"content_block_start","index":0,"content_block":{"type":"text"}}\n\n'
+ 'data: {"type":"content_block_stop","index":0}\n\n'
+ 'data: {"type":"error","error":{"type":"overloaded_error","message":"busy"}}\n\n'
+ )
+
+ def handler(_: httpx.Request) -> httpx.Response:
+ return httpx.Response(200, headers={"content-type": "text/event-stream"}, text=body)
+
+ async with httpx.AsyncClient(transport=httpx.MockTransport(handler)) as client:
+ events = await _events(AnthropicAdapter(client), _request("anthropic"))
+
+ assert not any(isinstance(event, BlockEnd) for event in events)
+ error = events[-1]
+ assert isinstance(error, ProviderError)
+ assert error.kind == "overloaded"
+ assert error.retryable is True
+
+
+async def test_responses_sets_client_side_state_rules_and_keeps_reasoning_item() -> None:
+ body = (
+ 'data: {"type":"response.output_item.added","output_index":0,"item":{"type":"reasoning","id":"rs_1"}}\n\n'
+ 'data: {"type":"response.reasoning_text.delta","output_index":0,"delta":"plan"}\n\n'
+ 'data: {"type":"response.output_item.done","output_index":0,"item":{"type":"reasoning","id":"rs_1","encrypted_content":"enc"}}\n\n'
+ 'data: {"type":"response.output_item.added","output_index":1,"item":{"type":"message","id":"msg_1"}}\n\n'
+ 'data: {"type":"response.output_text.delta","output_index":1,"delta":"done"}\n\n'
+ 'data: {"type":"response.completed","response":{"status":"completed","output":[{"type":"reasoning","id":"rs_1","encrypted_content":"enc"},{"type":"message","id":"msg_1","content":[{"type":"output_text","text":"done"}]}],"usage":{"input_tokens":2,"output_tokens":4,"output_tokens_details":{"reasoning_tokens":1}}}}\n\n'
+ )
+ captured: dict[str, Any] = {}
+
+ def handler(request: httpx.Request) -> httpx.Response:
+ captured.update(json.loads(request.content))
+ return httpx.Response(200, headers={"content-type": "text/event-stream"}, text=body)
+
+ async with httpx.AsyncClient(transport=httpx.MockTransport(handler)) as client:
+ events = await _events(OpenAIResponsesAdapter(client), _request("openai_responses"))
+
+ assert captured["store"] is False
+ assert "previous_response_id" not in captured
+ assert captured["include"] == ["reasoning.encrypted_content"]
+ final = events[-1]
+ assert isinstance(final, Done)
+ assert final.message.content[0] == ThinkingBlock(
+ "plan",
+ json.dumps(
+ {"type": "reasoning", "id": "rs_1", "encrypted_content": "enc"},
+ separators=(",", ":"),
+ ),
+ )
+ assert final.message.content[1] == TextBlock("done")
+ assert final.message.usage == Usage(input_tokens=2, output_tokens=4, reasoning_tokens=1)
+
+
+async def test_responses_summary_done_adds_separator() -> None:
+ body = (
+ 'data: {"type":"response.output_item.added","output_index":0,"item":{"type":"reasoning","id":"rs_1"}}\n\n'
+ 'data: {"type":"response.reasoning_summary_part.added","output_index":0}\n\n'
+ 'data: {"type":"response.reasoning_summary_text.delta","output_index":0,"delta":"plan"}\n\n'
+ 'data: {"type":"response.reasoning_summary_part.done","output_index":0}\n\n'
+ 'data: {"type":"response.completed","response":{"status":"completed"}}\n\n'
+ )
+
+ def handler(_: httpx.Request) -> httpx.Response:
+ return httpx.Response(200, headers={"content-type": "text/event-stream"}, text=body)
+
+ async with httpx.AsyncClient(transport=httpx.MockTransport(handler)) as client:
+ events = await _events(OpenAIResponsesAdapter(client), _request("openai_responses"))
+
+ assert isinstance(events[-1], Done)
+ assert events[-1].message.content == (ThinkingBlock("plan\n\n", None),)
+
+
+async def test_responses_summary_done_rejects_non_integer_output_index() -> None:
+ body = (
+ 'data: {"type":"response.output_item.added","output_index":0,"item":{"type":"reasoning","id":"rs_1"}}\n\n'
+ 'data: {"type":"response.reasoning_summary_part.done","output_index":"0"}\n\n'
+ )
+
+ def handler(_: httpx.Request) -> httpx.Response:
+ return httpx.Response(200, headers={"content-type": "text/event-stream"}, text=body)
+
+ async with httpx.AsyncClient(transport=httpx.MockTransport(handler)) as client:
+ events = await _events(OpenAIResponsesAdapter(client), _request("openai_responses"))
+
+ error = events[-1]
+ assert isinstance(error, ProviderError)
+ assert error.kind == "invalid_request"
+
+
+async def test_responses_known_lifecycle_events_are_accounted_for() -> None:
+ body = (
+ 'data: {"type":"response.created","response":{"id":"r","status":"in_progress"}}\n\n'
+ 'data: {"type":"response.in_progress","response":{"status":"in_progress"}}\n\n'
+ 'data: {"type":"response.queued","response":{"status":"queued"}}\n\n'
+ 'data: {"type":"response.output_item.added","output_index":0,"item":{"type":"reasoning","id":"rs_1"}}\n\n'
+ 'data: {"type":"response.reasoning_summary_part.added","output_index":0}\n\n'
+ 'data: {"type":"response.reasoning_summary_text.delta","output_index":0,"delta":"plan"}\n\n'
+ 'data: {"type":"response.reasoning_summary_part.done","output_index":0}\n\n'
+ 'data: {"type":"response.content_part.added","output_index":0}\n\n'
+ 'data: {"type":"response.content_part.done","output_index":0}\n\n'
+ 'data: {"type":"response.output_text.done","output_index":0}\n\n'
+ 'data: {"type":"response.reasoning_text.done","output_index":0}\n\n'
+ 'data: {"type":"response.reasoning_summary_text.done","output_index":0}\n\n'
+ 'data: {"type":"response.completed","response":{"status":"completed"}}\n\n'
+ )
+
+ def handler(_: httpx.Request) -> httpx.Response:
+ return httpx.Response(200, headers={"content-type": "text/event-stream"}, text=body)
+
+ async with httpx.AsyncClient(transport=httpx.MockTransport(handler)) as client:
+ events = await _events(OpenAIResponsesAdapter(client), _request("openai_responses"))
+
+ assert isinstance(events[-1], Done)
+ assert events[-1].message.content == (ThinkingBlock("plan\n\n"),)
+
+
+async def test_responses_custom_tool_events_are_ignored_without_custom_tool_blocks() -> None:
+ body = (
+ 'data: {"type":"response.output_item.added","output_index":0,"item":{"type":"custom_tool_call","id":"ct_1","call_id":"call_1","name":"lookup"}}\n\n'
+ 'data: {"type":"response.custom_tool_call_input.delta","output_index":0,"delta":"{\\"query\\":\\"x\\"}"}\n\n'
+ 'data: {"type":"response.custom_tool_call_input.done","output_index":0,"input":"{\\"query\\":\\"x\\"}"}\n\n'
+ 'data: {"type":"response.output_item.done","output_index":0,"item":{"type":"custom_tool_call","id":"ct_1","call_id":"call_1","name":"lookup","input":"{\\"query\\":\\"x\\"}"}}\n\n'
+ 'data: {"type":"response.completed","response":{"status":"completed"}}\n\n'
+ )
+
+ def handler(_: httpx.Request) -> httpx.Response:
+ return httpx.Response(200, headers={"content-type": "text/event-stream"}, text=body)
+
+ async with httpx.AsyncClient(transport=httpx.MockTransport(handler)) as client:
+ events = await _events(OpenAIResponsesAdapter(client), _request("openai_responses"))
+
+ assert isinstance(events[-1], Done)
+ assert events[-1].message.content == ()
+
+
+async def test_responses_top_level_error_frame_is_classified() -> None:
+ body = 'data: {"type":"error","error":{"code":"server_error","message":"failed"}}\n\n'
+
+ def handler(_: httpx.Request) -> httpx.Response:
+ return httpx.Response(200, headers={"content-type": "text/event-stream"}, text=body)
+
+ async with httpx.AsyncClient(transport=httpx.MockTransport(handler)) as client:
+ events = await _events(OpenAIResponsesAdapter(client), _request("openai_responses"))
+
+ assert isinstance(events[-1], ProviderError)
+ assert events[-1].kind == "server"
+ assert events[-1].retryable is True
+
+
+async def test_chat_accepts_integer_error_code_from_openai_compatible_servers() -> None:
+ body = (
+ 'data: {"error":{"type":"InternalServerError","code":500,'
+ '"message":"Internal server error"}}\n\n'
+ )
+
+ def handler(_: httpx.Request) -> httpx.Response:
+ return httpx.Response(200, headers={"content-type": "text/event-stream"}, text=body)
+
+ async with httpx.AsyncClient(transport=httpx.MockTransport(handler)) as client:
+ events = await _events(OpenAIChatAdapter(client), _request("openai_chat"))
+
+ error = events[-1]
+ assert isinstance(error, ProviderError)
+ assert error.kind == "server"
+ assert error.retryable is True
+
+
+ ("body", "expected_kind"),
+ [
+ (
+ 'data: {"type":"error","error":{"type":"context_length_exceeded"}}\n\n',
+ "overflow",
+ ),
+ (
+ 'data: {"type":"response.failed","response":{"status":"failed","error":{"type":"context_length_exceeded"}}}\n\n',
+ "overflow",
+ ),
+ (
+ 'data: {"type":"response.completed","response":{"status":"failed","error":{"type":"context_length_exceeded"}}}\n\n',
+ "overflow",
+ ),
+ ],
+)
+async def test_responses_error_classification_uses_the_complete_envelope(
+ body: str,
+ expected_kind: str,
+) -> None:
+ def handler(_: httpx.Request) -> httpx.Response:
+ return httpx.Response(200, headers={"content-type": "text/event-stream"}, text=body)
+
+ async with httpx.AsyncClient(transport=httpx.MockTransport(handler)) as client:
+ events = await _events(OpenAIResponsesAdapter(client), _request("openai_responses"))
+
+ error = events[-1]
+ assert isinstance(error, ProviderError)
+ assert error.kind == expected_kind
+
+
+async def test_responses_error_message_excludes_response_request_metadata() -> None:
+ body = (
+ 'data: {"type":"response.failed","response":{"status":"failed",'
+ '"error":{"code":"server_error","message":"upstream failed"},'
+ '"instructions":"secret system prompt","tools":[{"name":"secret"}]}}\n\n'
+ )
+
+ def handler(_: httpx.Request) -> httpx.Response:
+ return httpx.Response(200, headers={"content-type": "text/event-stream"}, text=body)
+
+ async with httpx.AsyncClient(transport=httpx.MockTransport(handler)) as client:
+ events = await _events(OpenAIResponsesAdapter(client), _request("openai_responses"))
+
+ error = events[-1]
+ assert isinstance(error, ProviderError)
+ assert error.kind == "server"
+ assert error.message == "upstream failed"
+ assert "secret system prompt" not in error.message
+
+
+async def test_responses_failed_without_error_details_has_safe_fixed_message() -> None:
+ body = (
+ 'data: {"type":"response.failed","response":{"status":"failed","error":null,'
+ '"instructions":"If you hit a rate limit, wait.","tools":[{"name":"secret"}]}}\n\n'
+ )
+
+ def handler(_: httpx.Request) -> httpx.Response:
+ return httpx.Response(200, headers={"content-type": "text/event-stream"}, text=body)
+
+ async with httpx.AsyncClient(transport=httpx.MockTransport(handler)) as client:
+ events = await _events(OpenAIResponsesAdapter(client), _request("openai_responses"))
+
+ error = events[-1]
+ assert isinstance(error, ProviderError)
+ assert error.kind == "unknown"
+ assert error.retryable is False
+ assert error.message == "OpenAI Responses response failed"
+
+
+async def test_responses_completed_without_status_follows_pi_default() -> None:
+ body = 'data: {"type":"response.completed","response":{"output":[]}}\n\n'
+
+ def handler(_: httpx.Request) -> httpx.Response:
+ return httpx.Response(200, headers={"content-type": "text/event-stream"}, text=body)
+
+ async with httpx.AsyncClient(transport=httpx.MockTransport(handler)) as client:
+ events = await _events(OpenAIResponsesAdapter(client), _request("openai_responses"))
+
+ final = events[-1]
+ assert isinstance(final, Done)
+ assert final.message.stop_reason == "stop"
+
+
+async def test_responses_completed_with_null_output_follows_pi_default() -> None:
+ body = (
+ 'data: {"type":"response.output_item.added","output_index":0,'
+ '"item":{"type":"message","id":"msg_1"}}\n\n'
+ 'data: {"type":"response.output_text.delta","output_index":0,"delta":"hi"}\n\n'
+ 'data: {"type":"response.completed","response":{"status":"completed","output":null}}\n\n'
+ )
+
+ def handler(_: httpx.Request) -> httpx.Response:
+ return httpx.Response(200, headers={"content-type": "text/event-stream"}, text=body)
+
+ async with httpx.AsyncClient(transport=httpx.MockTransport(handler)) as client:
+ events = await _events(OpenAIResponsesAdapter(client), _request("openai_responses"))
+
+ final = events[-1]
+ assert isinstance(final, Done)
+ assert final.message.stop_reason == "stop"
+ assert final.message.content == (TextBlock("hi"),)
+
+
+async def test_responses_ignores_unread_fields_on_non_function_output_items() -> None:
+ body = (
+ 'data: {"type":"response.output_item.added","output_index":0,'
+ '"item":{"type":"tool_search_call","arguments":{}}}\n\n'
+ 'data: {"type":"response.output_item.done","output_index":0,'
+ '"item":{"type":"tool_search_call","arguments":{}}}\n\n'
+ 'data: {"type":"response.output_item.added","output_index":1,'
+ '"item":{"type":"message","id":"msg_1"}}\n\n'
+ 'data: {"type":"response.output_text.delta","output_index":1,"delta":"hi"}\n\n'
+ 'data: {"type":"response.completed","response":{"status":"completed","output":null}}\n\n'
+ )
+
+ def handler(_: httpx.Request) -> httpx.Response:
+ return httpx.Response(200, headers={"content-type": "text/event-stream"}, text=body)
+
+ async with httpx.AsyncClient(transport=httpx.MockTransport(handler)) as client:
+ events = await _events(OpenAIResponsesAdapter(client), _request("openai_responses"))
+
+ final = events[-1]
+ assert isinstance(final, Done)
+ assert final.message.content == (TextBlock("hi"),)
+
+
+ ("adapter_type", "protocol", "body", "expected_kind"),
+ [
+ (
+ AnthropicAdapter,
+ "anthropic",
+ 'event: error\ndata: {"type":"error","error":{"type":"overloaded_error","code":529,"message":"Overloaded"}}\n\n',
+ "overloaded",
+ ),
+ ],
+)
+async def test_provider_error_ignores_unconsumed_code_types(
+ adapter_type: Any,
+ protocol: str,
+ body: str,
+ expected_kind: str,
+) -> None:
+ def handler(_: httpx.Request) -> httpx.Response:
+ return httpx.Response(200, headers={"content-type": "text/event-stream"}, text=body)
+
+ async with httpx.AsyncClient(transport=httpx.MockTransport(handler)) as client:
+ events = await _events(adapter_type(client), _request(protocol))
+
+ error = events[-1]
+ assert isinstance(error, ProviderError)
+ assert error.kind == expected_kind
+ assert error.retryable is True
+
+
+ ("reason", "expected"),
+ [("content_filter", "safety"), ("unknown_reason", "error")],
+)
+async def test_responses_incomplete_reasons_have_explicit_outcomes(reason: str, expected: str) -> None:
+ body = (
+ f'data: {{"type":"response.incomplete","response":{{"status":"incomplete","incomplete_details":{{"reason":"{reason}"}}}}}}\n\n'
+ )
+
+ def handler(_: httpx.Request) -> httpx.Response:
+ return httpx.Response(200, headers={"content-type": "text/event-stream"}, text=body)
+
+ async with httpx.AsyncClient(transport=httpx.MockTransport(handler)) as client:
+ events = await _events(OpenAIResponsesAdapter(client), _request("openai_responses"))
+
+ terminal = events[-1]
+ if expected == "safety":
+ assert isinstance(terminal, Done)
+ assert terminal.message.stop_reason == "safety"
+ else:
+ assert isinstance(terminal, ProviderError)
+ assert terminal.kind == "unknown"
+
+
+async def test_responses_incomplete_without_status_is_not_success() -> None:
+ body = (
+ 'data: {"type":"response.incomplete","response":'
+ '{"incomplete_details":{"reason":"unknown_reason"}}}\n\n'
+ )
+
+ def handler(_: httpx.Request) -> httpx.Response:
+ return httpx.Response(200, headers={"content-type": "text/event-stream"}, text=body)
+
+ async with httpx.AsyncClient(transport=httpx.MockTransport(handler)) as client:
+ events = await _events(OpenAIResponsesAdapter(client), _request("openai_responses"))
+
+ terminal = events[-1]
+ assert isinstance(terminal, ProviderError)
+ assert terminal.kind == "unknown"
+ assert terminal.partial is None
+
+
+ ("adapter_type", "protocol", "body"),
+ [
+ (
+ AnthropicAdapter,
+ "anthropic",
+ (
+ 'event: message_start\n'
+ 'data: {"type":"message_start","message":{"usage":{"input_tokens":1}}}\n\n'
+ 'event: content_block_start\n'
+ 'data: {"type":"content_block_start","index":0,'
+ '"content_block":{"type":"thinking","thinking":""}}\n\n'
+ 'event: content_block_delta\n'
+ 'data: {"type":"content_block_delta","index":0,'
+ '"delta":{"type":"thinking_delta","thinking":"ab"}}\n\n'
+ 'event: content_block_delta\n'
+ 'data: {"type":"content_block_delta","index":0,'
+ '"delta":{"type":"thinking_delta","thinking":"cd"}}\n\n'
+ ),
+ ),
+ (
+ OpenAIChatAdapter,
+ "openai_chat",
+ (
+ 'data: {"choices":[{"delta":{"content":"ab"}}]}\n\n'
+ 'data: {"choices":[{"delta":{"content":"cd"}}]}\n\n'
+ ),
+ ),
+ (
+ OpenAIResponsesAdapter,
+ "openai_responses",
+ (
+ 'data: {"type":"response.output_item.added","output_index":0,'
+ '"item":{"type":"function_call","id":"fc_1","call_id":"call_1","name":"read"}}\n\n'
+ 'data: {"type":"response.function_call_arguments.delta",'
+ '"output_index":0,"delta":"ab"}\n\n'
+ 'data: {"type":"response.function_call_arguments.delta",'
+ '"output_index":0,"delta":"cd"}\n\n'
+ ),
+ ),
+ ],
+)
+async def test_cumulative_output_budget_covers_text_thinking_and_tool_arguments(
+ monkeypatch: pytest.MonkeyPatch,
+ adapter_type: Any,
+ protocol: str,
+ body: str,
+) -> None:
+ # Fixed wire data, independent of the code's computed accounting. The cap
+ # admits identity/slot overhead and the first delta, but not the second.
+ body = body.replace('"ab"', '"' + "a" * 8192 + '"')
+ body = body.replace('"cd"', '"' + "b" * 8192 + '"')
+ monkeypatch.setattr(common_module, "MAX_CUMULATIVE_OUTPUT_CHARS", 16384)
+
+ def handler(_: httpx.Request) -> httpx.Response:
+ return httpx.Response(200, headers={"content-type": "text/event-stream"}, text=body)
+
+ async with httpx.AsyncClient(transport=httpx.MockTransport(handler)) as client:
+ events = await _events(adapter_type(client), _request(protocol))
+
+ error = events[-1]
+ assert isinstance(error, ProviderError)
+ assert error.kind == "invalid_request"
+ assert error.retryable is False
+ assert "output budget" in error.message.lower()
+ assert error.partial is not None
+ delta_type = {
+ AnthropicAdapter: ThinkingDelta,
+ OpenAIChatAdapter: TextDelta,
+ OpenAIResponsesAdapter: ToolCallDelta,
+ }[adapter_type]
+ deltas = [event for event in events if isinstance(event, delta_type)]
+ assert len(deltas) == 1
+ if adapter_type is OpenAIResponsesAdapter:
+ assert deltas[0].arguments_delta == "a" * 8192
+ else:
+ assert deltas[0].delta == "a" * 8192
+
+
+async def test_cumulative_output_budget_covers_opaque_reasoning_details(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ monkeypatch.setattr(common_module, "MAX_CUMULATIVE_OUTPUT_CHARS", 4096)
+ opaque = "x" * 8192
+ body = (
+ "data: "
+ + json.dumps(
+ {
+ "choices": [
+ {
+ "delta": {
+ "reasoning_details": [
+ {"type": "reasoning.encrypted", "data": opaque}
+ ]
+ },
+ "finish_reason": "stop",
+ }
+ ]
+ }
+ )
+ + "\n\n"
+ )
+
+ def handler(_: httpx.Request) -> httpx.Response:
+ return httpx.Response(200, headers={"content-type": "text/event-stream"}, text=body)
+
+ async with httpx.AsyncClient(transport=httpx.MockTransport(handler)) as client:
+ events = await _events(OpenAIChatAdapter(client), _request("openai_chat"))
+
+ error = events[-1]
+ assert isinstance(error, ProviderError)
+ assert error.kind == "invalid_request"
+ assert "output budget" in error.message.lower()
+
+
+def test_cumulative_output_budget_covers_tool_identity(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ monkeypatch.setattr(common_module, "MAX_CUMULATIVE_OUTPUT_CHARS", 8192)
+ assembler = StreamAssembler(
+ origin=Origin("openai", "openai_chat", "model"),
+ protocol="openai_chat",
+ )
+ with pytest.raises(OutputBudgetExceeded):
+ assembler.tool_start(
+ "tool",
+ name="n" * 16384,
+ call_id="call",
+ native_id="native",
+ )
+
+
+def test_cumulative_output_budget_covers_raw_responses_reasoning_items(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ monkeypatch.setattr(common_module, "MAX_CUMULATIVE_OUTPUT_CHARS", 8192)
+ assembler = StreamAssembler(
+ origin=Origin("openai", "openai_responses", "model"),
+ protocol="openai_responses",
+ )
+ with pytest.raises(OutputBudgetExceeded):
+ assembler.merge_reasoning_item(
+ 0,
+ {
+ "type": "reasoning",
+ "id": "rs_1",
+ "summary": [],
+ "content": [{"type": "summary_text", "text": "x" * 16384}],
+ },
+ )
+
+
+def test_cumulative_output_budget_covers_unstarted_tool_aliases(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ monkeypatch.setattr(common_module, "MAX_CUMULATIVE_OUTPUT_CHARS", 4096)
+ assembler = StreamAssembler(
+ origin=Origin("openai", "openai_chat", "model"),
+ protocol="openai_chat",
+ )
+ with pytest.raises(OutputBudgetExceeded):
+ for index in range(4):
+ assembler.bind_tool_alias(
+ ("tool", index),
+ f"call-{index}-" + ("x" * 2048),
+ )
+
+
+def test_cumulative_output_budget_covers_empty_tool_states(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ monkeypatch.setattr(common_module, "MAX_CUMULATIVE_OUTPUT_CHARS", 8192)
+ assembler = StreamAssembler(
+ origin=Origin("openai", "openai_chat", "model"),
+ protocol="openai_chat",
+ )
+
+ with pytest.raises(OutputBudgetExceeded):
+ for index in range(5):
+ assembler.tool_start(("tool", index))
+
+
+def test_cumulative_output_budget_charges_empty_content_slots(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ monkeypatch.setattr(common_module, "MAX_CUMULATIVE_OUTPUT_CHARS", 4096)
+ assembler = StreamAssembler(
+ origin=Origin("anthropic", "anthropic", "model"),
+ protocol="anthropic",
+ )
+ assembler.ensure_text_slot(0)
+ assembler.ensure_text_slot(1)
+ assert assembler._output_chars == 4096
+ with pytest.raises(OutputBudgetExceeded):
+ assembler.ensure_text_slot(2)
+
+
+async def test_many_small_chat_deltas_preserve_the_complete_text() -> None:
+ count = 20_000
+ body = (
+ 'data: {"choices":[{"delta":{"content":"x"}}]}\n\n' * count
+ + 'data: {"choices":[{"delta":{},"finish_reason":"stop"}]}\n\n'
+ + "data: [DONE]\n\n"
+ )
+
+ def handler(_: httpx.Request) -> httpx.Response:
+ return httpx.Response(200, headers={"content-type": "text/event-stream"}, text=body)
+
+ async with httpx.AsyncClient(transport=httpx.MockTransport(handler)) as client:
+ events = await _events(OpenAIChatAdapter(client), _request("openai_chat"))
+
+ final = events[-1]
+ assert isinstance(final, Done)
+ assert final.message.content == (TextBlock(text="x" * count),)
+
+
[email protected]("status", ["failed", "cancelled"])
+async def test_responses_failed_or_cancelled_status_is_terminal_provider_error(status: str) -> None:
+ body = f'data: {{"type":"response.completed","response":{{"status":"{status}"}}}}\n\n'
+
+ def handler(_: httpx.Request) -> httpx.Response:
+ return httpx.Response(200, headers={"content-type": "text/event-stream"}, text=body)
+
+ async with httpx.AsyncClient(transport=httpx.MockTransport(handler)) as client:
+ events = await _events(OpenAIResponsesAdapter(client), _request("openai_responses"))
+
+ error = events[-1]
+ assert isinstance(error, ProviderError)
+ assert error.kind == "unknown"
+
+
+async def test_responses_non_array_terminal_output_is_malformed() -> None:
+ body = (
+ 'data: {"type":"response.completed","response":{"status":"completed","output":{}}}\n\n'
+ )
+
+ def handler(_: httpx.Request) -> httpx.Response:
+ return httpx.Response(200, headers={"content-type": "text/event-stream"}, text=body)
+
+ async with httpx.AsyncClient(transport=httpx.MockTransport(handler)) as client:
+ events = await _events(OpenAIResponsesAdapter(client), _request("openai_responses"))
+
+ error = events[-1]
+ assert isinstance(error, ProviderError)
+ assert error.kind == "invalid_request"
+ assert "output" in error.message
+
+
+async def test_responses_terminal_output_item_type_must_be_a_string() -> None:
+ body = (
+ 'data: {"type":"response.completed","response":{"status":"completed",'
+ '"output":[{"type":7}]}}\n\n'
+ )
+
+ def handler(_: httpx.Request) -> httpx.Response:
+ return httpx.Response(200, headers={"content-type": "text/event-stream"}, text=body)
+
+ async with httpx.AsyncClient(transport=httpx.MockTransport(handler)) as client:
+ events = await _events(OpenAIResponsesAdapter(client), _request("openai_responses"))
+
+ error = events[-1]
+ assert isinstance(error, ProviderError)
+ assert error.kind == "invalid_request"
+ assert "type" in error.message
+
+
+def test_responses_replay_preserves_output_item_order() -> None:
+ history = (
+ AssistantMessage(
+ content=(
+ ThinkingBlock("plan", json.dumps({"id": "rs_1", "encrypted_content": "enc"}, separators=(",", ":"))),
+ TextBlock(text="answer"),
+ ),
+ origin=Origin("openai", "openai_responses", "model-x"),
+ stop_reason="stop",
+ ),
+ )
+
+ payload = build_responses_payload(
+ _request("openai_responses", messages=history),
+ history,
+ )
+
+ assert payload["input"][0]["type"] == "reasoning"
+ assert payload["input"][1]["role"] == "assistant"
+
+
+async def test_responses_uses_item_id_for_parallel_argument_deltas_and_incomplete_stop() -> None:
+ body = (
+ 'data: {"type":"response.output_item.added","output_index":0,"item":{"type":"function_call","id":"fc_item_a","call_id":"call_a","name":"read"}}\n\n'
+ 'data: {"type":"response.output_item.added","output_index":1,"item":{"type":"function_call","id":"fc_item_b","call_id":"call_b","name":"read"}}\n\n'
+ 'data: {"type":"response.function_call_arguments.delta","item_id":"fc_item_b","delta":"{\\"path\\":\\"b\\"}"}\n\n'
+ 'data: {"type":"response.function_call_arguments.delta","item_id":"fc_item_a","delta":"{\\"path\\":\\"a\\"}"}\n\n'
+ 'data: {"type":"response.incomplete","response":{"status":"incomplete","incomplete_details":{"reason":"max_output_tokens"}}}\n\n'
+ )
+
+ def handler(_: httpx.Request) -> httpx.Response:
+ return httpx.Response(200, headers={"content-type": "text/event-stream"}, text=body)
+
+ async with httpx.AsyncClient(transport=httpx.MockTransport(handler)) as client:
+ events = await _events(OpenAIResponsesAdapter(client), _request("openai_responses"))
+
+ final = events[-1]
+ assert isinstance(final, Done)
+ assert final.message.stop_reason == "length"
+ assert [call.arguments for call in final.message.tool_calls] == [{"path": "a"}, {"path": "b"}]
+
+
+async def test_responses_argument_done_emits_only_the_unseen_suffix() -> None:
+ body = (
+ 'data: {"type":"response.output_item.added","output_index":0,"item":{"type":"function_call","id":"fc_1","call_id":"call_1","name":"read"}}\n\n'
+ 'data: {"type":"response.function_call_arguments.delta","output_index":0,"delta":"{\\"path\\":"}\n\n'
+ 'data: {"type":"response.function_call_arguments.done","output_index":0,"arguments":"{\\"path\\":\\"x\\"}"}\n\n'
+ 'data: {"type":"response.output_item.done","output_index":0,"item":{"type":"function_call","id":"fc_1","call_id":"call_1","name":"read","arguments":"{\\"path\\":\\"x\\"}"}}\n\n'
+ 'data: {"type":"response.completed","response":{"status":"completed"}}\n\n'
+ )
+
+ def handler(_: httpx.Request) -> httpx.Response:
+ return httpx.Response(200, headers={"content-type": "text/event-stream"}, text=body)
+
+ async with httpx.AsyncClient(transport=httpx.MockTransport(handler)) as client:
+ events = await _events(OpenAIResponsesAdapter(client), _request("openai_responses"))
+
+ assert [event.arguments_delta for event in events if isinstance(event, ToolCallDelta)] == [
+ '{"path":',
+ '"x"}',
+ ]
+ assert isinstance(events[-1], Done)
+ assert events[-1].message.tool_calls[0].arguments == {"path": "x"}
+
+
+async def test_responses_empty_output_item_arguments_keep_streamed_arguments() -> None:
+ body = (
+ 'data: {"type":"response.output_item.added","output_index":0,"item":{"type":"function_call","id":"fc_1","call_id":"call_1","name":"read"}}\n\n'
+ 'data: {"type":"response.function_call_arguments.delta","output_index":0,"delta":"{\\"path\\":\\"x\\"}"}\n\n'
+ 'data: {"type":"response.output_item.done","output_index":0,"item":{"type":"function_call","id":"fc_1","call_id":"call_1","name":"read","arguments":""}}\n\n'
+ 'data: {"type":"response.completed","response":{"status":"completed"}}\n\n'
+ )
+
+ def handler(_: httpx.Request) -> httpx.Response:
+ return httpx.Response(200, headers={"content-type": "text/event-stream"}, text=body)
+
+ async with httpx.AsyncClient(transport=httpx.MockTransport(handler)) as client:
+ events = await _events(OpenAIResponsesAdapter(client), _request("openai_responses"))
+
+ final = events[-1]
+ assert isinstance(final, Done)
+ assert final.message.tool_calls[0].arguments == {"path": "x"}
+
+
+async def test_responses_reasoning_signature_survives_terminal_snapshot_without_encrypted_content() -> None:
+ body = (
+ 'data: {"type":"response.output_item.added","output_index":0,"item":{"type":"reasoning","id":"rs_1"}}\n\n'
+ 'data: {"type":"response.output_item.done","output_index":0,"item":{"type":"reasoning","id":"rs_1","encrypted_content":"enc1"}}\n\n'
+ 'data: {"type":"response.completed","response":{"status":"completed","output":[{"type":"reasoning","id":"rs_1","summary":[]}]}}\n\n'
+ )
+
+ def handler(_: httpx.Request) -> httpx.Response:
+ return httpx.Response(200, headers={"content-type": "text/event-stream"}, text=body)
+
+ async with httpx.AsyncClient(transport=httpx.MockTransport(handler)) as client:
+ events = await _events(OpenAIResponsesAdapter(client), _request("openai_responses"))
+
+ final = events[-1]
+ assert isinstance(final, Done)
+ assert json.loads(final.message.content[0].signature or "")["encrypted_content"] == "enc1"
+
+
+async def test_responses_late_tool_argument_delta_after_close_is_ignored() -> None:
+ body = (
+ 'data: {"type":"response.output_item.added","output_index":0,"item":{"type":"function_call","id":"fc_1","call_id":"call_1","name":"read"}}\n\n'
+ 'data: {"type":"response.output_item.done","output_index":0,"item":{"type":"function_call","id":"fc_1","call_id":"call_1","name":"read","arguments":"{\\"path\\":\\"x\\"}"}}\n\n'
+ 'data: {"type":"response.function_call_arguments.delta","output_index":0,"delta":"LATE"}\n\n'
+ 'data: {"type":"response.completed","response":{"status":"completed"}}\n\n'
+ )
+
+ def handler(_: httpx.Request) -> httpx.Response:
+ return httpx.Response(200, headers={"content-type": "text/event-stream"}, text=body)
+
+ async with httpx.AsyncClient(transport=httpx.MockTransport(handler)) as client:
+ events = await _events(OpenAIResponsesAdapter(client), _request("openai_responses"))
+
+ final = events[-1]
+ assert isinstance(final, Done)
+ assert final.message.tool_calls[0].arguments == {"path": "x"}
+
+
+async def test_responses_rejects_unfinished_tool_call_on_completed_response() -> None:
+ body = (
+ 'data: {"type":"response.output_item.added","output_index":0,"item":{"type":"function_call","id":"fc_1","call_id":"call_1","name":"read"}}\n\n'
+ 'data: {"type":"response.function_call_arguments.delta","output_index":0,"delta":"{\\"path\\":\\"x\\"}"}\n\n'
+ 'data: {"type":"response.completed","response":{"status":"completed"}}\n\n'
+ )
+
+ def handler(_: httpx.Request) -> httpx.Response:
+ return httpx.Response(200, headers={"content-type": "text/event-stream"}, text=body)
+
+ async with httpx.AsyncClient(transport=httpx.MockTransport(handler)) as client:
+ events = await _events(OpenAIResponsesAdapter(client), _request("openai_responses"))
+
+ assert isinstance(events[-1], ProviderError)
+ assert events[-1].kind == "invalid_request"
+ assert "unfinished tool call" in events[-1].message
+
+
+async def test_responses_ignores_final_only_function_call_like_pi() -> None:
+ body = (
+ 'data: {"type":"response.completed","response":{"status":"completed","output":[{"type":"function_call","id":"fc_1","call_id":"call_1","name":"read","arguments":"{}"}]}}\n\n'
+ )
+
+ def handler(_: httpx.Request) -> httpx.Response:
+ return httpx.Response(200, headers={"content-type": "text/event-stream"}, text=body)
+
+ async with httpx.AsyncClient(transport=httpx.MockTransport(handler)) as client:
+ events = await _events(OpenAIResponsesAdapter(client), _request("openai_responses"))
+
+ assert isinstance(events[-1], Done)
+ assert events[-1].message.stop_reason == "stop"
+ assert events[-1].message.tool_calls == ()
+
+
+async def test_responses_done_alias_follows_terminal_response_state() -> None:
+ body = (
+ 'data: {"type":"response.output_item.added","output_index":0,"item":{"type":"message","id":"msg_1"}}\n\n'
+ 'data: {"type":"response.done","response":{"status":"completed","output":[{"type":"message","id":"msg_1","content":[{"type":"output_text","text":"done"}]}]}}\n\n'
+ )
+
+ def handler(_: httpx.Request) -> httpx.Response:
+ return httpx.Response(200, headers={"content-type": "text/event-stream"}, text=body)
+
+ async with httpx.AsyncClient(transport=httpx.MockTransport(handler)) as client:
+ events = await _events(OpenAIResponsesAdapter(client), _request("openai_responses"))
+
+ assert isinstance(events[-1], Done)
+ assert events[-1].message.stop_reason == "stop"
+
+
+async def test_responses_does_not_adopt_terminal_message_snapshot() -> None:
+ body = (
+ 'data: {"type":"response.output_item.added","output_index":0,"item":{"type":"message","id":"msg_1"}}\n\n'
+ 'data: {"type":"response.completed","response":{"status":"completed","output":[{"type":"message","id":"msg_1","content":[{"type":"output_text","text":"hello "},{"type":"output_text","text":"world"}]}]}}\n\n'
+ )
+
+ def handler(_: httpx.Request) -> httpx.Response:
+ return httpx.Response(200, headers={"content-type": "text/event-stream"}, text=body)
+
+ async with httpx.AsyncClient(transport=httpx.MockTransport(handler)) as client:
+ events = await _events(OpenAIResponsesAdapter(client), _request("openai_responses"))
+
+ assert isinstance(events[-1], Done)
+ assert events[-1].message.content == (TextBlock(""),)
+
+
+async def test_responses_refusal_is_not_normalized_to_stop() -> None:
+ body = (
+ 'data: {"type":"response.output_item.added","output_index":0,"item":{"type":"message","id":"msg_1"}}\n\n'
+ 'data: {"type":"response.refusal.delta","delta":"cannot help"}\n\n'
+ 'data: {"type":"response.completed","response":{"status":"completed"}}\n\n'
+ )
+
+ def handler(_: httpx.Request) -> httpx.Response:
+ return httpx.Response(200, headers={"content-type": "text/event-stream"}, text=body)
+
+ async with httpx.AsyncClient(transport=httpx.MockTransport(handler)) as client:
+ events = await _events(OpenAIResponsesAdapter(client), _request("openai_responses"))
+
+ final = events[-1]
+ assert isinstance(final, Done)
+ assert final.message.stop_reason == "refusal"
+
+
+async def test_responses_orphan_refusal_delta_is_ignored_like_pi() -> None:
+ body = (
+ 'data: {"type":"response.refusal.delta","output_index":3,"delta":"cannot help"}\n\n'
+ 'data: {"type":"response.completed","response":{"status":"completed"}}\n\n'
+ )
+
+ def handler(_: httpx.Request) -> httpx.Response:
+ return httpx.Response(200, headers={"content-type": "text/event-stream"}, text=body)
+
+ async with httpx.AsyncClient(transport=httpx.MockTransport(handler)) as client:
+ events = await _events(OpenAIResponsesAdapter(client), _request("openai_responses"))
+
+ final = events[-1]
+ assert isinstance(final, Done)
+ assert final.message.stop_reason == "stop"
+ assert final.message.content == ()
+
+
+async def test_responses_refusal_does_not_skip_message_snapshot_merge() -> None:
+ body = (
+ 'data: {"type":"response.output_item.added","output_index":0,"item":{"type":"message","id":"msg_1"}}\n\n'
+ 'data: {"type":"response.refusal.delta","output_index":0,"delta":"cannot"}\n\n'
+ 'data: {"type":"response.output_item.done","output_index":0,"item":{"type":"message","id":"msg_1","content":[{"type":"output_text","text":"cannot help"}]}}\n\n'
+ 'data: {"type":"response.completed","response":{"status":"completed"}}\n\n'
+ )
+
+ def handler(_: httpx.Request) -> httpx.Response:
+ return httpx.Response(200, headers={"content-type": "text/event-stream"}, text=body)
+
+ async with httpx.AsyncClient(transport=httpx.MockTransport(handler)) as client:
+ events = await _events(OpenAIResponsesAdapter(client), _request("openai_responses"))
+
+ assert [event.delta for event in events if isinstance(event, TextDelta)] == [
+ "cannot",
+ " help",
+ ]
+ assert isinstance(events[-1], Done)
+ assert events[-1].message.content == (TextBlock("cannot help"),)
+
+
+async def test_responses_terminal_refusal_output_sets_refusal_stop_reason() -> None:
+ body = (
+ 'data: {"type":"response.output_item.added","output_index":0,"item":{"type":"message","id":"msg_1"}}\n\n'
+ 'data: {"type":"response.completed","response":{"status":"completed","output":[{"type":"message","id":"msg_1","content":[{"type":"refusal","refusal":"cannot help"}]}]}}\n\n'
+ )
+
+ def handler(_: httpx.Request) -> httpx.Response:
+ return httpx.Response(200, headers={"content-type": "text/event-stream"}, text=body)
+
+ async with httpx.AsyncClient(transport=httpx.MockTransport(handler)) as client:
+ events = await _events(OpenAIResponsesAdapter(client), _request("openai_responses"))
+
+ final = events[-1]
+ assert isinstance(final, Done)
+ assert final.message.stop_reason == "refusal"
+
+
+async def test_responses_failed_server_code_is_retryable_before_streaming() -> None:
+ body = (
+ 'data: {"type":"response.failed","response":{"status":"failed","error":{"code":"server_error","message":"upstream failed"}}}\n\n'
+ )
+
+ def handler(_: httpx.Request) -> httpx.Response:
+ return httpx.Response(200, headers={"content-type": "text/event-stream"}, text=body)
+
+ async with httpx.AsyncClient(transport=httpx.MockTransport(handler)) as client:
+ events = await _events(OpenAIResponsesAdapter(client), _request("openai_responses"))
+
+ error = events[-1]
+ assert isinstance(error, ProviderError)
+ assert error.kind == "server"
+ assert error.retryable is True
+
+
+async def test_responses_reasoning_only_failure_has_no_partial() -> None:
+ body = (
+ 'data: {"type":"response.output_item.added","output_index":0,'
+ '"item":{"type":"reasoning","id":"rs_1","summary":[],"content":[]}}\n\n'
+ 'data: {"type":"response.failed","response":{"status":"failed",'
+ '"error":{"code":"server_error","message":"upstream failed"}}}\n\n'
+ )
+
+ def handler(_: httpx.Request) -> httpx.Response:
+ return httpx.Response(200, headers={"content-type": "text/event-stream"}, text=body)
+
+ async with httpx.AsyncClient(transport=httpx.MockTransport(handler)) as client:
+ events = await _events(OpenAIResponsesAdapter(client), _request("openai_responses"))
+
+ error = events[-1]
+ assert isinstance(error, ProviderError)
+ assert error.partial is None
+
+
+async def test_responses_failed_tool_start_is_not_replayed_in_partial() -> None:
+ body = (
+ 'data: {"type":"response.output_item.added","output_index":0,"item":{"type":"function_call","id":"fc_1","call_id":"call_1","name":"read"}}\n\n'
+ 'data: {"type":"response.failed","response":{"status":"failed","error":{"code":"server_error","message":"upstream failed"}}}\n\n'
+ )
+
+ def handler(_: httpx.Request) -> httpx.Response:
+ return httpx.Response(200, headers={"content-type": "text/event-stream"}, text=body)
+
+ async with httpx.AsyncClient(transport=httpx.MockTransport(handler)) as client:
+ events = await _events(OpenAIResponsesAdapter(client), _request("openai_responses"))
+
+ error = events[-1]
+ assert isinstance(error, ProviderError)
+ assert error.retryable is False
+ assert error.partial is not None
+ assert error.partial.tool_calls == ()
+
+
+async def test_responses_orphan_argument_events_are_ignored_like_pi() -> None:
+ body = (
+ 'data: {"type":"response.output_item.added","output_index":0,"item":{"type":"reasoning","id":"rs_1"}}\n\n'
+ 'data: {"type":"response.output_item.added","output_index":1,"item":{"type":"function_call","id":"fc_1","call_id":"call_1","name":"read"}}\n\n'
+ 'data: {"type":"response.function_call_arguments.delta","delta":"orphan"}\n\n'
+ 'data: {"type":"response.function_call_arguments.done","arguments":"{\\"orphan\\":true}"}\n\n'
+ 'data: {"type":"response.output_item.done","output_index":1,"item":{"type":"function_call","id":"fc_1","call_id":"call_1","name":"read","arguments":"{}"}}\n\n'
+ 'data: {"type":"response.completed","response":{"status":"completed"}}\n\n'
+ )
+
+ def handler(_: httpx.Request) -> httpx.Response:
+ return httpx.Response(200, headers={"content-type": "text/event-stream"}, text=body)
+
+ async with httpx.AsyncClient(transport=httpx.MockTransport(handler)) as client:
+ events = await _events(OpenAIResponsesAdapter(client), _request("openai_responses"))
+
+ assert isinstance(events[-1], Done)
+ assert events[-1].message.tool_calls[0].arguments == {}
+
+
+async def test_responses_output_item_done_can_create_a_function_call_slot() -> None:
+ body = (
+ 'data: {"type":"response.output_item.done","output_index":0,"item":{"type":"function_call","id":"fc_1","call_id":"call_1","name":"read","arguments":"{\\"path\\":\\"x\\"}"}}\n\n'
+ 'data: {"type":"response.completed","response":{"status":"completed"}}\n\n'
+ )
+
+ def handler(_: httpx.Request) -> httpx.Response:
+ return httpx.Response(200, headers={"content-type": "text/event-stream"}, text=body)
+
+ async with httpx.AsyncClient(transport=httpx.MockTransport(handler)) as client:
+ events = await _events(OpenAIResponsesAdapter(client), _request("openai_responses"))
+
+ assert any(isinstance(event, ToolCallStart) for event in events)
+ assert [event.arguments_delta for event in events if isinstance(event, ToolCallDelta)] == [
+ '{"path":"x"}'
+ ]
+ assert isinstance(events[-1], Done)
+ assert events[-1].message.tool_calls[0].arguments == {"path": "x"}
+
+
+async def test_responses_missing_output_index_uses_one_shared_fallback_slot() -> None:
+ body = (
+ 'data: {"type":"response.output_item.added","item":{"type":"reasoning","id":"rs_1"}}\n\n'
+ 'data: {"type":"response.output_item.added","item":{"type":"function_call","id":"fc_1","call_id":"call_1","name":"read"}}\n\n'
+ 'data: {"type":"response.function_call_arguments.delta","delta":"{\\"path\\":\\"x\\"}"}\n\n'
+ 'data: {"type":"response.output_item.done","item":{"type":"function_call","id":"fc_1","call_id":"call_1","name":"read","arguments":"{\\"path\\":\\"x\\"}"}}\n\n'
+ 'data: {"type":"response.completed","response":{"status":"completed"}}\n\n'
+ )
+
+ def handler(_: httpx.Request) -> httpx.Response:
+ return httpx.Response(200, headers={"content-type": "text/event-stream"}, text=body)
+
+ async with httpx.AsyncClient(transport=httpx.MockTransport(handler)) as client:
+ events = await _events(OpenAIResponsesAdapter(client), _request("openai_responses"))
+
+ assert [event.arguments_delta for event in events if isinstance(event, ToolCallDelta)] == [
+ '{"path":"x"}'
+ ]
+ assert isinstance(events[-1], Done)
+ assert events[-1].message.tool_calls[0].arguments == {"path": "x"}
+
+
+async def test_responses_consecutive_missing_output_indexes_rebind_tool_slots() -> None:
+ body = (
+ 'data: {"type":"response.output_item.added","item":{"type":"function_call","id":"fc_a","call_id":"call_a","name":"read"}}\n\n'
+ 'data: {"type":"response.output_item.added","item":{"type":"function_call","id":"fc_b","call_id":"call_b","name":"read"}}\n\n'
+ 'data: {"type":"response.function_call_arguments.delta","item_id":"fc_a","delta":"{\\"path\\":\\"a\\"}"}\n\n'
+ 'data: {"type":"response.function_call_arguments.delta","item_id":"fc_b","delta":"{\\"path\\":\\"b\\"}"}\n\n'
+ 'data: {"type":"response.output_item.done","item":{"type":"function_call","id":"fc_a","call_id":"call_a","name":"read","arguments":"{\\"path\\":\\"a\\"}"}}\n\n'
+ 'data: {"type":"response.output_item.done","item":{"type":"function_call","id":"fc_b","call_id":"call_b","name":"read","arguments":"{\\"path\\":\\"b\\"}"}}\n\n'
+ 'data: {"type":"response.completed","response":{"status":"completed"}}\n\n'
+ )
+
+ def handler(_: httpx.Request) -> httpx.Response:
+ return httpx.Response(200, headers={"content-type": "text/event-stream"}, text=body)
+
+ async with httpx.AsyncClient(transport=httpx.MockTransport(handler)) as client:
+ events = await _events(OpenAIResponsesAdapter(client), _request("openai_responses"))
+
+ final = events[-1]
+ assert isinstance(final, Done)
+ assert [call.arguments for call in final.message.tool_calls] == [
+ {"path": "a"},
+ {"path": "b"},
+ ]
+
+
+async def test_responses_missing_tool_ids_reuse_the_open_fallback_slot() -> None:
+ body = (
+ 'data: {"type":"response.output_item.added","item":{"type":"function_call","call_id":"call_1","name":"read"}}\n\n'
+ 'data: {"type":"response.function_call_arguments.delta","delta":"{\\"path\\":\\"x\\"}"}\n\n'
+ 'data: {"type":"response.output_item.done","item":{"type":"function_call","call_id":"call_1","name":"read","arguments":"{\\"path\\":\\"x\\"}"}}\n\n'
+ 'data: {"type":"response.completed","response":{"status":"completed"}}\n\n'
+ )
+
+ def handler(_: httpx.Request) -> httpx.Response:
+ return httpx.Response(200, headers={"content-type": "text/event-stream"}, text=body)
+
+ async with httpx.AsyncClient(transport=httpx.MockTransport(handler)) as client:
+ events = await _events(OpenAIResponsesAdapter(client), _request("openai_responses"))
+
+ starts = [event for event in events if isinstance(event, ToolCallStart)]
+ final = events[-1]
+ assert len(starts) == 1
+ assert isinstance(final, Done)
+ assert final.message.tool_calls[0].arguments == {"path": "x"}
+
+
+async def test_responses_non_tool_missing_output_index_keeps_pi_fallback() -> None:
+ body = (
+ 'data: {"type":"response.output_item.added","item":{"type":"function_call","call_id":"call_1","name":"read"}}\n\n'
+ 'data: {"type":"response.function_call_arguments.delta","delta":"{\\"path\\":\\"x\\"}"}\n\n'
+ 'data: {"type":"response.output_item.done","item":{"type":"function_call","call_id":"call_1","name":"read","arguments":"{\\"path\\":\\"x\\"}"}}\n\n'
+ 'data: {"type":"response.output_item.added","item":{"type":"message"}}\n\n'
+ 'data: {"type":"response.output_text.delta","delta":"hello"}\n\n'
+ 'data: {"type":"response.output_item.done","item":{"type":"message","content":[{"type":"output_text","text":"hello"}]}}\n\n'
+ 'data: {"type":"response.completed","response":{"status":"completed"}}\n\n'
+ )
+
+ def handler(_: httpx.Request) -> httpx.Response:
+ return httpx.Response(200, headers={"content-type": "text/event-stream"}, text=body)
+
+ async with httpx.AsyncClient(transport=httpx.MockTransport(handler)) as client:
+ events = await _events(OpenAIResponsesAdapter(client), _request("openai_responses"))
+
+ final = events[-1]
+ assert isinstance(final, Done)
+ assert final.message.content == (
+ ToolCallBlock("call_1", "read", {"path": "x"}),
+ TextBlock("hello"),
+ )
+
+
+async def test_responses_empty_slots_close_before_late_deltas() -> None:
+ body = (
+ 'data: {"type":"response.output_item.added","output_index":0,"item":{"type":"message","id":"msg_1"}}\n\n'
+ 'data: {"type":"response.output_item.added","output_index":1,"item":{"type":"reasoning","id":"rs_1"}}\n\n'
+ 'data: {"type":"response.output_item.done","output_index":0,"item":{"type":"message","id":"msg_1","content":[]}}\n\n'
+ 'data: {"type":"response.output_item.done","output_index":1,"item":{"type":"reasoning","id":"rs_1","summary":[]}}\n\n'
+ 'data: {"type":"response.output_text.delta","output_index":0,"delta":"late text"}\n\n'
+ 'data: {"type":"response.reasoning_text.delta","output_index":1,"delta":"late thinking"}\n\n'
+ 'data: {"type":"response.completed","response":{"status":"completed"}}\n\n'
+ )
+
+ def handler(_: httpx.Request) -> httpx.Response:
+ return httpx.Response(200, headers={"content-type": "text/event-stream"}, text=body)
+
+ async with httpx.AsyncClient(transport=httpx.MockTransport(handler)) as client:
+ events = await _events(OpenAIResponsesAdapter(client), _request("openai_responses"))
+
+ assert not [event for event in events if isinstance(event, TextDelta)]
+ assert isinstance(events[-1], Done)
+ assert events[-1].message.content == (TextBlock(""), ThinkingBlock(""))
+
+
+async def test_responses_output_item_done_replaces_a_different_text_snapshot() -> None:
+ body = (
+ 'data: {"type":"response.output_item.added","output_index":0,"item":{"type":"message","id":"msg_1"}}\n\n'
+ 'data: {"type":"response.output_text.delta","output_index":0,"delta":"Hello world"}\n\n'
+ 'data: {"type":"response.output_item.done","output_index":0,"item":{"type":"message","id":"msg_1","content":[{"type":"output_text","text":"Hello, world"}]}}\n\n'
+ 'data: {"type":"response.completed","response":{"status":"completed"}}\n\n'
+ )
+
+ def handler(_: httpx.Request) -> httpx.Response:
+ return httpx.Response(200, headers={"content-type": "text/event-stream"}, text=body)
+
+ async with httpx.AsyncClient(transport=httpx.MockTransport(handler)) as client:
+ events = await _events(OpenAIResponsesAdapter(client), _request("openai_responses"))
+
+ assert isinstance(events[-1], Done)
+ assert events[-1].message.content == (TextBlock("Hello, world"),)
+
+
+async def test_responses_output_item_done_closes_slot_before_late_delta() -> None:
+ body = (
+ 'data: {"type":"response.output_item.added","output_index":0,"item":{"type":"message","id":"msg_1"}}\n\n'
+ 'data: {"type":"response.output_text.delta","output_index":0,"delta":"a"}\n\n'
+ 'data: {"type":"response.output_item.done","output_index":0,"item":{"type":"message","id":"msg_1","content":[{"type":"output_text","text":"a"}]}}\n\n'
+ 'data: {"type":"response.output_text.delta","output_index":0,"delta":"LATE"}\n\n'
+ 'data: {"type":"response.completed","response":{"status":"completed"}}\n\n'
+ )
+
+ def handler(_: httpx.Request) -> httpx.Response:
+ return httpx.Response(200, headers={"content-type": "text/event-stream"}, text=body)
+
+ async with httpx.AsyncClient(transport=httpx.MockTransport(handler)) as client:
+ events = await _events(OpenAIResponsesAdapter(client), _request("openai_responses"))
+
+ assert [event.delta for event in events if isinstance(event, TextDelta)] == ["a"]
+ assert [event.index for event in events if isinstance(event, BlockEnd)] == [0]
+ assert isinstance(events[-1], Done)
+ assert events[-1].message.content == (TextBlock("a"),)
+
+
+async def test_chat_completions_reassembles_parallel_calls() -> None:
+ body = (
+ 'data: {"choices":[{"delta":{"tool_calls":[{"index":0,"id":"call_a","function":{"name":"read","arguments":"{\\"path\\":\\"a\\"}"}}]},"finish_reason":null}]}\n\n'
+ 'data: {"choices":[{"delta":{"tool_calls":[{"index":1,"id":"call_b","function":{"name":"read","arguments":"{\\"path\\":\\"b\\"}"}}]},"finish_reason":null}]}\n\n'
+ 'data: {"choices":[{"delta":{},"finish_reason":"tool_calls"}],"usage":{"prompt_tokens":3,"completion_tokens":2}}\n\n'
+ "data: [DONE]\n\n"
+ )
+
+ def handler(_: httpx.Request) -> httpx.Response:
+ return httpx.Response(200, headers={"content-type": "text/event-stream"}, text=body)
+
+ async with httpx.AsyncClient(transport=httpx.MockTransport(handler)) as client:
+ events = await _events(OpenAIChatAdapter(client), _request("openai_chat"))
+
+ final = events[-1]
+ assert isinstance(final, Done)
+ assert final.message.stop_reason == "tool_use"
+ assert [call.arguments for call in final.message.tool_calls] == [{"path": "a"}, {"path": "b"}]
+
+
+async def test_chat_reuses_indexless_tool_slot_for_argument_only_delta() -> None:
+ body = (
+ 'data: {"choices":[{"delta":{"tool_calls":[{"id":"call_a","function":{"name":"read"}}]}}]}\n\n'
+ 'data: {"choices":[{"delta":{"tool_calls":[{"function":{"arguments":"{\\"path\\":\\"x\\"}"}}]},"finish_reason":"tool_calls"}]}\n\n'
+ "data: [DONE]\n\n"
+ )
+
+ def handler(_: httpx.Request) -> httpx.Response:
+ return httpx.Response(200, headers={"content-type": "text/event-stream"}, text=body)
+
+ async with httpx.AsyncClient(transport=httpx.MockTransport(handler)) as client:
+ events = await _events(OpenAIChatAdapter(client), _request("openai_chat"))
+
+ final = events[-1]
+ assert isinstance(final, Done)
+ assert final.message.tool_calls[0].id == "call_a"
+ assert final.message.tool_calls[0].arguments == {"path": "x"}
+
+
+ ("first", "second"),
+ [
+ (
+ {"index": 1, "id": "call_a", "function": {"name": "read"}},
+ {"id": "call_b", "function": {"name": "write", "arguments": '{"q":2}'}},
+ ),
+ (
+ {"id": "call_a", "function": {"name": "read"}},
+ {"index": 0, "id": "call_b", "function": {"name": "write", "arguments": '{"q":2}'}},
+ ),
+ (
+ {"id": "call_a", "function": {"name": "read"}},
+ {"id": "call_b", "function": {"name": "write", "arguments": '{"q":2}'}},
+ ),
+ ],
+)
+async def test_chat_indexed_and_indexless_tool_calls_do_not_collide(
+ first: dict[str, Any],
+ second: dict[str, Any],
+) -> None:
+ body = (
+ f'data: {json.dumps({"choices": [{"delta": {"tool_calls": [first]}}]})}\n\n'
+ f'data: {json.dumps({"choices": [{"delta": {"tool_calls": [second]}}]})}\n\n'
+ 'data: {"choices":[{"delta":{},"finish_reason":"tool_calls"}]}\n\n'
+ "data: [DONE]\n\n"
+ )
+
+ def handler(_: httpx.Request) -> httpx.Response:
+ return httpx.Response(200, headers={"content-type": "text/event-stream"}, text=body)
+
+ async with httpx.AsyncClient(transport=httpx.MockTransport(handler)) as client:
+ events = await _events(OpenAIChatAdapter(client), _request("openai_chat"))
+
+ starts = [event for event in events if isinstance(event, ToolCallStart)]
+ final = events[-1]
+ assert isinstance(final, Done)
+ assert [start.name for start in starts] == ["read", "write"]
+ assert [call.name for call in final.message.tool_calls] == ["read", "write"]
+ assert [call.arguments for call in final.message.tool_calls] == [{}, {"q": 2}]
+
+
+async def test_chat_uses_choice_usage_fallback() -> None:
+ body = (
+ 'data: {"choices":[{"delta":{"content":"ok"},"usage":{"prompt_tokens":3,"completion_tokens":2},"finish_reason":"stop"}]}\n\n'
+ "data: [DONE]\n\n"
+ )
+
+ def handler(_: httpx.Request) -> httpx.Response:
+ return httpx.Response(200, headers={"content-type": "text/event-stream"}, text=body)
+
+ async with httpx.AsyncClient(transport=httpx.MockTransport(handler)) as client:
+ events = await _events(OpenAIChatAdapter(client), _request("openai_chat"))
+
+ assert isinstance(events[-1], Done)
+ assert events[-1].message.usage == Usage(input_tokens=3, output_tokens=2)
+
+
+async def test_chat_reuses_tool_id_received_before_function_name() -> None:
+ body = (
+ 'data: {"choices":[{"delta":{"tool_calls":[{"index":0,"id":"provider-call"}]}}]}\n\n'
+ 'data: {"choices":[{"delta":{"tool_calls":[{"index":0,"function":{"name":"read","arguments":"{\\"path\\":\\"x\\"}"}}]},"finish_reason":"tool_calls"}]}\n\n'
+ "data: [DONE]\n\n"
+ )
+
+ def handler(_: httpx.Request) -> httpx.Response:
+ return httpx.Response(200, headers={"content-type": "text/event-stream"}, text=body)
+
+ async with httpx.AsyncClient(transport=httpx.MockTransport(handler)) as client:
+ events = await _events(OpenAIChatAdapter(client), _request("openai_chat"))
+
+ assert isinstance(events[-1], Done)
+ assert events[-1].message.tool_calls[0].id == "provider-call"
+
+
+async def test_chat_late_tool_id_matches_tool_call_start_id() -> None:
+ body = (
+ 'data: {"choices":[{"delta":{"tool_calls":[{"index":0,"function":{"name":"read"}}]}}]}\n\n'
+ 'data: {"choices":[{"delta":{"tool_calls":[{"index":0,"id":"provider-call","function":{"arguments":"{\\"path\\":\\"x\\"}"}}]},"finish_reason":"tool_calls"}]}\n\n'
+ "data: [DONE]\n\n"
+ )
+
+ def handler(_: httpx.Request) -> httpx.Response:
+ return httpx.Response(200, headers={"content-type": "text/event-stream"}, text=body)
+
+ async with httpx.AsyncClient(transport=httpx.MockTransport(handler)) as client:
+ events = await _events(OpenAIChatAdapter(client), _request("openai_chat"))
+
+ start = next(event for event in events if isinstance(event, ToolCallStart))
+ final = events[-1]
+ assert isinstance(final, Done)
+ assert start.id == final.message.tool_calls[0].id
+ assert final.message.tool_calls[0].native_id == "provider-call"
+
+
+async def test_chat_malformed_tool_arguments_keep_text_and_usage_in_partial() -> None:
+ body = (
+ 'data: {"choices":[{"delta":{"content":"before "}}]}\n\n'
+ 'data: {"choices":[{"delta":{"tool_calls":[{"index":0,"function":{"name":"read","arguments":"not-json"}}]},"finish_reason":"tool_calls"}],"usage":{"prompt_tokens":3,"completion_tokens":2}}\n\n'
+ "data: [DONE]\n\n"
+ )
+
+ def handler(_: httpx.Request) -> httpx.Response:
+ return httpx.Response(200, headers={"content-type": "text/event-stream"}, text=body)
+
+ async with httpx.AsyncClient(transport=httpx.MockTransport(handler)) as client:
+ events = await _events(OpenAIChatAdapter(client), _request("openai_chat"))
+
+ error = events[-1]
+ assert isinstance(error, ProviderError)
+ assert error.kind == "invalid_request"
+ assert error.partial is not None
+ assert error.partial.usage == Usage(input_tokens=3, output_tokens=2)
+ assert error.partial.content == (TextBlock("before "),)
+
+
+async def test_chat_accumulates_reasoning_details_across_deltas() -> None:
+ body = (
+ 'data: {"choices":[{"delta":{"reasoning_details":[{"type":"reasoning.text","text":"a"}]}}]}\n\n'
+ 'data: {"choices":[{"delta":{"reasoning_details":[{"type":"reasoning.text","text":"b"}]},"finish_reason":"stop"}]}\n\n'
+ "data: [DONE]\n\n"
+ )
+
+ def handler(_: httpx.Request) -> httpx.Response:
+ return httpx.Response(200, headers={"content-type": "text/event-stream"}, text=body)
+
+ async with httpx.AsyncClient(transport=httpx.MockTransport(handler)) as client:
+ events = await _events(OpenAIChatAdapter(client), _request("openai_chat"))
+
+ assert isinstance(events[-1], Done)
+ assert events[-1].message.content == (
+ ThinkingBlock(
+ "",
+ json.dumps([{"type": "reasoning.text", "text": "ab"}], separators=(",", ":")),
+ ),
+ )
+
+
+async def test_chat_finish_reason_end_maps_to_stop() -> None:
+ body = 'data: {"choices":[{"delta":{"content":"ok"},"finish_reason":"end"}]}\n\ndata: [DONE]\n\n'
+
+ def handler(_: httpx.Request) -> httpx.Response:
+ return httpx.Response(200, headers={"content-type": "text/event-stream"}, text=body)
+
+ async with httpx.AsyncClient(transport=httpx.MockTransport(handler)) as client:
+ events = await _events(OpenAIChatAdapter(client), _request("openai_chat"))
+
+ assert isinstance(events[-1], Done)
+ assert events[-1].message.stop_reason == "stop"
+
+
+async def test_anthropic_abort_after_message_start_keeps_usage_in_partial() -> None:
+ stream = _StalledStream(
+ b'data: {"type":"message_start","message":{"usage":{"input_tokens":7,"output_tokens":9,'
+ b'"output_tokens_details":{"thinking_tokens":6}}}}\n\n'
+ )
+
+ def handler(_: httpx.Request) -> httpx.Response:
+ return httpx.Response(200, headers={"content-type": "text/event-stream"}, stream=stream)
+
+ cancel = CancelToken()
+ async with httpx.AsyncClient(transport=httpx.MockTransport(handler)) as client:
+ task = asyncio.create_task(_events(AnthropicAdapter(client), _request("anthropic"), cancel))
+ await stream.started.wait()
+ await asyncio.sleep(0.05)
+ cancel.cancel("cancelled after usage")
+ events = await asyncio.wait_for(task, timeout=1)
+
+ assert isinstance(events[-1], ProviderError)
+ assert events[-1].partial is not None
+ assert events[-1].partial.content == ()
+ assert events[-1].partial.usage == Usage(input_tokens=7, output_tokens=9, reasoning_tokens=6)
+
+
+ ("delta_usage", "expected"),
+ [
+ (None, Usage(7, 9, 3, 5, 6)),
+ ({}, Usage(7, 9, 3, 5, 6)),
+ ({"input_tokens": None, "output_tokens": None, "cache_read_input_tokens": None,
+ "cache_creation_input_tokens": None, "output_tokens_details": None}, Usage(7, 9, 3, 5, 6)),
+ ({"output_tokens_details": {}}, Usage(7, 9, 3, 5, 6)),
+ ({"output_tokens_details": {"thinking_tokens": None}}, Usage(7, 9, 3, 5, 6)),
+ ({"cache_creation": {}}, Usage(7, 9, 3, 5, 6)),
+ ({"cache_creation": None}, Usage(7, 9, 3, 5, 6)),
+ ({"cache_creation_input_tokens": None, "cache_creation": {
+ "ephemeral_5m_input_tokens": None, "ephemeral_1h_input_tokens": None}}, Usage(7, 9, 3, 5, 6)),
+ ({"cache_creation": {"ephemeral_5m_input_tokens": None}}, Usage(7, 9, 3, 5, 6)),
+ ({"cache_creation": {"ephemeral_1h_input_tokens": None}}, Usage(7, 9, 3, 5, 6)),
+ ({"cache_creation": {"ephemeral_5m_input_tokens": 2}}, Usage(7, 9, 3, 2, 6)),
+ ({"cache_creation": {"ephemeral_1h_input_tokens": 3}}, Usage(7, 9, 3, 3, 6)),
+ ({"cache_creation": {"ephemeral_5m_input_tokens": 0,
+ "ephemeral_1h_input_tokens": 0}}, Usage(7, 9, 3, 0, 6)),
+ ({"cache_creation_input_tokens": 0, "cache_creation": {
+ "ephemeral_5m_input_tokens": 2, "ephemeral_1h_input_tokens": 3}}, Usage(7, 9, 3, 0, 6)),
+ ({"input_tokens": 0, "output_tokens": 0, "cache_read_input_tokens": 0,
+ "cache_creation_input_tokens": 0, "output_tokens_details": {"thinking_tokens": 0}},
+ Usage(0, 0, 0, 0, 0)),
+ ({"input_tokens": 11, "output_tokens": 18, "cache_read_input_tokens": 4,
+ "cache_creation_input_tokens": 8, "output_tokens_details": {"thinking_tokens": 12}},
+ Usage(11, 18, 4, 8, 12)),
+ ],
+)
+async def test_anthropic_usage_fields_share_start_and_delta_normalization(
+ delta_usage: dict[str, Any] | None, expected: Usage,
+) -> None:
+ # Pi's non-null delta merge applies to every field. C-2 additionally keeps
+ # an admitted thinking-token count when it is supplied at message_start.
+ frames = [
+ {"type": "message_start", "message": {"usage": {
+ "input_tokens": 7, "output_tokens": 9, "cache_read_input_tokens": 3,
+ "cache_creation_input_tokens": 5, "output_tokens_details": {"thinking_tokens": 6},
+ }}},
+ {"type": "message_delta", "delta": {"stop_reason": "end_turn"}, "usage": delta_usage},
+ {"type": "message_stop"},
+ ]
+ body = "".join(f"data: {json.dumps(frame)}\n\n" for frame in frames)
+
+ def handler(_: httpx.Request) -> httpx.Response:
+ return httpx.Response(200, headers={"content-type": "text/event-stream"}, text=body)
+
+ async with httpx.AsyncClient(transport=httpx.MockTransport(handler)) as client:
+ events = await _events(AnthropicAdapter(client), _request("anthropic"))
+
+ final = events[-1]
+ assert isinstance(final, Done)
+ assert final.message.usage == expected
+
+
[email protected](("protocol", "usage", "expected"), [
+ ("anthropic", {
+ "input_tokens": 7, "output_tokens": 9, "cache_read_input_tokens": 3,
+ "cache_creation_input_tokens": 5,
+ "cache_creation": {"ephemeral_5m_input_tokens": 2, "ephemeral_1h_input_tokens": 3},
+ "output_tokens_details": {"thinking_tokens": 6},
+ "server_tool_use": {"web_fetch_requests": 1, "web_search_requests": 2},
+ "inference_geo": "us", "service_tier": "standard",
+ }, Usage(7, 9, 3, 5, 6)),
+ ("openai_chat", {
+ "prompt_tokens": 100, "completion_tokens": 33, "total_tokens": 133,
+ "prompt_tokens_details": {
+ "audio_tokens": 1, "image_tokens": 2, "text_tokens": 97,
+ "cached_tokens": 50, "cache_write_tokens": 30,
+ },
+ "completion_tokens_details": {
+ "accepted_prediction_tokens": 3, "rejected_prediction_tokens": 4,
+ "audio_tokens": 1, "text_tokens": 11, "reasoning_tokens": 21,
+ },
+ }, Usage(20, 33, 50, 30, 21)),
+ ("openai_responses", {
+ "input_tokens": 10, "input_tokens_details": {"cached_tokens": 3, "cache_write_tokens": 2},
+ "output_tokens": 4, "output_tokens_details": {"reasoning_tokens": 2}, "total_tokens": 14,
+ }, Usage(5, 4, 3, 2, 2)),
+])
+async def test_documented_usage_objects_map_totals_without_double_counting_breakdowns(
+ protocol: str, usage: dict[str, Any], expected: Usage,
+) -> None:
+ # Official Usage/CompletionUsage/ResponseUsage fields, including ignored
+ # subcategories: they must not be added on top of inclusive token totals.
+ if protocol == "anthropic":
+ frames = [
+ {"type": "message_start", "message": {"usage": usage}},
+ {"type": "message_delta", "delta": {"stop_reason": "end_turn"}},
+ {"type": "message_stop"},
+ ]
+ elif protocol == "openai_chat":
+ frames = [{"choices": [{"delta": {}, "finish_reason": "stop"}], "usage": usage}]
+ else:
+ frames = [{"type": "response.completed", "response": {"status": "completed", "usage": usage}}]
+ body = "".join(f"data: {json.dumps(frame)}\n\n" for frame in frames)
+ if protocol == "openai_chat":
+ body += "data: [DONE]\n\n"
+ async with httpx.AsyncClient(transport=httpx.MockTransport(lambda _: httpx.Response(200, text=body))) as client:
+ events = await _events(adapter_class(protocol)(client), _request(protocol))
+ assert isinstance(events[-1], Done)
+ assert events[-1].message.usage == expected
+
+
+def test_chat_reasoning_models_use_completion_token_limit() -> None:
+ payload = build_chat_payload(_request("openai_chat", model_id="gpt-5-mini"), ())
+
+ assert payload["max_completion_tokens"] == 128
+ assert "max_tokens" not in payload
+
+
+ ("builder", "protocol", "field"),
+ [
+ (build_chat_payload, "openai_chat", "reasoning_effort"),
+ (build_responses_payload, "openai_responses", "reasoning"),
+ ],
+)
+def test_openai_payloads_forward_explicit_none_reasoning_effort(
+ builder: Any,
+ protocol: str,
+ field: str,
+) -> None:
+ payload = builder(_request(protocol, reasoning_effort="none"), ())
+
+ if field == "reasoning_effort":
+ assert payload[field] == "none"
+ else:
+ assert payload[field] == {"effort": "none", "summary": "auto"}
+ assert "include" not in payload
+
+
+def test_anthropic_adaptive_xhigh_maps_to_max_effort() -> None:
+ payload = build_messages_payload(
+ _request("anthropic", model_id="claude-opus-5", reasoning_effort="xhigh"),
+ (),
+ )
+
+ assert payload["thinking"] == {"type": "adaptive"}
+ assert payload["output_config"] == {"effort": "max"}
+
+
[email protected]("supports_images", [True, False])
[email protected]("followed_by_user", [True, False])
+async def test_chat_tool_result_images_follow_the_complete_tool_group(
+ supports_images: bool, followed_by_user: bool,
+) -> None:
+ # Pi batches images after all consecutive tool results. The real adapter
+ # also has to load snapshots and preserve C-1's non-vision placeholders.
+ assistant = AssistantMessage(
+ content=tuple(ToolCallBlock(f"call_{i}", "read", {}) for i in range(3)),
+ origin=Origin("openai", "openai_chat", "model-x"),
+ stop_reason="tool_use",
+ )
+ messages = (
+ assistant,
+ ToolResultMessage("call_0", "read", (ImageBlock("image/png", "media-1", "one.png"),)),
+ ToolResultMessage("call_1", "read", (
+ TextBlock("Read image file"), ImageBlock("image/png", "media-2", "two.png"),
+ )),
+ ToolResultMessage("call_2", "read", ()),
+ )
+ if followed_by_user:
+ messages += (UserMessage((TextBlock("Compare them"),)),)
+ class ToolImageLoader(_Loader):
+ async def load(self, media_token: str) -> tuple[bytes, str]:
+ self.tokens.append(media_token)
+ return {
+ "media-1": (b"first", "image/jpeg"),
+ "media-2": (b"second", "image/png"),
+ }[media_token]
+
+ loader = ToolImageLoader()
+ captured: dict[str, Any] = {}
+
+ def handler(request: httpx.Request) -> httpx.Response:
+ captured.update(json.loads(request.content))
+ return httpx.Response(
+ 200, text='data: {"choices":[{"delta":{},"finish_reason":"stop"}]}\n\ndata: [DONE]\n\n',
+ )
+
+ async with httpx.AsyncClient(transport=httpx.MockTransport(handler)) as client:
+ events = await _events(
+ OpenAIChatAdapter(client, media_loader=loader),
+ _request("openai_chat", messages=messages, supports_images=supports_images),
+ )
+ assert isinstance(events[-1], Done)
+ wire = captured["messages"]
+ assert [message["role"] for message in wire] == (
+ ["system", "assistant", "tool", "tool", "tool"]
+ + (["user"] if supports_images else [])
+ + (["user"] if followed_by_user else [])
+ )
+ assert [message["tool_call_id"] for message in wire[2:5]] == ["call_0", "call_1", "call_2"]
+ assert [call["id"] for call in wire[1]["tool_calls"]] == ["call_0", "call_1", "call_2"]
+ assert wire[4]["content"] == "(no tool output)"
+ assert "media-1" not in json.dumps(wire)
+ assert "media-2" not in json.dumps(wire)
+ if supports_images:
+ assert loader.tokens == ["media-1", "media-2"]
+ assert wire[2]["content"] == "(see attached image)"
+ assert wire[3]["content"] == "Read image file"
+ assert wire[5]["content"] == [
+ {"type": "text", "text": "Attached image(s) from tool result:"},
+ {"type": "image_url", "image_url": {"url": "data:image/jpeg;base64,Zmlyc3Q="}},
+ {"type": "image_url", "image_url": {"url": "data:image/png;base64,c2Vjb25k"}},
+ ]
+ else:
+ assert loader.tokens == []
+ assert wire[2]["content"] == "[image: one.png]"
+ assert wire[3]["content"] == "Read image file\n[image: two.png]"
+ if followed_by_user:
+ assert wire[-1] == {"role": "user", "content": "Compare them"}
+
+
+async def test_chat_emits_block_end_for_each_final_block() -> None:
+ body = (
+ 'data: {"choices":[{"delta":{"content":"ok"},"finish_reason":"stop"}]}\n\n'
+ "data: [DONE]\n\n"
+ )
+
+ def handler(_: httpx.Request) -> httpx.Response:
+ return httpx.Response(200, headers={"content-type": "text/event-stream"}, text=body)
+
+ async with httpx.AsyncClient(transport=httpx.MockTransport(handler)) as client:
+ events = await _events(OpenAIChatAdapter(client), _request("openai_chat"))
+
+ assert any(isinstance(event, BlockEnd) and event.index == 0 for event in events)
+ assert isinstance(events[-1], Done)
+
+
+ ("adapter_type", "protocol", "body", "expected"),
+ [
+ (
+ OpenAIChatAdapter,
+ "openai_chat",
+ 'data: {"choices":[{"delta":{},"finish_reason":"stop"}],"usage":{"prompt_tokens":10,"completion_tokens":4,"prompt_tokens_details":{"cached_tokens":3,"cache_write_tokens":2}}}\n\n'
+ "data: [DONE]\n\n",
+ Usage(input_tokens=5, output_tokens=4, cache_read_tokens=3, cache_write_tokens=2),
+ ),
+ (
+ OpenAIResponsesAdapter,
+ "openai_responses",
+ 'data: {"type":"response.completed","response":{"status":"completed","usage":{"input_tokens":10,"output_tokens":4,"input_tokens_details":{"cached_tokens":3,"cache_write_tokens":2},"output_tokens_details":{"reasoning_tokens":2}}}}\n\n',
+ Usage(input_tokens=5, output_tokens=4, cache_read_tokens=3, cache_write_tokens=2, reasoning_tokens=2),
+ ),
+ ],
+)
+async def test_provider_usage_excludes_cached_input_tokens(
+ adapter_type: Any,
+ protocol: str,
+ body: str,
+ expected: Usage,
+) -> None:
+ def handler(_: httpx.Request) -> httpx.Response:
+ return httpx.Response(200, headers={"content-type": "text/event-stream"}, text=body)
+
+ async with httpx.AsyncClient(transport=httpx.MockTransport(handler)) as client:
+ events = await _events(adapter_type(client), _request(protocol))
+
+ final = events[-1]
+ assert isinstance(final, Done)
+ assert final.message.usage == expected
+
+
[email protected]("usage_location", ["chunk", "choice"])
+ ("fields", "expected"),
+ [
+ # The first two wire fixtures come from Pi's openai-completions-tool-choice
+ # usage tests; the rest exercise parseChunkUsage's exact nullish order.
+ ({"prompt_tokens": 100, "completion_tokens": 5,
+ "prompt_tokens_details": {"cached_tokens": 50, "cache_write_tokens": 30},
+ "completion_tokens_details": {"reasoning_tokens": 0}}, Usage(20, 5, 50, 30, 0)),
+ ({"prompt_tokens": 10, "completion_tokens": 33,
+ "prompt_tokens_details": {"cached_tokens": 0},
+ "completion_tokens_details": {"reasoning_tokens": 21}}, Usage(10, 33, 0, 0, 21)),
+ ({"prompt_tokens": 100, "prompt_tokens_details": {}, "prompt_cache_hit_tokens": 80}, Usage(20, 0, 80)),
+ ({"prompt_tokens": 100, "prompt_tokens_details": {"cache_write_tokens": 5},
+ "cached_tokens": 80}, Usage(15, 0, 80, 5)),
+ ({"prompt_tokens": 100, "prompt_tokens_details": {"cached_tokens": None},
+ "prompt_cache_hit_tokens": 80, "cached_tokens": 90}, Usage(20, 0, 80)),
+ ({"prompt_tokens": 100, "prompt_tokens_details": {"cached_tokens": 0},
+ "prompt_cache_hit_tokens": 80, "cached_tokens": 90}, Usage(100)),
+ ({"prompt_tokens": 100, "prompt_cache_hit_tokens": 0, "cached_tokens": 90}, Usage(100)),
+ ({"prompt_tokens": 100, "prompt_cache_hit_tokens": None, "cached_tokens": 90}, Usage(10, 0, 90)),
+ ({"prompt_tokens": 100, "prompt_tokens_details": None, "cached_tokens": 90}, Usage(10, 0, 90)),
+ ({"prompt_tokens": 100, "prompt_tokens_details": {"cached_tokens": 80, "cache_write_tokens": 30}},
+ Usage(0, 0, 80, 30)),
+ ],
+)
+async def test_chat_usage_fields_follow_pi_nullish_precedence(
+ usage_location: str, fields: dict[str, Any], expected: Usage,
+) -> None:
+ choice = {"delta": {}, "finish_reason": "stop"}
+ frame: dict[str, Any] = {"choices": [choice]}
+ (frame if usage_location == "chunk" else choice)["usage"] = fields
+ body = f"data: {json.dumps(frame)}\n\ndata: [DONE]\n\n"
+ async with httpx.AsyncClient(transport=httpx.MockTransport(lambda _: httpx.Response(200, text=body))) as client:
+ events = await _events(OpenAIChatAdapter(client), _request("openai_chat"))
+ assert isinstance(events[-1], Done)
+ assert events[-1].message.usage == expected
+
+
+async def test_anthropic_usage_keeps_total_cache_write_tokens() -> None:
+ body = (
+ 'data: {"type":"message_start","message":{"usage":{"input_tokens":1,"cache_creation_input_tokens":25,"cache_creation":{"ephemeral_5m_input_tokens":15,"ephemeral_1h_input_tokens":10}}}}\n\n'
+ 'data: {"type":"message_delta","delta":{"stop_reason":"end_turn"}}\n\n'
+ 'data: {"type":"message_stop"}\n\n'
+ )
+
+ def handler(_: httpx.Request) -> httpx.Response:
+ return httpx.Response(200, headers={"content-type": "text/event-stream"}, text=body)
+
+ async with httpx.AsyncClient(transport=httpx.MockTransport(handler)) as client:
+ events = await _events(AnthropicAdapter(client), _request("anthropic"))
+
+ final = events[-1]
+ assert isinstance(final, Done)
+ assert final.message.usage == Usage(input_tokens=1, cache_write_tokens=25)
+
+
+async def test_anthropic_usage_falls_back_to_nested_cache_write_tokens() -> None:
+ body = (
+ 'data: {"type":"message_start","message":{"usage":{"input_tokens":1,"cache_creation":{"ephemeral_5m_input_tokens":15,"ephemeral_1h_input_tokens":10}}}}\n\n'
+ 'data: {"type":"message_delta","delta":{"stop_reason":"end_turn"}}\n\n'
+ 'data: {"type":"message_stop"}\n\n'
+ )
+
+ def handler(_: httpx.Request) -> httpx.Response:
+ return httpx.Response(200, headers={"content-type": "text/event-stream"}, text=body)
+
+ async with httpx.AsyncClient(transport=httpx.MockTransport(handler)) as client:
+ events = await _events(AnthropicAdapter(client), _request("anthropic"))
+
+ final = events[-1]
+ assert isinstance(final, Done)
+ assert final.message.usage == Usage(input_tokens=1, cache_write_tokens=25)
+
+
+async def test_chat_reasoning_field_is_replayed_as_a_marker() -> None:
+ body = (
+ 'data: {"choices":[{"delta":{"reasoning_content":"plan"},"finish_reason":"stop"}]}\n\n'
+ "data: [DONE]\n\n"
+ )
+
+ def handler(_: httpx.Request) -> httpx.Response:
+ return httpx.Response(200, headers={"content-type": "text/event-stream"}, text=body)
+
+ async with httpx.AsyncClient(transport=httpx.MockTransport(handler)) as client:
+ events = await _events(OpenAIChatAdapter(client), _request("openai_chat"))
+
+ final = events[-1]
+ assert isinstance(final, Done)
+ assert final.message.content == (ThinkingBlock("plan", "reasoning_content"),)
+
+
+async def test_malformed_tool_arguments_are_terminal_invalid_requests() -> None:
+ body = (
+ 'data: {"choices":[{"delta":{"tool_calls":[{"index":0,"id":"call_bad","function":{"name":"read","arguments":"not-json"}}]},"finish_reason":null}]}\n\n'
+ 'data: {"choices":[{"delta":{},"finish_reason":"tool_calls"}]}\n\n'
+ "data: [DONE]\n\n"
+ )
+
+ def handler(_: httpx.Request) -> httpx.Response:
+ return httpx.Response(200, headers={"content-type": "text/event-stream"}, text=body)
+
+ async with httpx.AsyncClient(transport=httpx.MockTransport(handler)) as client:
+ events = await _events(OpenAIChatAdapter(client), _request("openai_chat"))
+
+ error = events[-1]
+ assert isinstance(error, ProviderError)
+ assert error.kind == "invalid_request"
+ assert error.retryable is False
+ assert "malformed tool arguments" in error.message
+
+
[email protected]("served_hop", [None, "invalid", '{"provider":"anthropic","api":"anthropic","model":"model-x"}'])
+async def test_gateway_origin_sanitization_preserves_streamed_block_indexes(served_hop: str | None) -> None:
+ body = (
+ 'data: {"type":"message_start","message":{"usage":{}}}\n\n'
+ 'data: {"type":"content_block_start","index":0,"content_block":{"type":"redacted_thinking","data":"opaque"}}\n\n'
+ 'data: {"type":"content_block_stop","index":0}\n\n'
+ 'data: {"type":"content_block_start","index":1,"content_block":{"type":"thinking","signature":"sig"}}\n\n'
+ 'data: {"type":"content_block_delta","index":1,"delta":{"type":"thinking_delta","thinking":"x"}}\n\n'
+ 'data: {"type":"content_block_start","index":2,"content_block":{"type":"text","text":"visible"}}\n\n'
+ 'data: {"type":"content_block_start","index":3,"content_block":{"type":"tool_use","id":"t","name":"read"}}\n\n'
+ 'data: {"type":"message_delta","delta":{"stop_reason":"tool_use"}}\n\n'
+ 'data: {"type":"message_stop"}\n\n'
+ )
+
+ def handler(_: httpx.Request) -> httpx.Response:
+ headers = {"content-type": "text/event-stream"}
+ if served_hop is not None:
+ headers["x-avibe-served-hop"] = served_hop
+ return httpx.Response(200, headers=headers, text=body)
+
+ async with httpx.AsyncClient(transport=httpx.MockTransport(handler)) as client:
+ events = await _events(
+ AnthropicAdapter(client, gateway=True),
+ _request("anthropic"),
+ )
+
+ final = events[-1]
+ assert isinstance(final, Done)
+ verified = served_hop is not None and served_hop != "invalid"
+ assert len(final.message.content) == (4 if verified else 3)
+ assert any(isinstance(block, ThinkingBlock) and block.redacted for block in final.message.content) == verified
+ for event in events:
+ if isinstance(event, ThinkingDelta):
+ assert isinstance(final.message.content[event.index], ThinkingBlock)
+ assert final.message.content[event.index].text == "x"
+ elif isinstance(event, TextDelta):
+ assert final.message.content[event.index] == TextBlock("visible")
+ elif isinstance(event, ToolCallStart):
+ assert isinstance(final.message.content[event.index], ToolCallBlock)
+ assert final.message.content[event.index].id == event.id
+ if not verified:
+ assert all(not isinstance(block, ThinkingBlock) or block.signature is None for block in final.message.content)
+ assert all(not isinstance(block, ToolCallBlock) or block.signature is None for block in final.message.content)
+
+
+class _Loader(MediaLoader):
+ def __init__(self) -> None:
+ self.tokens: list[str] = []
+
+ async def load(self, media_token: str) -> tuple[bytes, str]:
+ self.tokens.append(media_token)
+ return b"snapshot", "image/jpeg"
+
+
+async def test_media_loader_bytes_are_resolved_at_request_time() -> None:
+ captured: dict[str, Any] = {}
+ loader = _Loader()
+
+ def handler(request: httpx.Request) -> httpx.Response:
+ captured.update(json.loads(request.content))
+ return httpx.Response(
+ 200,
+ headers={"content-type": "text/event-stream"},
+ text='data: {"choices":[{"delta":{"content":"ok"},"finish_reason":"stop"}]}\n\ndata: [DONE]\n\n',
+ )
+
+ message = UserMessage((ImageBlock("image/png", "media-1", "x.png"),))
+ async with httpx.AsyncClient(transport=httpx.MockTransport(handler)) as client:
+ await _events(
+ OpenAIChatAdapter(client, media_loader=loader),
+ _request("openai_chat", messages=(message,), supports_images=True),
+ )
+
+ assert loader.tokens == ["media-1"]
+ image_part = captured["messages"][1]["content"][0]
+ assert image_part["image_url"]["url"] == f"data:image/jpeg;base64,{base64.b64encode(b'snapshot').decode()}"
+
+
+class _FailingLoader(MediaLoader):
+ async def load(self, media_token: str) -> tuple[bytes, str]:
+ raise FileNotFoundError(media_token)
+
+
+async def test_media_loader_failure_is_a_provider_error() -> None:
+ message = UserMessage((ImageBlock("image/png", "missing", "missing.png"),))
+ adapter = OpenAIChatAdapter(
+ httpx.AsyncClient(transport=httpx.MockTransport(lambda _: httpx.Response(500))),
+ media_loader=_FailingLoader(),
+ )
+
+ events = await _events(
+ adapter,
+ _request("openai_chat", messages=(message,), supports_images=True),
+ )
+
+ assert isinstance(events[-1], ProviderError)
+ assert events[-1].kind == "unknown"
+
+
+ ("adapter_type", "protocol"),
+ [
+ (AnthropicAdapter, "anthropic"),
+ (OpenAIChatAdapter, "openai_chat"),
+ (OpenAIResponsesAdapter, "openai_responses"),
+ ],
+)
+async def test_adapter_error_bodies_use_shared_json_redaction(
+ adapter_type: Any,
+ protocol: str,
+) -> None:
+ def handler(_: httpx.Request) -> httpx.Response:
+ return httpx.Response(
+ 400,
+ text='{"detail":{"secretKey":"SKSECRET1","aws_secret_access_key":"AWSSECRET"}}',
+ )
+
+ async with httpx.AsyncClient(transport=httpx.MockTransport(handler)) as client:
+ events = await _events(adapter_type(client), _request(protocol))
+
+ error = events[-1]
+ assert isinstance(error, ProviderError)
+ assert "SKSECRET1" not in error.message
+ assert "AWSSECRET" not in error.message
+
+
+ ("event_type", "fields"),
+ [
+ ("response.output_text.delta", {"output_index": 0}),
+ ("response.refusal.delta", {"output_index": 0}),
+ ("response.reasoning_summary_text.delta", {"output_index": 0}),
+ ("response.reasoning_text.delta", {"output_index": 0}),
+ ("response.function_call_arguments.delta", {"output_index": 0}),
+ ],
+)
+async def test_responses_delta_events_require_string_payload(
+ event_type: str,
+ fields: dict[str, Any],
+) -> None:
+ body = f"data: {json.dumps({'type': event_type, **fields})}\n\n"
+
+ def handler(_: httpx.Request) -> httpx.Response:
+ return httpx.Response(200, headers={"content-type": "text/event-stream"}, text=body)
+
+ async with httpx.AsyncClient(
+ transport=httpx.MockTransport(handler)
+ ) as client:
+ events = await _events(OpenAIResponsesAdapter(client), _request("openai_responses"))
+
+ error = events[-1]
+ assert isinstance(error, ProviderError)
+ assert error.kind == "invalid_request"
+ assert event_type in error.message
+ assert events[-1].retryable is False
+
+
+ "payload",
+ [
+ {"output_index": 0, "delta": "lost"},
+ {"type": None, "output_index": 0, "delta": "lost"},
+ ],
+)
+async def test_responses_named_event_requires_string_payload_type(
+ payload: dict[str, Any],
+) -> None:
+ body = "event: response.output_text.delta\n" + f"data: {json.dumps(payload)}\n\n"
+
+ def handler(_: httpx.Request) -> httpx.Response:
+ return httpx.Response(
+ 200,
+ headers={"content-type": "text/event-stream"},
+ text=body,
+ )
+
+ async with httpx.AsyncClient(transport=httpx.MockTransport(handler)) as client:
+ events = await _events(OpenAIResponsesAdapter(client), _request("openai_responses"))
+
+ error = events[-1]
+ assert isinstance(error, ProviderError)
+ assert error.kind == "invalid_request"
+ assert "type" in error.message
+
+
+async def test_anthropic_named_event_requires_string_payload_type() -> None:
+ body = (
+ "event: content_block_delta\n"
+ 'data: {"type":5,"index":0,"delta":{"type":"text_delta","text":"lost"}}\n\n'
+ )
+
+ def handler(_: httpx.Request) -> httpx.Response:
+ return httpx.Response(
+ 200,
+ headers={"content-type": "text/event-stream"},
+ text=body,
+ )
+
+ async with httpx.AsyncClient(transport=httpx.MockTransport(handler)) as client:
+ events = await _events(AnthropicAdapter(client), _request("anthropic"))
+
+ error = events[-1]
+ assert isinstance(error, ProviderError)
+ assert error.kind == "invalid_request"
+ assert "type" in error.message
+
+
+async def test_anthropic_named_event_rejects_null_payload_type() -> None:
+ body = (
+ "event: content_block_delta\n"
+ 'data: {"type":null,"index":0,"delta":{"type":"text_delta","text":"lost"}}\n\n'
+ )
+
+ def handler(_: httpx.Request) -> httpx.Response:
+ return httpx.Response(
+ 200,
+ headers={"content-type": "text/event-stream"},
+ text=body,
+ )
+
+ async with httpx.AsyncClient(transport=httpx.MockTransport(handler)) as client:
+ events = await _events(AnthropicAdapter(client), _request("anthropic"))
+
+ error = events[-1]
+ assert isinstance(error, ProviderError)
+ assert error.kind == "invalid_request"
+ assert "type" in error.message
+
+
+async def test_pre_cancelled_request_yields_non_retryable_abort() -> None:
+ cancel = CancelToken()
+ cancel.cancel("user stopped")
+ adapter = OpenAIChatAdapter(httpx.AsyncClient(transport=httpx.MockTransport(lambda _: httpx.Response(500))))
+ try:
+ events = await _events(adapter, _request("openai_chat"), cancel)
+ finally:
+ await adapter.aclose()
+ assert len(events) == 1
+ assert isinstance(events[0], ProviderError)
+ assert events[0].kind == "aborted"
+ assert events[0].retryable is False
+
+
+async def test_stream_error_after_a_delta_is_terminal_and_keeps_partial() -> None:
+ body = (
+ 'data: {"choices":[{"delta":{"content":"partial"}}]}\n\n'
+ "data: not-json\n\n"
+ )
+
+ def handler(_: httpx.Request) -> httpx.Response:
+ return httpx.Response(200, headers={"content-type": "text/event-stream"}, text=body)
+
+ async with httpx.AsyncClient(transport=httpx.MockTransport(handler)) as client:
+ events = await _events(OpenAIChatAdapter(client), _request("openai_chat"))
+
+ error = events[-1]
+ assert isinstance(error, ProviderError)
+ assert error.retryable is False
+ assert error.partial is not None
+ assert error.partial.content == (TextBlock(text="partial"),)
+
+
+async def test_http_413_is_classified_as_overflow() -> None:
+ def handler(_: httpx.Request) -> httpx.Response:
+ return httpx.Response(413, text='{"error":{"message":"request too large"}}')
+
+ async with httpx.AsyncClient(transport=httpx.MockTransport(handler)) as client:
+ events = await _events(OpenAIChatAdapter(client), _request("openai_chat"))
+
+ error = events[-1]
+ assert isinstance(error, ProviderError)
+ assert error.kind == "overflow"
+ assert error.status == 413
+ assert error.retryable is False
+
+
+async def test_http_redirect_is_terminal_invalid_request() -> None:
+ def handler(_: httpx.Request) -> httpx.Response:
+ return httpx.Response(
+ 307,
+ headers={"location": "https://other.test/v1"},
+ text='{"error":{"message":"password=super-secret"}}',
+ )
+
+ async with httpx.AsyncClient(transport=httpx.MockTransport(handler)) as client:
+ events = await _events(OpenAIChatAdapter(client), _request("openai_chat"))
+
+ error = events[-1]
+ assert isinstance(error, ProviderError)
+ assert error.kind == "invalid_request"
+ assert error.status == 307
+ assert error.retryable is False
+ assert "super-secret" not in error.message
+
+
+async def test_ipv6_endpoint_in_error_text_keeps_one_sanitized_terminal() -> None:
+ def handler(_: httpx.Request) -> httpx.Response:
+ return httpx.Response(
+ 502,
+ text="upstream http://[::1]:8080/v1 refused",
+ )
+
+ async with httpx.AsyncClient(transport=httpx.MockTransport(handler)) as client:
+ events = await _events(OpenAIChatAdapter(client), _request("openai_chat"))
+
+ assert len([event for event in events if isinstance(event, ProviderError)]) == 1
+ error = events[-1]
+ assert isinstance(error, ProviderError)
+ assert error.kind == "server"
+ assert error.retryable is True
+ assert "http://[::1]:8080/v1" in error.message
+
+
+async def test_error_body_reader_applies_a_byte_cap() -> None:
+ response = httpx.Response(500, content=b"x" * 70_000)
+
+ body = await read_response_body(response, CancelToken(), max_bytes=64 * 1024)
+
+ assert body is not None
+ assert len(body.encode()) == 64 * 1024
+
+
+class _StalledStream(httpx.AsyncByteStream):
+ def __init__(self, first_chunk: bytes | None = None) -> None:
+ self.started = asyncio.Event()
+ self.release = asyncio.Event()
+ self.closed = asyncio.Event()
+ self.first_chunk = first_chunk or b'data: {"choices":[{"delta":{"content":"partial"}}]}\n\n'
+
+ async def __aiter__(self):
+ self.started.set()
+ yield self.first_chunk
+ await self.release.wait()
+
+ async def aclose(self) -> None:
+ self.closed.set()
+
+
+class _StalledFirstByteStream(httpx.AsyncByteStream):
+ def __init__(self) -> None:
+ self.started = asyncio.Event()
+ self.closed = asyncio.Event()
+ self.release = asyncio.Event()
+
+ async def __aiter__(self):
+ self.started.set()
+ await self.release.wait()
+ yield b"data: [DONE]\n\n"
+
+ async def aclose(self) -> None:
+ self.closed.set()
+
+
+class _NonCooperativeReadStream(httpx.AsyncByteStream):
+ def __init__(self) -> None:
+ self.started = asyncio.Event()
+ self.release = asyncio.Event()
+ self.cancel_seen = asyncio.Event()
+ self.cancel_count = 0
+ self.closed = asyncio.Event()
+
+ async def __aiter__(self):
+ self.started.set()
+ while not self.release.is_set():
+ try:
+ await self.release.wait()
+ except asyncio.CancelledError:
+ self.cancel_count += 1
+ self.cancel_seen.set()
+ yield b"data: [DONE]\n\n"
+
+ async def aclose(self) -> None:
+ self.closed.set()
+ self.release.set()
+
+
[email protected]("phase", ["open", "first_byte", "idle"])
+async def test_shared_driver_bounds_each_network_wait(
+ monkeypatch: pytest.MonkeyPatch,
+ phase: str,
+) -> None:
+ import core.agent_core.ai._common as common
+
+ monkeypatch.setattr(common, "CONNECT_TIMEOUT_S", 0.01)
+ monkeypatch.setattr(common, "TIME_TO_FIRST_BYTE_TIMEOUT_S", 0.01)
+ monkeypatch.setattr(common, "IDLE_CHUNK_TIMEOUT_S", 0.01)
+ opened = asyncio.Event()
+ first_byte_stream = _StalledFirstByteStream()
+ idle_stream = _StalledStream(
+ b'data: {"choices":[{"delta":{},"finish_reason":null}]}\n\n'
+ )
+
+ async def handler(_: httpx.Request) -> httpx.Response:
+ if phase == "open":
+ opened.set()
+ await asyncio.Event().wait()
+ if phase == "first_byte":
+ return httpx.Response(
+ 200,
+ headers={"content-type": "text/event-stream"},
+ stream=first_byte_stream,
+ )
+ return httpx.Response(
+ 200,
+ headers={"content-type": "text/event-stream"},
+ stream=idle_stream,
+ )
+
+ async with httpx.AsyncClient(transport=httpx.MockTransport(handler)) as client:
+ task = asyncio.create_task(
+ _events(OpenAIChatAdapter(client), _request("openai_chat"))
+ )
+ if phase == "open":
+ await opened.wait()
+ elif phase == "first_byte":
+ await first_byte_stream.started.wait()
+ else:
+ await idle_stream.started.wait()
+ events = await asyncio.wait_for(task, timeout=1)
+
+ error = events[-1]
+ assert isinstance(error, ProviderError)
+ assert error.kind == "network"
+ assert error.retryable is True
+ assert error.partial is None
+ if phase == "first_byte":
+ assert first_byte_stream.closed.is_set()
+ elif phase == "idle":
+ assert idle_stream.closed.is_set()
+
+
+async def test_non_cooperative_stream_cancellation_join_does_not_block_driver(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ import core.agent_core.ai._common as common
+
+ monkeypatch.setattr(common, "TIME_TO_FIRST_BYTE_TIMEOUT_S", 0.01)
+ monkeypatch.setattr(common, "CLEANUP_TIMEOUT_S", 0.01)
+ stream = _NonCooperativeReadStream()
+
+ def handler(_: httpx.Request) -> httpx.Response:
+ return httpx.Response(
+ 200,
+ headers={"content-type": "text/event-stream"},
+ stream=stream,
+ )
+
+ async with httpx.AsyncClient(transport=httpx.MockTransport(handler)) as client:
+ task = asyncio.create_task(_events(OpenAIChatAdapter(client), _request("openai_chat")))
+ await stream.started.wait()
+ events = await asyncio.wait_for(task, timeout=0.5)
+
+ error = events[-1]
+ assert isinstance(error, ProviderError)
+ assert error.kind == "network"
+ assert error.retryable is True
+ assert stream.cancel_seen.is_set()
+ assert stream.cancel_count == 1
+ assert stream.closed.is_set()
+
+
+async def test_cancellation_after_placeholder_slot_has_no_partial_message() -> None:
+ stream = _StalledStream(
+ b'data: {"type":"response.output_item.added","output_index":0,"item":{"type":"message","id":"msg_1"}}\n\n'
+ )
+
+ def handler(_: httpx.Request) -> httpx.Response:
+ return httpx.Response(
+ 200,
+ headers={"content-type": "text/event-stream"},
+ stream=stream,
+ )
+
+ cancel = CancelToken()
+ async with httpx.AsyncClient(transport=httpx.MockTransport(handler)) as client:
+ task = asyncio.create_task(_events(OpenAIResponsesAdapter(client), _request("openai_responses"), cancel))
+ await stream.started.wait()
+ cancel.cancel("cancelled after placeholder")
+ events = await asyncio.wait_for(task, timeout=1)
+
+ error = events[-1]
+ assert isinstance(error, ProviderError)
+ assert error.kind == "aborted"
+ assert error.partial is None
+
+
+class _StalledErrorBody(httpx.AsyncByteStream):
+ def __init__(self) -> None:
+ self.started = asyncio.Event()
+ self.release = asyncio.Event()
+ self.closed = asyncio.Event()
+
+ async def __aiter__(self):
+ self.started.set()
+ await self.release.wait()
+ yield b'{"error":{"message":"late"}}'
+
+ async def aclose(self) -> None:
+ self.closed.set()
+
+
+class _ErrorBodyReadFailure(httpx.AsyncByteStream):
+ def __init__(self) -> None:
+ self.started = asyncio.Event()
+ self.closed = asyncio.Event()
+
+ async def __aiter__(self):
+ self.started.set()
+ raise OSError("error body read failed")
+ yield b""
+
+ async def aclose(self) -> None:
+ self.closed.set()
+
+
+async def test_redirect_error_body_read_failure_is_terminal_invalid_request(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ import core.agent_core.ai._common as common
+
+ monkeypatch.setattr(common, "TIME_TO_FIRST_BYTE_TIMEOUT_S", 0.01)
+ stream = _ErrorBodyReadFailure()
+
+ def handler(_: httpx.Request) -> httpx.Response:
+ return httpx.Response(307, stream=stream)
+
+ async with httpx.AsyncClient(transport=httpx.MockTransport(handler)) as client:
+ events = await _events(OpenAIChatAdapter(client), _request("openai_chat"))
+
+ error = events[-1]
+ assert isinstance(error, ProviderError)
+ assert error.kind == "invalid_request"
+ assert error.status == 307
+ assert error.retryable is False
+
+
+class _StalledLoader(MediaLoader):
+ def __init__(self) -> None:
+ self.started = asyncio.Event()
+ self.release = asyncio.Event()
+
+ async def load(self, media_token: str) -> tuple[bytes, str]:
+ del media_token
+ self.started.set()
+ await self.release.wait()
+ return b"snapshot", "image/png"
+
+
+class _StalledResolver:
+ def __init__(self) -> None:
+ self.started = asyncio.Event()
+ self.release = asyncio.Event()
+
+ async def __call__(self, headers: Mapping[str, str]) -> Origin | None:
+ del headers
+ self.started.set()
+ await self.release.wait()
+ return Origin("served", "openai_chat", "served-model")
+
+
+class _CloseFailStream(httpx.AsyncByteStream):
+ def __init__(self, body: bytes) -> None:
+ self.body = body
+
+ async def __aiter__(self):
+ yield self.body
+
+ async def aclose(self) -> None:
+ raise OSError("close failed")
+
+
+class _TrackCloseStream(httpx.AsyncByteStream):
+ def __init__(self, body: bytes) -> None:
+ self.body = body
+ self.closed = asyncio.Event()
+
+ async def __aiter__(self):
+ yield self.body
+
+ async def aclose(self) -> None:
+ self.closed.set()
+
+
[email protected]("protocol", ["anthropic", "openai_chat", "openai_responses"])
[email protected]("completion", ["same_cycle", "during_join", "detached"])
+async def test_cancelled_header_arrival_disposes_the_unclaimed_response(
+ monkeypatch: pytest.MonkeyPatch, protocol: str, completion: str,
+) -> None:
+ monkeypatch.setattr(common_module, "CLEANUP_TIMEOUT_S", 0.01)
+ cancel = CancelToken()
+ started = asyncio.Event()
+ release = asyncio.Event()
+ stream = _TrackCloseStream(b"")
+
+ async def handler(_: httpx.Request) -> httpx.Response:
+ started.set()
+ if completion == "same_cycle":
+ cancel.cancel("header race")
+ else:
+ try:
+ await asyncio.Event().wait()
+ except asyncio.CancelledError:
+ if completion == "detached":
+ await release.wait()
+ return httpx.Response(200, stream=stream)
+
+ try:
+ async with httpx.AsyncClient(transport=httpx.MockTransport(handler)) as client:
+ task = asyncio.create_task(_events(adapter_class(protocol)(client), _request(protocol), cancel))
+ await started.wait()
+ cancel.cancel("header race")
+ events = await asyncio.wait_for(task, 1)
+ assert len(events) == 1
+ assert isinstance(events[0], ProviderError)
+ assert events[0].kind == "aborted"
+ release.set()
+ await asyncio.wait_for(stream.closed.wait(), 1)
+ finally:
+ release.set()
+ await stream.aclose()
+
+
+class _StalledCloseStream(httpx.AsyncByteStream):
+ def __init__(self, body: bytes) -> None:
+ self.body = body
+ self.started = asyncio.Event()
+ self.release = asyncio.Event()
+
+ async def __aiter__(self):
+ yield self.body
+
+ async def aclose(self) -> None:
+ self.started.set()
+ await self.release.wait()
+
+
+class _DelayedReadErrorStream(httpx.AsyncByteStream):
+ def __init__(self, first_chunk: bytes, order: list[str]) -> None:
+ self.first_chunk = first_chunk
+ self.order = order
+ self.read_started = asyncio.Event()
+ self.release = asyncio.Event()
+
+ async def __aiter__(self):
+ yield self.first_chunk
+ self.read_started.set()
+ await self.release.wait()
+ raise OSError("delayed transport read failed")
+
+ async def aclose(self) -> None:
+ self.order.append("close")
+
+
+class _StalledCloseFailStream(httpx.AsyncByteStream):
+ def __init__(self) -> None:
+ self.started = asyncio.Event()
+ self.release = asyncio.Event()
+
+ async def __aiter__(self):
+ self.started.set()
+ await self.release.wait()
+ yield b""
+
+ async def aclose(self) -> None:
+ raise OSError("close failed while cancelled")
+
+
+class _CancelAfterEofCloseFailStream(httpx.AsyncByteStream):
+ def __init__(self, body: bytes, cancel: CancelToken) -> None:
+ self.body = body
+ self.cancel = cancel
+
+ async def __aiter__(self):
+ yield self.body
+ self.cancel.cancel("cancelled after stream EOF")
+
+ async def aclose(self) -> None:
+ raise OSError("close failed after cancellation")
+
+
+_CANCELLATION_CASES = (
+ (AnthropicAdapter, "anthropic", 'data: {"type":"content_block_delta","index":0,"delta":{"type":"text_delta","text":"partial"}}\n\n'),
+ (OpenAIChatAdapter, "openai_chat", 'data: {"choices":[{"delta":{"content":"partial"},"finish_reason":null}]}\n\n'),
+ (OpenAIResponsesAdapter, "openai_responses", 'data: {"type":"response.output_text.delta","delta":"partial"}\n\n'),
+)
+
+
[email protected](("adapter_type", "protocol", "stream_body"), _CANCELLATION_CASES)
[email protected]("phase", ["open", "stream", "error_body", "media_load"])
+async def test_all_adapters_cancel_at_every_http_lifecycle_phase(
+ adapter_type: Any,
+ protocol: str,
+ stream_body: str,
+ phase: str,
+) -> None:
+ started = asyncio.Event()
+ stalled_stream = _StalledStream(stream_body.encode())
+ stalled_body = _StalledErrorBody()
+ stalled_loader = _StalledLoader()
+
+ async def handler(_: httpx.Request) -> httpx.Response:
+ if phase == "open":
+ started.set()
+ await asyncio.Event().wait()
+ if phase == "stream":
+ return httpx.Response(
+ 200,
+ headers={"content-type": "text/event-stream"},
+ stream=stalled_stream,
+ )
+ if phase == "error_body":
+ return httpx.Response(500, stream=stalled_body)
+ return httpx.Response(
+ 200,
+ headers={"content-type": "text/event-stream"},
+ text=stream_body,
+ )
+
+ cancel = CancelToken()
+ if phase == "media_load":
+ request = _request(
+ protocol,
+ messages=(UserMessage((ImageBlock("image/png", "media-1", "image.png"),)),),
+ supports_images=True,
+ )
+ else:
+ request = _request(protocol)
+ async with httpx.AsyncClient(transport=httpx.MockTransport(handler)) as client:
+ adapter = adapter_type(
+ client,
+ media_loader=stalled_loader if phase == "media_load" else None,
+ )
+ task = asyncio.create_task(_events(adapter, request, cancel))
+ if phase == "open":
+ await started.wait()
+ elif phase == "stream":
+ await stalled_stream.started.wait()
+ elif phase == "error_body":
+ await stalled_body.started.wait()
+ else:
+ await stalled_loader.started.wait()
+ cancel.cancel(f"cancelled during {phase}")
+ events = await asyncio.wait_for(task, timeout=1)
+
+ assert isinstance(events[-1], ProviderError)
+ assert events[-1].kind == "aborted"
+ if phase == "stream":
+ assert stalled_stream.closed.is_set()
+ elif phase == "error_body":
+ assert stalled_body.closed.is_set()
+
+
[email protected](("adapter_type", "protocol", "stream_body"), _CANCELLATION_CASES)
+async def test_all_adapters_cancel_during_served_hop_resolution(
+ adapter_type: Any,
+ protocol: str,
+ stream_body: str,
+) -> None:
+ resolver = _StalledResolver()
+
+ def handler(_: httpx.Request) -> httpx.Response:
+ return httpx.Response(
+ 200,
+ headers={"content-type": "text/event-stream"},
+ text=stream_body,
+ )
+
+ cancel = CancelToken()
+ async with httpx.AsyncClient(transport=httpx.MockTransport(handler)) as client:
+ adapter = adapter_type(client, served_hop_resolver=resolver, gateway=True)
+ task = asyncio.create_task(_events(adapter, _request(protocol), cancel))
+ await resolver.started.wait()
+ cancel.cancel("cancelled during served-hop resolution")
+ events = await asyncio.wait_for(task, timeout=1)
+
+ assert len(events) == 1
+ assert isinstance(events[0], ProviderError)
+ assert events[0].kind == "aborted"
+
+
[email protected]("protocol", ["anthropic", "openai_chat", "openai_responses"])
[email protected](("status", "kind", "retryable"), [
+ (302, "invalid_request", False), (401, "auth", False), (403, "auth", False),
+ (429, "rate_limit", True), (503, "server", True),
+])
[email protected]("broken_body", [False, True])
+async def test_http_error_classification_precedes_served_hop_resolution(
+ protocol: str, status: int, kind: str, retryable: bool, broken_body: bool,
+) -> None:
+ # A resolver failure must not replace an already-known HTTP error. This
+ # also protects status/Retry-After when the error body itself cannot be read.
+ resolver_calls = []
+ closed = []
+
+ async def resolver(headers: Mapping[str, str]) -> Origin | None:
+ resolver_calls.append(headers)
+ raise RuntimeError("served-hop resolution failed")
+
+ class Body(httpx.AsyncByteStream):
+ async def __aiter__(self):
+ if broken_body:
+ raise OSError("body read failed")
+ yield b'{"error":{"message":"upstream unavailable"}}'
+
+ async def aclose(self) -> None:
+ closed.append(True)
+
+ async with httpx.AsyncClient(transport=httpx.MockTransport(
+ lambda _: httpx.Response(status, headers={"retry-after": "7"}, stream=Body()),
+ )) as client:
+ events = await _events(
+ adapter_class(protocol)(client, served_hop_resolver=resolver, gateway=True), _request(protocol),
+ )
+ assert len(events) == 1
+ error = events[0]
+ assert isinstance(error, ProviderError)
+ assert (error.kind, error.status, error.retryable) == (kind, status, retryable)
+ assert error.retry_after_s == 7
+ assert resolver_calls == []
+ assert closed
+
+
[email protected](("adapter_type", "protocol", "body"), [
+ (
+ AnthropicAdapter,
+ "anthropic",
+ (
+ 'data: {"type":"message_delta","delta":{"stop_reason":"end_turn"}}\n\n'
+ 'data: {"type":"message_stop"}\n\n'
+ ),
+ ),
+ (
+ OpenAIChatAdapter,
+ "openai_chat",
+ 'data: [DONE]\n\n',
+ ),
+ (
+ OpenAIResponsesAdapter,
+ "openai_responses",
+ 'data: {"type":"response.completed","response":{"status":"completed"}}\n\n',
+ ),
+])
+async def test_close_failure_cannot_emit_a_second_terminal_event(
+ adapter_type: Any,
+ protocol: str,
+ body: str,
+) -> None:
+ def handler(_: httpx.Request) -> httpx.Response:
+ return httpx.Response(
+ 200,
+ headers={"content-type": "text/event-stream"},
+ stream=_CloseFailStream(body.encode()),
+ )
+
+ async with httpx.AsyncClient(transport=httpx.MockTransport(handler)) as client:
+ events = await _events(adapter_type(client), _request(protocol))
+
+ terminals = [event for event in events if isinstance(event, (Done, ProviderError))]
+ assert len(terminals) == 1
+
+
+async def test_consumer_close_suppresses_response_close_failure() -> None:
+ body = b'data: {"choices":[{"delta":{"content":"partial"}}]}\n\n'
+
+ def handler(_: httpx.Request) -> httpx.Response:
+ return httpx.Response(
+ 200,
+ headers={"content-type": "text/event-stream"},
+ stream=_CloseFailStream(body),
+ )
+
+ async with httpx.AsyncClient(transport=httpx.MockTransport(handler)) as client:
+ stream = OpenAIChatAdapter(client).stream(_request("openai_chat"), CancelToken())
+ first = await anext(stream)
+ assert isinstance(first, TextDelta)
+ await stream.aclose()
+
+
+ ("adapter_type", "protocol", "body"),
+ [
+ (
+ AnthropicAdapter,
+ "anthropic",
+ b'data: {"type":"message_delta","delta":{"stop_reason":"end_turn"}}\n\n'
+ b'data: {"type":"message_stop"}\n\n',
+ ),
+ (
+ OpenAIChatAdapter,
+ "openai_chat",
+ b'data: {"choices":[{"delta":{},"finish_reason":"stop"}]}\n\n'
+ b'data: [DONE]\n\n',
+ ),
+ (
+ OpenAIResponsesAdapter,
+ "openai_responses",
+ b'data: {"type":"response.completed","response":{"status":"completed"}}\n\n',
+ ),
+ ],
+)
+async def test_stalled_response_close_is_bounded(
+ monkeypatch: pytest.MonkeyPatch,
+ adapter_type: Any,
+ protocol: str,
+ body: bytes,
+) -> None:
+ import core.agent_core.ai._common as common
+
+ monkeypatch.setattr(common, "CLEANUP_TIMEOUT_S", 0.01)
+ stream = _StalledCloseStream(body)
+
+ def handler(_: httpx.Request) -> httpx.Response:
+ return httpx.Response(
+ 200,
+ headers={"content-type": "text/event-stream"},
+ stream=stream,
+ )
+
+ async with httpx.AsyncClient(transport=httpx.MockTransport(handler)) as client:
+ events = await asyncio.wait_for(
+ _events(adapter_type(client), _request(protocol)),
+ timeout=1,
+ )
+
+ assert isinstance(events[-1], Done)
+ assert stream.started.is_set()
+
+
+ ("adapter_type", "protocol", "body"),
+ [
+ (
+ AnthropicAdapter,
+ "anthropic",
+ b'data: {"type":"message_delta","delta":{"stop_reason":"end_turn"}}\n\n'
+ b'data: {"type":"message_stop"}\n\n',
+ ),
+ (
+ OpenAIChatAdapter,
+ "openai_chat",
+ b'data: {"choices":[{"delta":{},"finish_reason":"stop"}]}\n\n'
+ b'data: [DONE]\n\n',
+ ),
+ (
+ OpenAIResponsesAdapter,
+ "openai_responses",
+ b'data: {"type":"response.completed","response":{"status":"completed"}}\n\n',
+ ),
+ ],
+)
+async def test_cancellation_during_response_cleanup_is_preserved(
+ adapter_type: Any,
+ protocol: str,
+ body: bytes,
+) -> None:
+ stream = _StalledCloseStream(body)
+
+ def handler(_: httpx.Request) -> httpx.Response:
+ return httpx.Response(
+ 200,
+ headers={"content-type": "text/event-stream"},
+ stream=stream,
+ )
+
+ async with httpx.AsyncClient(transport=httpx.MockTransport(handler)) as client:
+ task = asyncio.create_task(_events(adapter_type(client), _request(protocol)))
+ await stream.started.wait()
+ task.cancel()
+ with pytest.raises(asyncio.CancelledError):
+ await task
+
+
+ ("adapter_type", "protocol", "status", "kind", "retryable"),
+ [
+ (AnthropicAdapter, "anthropic", 401, "auth", False),
+ (OpenAIChatAdapter, "openai_chat", 401, "auth", False),
+ (OpenAIResponsesAdapter, "openai_responses", 401, "auth", False),
+ (AnthropicAdapter, "anthropic", 429, "rate_limit", True),
+ (OpenAIChatAdapter, "openai_chat", 429, "rate_limit", True),
+ (OpenAIResponsesAdapter, "openai_responses", 429, "rate_limit", True),
+ ],
+)
+async def test_error_body_read_failure_preserves_http_classification(
+ adapter_type: Any,
+ protocol: str,
+ status: int,
+ kind: str,
+ retryable: bool,
+) -> None:
+ stream = _ErrorBodyReadFailure()
+
+ def handler(_: httpx.Request) -> httpx.Response:
+ return httpx.Response(
+ status,
+ headers={"Retry-After": "7"},
+ stream=stream,
+ )
+
+ async with httpx.AsyncClient(transport=httpx.MockTransport(handler)) as client:
+ events = await _events(adapter_type(client), _request(protocol))
+
+ error = events[-1]
+ assert isinstance(error, ProviderError)
+ assert error.kind == kind
+ assert error.retryable is retryable
+ assert error.status == status
+ assert error.retry_after_s == 7
+ assert stream.closed.is_set()
+
+
+async def test_oversized_sse_pending_line_is_terminal_malformed_error(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ monkeypatch.setattr(sse_module, "DEFAULT_MAX_PENDING_LINE_SIZE", 8)
+
+ def handler(_: httpx.Request) -> httpx.Response:
+ return httpx.Response(
+ 200,
+ headers={"content-type": "text/event-stream"},
+ text="data: too-large-without-a-line-ending",
+ )
+
+ async with httpx.AsyncClient(transport=httpx.MockTransport(handler)) as client:
+ events = await _events(OpenAIChatAdapter(client), _request("openai_chat"))
+
+ error = events[-1]
+ assert isinstance(error, ProviderError)
+ assert error.kind == "invalid_request"
+ assert error.retryable is False
+ assert "SSE" in error.message
+
+
+ ("adapter_type", "protocol", "body"),
+ [
+ (
+ AnthropicAdapter,
+ "anthropic",
+ b'data: {"type":"message_delta","delta":{"stop_reason":"end_turn"}}\n\n'
+ b'data: {"type":"message_stop"}\n\n',
+ ),
+ (
+ OpenAIChatAdapter,
+ "openai_chat",
+ b'data: {"choices":[{"delta":{},"finish_reason":"stop"}]}\n\n'
+ b'data: [DONE]\n\n',
+ ),
+ (
+ OpenAIResponsesAdapter,
+ "openai_responses",
+ b'data: {"type":"response.completed","response":{"status":"completed"}}\n\n',
+ ),
+ ],
+)
+async def test_consumer_close_after_terminal_closes_response(
+ adapter_type: Any,
+ protocol: str,
+ body: bytes,
+) -> None:
+ stream = _TrackCloseStream(body)
+
+ def handler(_: httpx.Request) -> httpx.Response:
+ return httpx.Response(
+ 200,
+ headers={"content-type": "text/event-stream"},
+ stream=stream,
+ )
+
+ async with httpx.AsyncClient(transport=httpx.MockTransport(handler)) as client:
+ response_stream = adapter_type(client).stream(_request(protocol), CancelToken())
+ while not isinstance((event := await anext(response_stream)), (Done, ProviderError)):
+ pass
+ await response_stream.aclose()
+
+ assert stream.closed.is_set()
+
+
+async def test_task_cancellation_is_not_replaced_by_response_close_failure() -> None:
+ stream = _StalledCloseFailStream()
+
+ def handler(_: httpx.Request) -> httpx.Response:
+ return httpx.Response(
+ 200,
+ headers={"content-type": "text/event-stream"},
+ stream=stream,
+ )
+
+ async with httpx.AsyncClient(transport=httpx.MockTransport(handler)) as client:
+ task = asyncio.create_task(_events(OpenAIChatAdapter(client), _request("openai_chat")))
+ await stream.started.wait()
+ task.cancel()
+ with pytest.raises(asyncio.CancelledError):
+ await task
+
+
+async def test_chat_post_loop_cancel_with_close_failure_emits_one_terminal_event() -> None:
+ cancel = CancelToken()
+ body = b'data: {"choices":[{"delta":{"content":"partial"}}]}\n\n'
+
+ def handler(_: httpx.Request) -> httpx.Response:
+ return httpx.Response(
+ 200,
+ headers={"content-type": "text/event-stream"},
+ stream=_CancelAfterEofCloseFailStream(body, cancel),
+ )
+
+ async with httpx.AsyncClient(transport=httpx.MockTransport(handler)) as client:
+ events = await _events(OpenAIChatAdapter(client), _request("openai_chat"), cancel)
+
+ terminals = [event for event in events if isinstance(event, (Done, ProviderError))]
+ assert len(terminals) == 1
+ assert isinstance(terminals[0], ProviderError)
+ assert terminals[0].kind == "aborted"
+
+
+_DELAYED_READ_ERROR_CASES = (
+ (
+ AnthropicAdapter,
+ "anthropic",
+ b'data: {"type":"content_block_start","index":0,"content_block":{"type":"text"}}\n\n'
+ b'data: {"type":"content_block_delta","index":0,"delta":{"type":"text_delta","text":"partial"}}\n\n',
+ ),
+ (
+ OpenAIChatAdapter,
+ "openai_chat",
+ b'data: {"choices":[{"delta":{"content":"partial"},"finish_reason":null}]}\n\n',
+ ),
+ (
+ OpenAIResponsesAdapter,
+ "openai_responses",
+ b'data: {"type":"response.output_item.added","output_index":0,"item":{"type":"message","id":"msg_1"}}\n\n'
+ b'data: {"type":"response.output_text.delta","output_index":0,"delta":"partial"}\n\n',
+ ),
+)
+
+
[email protected](("adapter_type", "protocol", "first_chunk"), _DELAYED_READ_ERROR_CASES)
+async def test_delayed_transport_read_emits_terminal_before_close(
+ adapter_type: Any,
+ protocol: str,
+ first_chunk: bytes,
+) -> None:
+ order: list[str] = []
+ stream = _DelayedReadErrorStream(first_chunk, order)
+
+ def handler(_: httpx.Request) -> httpx.Response:
+ return httpx.Response(
+ 200,
+ headers={"content-type": "text/event-stream"},
+ stream=stream,
+ )
+
+ events: list[Any] = []
+
+ async def collect() -> None:
+ async for event in adapter.stream(_request(protocol), CancelToken()):
+ events.append(event)
+ if isinstance(event, ProviderError):
+ order.append("terminal")
+
+ async with httpx.AsyncClient(transport=httpx.MockTransport(handler)) as client:
+ adapter = adapter_type(client)
+ task = asyncio.create_task(collect())
+ await stream.read_started.wait()
+ stream.release.set()
+ await task
+ await adapter.aclose()
+
+ assert order == ["terminal", "close"]
+ terminals = [event for event in events if isinstance(event, (Done, ProviderError))]
+ assert len(terminals) == 1
+ assert isinstance(terminals[0], ProviderError)
+ assert terminals[0].kind == "network"
+ assert terminals[0].retryable is False
+
+
+_WIRE_EVENT_CASES = (
+ (
+ AnthropicAdapter,
+ "anthropic",
+ (
+ 'data: {"type":"ping"}\n\n'
+ 'data: {"type":"message_delta","delta":{"stop_reason":"end_turn"}}\n\n'
+ 'data: {"type":"message_stop"}\n\n'
+ ),
+ "done",
+ "stop",
+ None,
+ None,
+ ),
+ (
+ AnthropicAdapter,
+ "anthropic",
+ (
+ 'data: {"type":"message_start","message":{"usage":{"input_tokens":4}}}\n\n'
+ 'data: {"type":"error","error":{"type":"overloaded_error","message":"busy"}}\n\n'
+ ),
+ "error",
+ None,
+ "overloaded",
+ True,
+ ),
+ (
+ AnthropicAdapter,
+ "anthropic",
+ 'event: error\ndata: {"type":"error","error":{"type":"authentication_error","message":"bad key"}}\n\n',
+ "error",
+ None,
+ "auth",
+ False,
+ ),
+ (
+ AnthropicAdapter,
+ "anthropic",
+ (
+ 'data: {"type":"message_start","message":{"usage":{"input_tokens":4}}}\n\n'
+ 'data: {"type":"content_block_start","index":0,"content_block":{"type":"text"}}\n\n'
+ 'data: {"type":"content_block_delta","index":0,"delta":{"type":"text_delta","text":"partial"}}\n\n'
+ 'data: {"type":"error","error":{"type":"api_error","message":"failed"}}\n\n'
+ ),
+ "error",
+ None,
+ "server",
+ True,
+ ),
+ (
+ AnthropicAdapter,
+ "anthropic",
+ 'data: {"type":"content_block_start","index":0,"content_block":{"type":"tool_use","name":""}}\n\n',
+ "error",
+ None,
+ "invalid_request",
+ False,
+ ),
+ (
+ OpenAIChatAdapter,
+ "openai_chat",
+ 'data: {"error":{"type":"rate_limit_error","message":"slow down"}}\n\n',
+ "error",
+ None,
+ "rate_limit",
+ False,
+ ),
+ (
+ OpenAIChatAdapter,
+ "openai_chat",
+ 'data: {"error":{"type":"invalid_api_key","message":"bad key"}}\n\n',
+ "error",
+ None,
+ "auth",
+ False,
+ ),
+ (
+ OpenAIChatAdapter,
+ "openai_chat",
+ (
+ 'data: {"choices":[{"delta":{"function_call":{"name":"read"}}}]}\n\n'
+ 'data: {"choices":[{"delta":{"function_call":{"arguments":"{\\"path\\":"}}}]}\n\n'
+ 'data: {"choices":[{"delta":{"function_call":{"arguments":"\\"x\\"}"}},"finish_reason":"function_call"}]}\n\n'
+ "data: [DONE]\n\n"
+ ),
+ "done",
+ "tool_use",
+ None,
+ None,
+ ),
+ (
+ OpenAIChatAdapter,
+ "openai_chat",
+ 'data: {"choices":[{"delta":{"tool_calls":[{"index":0,"function":{"name":""}}]}}]}\n\n',
+ "error",
+ None,
+ "invalid_request",
+ False,
+ ),
+ (
+ OpenAIChatAdapter,
+ "openai_chat",
+ (
+ 'data: {"choices":[{"delta":{"content":"partial"}}]}\n\n'
+ 'data: {"error":{"type":"server_error","message":"failed"}}\n\n'
+ ),
+ "error",
+ None,
+ "server",
+ True,
+ ),
+ (
+ OpenAIResponsesAdapter,
+ "openai_responses",
+ (
+ 'data: {"type":"response.output_item.added","output_index":0,"item":{"type":"function_call","id":"fc_1","call_id":"call_1","name":"read"}}\n\n'
+ 'data: {"type":"response.failed","response":{"status":"failed","error":{"code":"server_error","message":"busy"},"usage":{"input_tokens":2}}}\n\n'
+ ),
+ "error",
+ None,
+ "server",
+ True,
+ ),
+ (
+ OpenAIResponsesAdapter,
+ "openai_responses",
+ (
+ 'data: {"type":"response.incomplete","response":{"status":"incomplete","error":{"code":"context_length_exceeded","message":"too long"},"usage":{"input_tokens":2}}}\n\n'
+ ),
+ "error",
+ None,
+ "overflow",
+ True,
+ ),
+ (
+ OpenAIResponsesAdapter,
+ "openai_responses",
+ 'data: {"type":"response.output_item.added","output_index":0,"item":{"type":"function_call","name":""}}\n\n',
+ "error",
+ None,
+ "invalid_request",
+ False,
+ ),
+ (
+ OpenAIResponsesAdapter,
+ "openai_responses",
+ 'data: {"type":"error","error":{"code":"permission","message":"denied"}}\n\n',
+ "error",
+ None,
+ "auth",
+ False,
+ ),
+)
+
+
+_WIRE_SHAPE_CASES = (
+ (
+ AnthropicAdapter,
+ "anthropic",
+ 'data: {"type":"content_block_start","index":0,"content_block":{"type":"thinking","signature":7}}\n\n',
+ ),
+ (
+ OpenAIChatAdapter,
+ "openai_chat",
+ 'data: {"choices":[{"delta":{},"finish_reason":"stop"}],"usage":[]}\n\n',
+ ),
+ (
+ OpenAIResponsesAdapter,
+ "openai_responses",
+ 'data: {"type":"response.completed","response":{"status":"completed","usage":[]}}\n\n',
+ ),
+ (
+ AnthropicAdapter,
+ "anthropic",
+ (
+ 'data: {"type":"content_block_start","index":0,'
+ '"content_block":{"type":7}}\n\n'
+ 'data: {"type":"message_delta","delta":{"stop_reason":"end_turn"}}\n\n'
+ 'data: {"type":"message_stop"}\n\n'
+ ),
+ ),
+ (
+ AnthropicAdapter,
+ "anthropic",
+ (
+ 'data: {"type":"content_block_start","index":0,'
+ '"content_block":{"type":"text"}}\n\n'
+ 'data: {"type":"content_block_delta","index":0,"delta":{"type":7}}\n\n'
+ ),
+ ),
+ (
+ AnthropicAdapter,
+ "anthropic",
+ (
+ 'data: {"type":"message_delta","delta":{"stop_reason":7}}\n\n'
+ 'data: {"type":"message_stop"}\n\n'
+ ),
+ ),
+ (
+ AnthropicAdapter,
+ "anthropic",
+ (
+ 'data: {"type":"content_block_start","index":0,'
+ '"content_block":{"type":"tool_use","id":7,"name":"read"}}\n\n'
+ ),
+ ),
+ (
+ OpenAIChatAdapter,
+ "openai_chat",
+ (
+ 'data: {"choices":[{"delta":{"tool_calls":[{"index":0,"function":"read"}]},'
+ '"finish_reason":"tool_calls"}]}\n\n'
+ ),
+ ),
+ (
+ OpenAIChatAdapter,
+ "openai_chat",
+ (
+ 'data: {"choices":[{"delta":{"tool_calls":[{"index":0,"id":7,'
+ '"function":{"name":"read","arguments":"{}"}}]},"finish_reason":"tool_calls"}]}\n\n'
+ ),
+ ),
+ (
+ OpenAIChatAdapter,
+ "openai_chat",
+ 'data: {"choices":[{"delta":{"reasoning_content":7},"finish_reason":"stop"}]}\n\n',
+ ),
+ (
+ OpenAIChatAdapter,
+ "openai_chat",
+ 'data: {"choices":[{"delta":{"reasoning_details":{}},"finish_reason":"stop"}]}\n\n',
+ ),
+ (
+ OpenAIResponsesAdapter,
+ "openai_responses",
+ 'data: {"type":"response.completed","response":{"status":5}}\n\n',
+ ),
+ (
+ OpenAIResponsesAdapter,
+ "openai_responses",
+ (
+ 'data: {"type":"response.completed","response":'
+ '{"status":"completed","error":"boom"}}\n\n'
+ ),
+ ),
+ (
+ OpenAIResponsesAdapter,
+ "openai_responses",
+ (
+ 'data: {"type":"response.incomplete","response":'
+ '{"status":"incomplete","incomplete_details":"max_output_tokens"}}\n\n'
+ ),
+ ),
+ *(
+ (adapter, protocol, f"data: {json.dumps(frame)}\n\n")
+ for adapter, protocol, frame in [
+ (AnthropicAdapter, "anthropic", {"type": "error", "error": []}),
+ (AnthropicAdapter, "anthropic", {"type": "error", "error": {"message": 7}}),
+ (OpenAIChatAdapter, "openai_chat", {"choices": [{"usage": [], "finish_reason": "stop"}]}),
+ (OpenAIChatAdapter, "openai_chat", {"choices": [{"delta": {"reasoning": 2}, "finish_reason": "stop"}]}),
+ (OpenAIChatAdapter, "openai_chat", {"choices": [{"delta": {"reasoning_text": 2}, "finish_reason": "stop"}]}),
+ (OpenAIChatAdapter, "openai_chat", {"choices": [{"delta": {"tool_calls": [{"index": "0", "function": {"name": "read"}}]}, "finish_reason": "tool_calls"}]}),
+ (OpenAIResponsesAdapter, "openai_responses", {"type": "response.created", "response": {"status": 2}}),
+ (OpenAIResponsesAdapter, "openai_responses", {"type": "error", "error": {"code": []}}),
+ (OpenAIResponsesAdapter, "openai_responses", {"type": "error", "error": {"type": 7}}),
+ (OpenAIResponsesAdapter, "openai_responses", {"type": "response.output_item.added", "item": {"type": 2}}),
+ (OpenAIResponsesAdapter, "openai_responses", {"type": "response.output_item.done", "item": {"type": "message", "content": {}}}),
+ (OpenAIResponsesAdapter, "openai_responses", {"type": "response.function_call_arguments.delta", "item_id": 2, "delta": "{}"}),
+ (OpenAIResponsesAdapter, "openai_responses", {"type": "response.failed", "error": {"message": 7, "code": []}}),
+ (OpenAIResponsesAdapter, "openai_responses", {"type": "response.failed", "response": {"error": {"message": 7}}}),
+ (OpenAIResponsesAdapter, "openai_responses", {"type": "response.failed", "response": {"error": [], "usage": {"input_tokens": 4}}}),
+ (OpenAIResponsesAdapter, "openai_responses", {"type": "response.failed", "response": {"usage": []}}),
+ (OpenAIResponsesAdapter, "openai_responses", {"type": "response.incomplete", "response": {"status": "incomplete", "incomplete_details": {"reason": 2}}}),
+ ]
+ ),
+)
+
+
[email protected]("source", ["http", "named", "data"])
+ ("adapter_type", "protocol", "error", "kind"),
+ [
+ (AnthropicAdapter, "anthropic", {"type": "permission_error", "message": "denied"}, "auth"),
+ (OpenAIChatAdapter, "openai_chat", {"code": "invalid_api_key", "message": "denied"}, "auth"),
+ (OpenAIResponsesAdapter, "openai_responses", {"code": "server_error", "message": "busy"}, "server"),
+ ],
+)
+async def test_provider_error_envelope_is_classified_identically_from_every_source(
+ source: str, adapter_type: Any, protocol: str, error: dict[str, Any], kind: str,
+) -> None:
+ envelope = json.dumps({"type": "error", "error": error})
+ body = envelope if source == "http" else (
+ ("event: error\n" if source == "named" else "") + f"data: {envelope}\n\n"
+ )
+
+ def handler(_: httpx.Request) -> httpx.Response:
+ return httpx.Response(400 if source == "http" else 200, text=body)
+
+ async with httpx.AsyncClient(transport=httpx.MockTransport(handler)) as client:
+ events = await _events(adapter_type(client), _request(protocol))
+
+ assert len(events) == 1
+ assert isinstance(events[0], ProviderError)
+ assert events[0].kind == kind
+ assert events[0].retryable == (kind == "server")
+
+
+ ("adapter_type", "protocol", "body", "outcome", "stop_reason", "error_kind", "partial"),
+ _WIRE_EVENT_CASES,
+)
+async def test_wire_event_matrix_has_one_explicit_outcome(
+ adapter_type: Any,
+ protocol: str,
+ body: str,
+ outcome: str,
+ stop_reason: str | None,
+ error_kind: str | None,
+ partial: bool | None,
+) -> None:
+ def handler(_: httpx.Request) -> httpx.Response:
+ return httpx.Response(200, headers={"content-type": "text/event-stream"}, text=body)
+
+ async with httpx.AsyncClient(transport=httpx.MockTransport(handler)) as client:
+ events = await _events(adapter_type(client), _request(protocol))
+
+ terminals = [event for event in events if isinstance(event, (Done, ProviderError))]
+ assert len(terminals) == 1
+ terminal = terminals[0]
+ if outcome == "done":
+ assert isinstance(terminal, Done)
+ assert terminal.message.stop_reason == stop_reason
+ else:
+ assert isinstance(terminal, ProviderError)
+ assert terminal.kind == error_kind
+ if partial:
+ assert terminal.partial is not None
+ elif partial is False:
+ assert terminal.partial is None
+
+
[email protected](("adapter_type", "protocol", "body"), _WIRE_SHAPE_CASES)
+async def test_known_wire_fields_with_wrong_types_are_terminal_malformed(
+ adapter_type: Any,
+ protocol: str,
+ body: str,
+) -> None:
+ def handler(_: httpx.Request) -> httpx.Response:
+ return httpx.Response(200, headers={"content-type": "text/event-stream"}, text=body)
+
+ async with httpx.AsyncClient(transport=httpx.MockTransport(handler)) as client:
+ events = await _events(adapter_type(client), _request(protocol))
+
+ terminals = [event for event in events if isinstance(event, (Done, ProviderError))]
+ assert len(terminals) == 1
+ assert isinstance(terminals[0], ProviderError)
+ assert terminals[0].kind == "invalid_request"
+
+
+async def test_cancellation_during_a_stalled_read_ends_with_aborted_error() -> None:
+ stream = _StalledStream()
+
+ def handler(_: httpx.Request) -> httpx.Response:
+ return httpx.Response(200, headers={"content-type": "text/event-stream"}, stream=stream)
+
+ cancel = CancelToken()
+ async with httpx.AsyncClient(transport=httpx.MockTransport(handler)) as client:
+ task = asyncio.create_task(_events(OpenAIChatAdapter(client), _request("openai_chat"), cancel))
+ await stream.started.wait()
+ cancel.cancel("cancelled by test")
+ events = await asyncio.wait_for(task, timeout=1)
+
+ assert isinstance(events[-1], ProviderError)
+ assert events[-1].kind == "aborted"
+ assert not any(isinstance(event, Done) for event in events)
+
+
+async def test_cancellation_during_stream_open_ends_with_aborted_error() -> None:
+ started = asyncio.Event()
+
+ async def handler(_: httpx.Request) -> httpx.Response:
+ started.set()
+ await asyncio.Event().wait()
+ raise AssertionError("unreachable")
+
+ cancel = CancelToken()
+ async with httpx.AsyncClient(transport=httpx.MockTransport(handler)) as client:
+ task = asyncio.create_task(_events(OpenAIChatAdapter(client), _request("openai_chat"), cancel))
+ await started.wait()
+ cancel.cancel("cancelled while opening")
+ events = await asyncio.wait_for(task, timeout=1)
+
+ assert events == [
+ ProviderError(
+ kind="aborted",
+ message="cancelled while opening",
+ retryable=False,
+ )
+ ]
+
+
+ ("adapter_type", "protocol", "body"),
+ [
+ (
+ AnthropicAdapter,
+ "anthropic",
+ 'data: {"type":"content_block_start","index":0,"content_block":{"type":"text"}}\n\ndata: {"type":"content_block_delta","index":0,"delta":{"type":"text_delta","text":"partial"}}\n\n',
+ ),
+ (
+ OpenAIChatAdapter,
+ "openai_chat",
+ 'data: {"choices":[{"delta":{"content":"partial"},"finish_reason":null}]}\n\n',
+ ),
+ (
+ OpenAIResponsesAdapter,
+ "openai_responses",
+ 'data: {"type":"response.output_item.added","output_index":0,"item":{"type":"message","id":"msg_1"}}\n\n'
+ 'data: {"type":"response.output_text.delta","output_index":0,"delta":"partial"}\n\n',
+ ),
+ ],
+)
+async def test_eof_without_protocol_terminal_is_not_success(
+ adapter_type: Any,
+ protocol: str,
+ body: str,
+) -> None:
+ def handler(_: httpx.Request) -> httpx.Response:
+ return httpx.Response(200, headers={"content-type": "text/event-stream"}, text=body)
+
+ async with httpx.AsyncClient(transport=httpx.MockTransport(handler)) as client:
+ events = await _events(adapter_type(client), _request(protocol))
+
+ assert isinstance(events[-1], ProviderError)
+ assert events[-1].retryable is False
+ assert events[-1].partial is not None
+ assert not any(isinstance(event, Done) for event in events)
+
+
+async def test_empty_reasoning_slot_does_not_disable_network_retry() -> None:
+ stream = _CloseFailStream(
+ b'data: {"type":"response.output_item.added","output_index":0,"item":{"type":"reasoning","id":"rs_1"}}\n\n'
+ )
+
+ def handler(_: httpx.Request) -> httpx.Response:
+ return httpx.Response(
+ 200,
+ headers={"content-type": "text/event-stream"},
+ stream=stream,
+ )
+
+ async with httpx.AsyncClient(transport=httpx.MockTransport(handler)) as client:
+ events = await _events(OpenAIResponsesAdapter(client), _request("openai_responses"))
+
+ error = events[-1]
+ assert isinstance(error, ProviderError)
+ assert error.kind == "network"
+ assert error.retryable is True
+ assert error.partial is None
+
+
+async def test_adapter_error_redaction_preserves_json_classification() -> None:
+ body = '{"details":[{"url":"https://model.test/v1?project=secret"}]}'
+
+ def handler(_: httpx.Request) -> httpx.Response:
+ return httpx.Response(413, text=body)
+
+ request = ModelRequest(
+ endpoint=ModelEndpoint(
+ protocol="openai_chat",
+ base_url="https://user:[email protected]/v1?token=secret",
+ model_id="model-x",
+ token="token",
+ provider="openai",
+ ),
+ system="system",
+ messages=(UserMessage((TextBlock(text="hello"),)),),
+ tools=(),
+ max_tokens=128,
+ )
+ async with httpx.AsyncClient(transport=httpx.MockTransport(handler)) as client:
+ events = await _events(OpenAIChatAdapter(client), request)
+
+ error = events[-1]
+ assert isinstance(error, ProviderError)
+ assert error.kind == "overflow"
+ parsed = json.loads(error.message)
+ assert parsed["details"][0]["url"] == "https://model.test/v1"
+ assert "password" not in error.message
+ assert "project=secret" not in error.message
+
+
+ "body",
+ [
+ '{"error":{"message":"x-goog-api-key: google-secret"}}',
+ '{"error":{"x-goog-api-key":"google-secret"}}',
+ "provider failed: x-goog-api-key=google-secret",
+ ],
+)
+async def test_shared_error_parser_redacts_google_api_key(body: str) -> None:
+ def handler(_: httpx.Request) -> httpx.Response:
+ return httpx.Response(500, text=body)
+
+ async with httpx.AsyncClient(transport=httpx.MockTransport(handler)) as client:
+ events = await _events(OpenAIChatAdapter(client), _request("openai_chat"))
+
+ error = events[-1]
+ assert isinstance(error, ProviderError)
+ assert "google-secret" not in error.message
+
+
+ ("adapter_type", "protocol", "body"),
+ [
+ (
+ AnthropicAdapter,
+ "anthropic",
+ (
+ 'data: {"type":"message_start","message":{"usage":{"input_tokens":-1}}}\n\n'
+ 'data: {"type":"message_delta","delta":{"stop_reason":"end_turn"}}\n\n'
+ 'data: {"type":"message_stop"}\n\n'
+ ),
+ ),
+ (
+ OpenAIChatAdapter,
+ "openai_chat",
+ (
+ 'data: {"choices":[{"delta":{"content":"ok"},"finish_reason":"stop"}],'
+ '"usage":{"prompt_tokens":-1}}\n\n'
+ "data: [DONE]\n\n"
+ ),
+ ),
+ (
+ OpenAIResponsesAdapter,
+ "openai_responses",
+ (
+ 'data: {"type":"response.completed","response":{"status":"completed",'
+ '"output":[],"usage":{"input_tokens":"2"}}}\n\n'
+ ),
+ ),
+ ],
+)
+async def test_adapters_reject_malformed_present_usage_counters(
+ adapter_type: Any,
+ protocol: str,
+ body: str,
+) -> None:
+ def handler(_: httpx.Request) -> httpx.Response:
+ return httpx.Response(200, headers={"content-type": "text/event-stream"}, text=body)
+
+ async with httpx.AsyncClient(transport=httpx.MockTransport(handler)) as client:
+ events = await _events(adapter_type(client), _request(protocol))
+
+ error = events[-1]
+ assert isinstance(error, ProviderError)
+ assert error.kind == "invalid_request"
+ assert "usage" in error.message.lower()
+
+
+async def test_chat_requires_finish_reason_before_done_marker() -> None:
+ body = "data: [DONE]\n\n"
+
+ def handler(_: httpx.Request) -> httpx.Response:
+ return httpx.Response(200, headers={"content-type": "text/event-stream"}, text=body)
+
+ async with httpx.AsyncClient(transport=httpx.MockTransport(handler)) as client:
+ events = await _events(OpenAIChatAdapter(client), _request("openai_chat"))
+
+ assert isinstance(events[-1], ProviderError)
+ assert events[-1].kind == "network"
+ assert events[-1].retryable is True
+ assert events[-1].partial is None
+
+
+async def test_chat_prompt_feedback_without_candidates_is_incomplete() -> None:
+ body = (
+ 'data: {"promptFeedback":{"blockReason":"SAFETY"}}\n\n'
+ "data: [DONE]\n\n"
+ )
+
+ def handler(_: httpx.Request) -> httpx.Response:
+ return httpx.Response(200, headers={"content-type": "text/event-stream"}, text=body)
+
+ async with httpx.AsyncClient(transport=httpx.MockTransport(handler)) as client:
+ events = await _events(OpenAIChatAdapter(client), _request("openai_chat"))
+
+ error = events[-1]
+ assert isinstance(error, ProviderError)
+ assert error.kind == "network"
+ assert error.retryable is True
+ assert error.partial is None
+
+
+async def test_chat_finish_reason_can_terminate_at_eof_without_done_marker() -> None:
+ body = 'data: {"choices":[{"delta":{"content":"ok"},"finish_reason":"stop"}]}\n\n'
+
+ def handler(_: httpx.Request) -> httpx.Response:
+ return httpx.Response(200, headers={"content-type": "text/event-stream"}, text=body)
+
+ async with httpx.AsyncClient(transport=httpx.MockTransport(handler)) as client:
+ events = await _events(OpenAIChatAdapter(client), _request("openai_chat"))
+
+ assert isinstance(events[-1], Done)
+ assert events[-1].message.stop_reason == "stop"
+
+
+async def test_chat_max_tokens_maps_to_length() -> None:
+ body = (
+ 'data: {"choices":[{"delta":{"content":"partial"},"finish_reason":"max_tokens"}]}\n\n'
+ "data: [DONE]\n\n"
+ )
+
+ def handler(_: httpx.Request) -> httpx.Response:
+ return httpx.Response(200, headers={"content-type": "text/event-stream"}, text=body)
+
+ async with httpx.AsyncClient(transport=httpx.MockTransport(handler)) as client:
+ events = await _events(OpenAIChatAdapter(client), _request("openai_chat"))
+
+ final = events[-1]
+ assert isinstance(final, Done)
+ assert final.message.stop_reason == "length"
+
+
[email protected]("native_reason", ["safety", "recitation"])
+async def test_chat_native_safety_overrides_stop(native_reason: str) -> None:
+ body = (
+ 'data: {"choices":[{"delta":{"tool_calls":[{"index":0,"id":"call_1","function":{"name":"read","arguments":"{}"}}]},"finish_reason":null}]}\n\n'
+ f'data: {json.dumps({"choices": [{"delta": {}, "finish_reason": "stop", "native_finish_reason": native_reason}]})}\n\n'
+ "data: [DONE]\n\n"
+ )
+
+ def handler(_: httpx.Request) -> httpx.Response:
+ return httpx.Response(200, headers={"content-type": "text/event-stream"}, text=body)
+
+ async with httpx.AsyncClient(transport=httpx.MockTransport(handler)) as client:
+ events = await _events(OpenAIChatAdapter(client), _request("openai_chat"))
+
+ final = events[-1]
+ assert isinstance(final, Done)
+ assert final.message.stop_reason == "safety"
+ assert len(final.message.tool_calls) == 1
+
+
+async def test_chat_unknown_finish_reason_is_canonical_error() -> None:
+ body = 'data: {"choices":[{"delta":{},"finish_reason":"future_reason"}]}\n\ndata: [DONE]\n\n'
+
+ def handler(_: httpx.Request) -> httpx.Response:
+ return httpx.Response(200, headers={"content-type": "text/event-stream"}, text=body)
+
+ async with httpx.AsyncClient(transport=httpx.MockTransport(handler)) as client:
+ events = await _events(OpenAIChatAdapter(client), _request("openai_chat"))
+
+ assert isinstance(events[-1], Done)
+ assert events[-1].message.stop_reason == "error"
+
+
+ "content",
+ [
+ [7],
+ [{"type": "output_text", "text": 7}],
+ [{"type": "refusal", "refusal": 7}],
+ ],
+)
+async def test_responses_rejects_malformed_message_content_parts(content: list[Any]) -> None:
+ body = (
+ 'data: {"type":"response.output_item.done","output_index":0,'
+ + json.dumps(
+ {
+ "item": {
+ "type": "message",
+ "content": content,
+ }
+ },
+ ensure_ascii=False,
+ )[1:]
+ + "\n\n"
+ )
+
+ def handler(_: httpx.Request) -> httpx.Response:
+ return httpx.Response(200, headers={"content-type": "text/event-stream"}, text=body)
+
+ async with httpx.AsyncClient(transport=httpx.MockTransport(handler)) as client:
+ events = await _events(OpenAIResponsesAdapter(client), _request("openai_responses"))
+
+ error = events[-1]
+ assert isinstance(error, ProviderError)
+ assert error.kind == "invalid_request"
+ assert error.retryable is False
+
+
+async def test_responses_rejects_malformed_terminal_message_content() -> None:
+ body = (
+ 'data: {"type":"response.completed","response":{"status":"completed",'
+ '"output":[{"type":"message","content":[{"type":"output_text","text":7}]}]}}\n\n'
+ )
+
+ def handler(_: httpx.Request) -> httpx.Response:
+ return httpx.Response(200, headers={"content-type": "text/event-stream"}, text=body)
+
+ async with httpx.AsyncClient(transport=httpx.MockTransport(handler)) as client:
+ events = await _events(OpenAIResponsesAdapter(client), _request("openai_responses"))
+
+ error = events[-1]
+ assert isinstance(error, ProviderError)
+ assert error.kind == "invalid_request"
+ assert error.retryable is False
+
+
+async def test_anthropic_message_stop_without_reason_is_terminal_error() -> None:
+ body = 'data: {"type":"message_stop"}\n\n'
+
+ def handler(_: httpx.Request) -> httpx.Response:
+ return httpx.Response(200, headers={"content-type": "text/event-stream"}, text=body)
+
+ async with httpx.AsyncClient(transport=httpx.MockTransport(handler)) as client:
+ events = await _events(AnthropicAdapter(client), _request("anthropic"))
+
+ assert isinstance(events[-1], ProviderError)
+ assert events[-1].kind == "invalid_request"
+
+
+async def test_anthropic_stop_reason_allows_eof_without_message_stop_like_pi() -> None:
+ body = 'data: {"type":"message_delta","delta":{"stop_reason":"end_turn"}}\n\n'
+
+ def handler(_: httpx.Request) -> httpx.Response:
+ return httpx.Response(200, headers={"content-type": "text/event-stream"}, text=body)
+
+ async with httpx.AsyncClient(transport=httpx.MockTransport(handler)) as client:
+ events = await _events(AnthropicAdapter(client), _request("anthropic"))
+
+ final = events[-1]
+ assert isinstance(final, Done)
+ assert final.message.stop_reason == "stop"
+
+
+async def test_anthropic_message_start_requires_message_stop_even_with_stop_reason() -> None:
+ body = (
+ 'event: message_start\n'
+ 'data: {"type":"message_start","message":{"usage":{"input_tokens":7}}}\n\n'
+ 'event: message_delta\n'
+ 'data: {"type":"message_delta","delta":{"stop_reason":"end_turn"}}\n\n'
+ )
+
+ def handler(_: httpx.Request) -> httpx.Response:
+ return httpx.Response(200, headers={"content-type": "text/event-stream"}, text=body)
+
+ async with httpx.AsyncClient(transport=httpx.MockTransport(handler)) as client:
+ events = await _events(AnthropicAdapter(client), _request("anthropic"))
+
+ error = events[-1]
+ assert isinstance(error, ProviderError)
+ assert error.kind == "network"
+ assert error.retryable is True
+ assert error.partial is not None
+ assert error.partial.usage == Usage(input_tokens=7)
+
+
+async def test_anthropic_malformed_data_only_frame_is_ignored_like_pi() -> None:
+ body = (
+ "data: not-json\n\n"
+ 'event: message_delta\n'
+ 'data: {"type":"message_delta","delta":{"stop_reason":"end_turn"}}\n\n'
+ 'event: message_stop\n'
+ 'data: {"type":"message_stop"}\n\n'
+ )
+
+ def handler(_: httpx.Request) -> httpx.Response:
+ return httpx.Response(200, headers={"content-type": "text/event-stream"}, text=body)
+
+ async with httpx.AsyncClient(transport=httpx.MockTransport(handler)) as client:
+ events = await _events(AnthropicAdapter(client), _request("anthropic"))
+
+ assert isinstance(events[-1], Done)
+ assert events[-1].message.stop_reason == "stop"
+
+
+async def test_chat_refusal_stop_is_not_overwritten_by_later_stop_reason() -> None:
+ body = (
+ 'data: {"choices":[{"delta":{"refusal":"cannot help"},"finish_reason":null}]}\n\n'
+ 'data: {"choices":[{"delta":{},"finish_reason":"stop"}]}\n\n'
+ "data: [DONE]\n\n"
+ )
+
+ def handler(_: httpx.Request) -> httpx.Response:
+ return httpx.Response(200, headers={"content-type": "text/event-stream"}, text=body)
+
+ async with httpx.AsyncClient(transport=httpx.MockTransport(handler)) as client:
+ events = await _events(OpenAIChatAdapter(client), _request("openai_chat"))
+
+ assert isinstance(events[-1], Done)
+ assert events[-1].message.stop_reason == "refusal"
+
+
+async def test_responses_message_output_item_done_backfills_text() -> None:
+ body = (
+ 'data: {"type":"response.output_item.added","output_index":0,"item":{"type":"message","id":"msg_1"}}\n\n'
+ 'data: {"type":"response.output_item.done","output_index":0,"item":{"type":"message","id":"msg_1","content":[{"type":"output_text","text":"done"}]}}\n\n'
+ 'data: {"type":"response.completed","response":{"status":"completed"}}\n\n'
+ )
+
+ def handler(_: httpx.Request) -> httpx.Response:
+ return httpx.Response(200, headers={"content-type": "text/event-stream"}, text=body)
+
+ async with httpx.AsyncClient(transport=httpx.MockTransport(handler)) as client:
+ events = await _events(OpenAIResponsesAdapter(client), _request("openai_responses"))
+
+ assert isinstance(events[-1], Done)
+ assert [event.delta for event in events if isinstance(event, TextDelta)] == ["done"]
+ assert events[-1].message.content == (TextBlock("done"),)
+
+
+async def test_responses_reasoning_snapshot_emits_unseen_suffix() -> None:
+ body = (
+ 'data: {"type":"response.output_item.added","output_index":0,"item":{"type":"reasoning","id":"rs_1"}}\n\n'
+ 'data: {"type":"response.reasoning_text.delta","output_index":0,"delta":"plan"}\n\n'
+ 'data: {"type":"response.output_item.done","output_index":0,"item":{"type":"reasoning","id":"rs_1","summary":[{"type":"summary_text","text":"plan"},{"type":"summary_text","text":"final"}]}}\n\n'
+ 'data: {"type":"response.completed","response":{"status":"completed"}}\n\n'
+ )
+
+ def handler(_: httpx.Request) -> httpx.Response:
+ return httpx.Response(200, headers={"content-type": "text/event-stream"}, text=body)
+
+ async with httpx.AsyncClient(transport=httpx.MockTransport(handler)) as client:
+ events = await _events(OpenAIResponsesAdapter(client), _request("openai_responses"))
+
+ assert [event.delta for event in events if isinstance(event, ThinkingDelta)] == [
+ "plan",
+ "\n\nfinal",
+ ]
+ assert isinstance(events[-1], Done)
+ assert events[-1].message.content == (ThinkingBlock("plan\n\nfinal"),)
+
+
+async def test_chat_typed_model_hub_error_frame_is_terminal() -> None:
+ body = (
+ 'data: {"choices":[{"delta":{"content":"partial"},"finish_reason":null}]}\n\n'
+ 'data: {"object":"chat.completion.chunk","type":"error","error":{"type":"server_error","message":"failed"},"choices":[]}\n\n'
+ )
+
+ def handler(_: httpx.Request) -> httpx.Response:
+ return httpx.Response(200, headers={"content-type": "text/event-stream"}, text=body)
+
+ async with httpx.AsyncClient(transport=httpx.MockTransport(handler)) as client:
+ events = await _events(OpenAIChatAdapter(client), _request("openai_chat"))
+
+ assert isinstance(events[-1], ProviderError)
+ assert events[-1].kind == "server"
+ assert events[-1].partial is not None
+ assert events[-1].partial.content == (TextBlock("partial"),)
+
+
+async def test_responses_snapshot_output_counts_as_streamed_partial() -> None:
+ body = (
+ 'data: {"type":"response.output_item.added","output_index":0,"item":{"type":"message","id":"msg_1"}}\n\n'
+ 'data: {"type":"response.output_item.done","output_index":0,"item":{"type":"message","id":"msg_1","content":[{"type":"output_text","text":"snapshot"}]}}\n\n'
+ 'data: {"type":"response.failed","response":{"status":"failed","error":{"code":"server_error","message":"failed"}}}\n\n'
+ )
+
+ def handler(_: httpx.Request) -> httpx.Response:
+ return httpx.Response(200, headers={"content-type": "text/event-stream"}, text=body)
+
+ async with httpx.AsyncClient(transport=httpx.MockTransport(handler)) as client:
+ events = await _events(OpenAIResponsesAdapter(client), _request("openai_responses"))
+
+ error = events[-1]
+ assert isinstance(error, ProviderError)
+ assert error.kind == "server"
+ assert error.retryable is False
+ assert error.partial is not None
+ assert error.partial.content == (TextBlock("snapshot"),)
+
+
[email protected]("field", ["content", "refusal"])
+async def test_chat_known_text_fields_reject_wrong_types(field: str) -> None:
+ delta = {field: 7}
+ body = f'data: {json.dumps({"choices": [{"delta": delta, "finish_reason": "stop"}]})}\n\n'
+
+ def handler(_: httpx.Request) -> httpx.Response:
+ return httpx.Response(200, headers={"content-type": "text/event-stream"}, text=body)
+
+ async with httpx.AsyncClient(transport=httpx.MockTransport(handler)) as client:
+ events = await _events(OpenAIChatAdapter(client), _request("openai_chat"))
+
+ error = events[-1]
+ assert isinstance(error, ProviderError)
+ assert error.kind == "invalid_request"
+
+
+async def test_chat_tool_call_without_integer_index_uses_native_id_alias() -> None:
+ body = (
+ 'data: {"choices":[{"delta":{"tool_calls":[{"id":"call_1","function":{"name":"read"}}]},"finish_reason":null}]}\n\n'
+ 'data: {"choices":[{"delta":{"tool_calls":[{"id":"call_1","function":{"arguments":"{\\"path\\":\\"x\\"}"}}]},"finish_reason":"tool_calls"}]}\n\n'
+ "data: [DONE]\n\n"
+ )
+
+ def handler(_: httpx.Request) -> httpx.Response:
+ return httpx.Response(200, headers={"content-type": "text/event-stream"}, text=body)
+
+ async with httpx.AsyncClient(transport=httpx.MockTransport(handler)) as client:
+ events = await _events(OpenAIChatAdapter(client), _request("openai_chat"))
+
+ assert isinstance(events[-1], Done)
+ assert events[-1].message.tool_calls[0].id == "call_1"
+ assert events[-1].message.tool_calls[0].arguments == {"path": "x"}
+
+
+async def test_chat_null_optional_fields_are_absent() -> None:
+ body = (
+ 'data: {"choices":[{"delta":{"content":"ok","tool_calls":null,"function_call":null},"finish_reason":"stop"}],"usage":null}\n\n'
+ 'data: {"choices":null,"usage":null}\n\n'
+ "data: [DONE]\n\n"
+ )
+
+ def handler(_: httpx.Request) -> httpx.Response:
+ return httpx.Response(200, headers={"content-type": "text/event-stream"}, text=body)
+
+ async with httpx.AsyncClient(transport=httpx.MockTransport(handler)) as client:
+ events = await _events(OpenAIChatAdapter(client), _request("openai_chat"))
+
+ assert isinstance(events[-1], Done)
+ assert events[-1].message.content == (TextBlock("ok"),)
+
+
+async def test_chat_tool_call_without_name_is_terminal_invalid_request() -> None:
+ body = (
+ 'data: {"choices":[{"delta":{"tool_calls":[{"index":0,"id":"call_1","function":{"arguments":"{}"}}]},"finish_reason":null}]}\n\n'
+ 'data: {"choices":[{"delta":{},"finish_reason":"tool_calls"}]}\n\n'
+ "data: [DONE]\n\n"
+ )
+
+ def handler(_: httpx.Request) -> httpx.Response:
+ return httpx.Response(200, headers={"content-type": "text/event-stream"}, text=body)
+
+ async with httpx.AsyncClient(transport=httpx.MockTransport(handler)) as client:
+ events = await _events(OpenAIChatAdapter(client), _request("openai_chat"))
+
+ assert isinstance(events[-1], ProviderError)
+ assert events[-1].kind == "invalid_request"
+ assert "tool call name is missing" in events[-1].message
+
+
+async def test_chat_arguments_before_name_are_emitted_after_tool_start() -> None:
+ body = (
+ 'data: {"choices":[{"delta":{"tool_calls":[{"index":0,"id":"call_1","function":{"arguments":"{\\"path\\":\\"x\\"}"}}]},"finish_reason":null}]}\n\n'
+ 'data: {"choices":[{"delta":{"tool_calls":[{"index":0,"function":{"name":"read","arguments":null}}]},"finish_reason":"tool_calls"}]}\n\n'
+ "data: [DONE]\n\n"
+ )
+
+ def handler(_: httpx.Request) -> httpx.Response:
+ return httpx.Response(200, headers={"content-type": "text/event-stream"}, text=body)
+
+ async with httpx.AsyncClient(transport=httpx.MockTransport(handler)) as client:
+ events = await _events(OpenAIChatAdapter(client), _request("openai_chat"))
+
+ assert [event.arguments_delta for event in events if isinstance(event, ToolCallDelta)] == [
+ '{"path":"x"}'
+ ]
+ assert isinstance(events[-1], Done)
+ assert events[-1].message.tool_calls[0].arguments == {"path": "x"}
+
+
+async def test_responses_non_prefix_arguments_done_emits_no_duplicate_delta() -> None:
+ body = (
+ 'data: {"type":"response.output_item.added","output_index":0,"item":{"type":"function_call","id":"fc_1","call_id":"call_1","name":"read"}}\n\n'
+ 'data: {"type":"response.function_call_arguments.delta","output_index":0,"delta":"{\\"a\\":1"}\n\n'
+ 'data: {"type":"response.function_call_arguments.done","output_index":0,"arguments":"{\\"a\\": 1}"}\n\n'
+ 'data: {"type":"response.output_item.done","output_index":0,"item":{"type":"function_call","id":"fc_1","call_id":"call_1","name":"read","arguments":"{\\"a\\": 1}"}}\n\n'
+ 'data: {"type":"response.completed","response":{"status":"completed"}}\n\n'
+ )
+
+ def handler(_: httpx.Request) -> httpx.Response:
+ return httpx.Response(200, headers={"content-type": "text/event-stream"}, text=body)
+
+ async with httpx.AsyncClient(transport=httpx.MockTransport(handler)) as client:
+ events = await _events(OpenAIResponsesAdapter(client), _request("openai_responses"))
+
+ assert [event.arguments_delta for event in events if isinstance(event, ToolCallDelta)] == ['{"a":1']
+ assert isinstance(events[-1], Done)
+ assert events[-1].message.tool_calls[0].arguments == {"a": 1}
+
+
+async def test_responses_summary_done_replaces_streaming_separator_after_late_delta() -> None:
+ body = (
+ 'data: {"type":"response.output_item.added","output_index":0,"item":{"type":"reasoning","id":"rs_1"}}\n\n'
+ 'data: {"type":"response.reasoning_summary_text.delta","output_index":0,"delta":"p1"}\n\n'
+ 'data: {"type":"response.reasoning_summary_part.done","output_index":0}\n\n'
+ 'data: {"type":"response.reasoning_summary_text.delta","output_index":0,"delta":"p2"}\n\n'
+ 'data: {"type":"response.output_item.done","output_index":0,"item":{"type":"reasoning","id":"rs_1","encrypted_content":"enc","summary":[{"type":"summary_text","text":"p1"},{"type":"summary_text","text":"p2"}]}}\n\n'
+ 'data: {"type":"response.completed","response":{"status":"completed"}}\n\n'
+ )
+
+ def handler(_: httpx.Request) -> httpx.Response:
+ return httpx.Response(200, headers={"content-type": "text/event-stream"}, text=body)
+
+ async with httpx.AsyncClient(transport=httpx.MockTransport(handler)) as client:
+ events = await _events(OpenAIResponsesAdapter(client), _request("openai_responses"))
+
+ assert isinstance(events[-1], Done)
+ assert events[-1].message.content == (
+ ThinkingBlock(
+ "p1\n\np2",
+ '{"type":"reasoning","id":"rs_1","encrypted_content":"enc","summary":[{"type":"summary_text","text":"p1"},{"type":"summary_text","text":"p2"}]}',
+ ),
+ )
diff --git a/tests/agent_core/ai/test_transform_sse_errors.py b/tests/agent_core/ai/test_transform_sse_errors.py
new file mode 100644
index 000000000..18aaad15b
--- /dev/null
+++ b/tests/agent_core/ai/test_transform_sse_errors.py
@@ -0,0 +1,608 @@
+from __future__ import annotations
+
+import hashlib
+import json
+
+import httpx
+import pytest
+
+from core.agent_core.ai._common import endpoint_origin
+from core.agent_core.ai.errors import classify_error, redact_provider_error, sanitize_endpoint_text
+from core.agent_core.ai.provider import ModelEndpoint
+from core.agent_core.ai.sse import SSEParseError, SSEParser
+from core.agent_core.ai.transform import SYNTHETIC_TOOL_RESULT, transform_messages
+from core.agent_core.messages import (
+ AssistantMessage,
+ ImageBlock,
+ Origin,
+ TextBlock,
+ ThinkingBlock,
+ ToolCallBlock,
+ ToolResultMessage,
+ UserMessage,
+)
+
+_PROTOCOL_ORIGINS = (
+ Origin("anthropic", "anthropic", "model"),
+ Origin("openai", "openai_chat", "model"),
+ Origin("openai", "openai_responses", "model"),
+)
+
+
+def _redacted_error(**kwargs: object):
+ return redact_provider_error(classify_error(**kwargs))
+
+
+def test_sse_parser_handles_split_crlf_comments_and_multiline_data() -> None:
+ parser = SSEParser()
+ events = []
+ for chunk in (b": keepalive\r", b"\n", b"event: message\r\n", b"data: one\r\n", b"data: two\r", b"\n\r\n"):
+ events.extend(parser.feed(chunk))
+
+ assert len(events) == 1
+ assert events[0].event == "message"
+ assert events[0].data == "one\ntwo"
+
+
+def test_sse_parser_preserves_utf8_codepoints_split_across_byte_chunks() -> None:
+ parser = SSEParser()
+ events = []
+ encoded = "data: 你好\n\n".encode("utf-8")
+ for byte in encoded:
+ events.extend(parser.feed(bytes([byte])))
+
+ assert events[0].data == "你好"
+
+
+def test_sse_parser_flushes_a_final_cr_line_ending() -> None:
+ assert SSEParser().feed("data: final\r") == []
+ parser = SSEParser()
+ parser.feed("data: final\r")
+ assert parser.finish()[0].data == "final"
+
+
+def test_sse_parser_strips_one_utf8_bom_at_stream_start() -> None:
+ parser = SSEParser()
+ events = parser.feed(b"\xef\xbb\xbfdata: first\n\n")
+ events.extend(parser.feed("data: second\n\n"))
+
+ assert [event.data for event in events] == ["first", "second"]
+
+
+def test_sse_parser_caps_pending_line_and_event_data() -> None:
+ parser = SSEParser(max_line_size=8, max_event_size=12)
+
+ with pytest.raises(SSEParseError, match="line"):
+ parser.feed("data: 123")
+
+ parser = SSEParser(max_line_size=128, max_event_size=8)
+ parser.feed("data: 1234\n")
+ with pytest.raises(SSEParseError, match="event"):
+ parser.feed("data: 5678\n")
+
+ large_event = SSEParser().feed(f"data: {'x' * (70 * 1024)}\n\n")
+ assert large_event[0].data == "x" * (70 * 1024)
+
+ with pytest.raises(ValueError, match="positive"):
+ SSEParser(max_line_size=0)
+
+
+def test_sse_parser_scans_many_short_lines_without_changing_event_shape() -> None:
+ parser = SSEParser()
+ line_count = 10_000
+
+ events = parser.feed(("data: x\n" * line_count) + "\n")
+
+ assert len(events) == 1
+ assert events[0].data == "\n".join(["x"] * line_count)
+
+
+def test_cross_provider_transform_drops_opaque_payload_and_answers_orphaned_calls() -> None:
+ source = Origin("openai", "openai_chat", "foreign-test")
+ target = Origin("anthropic", "anthropic", "claude-test")
+ call = ToolCallBlock("call|foreign", "read", {"path": "x"}, signature="foreign-opaque")
+ messages = (
+ UserMessage((ImageBlock("image/png", "token", "shot.png"),)),
+ AssistantMessage(
+ content=(ThinkingBlock("private", "opaque"), call),
+ origin=source,
+ stop_reason="tool_use",
+ ),
+ )
+
+ result = transform_messages(messages, target, supports_images=False)
+
+ assistant = result.messages[1]
+ assert isinstance(assistant, AssistantMessage)
+ assert assistant.content == (
+ TextBlock(text="private"),
+ ToolCallBlock(
+ id=result.tool_call_id_map["call|foreign"],
+ name="read",
+ arguments={"path": "x"},
+ ),
+ )
+ assert result.messages[0] == UserMessage((TextBlock(text="[image: shot.png]"),))
+ synthetic = result.messages[-1]
+ assert synthetic.tool_call_id == result.tool_call_id_map["call|foreign"] # type: ignore[attr-defined]
+ assert synthetic.content == (TextBlock(text=SYNTHETIC_TOOL_RESULT),) # type: ignore[attr-defined]
+ assert synthetic.is_error is True # type: ignore[attr-defined]
+
+
+def test_cross_provider_transform_drops_results_for_failed_tool_turns() -> None:
+ history = (
+ UserMessage((TextBlock(text="request"),)),
+ AssistantMessage(
+ content=(ToolCallBlock("failed-call", "read", {}),),
+ origin=Origin("openai", "openai_chat", "model"),
+ stop_reason="error",
+ ),
+ ToolResultMessage(
+ tool_call_id="failed-call",
+ tool_name="read",
+ content=(TextBlock(text="settled"),),
+ is_error=True,
+ ),
+ UserMessage((TextBlock(text="next request"),)),
+ )
+
+ transformed = transform_messages(history, Origin("anthropic", "anthropic", "model"))
+
+ assert not any(
+ isinstance(message, ToolResultMessage) and message.tool_call_id == "failed-call"
+ for message in transformed.messages
+ )
+
+
+def test_transform_keeps_normalized_tool_ids_unique_per_request() -> None:
+ unsafe_id = "bad:id"
+ colliding_safe_id = "call_" + hashlib.sha256(unsafe_id.encode()).hexdigest()[:24]
+ history = (
+ AssistantMessage(
+ content=(
+ ToolCallBlock(unsafe_id, "first", {"n": 1}),
+ ToolCallBlock(colliding_safe_id, "second", {"n": 2}),
+ ),
+ origin=Origin("openai", "openai_responses", "model"),
+ stop_reason="tool_use",
+ ),
+ )
+
+ transformed = transform_messages(history, Origin("anthropic", "anthropic", "model"))
+ assistant = transformed.messages[0]
+ assert isinstance(assistant, AssistantMessage)
+ assert len({call.id for call in assistant.tool_calls}) == 2
+ assert assistant.tool_calls[0].id == transformed.tool_call_id_map[unsafe_id]
+ assert assistant.tool_calls[1].id == transformed.tool_call_id_map[colliding_safe_id]
+
+
+def test_transform_correlates_reused_tool_ids_by_turn() -> None:
+ origin = Origin("openai", "openai_chat", "model")
+ history = (
+ AssistantMessage(
+ content=(ToolCallBlock("reused", "read", {"turn": 1}),),
+ origin=origin,
+ stop_reason="tool_use",
+ ),
+ ToolResultMessage(
+ tool_call_id="reused",
+ tool_name="read",
+ content=(TextBlock(text="first"),),
+ ),
+ AssistantMessage(
+ content=(ToolCallBlock("reused", "read", {"turn": 2}),),
+ origin=origin,
+ stop_reason="tool_use",
+ ),
+ ToolResultMessage(
+ tool_call_id="reused",
+ tool_name="read",
+ content=(TextBlock(text="second"),),
+ ),
+ )
+
+ transformed = transform_messages(history, Origin("anthropic", "anthropic", "model"))
+ assistants = [message for message in transformed.messages if isinstance(message, AssistantMessage)]
+ results = [message for message in transformed.messages if isinstance(message, ToolResultMessage)]
+
+ assert len(assistants) == 2
+ assert len(results) == 2
+ assert assistants[0].tool_calls[0].id != assistants[1].tool_calls[0].id
+ assert results[0].tool_call_id == assistants[0].tool_calls[0].id
+ assert results[1].tool_call_id == assistants[1].tool_calls[0].id
+
+
+def test_empty_provider_custom_endpoints_have_distinct_origins() -> None:
+ left = endpoint_origin(
+ ModelEndpoint("openai_chat", "https://one.example/v1", "same-model", "token")
+ )
+ right = endpoint_origin(
+ ModelEndpoint("openai_chat", "https://two.example/v1", "same-model", "token")
+ )
+
+ assert left != right
+ assert left.provider.startswith("endpoint:")
+ assert right.provider.startswith("endpoint:")
+
+
+def test_unnamed_custom_endpoint_origin_is_credential_free() -> None:
+ origin = endpoint_origin(
+ ModelEndpoint(
+ "openai_chat",
+ "https://user:[email protected]:8443/v1?api_key=query-secret",
+ "same-model",
+ "token",
+ )
+ )
+
+ assert "secret" not in origin.provider
+ assert "query-secret" not in origin.provider
+ assert origin.provider == "endpoint:https://one.example:8443/v1"
+
+
+def test_endpoint_redaction_handles_punctuation_in_credentials() -> None:
+ endpoint = "https://user:p,[email protected]:8443/v1?token=query-secret"
+
+ message = sanitize_endpoint_text(f"request failed at {endpoint}", endpoint)
+
+ assert message == "request failed at https://one.example:8443/v1"
+
+
+def test_error_classification_preserves_retry_after_and_stream_boundary() -> None:
+ limited = classify_error(status=429, body='{"error":{"message":"slow down"}}', headers={"Retry-After": "2"})
+ assert limited.kind == "rate_limit"
+ assert limited.retryable is True
+ assert limited.retry_after_s == 2
+
+ overflow = classify_error(status=400, body="context_length_exceeded")
+ assert overflow.kind == "overflow"
+ assert overflow.retryable is False
+
+ streamed = classify_error(status=503, body="overloaded", streamed=True)
+ assert streamed.kind == "overloaded"
+ assert streamed.retryable is False
+
+
+def test_overflow_classifies_cerebras_bodyless_status() -> None:
+ assert classify_error(status=400, body="400 status code (no body)").kind == "overflow"
+
+
[email protected]("status", [401, 403])
+def test_auth_statuses_are_not_retryable(status: int) -> None:
+ error = classify_error(status=status, body="denied")
+ assert error.kind == "auth"
+ assert error.retryable is False
+
+
+ "body",
+ [
+ "provider rejected password=super-secret",
+ "provider rejected https://model.test/v1?password=super-secret",
+ ],
+)
+def test_error_message_redacts_password_named_and_query_values(body: str) -> None:
+ error = _redacted_error(body=body)
+
+ assert "super-secret" not in error.message
+ assert "[redacted]" in error.message or error.message == "provider rejected https://model.test/v1"
+
+
+ "code",
+ [
+ "authentication_error",
+ "invalid_api_key",
+ "permission_error",
+ "permission",
+ "permission_denied",
+ "unauthenticated",
+ ],
+)
+def test_provider_auth_codes_are_not_retryable(code: str) -> None:
+ error = classify_error(code=code, body=f'{{"error":{{"code":"{code}"}}}}')
+
+ assert error.kind == "auth"
+ assert error.retryable is False
+
+
+def test_specific_provider_code_precedes_nested_detail_code() -> None:
+ error = classify_error(
+ status=400,
+ body=(
+ '{"error":{"code":"context_length_exceeded",'
+ '"details":[{"type":"rate_limit"}]}}'
+ ),
+ )
+
+ assert error.kind == "overflow"
+ assert error.retryable is False
+
+
+def test_network_errors_are_retryable_before_any_streamed_output() -> None:
+ error = classify_error(exc=httpx.ConnectError("connection failed"))
+ assert error.kind == "network"
+ assert error.retryable is True
+
+
+def test_error_json_without_message_redacts_sensitive_values() -> None:
+ error = _redacted_error(body='{"token":"secret-token","api_key":"sk-secret"}')
+
+ assert "secret-token" not in error.message
+ assert "sk-secret" not in error.message
+ assert "[redacted]" in error.message
+
+
+def test_error_message_redacts_quoted_json_nested_in_message() -> None:
+ error = _redacted_error(body='{"message":"{\\"token\\":\\"secret-token\\"}"}')
+
+ assert "secret-token" not in error.message
+ assert "[redacted]" in error.message
+
+
+def test_error_message_redacts_basic_authorization_credentials() -> None:
+ error = _redacted_error(body="provider echoed Authorization: Basic dXNlcjpwYXNz")
+
+ assert "dXNlcjpwYXNz" not in error.message
+ assert "Basic [redacted]" in error.message
+
+
+ ("body", "secret"),
+ [
+ ("Authorization: Bearer bearer-secret", "bearer-secret"),
+ ("Authorization: Basic basic-secret", "basic-secret"),
+ ("Authorization: Token token-secret", "token-secret"),
+ ("Authorization: Custom custom-secret", "custom-secret"),
+ ("Authorization: Custom realm=x, sig=sig-secret", "sig-secret"),
+ ("Authorization: abcdef0123456789secret", "abcdef0123456789secret"),
+ ("Authorization: abcdefghijk12345 (expired)", "abcdefghijk12345"),
+ ("OPENAI_API_KEY=abcdefghijk12345", "abcdefghijk12345"),
+ ("x-litellm-api-key: abcdefghijk12345", "abcdefghijk12345"),
+ ("Invalid X-Portkey-Api-Key: pk_abcdef123456", "pk_abcdef123456"),
+ ("X-Authorization-Token: plainsecret1", "plainsecret1"),
+ ("authorization_token=plainsecret1", "plainsecret1"),
+ ("cookie_secret=plainsecret1", "plainsecret1"),
+ ("access_key=plainsecret1", "plainsecret1"),
+ ("client_key=plainsecret1", "plainsecret1"),
+ ('"access_key": "plainsecret1"', "plainsecret1"),
+ ('"Authorization":"rawkey-secret"', "rawkey-secret"),
+ ("X-Authorization: plain-secret", "plain-secret"),
+ ("Helicone-Auth: Bearer helicone-secret", "helicone-secret"),
+ ("Access Key: AKIAIOSFODNN7EXAMPLE", "AKIAIOSFODNN7EXAMPLE"),
+ ("X-Auth-Token: Bearer abc123SECRET", "abc123SECRET"),
+ ("X-Api-Key: Bearer abc123SECRET", "abc123SECRET"),
+ ("client_secret: two words SECRET", "two words SECRET"),
+ ('Authorization: Digest username="u", response="digest-secret"', "digest-secret"),
+ ('password=hunter2SECRET is wrong', "hunter2SECRET"),
+ ("provider failed: password=secret", "secret"),
+ ("api_key='QUOTEDSECRET'", "QUOTEDSECRET"),
+ ('password="hunter2SECRET"', "hunter2SECRET"),
+ ('token = "quoted-token"', "quoted-token"),
+ ("X-API-Key: abc123SECRET\r\nContent-Type: application/json", "abc123SECRET"),
+ ("Proxy-Authorization: Custom proxy-secret", "proxy-secret"),
+ ("X-Goog-Api-Key: AIza-header-secret", "AIza-header-secret"),
+ ("Ocp-Apim-Subscription-Key: subscription-secret", "subscription-secret"),
+ ("Invalid API Key: gsk_live-secret", "gsk_live-secret"),
+ ('{"detail":{"secretKey":"SKSECRET1"}}', "SKSECRET1"),
+ ('{"detail":{"aws_secret_access_key":"AWSSECRET"}}', "AWSSECRET"),
+ ('{"detail":{"upstream_access_token_v2":"TOKSECRET"}}', "TOKSECRET"),
+ ('{"message":"access_token=access-secret"}', "access-secret"),
+ ('{"message":"refresh_token: refresh-secret"}', "refresh-secret"),
+ ('{"message":"client_secret=client-secret"}', "client-secret"),
+ ('{"X-API-Key":"header-secret"}', "header-secret"),
+ ("Cookie: theme=dark; JSESSIONID=cookie-secret", "cookie-secret"),
+ ("Set-Cookie: session=set-cookie-secret; Path=/", "set-cookie-secret"),
+ ("provider returned sk-live-token", "sk-live-token"),
+ ("provider returned AIza-live-token", "AIza-live-token"),
+ ("provider returned ghp_live-token", "ghp_live-token"),
+ ("upstream rejected Bearer abc123XYZsecretval", "abc123XYZsecretval"),
+ (
+ "provider returned "
+ "eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiIxMjMifQ.signature",
+ "eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiIxMjMifQ.signature",
+ ),
+ ],
+)
+def test_error_redactor_covers_key_scheme_and_token_shapes(body: str, secret: str) -> None:
+ error = _redacted_error(body=body)
+
+ assert secret not in error.message
+ assert "[redacted]" in error.message
+
+
+ "body",
+ [
+ "max_tokens: 200000 > 64000",
+ "thinking.budget_tokens: Input should be positive",
+ "model token limit exceeded",
+ "Basic validation failed",
+ "token_limit: 8192",
+ "token_count: 8192",
+ '{"token_limit":8192,"token_count":8192}',
+ ],
+)
+def test_error_redactor_does_not_garble_non_credentials(body: str) -> None:
+ assert _redacted_error(body=body).message == body
+
+
+ "body",
+ [
+ "https://gw.example/v1?filter[a]=1&sig=SIGSECRET",
+ "https://gw.example/v1?fields=a,b&sig=SIGSECRET",
+ "https://gw.example/v1?q=(a)&sig=SIGSECRET",
+ "https://user:pw@/x?token=SECRET",
+ ],
+)
+def test_error_redactor_strips_complete_credential_bearing_urls(body: str) -> None:
+ error = _redacted_error(body=body)
+
+ assert "SIGSECRET" not in error.message
+ assert "SECRET" not in error.message
+ assert "user:pw@" not in error.message
+
+
+def test_structured_json_redaction_preserves_sibling_fields() -> None:
+ error = _redacted_error(
+ body='{"error":{"type":"invalid_request_error","api_key":"zzz","param":"model"}}'
+ )
+
+ assert error.message == (
+ '{"error":{"type":"invalid_request_error","api_key":"[redacted]","param":"model"}}'
+ )
+
+
+def test_configured_literal_is_replaced_before_token_shape_redaction() -> None:
+ from core.agent_core.ai.errors import redact_provider_text
+
+ redacted = redact_provider_text(
+ r"Illegal header value b'opaque.private~value\n'",
+ literal_secrets=("opaque.private~value\n",),
+ )
+
+ assert redacted == "Illegal header value b'[redacted]'"
+
+
+ ("diagnostic", "expected"),
+ [
+ ("request at https://x.example/chat. retry", "request at https://x.example/chat. retry"),
+ ("request (https://x.example/chat?sig=secret).", "request (https://x.example/chat)."),
+ (
+ json.dumps({"detail": '"https://x.example/y?sig=secret"'}),
+ json.dumps({"detail": '"https://x.example/y"'}, separators=(",", ":")),
+ ),
+ ],
+)
+def test_diagnostic_url_redaction_preserves_surrounding_syntax(
+ diagnostic: str, expected: str,
+) -> None:
+ from core.agent_core.ai._common import StreamAssembler
+
+ assembler = StreamAssembler(origin=Origin("p", "openai_chat", "m"), protocol="openai_chat")
+ error = assembler.terminal(assembler.error(diagnostic, kind="invalid_request"))
+ assert error.message == expected
+
+
+def test_endpoint_is_sanitized_before_diagnostic_redaction() -> None:
+ endpoint = "https://gw.example/v1?key=K&sig=SIGSECRET&x=1"
+ from core.agent_core.ai._common import StreamAssembler
+
+ assembler = StreamAssembler(
+ origin=Origin("openai", "openai_chat", "model"),
+ protocol="openai_chat",
+ endpoint_url=endpoint,
+ )
+ error = assembler.terminal(assembler.error(
+ f"request failed at {endpoint}/chat/completions",
+ kind="invalid_request",
+ ))
+
+ assert "SIGSECRET" not in error.message
+ assert "x=1" not in error.message
+ assert "https://gw.example/v1/chat/completions" in error.message
+
+
+ ("configured", "diagnostic"),
+ [
+ (
+ "plainSECRETvalue123",
+ "Illegal header value b'Bearer plainSECRETvalue123\\n'",
+ ),
+ (
+ "TOKENSECRET77\n",
+ "Illegal header value b'Bearer TOKENSECRET77\\n'",
+ ),
+ ],
+)
+def test_boundary_redacts_configured_request_credentials_in_transport_errors(
+ configured: str,
+ diagnostic: str,
+) -> None:
+ from core.agent_core.ai._common import StreamAssembler
+
+ assembler = StreamAssembler(
+ origin=Origin("openai", "openai_chat", "model"),
+ protocol="openai_chat",
+ sensitive_values=(configured,),
+ )
+ error = assembler.terminal(assembler.exception(ValueError(diagnostic)))
+
+ assert configured.strip() not in error.message
+ assert "Bearer [redacted]" in error.message
+
+
+def test_request_credential_values_uses_shared_sensitive_key_vocabulary() -> None:
+ from core.agent_core.ai._common import request_credential_values
+ from core.agent_core.ai.provider import ModelEndpoint
+
+ endpoint = ModelEndpoint(
+ protocol="openai_chat",
+ base_url="https://gateway.example/v1",
+ model_id="model",
+ token="endpoint-token-value",
+ request_headers={
+ "Ocp-Apim-Subscription-Key": "subscription-value",
+ "X-Credential": "credential-value",
+ "X-Private-Key": "private-value",
+ },
+ )
+
+ assert request_credential_values(endpoint) == (
+ "endpoint-token-value",
+ "subscription-value",
+ "credential-value",
+ "private-value",
+ )
+
+
+def test_short_configured_placeholders_do_not_redact_diagnostic_text() -> None:
+ from core.agent_core.ai.errors import redact_provider_text
+
+ assert redact_provider_text(
+ "model none-large uses token budget",
+ literal_secrets=("token", "key", "none"),
+ ) == "model none-large uses token budget"
+
+
[email protected]("source", _PROTOCOL_ORIGINS)
[email protected]("target", _PROTOCOL_ORIGINS)
+def test_history_from_each_protocol_can_be_replayed_without_foreign_opaque_state(
+ source: Origin,
+ target: Origin,
+) -> None:
+ call_id = "native|call"
+ history = (
+ UserMessage((TextBlock(text="question"),)),
+ AssistantMessage(
+ content=(
+ ThinkingBlock("private", "thinking-signature"),
+ ToolCallBlock(call_id, "read", {"path": "x"}, signature="tool-signature"),
+ ),
+ origin=source,
+ stop_reason="tool_use",
+ ),
+ ToolResultMessage(
+ tool_call_id=call_id,
+ tool_name="read",
+ content=(TextBlock(text="result"),),
+ ),
+ )
+
+ transformed = transform_messages(history, target, supports_images=True)
+ assistant = next(message for message in transformed.messages if isinstance(message, AssistantMessage))
+ result = next(message for message in transformed.messages if isinstance(message, ToolResultMessage))
+ assert result.tool_call_id == assistant.tool_calls[0].id
+ assert any(isinstance(message, ToolResultMessage) for message in transformed.messages)
+ if source == target:
+ assert assistant.content[0] == ThinkingBlock("private", "thinking-signature")
+ assert assistant.tool_calls[0].signature == "tool-signature"
+ else:
+ assert all(
+ not isinstance(block, ThinkingBlock) or block.signature is None
+ for block in assistant.content
+ )
+ assert assistant.tool_calls[0].signature is None