CubeLoop — a Pythonic, async-native agent harness core designed for high performance, readability, and production-grade persistence.
Python agent-frameworkagent-harnessagent-runtimeagentic-aiai-agentsai-frameworkanthropicharnessharness-engineeringharness-frameworklanggraphlanggraph-alternativellmmcpopenaipi-agentpi-agent-corepythonpython-agent
feat(providers): add listener registry to Provider base class (#80)
Chris5e2edcaeb491
diff --git a/cubepi/__init__.py b/cubepi/__init__.pyindex 09d0815..093c22b 100644--- a/cubepi/__init__.py+++ b/cubepi/__init__.py@@ -11,6 +11,7 @@ from cubepi.agent import (from cubepi.middleware import Middleware, compose_middlewarefrom cubepi.providers import (AssistantMessage,+ BaseProvider,Message,MessageStream,Model,@@ -33,6 +34,7 @@ __all__ = ["AgentTool","AgentToolResult","AssistantMessage",+ "BaseProvider","Message","MessageStream","Middleware",diff --git a/cubepi/providers/__init__.py b/cubepi/providers/__init__.pyindex fb00b08..78b75ce 100644--- a/cubepi/providers/__init__.py+++ b/cubepi/providers/__init__.py@@ -1,12 +1,16 @@from cubepi.providers.base import (AssistantMessage,+ BaseProvider,Content,ImageContent,Message,MessageStream,Model,ModelCost,+ OnChunkCallback,OnPayloadCallback,+ OnRequestCallback,+ OnResponseBodyCallback,OnResponseCallback,Provider,ProviderResponse,@@ -59,6 +63,7 @@ def get_openai_responses_provider():__all__ = ["AssistantMessage",+ "BaseProvider","Content","FauxProvider","ImageContent",@@ -66,7 +71,10 @@ __all__ = ["MessageStream","Model","ModelCost",+ "OnChunkCallback","OnPayloadCallback",+ "OnRequestCallback",+ "OnResponseBodyCallback","OnResponseCallback","Provider","ProviderResponse",diff --git a/cubepi/providers/anthropic.py b/cubepi/providers/anthropic.pyindex 96ed04c..0a279c2 100644--- a/cubepi/providers/anthropic.py+++ b/cubepi/providers/anthropic.py@@ -6,6 +6,7 @@ from typing import Any, Literal, Protocol, runtime_checkablefrom cubepi.providers.base import (AssistantMessage,+ BaseProvider,ImageContent,Message,MessageStream,@@ -20,6 +21,8 @@ from cubepi.providers.base import (ToolResultMessage,Usage,UserMessage,+ _fire_request_listeners,+ _fire_response_listeners,adjust_max_tokens_for_thinking,invoke_on_payload,invoke_on_response,@@ -57,7 +60,7 @@ class DefaultCacheMarkerPolicy:return [len(messages) - 1] if messages else []-class AnthropicProvider:+class AnthropicProvider(BaseProvider):def __init__(self,*,@@ -66,6 +69,7 @@ class AnthropicProvider:cache_retention: CacheRetention = "short",cache_policy: CacheMarkerPolicy | None = None,) -> None:+ super().__init__()import anthropickwargs: dict[str, Any] = {"api_key": api_key}@@ -138,9 +142,12 @@ class AnthropicProvider:}async def _produce() -> None:+ body: dict | None = None+ exc: BaseException | None = Nonetry:nonlocal kwargskwargs = await invoke_on_payload(opts.on_payload, kwargs, model)+ await _fire_request_listeners(self._request_listeners, kwargs, model)async with self._client.messages.stream(**kwargs) as stream:# Invoke on_response with HTTP metadata if available@@ -162,8 +169,12 @@ class AnthropicProvider:provider_id=model.provider,model_id=model.id,)- ms.push(- StreamEvent(type="start", partial=partial.model_copy(deep=True))+ await self._emit(+ ms,+ StreamEvent(+ type="start", partial=partial.model_copy(deep=True)+ ),+ model,)async for event in stream:@@ -174,34 +185,44 @@ class AnthropicProvider:"error_message": "Request was aborted",})- ms.push(+ await self._emit(+ ms,StreamEvent(type="error",error_message="Request was aborted",- )+ ),+ model,)ms.set_result(aborted)return- self._handle_event(event, partial, ms)+ await self._handle_event(event, partial, ms, model)final_msg = await stream.get_final_message()result = self._convert_response(final_msg, model)- ms.push(StreamEvent(type="done"))+ body = self._assemble_response(final_msg)+ await self._emit(ms, StreamEvent(type="done"), model)ms.set_result(result)- except BaseException as exc:+ except BaseException as e:+ exc = eerror_msg = AssistantMessage(content=[],stop_reason="error",- error_message=str(exc),+ error_message=str(e),usage=Usage(),timestamp=time.time(),)- ms.push(StreamEvent(type="error", error_message=str(exc)))+ await self._emit(+ ms, StreamEvent(type="error", error_message=str(e)), model+ )ms.set_result(error_msg)- if not isinstance(exc, Exception):+ if not isinstance(e, Exception):raise+ finally:+ await _fire_response_listeners(+ self._response_listeners, body, model, exc+ )ms.attach_task(asyncio.create_task(_produce()))return ms@@ -331,8 +352,12 @@ class AnthropicProvider:"input_schema": td.parameters,}- def _handle_event(- self, event: Any, partial: AssistantMessage, ms: MessageStream+ async def _handle_event(+ self,+ event: Any,+ partial: AssistantMessage,+ ms: MessageStream,+ model: Model,) -> None:etype = getattr(event, "type", "")if etype == "content_block_start":@@ -340,32 +365,38 @@ class AnthropicProvider:block = event.content_blockif block.type == "text":partial.content.append(TextContent(text=""))- ms.push(+ await self._emit(+ ms,StreamEvent(type="text_start",content_index=idx,partial=partial.model_copy(deep=True),- )+ ),+ model,)elif block.type == "thinking":partial.content.append(ThinkingContent(thinking=""))- ms.push(+ await self._emit(+ ms,StreamEvent(type="thinking_start",content_index=idx,partial=partial.model_copy(deep=True),- )+ ),+ model,)elif block.type == "tool_use":partial.content.append(ToolCall(id=block.id, name=block.name, arguments={}))- ms.push(+ await self._emit(+ ms,StreamEvent(type="toolcall_start",content_index=idx,partial=partial.model_copy(deep=True),- )+ ),+ model,)elif etype == "content_block_delta":idx = getattr(event, "index", len(partial.content) - 1)@@ -375,65 +406,128 @@ class AnthropicProvider:partial.content[-1] = TextContent(text=partial.content[-1].text + delta.text)- ms.push(+ await self._emit(+ ms,StreamEvent(type="text_delta",delta=delta.text,content_index=idx,partial=partial.model_copy(deep=True),- )+ ),+ model,)elif hasattr(delta, "thinking"):if partial.content and isinstance(partial.content[-1], ThinkingContent):partial.content[-1] = ThinkingContent(thinking=partial.content[-1].thinking + delta.thinking)- ms.push(+ await self._emit(+ ms,StreamEvent(type="thinking_delta",delta=delta.thinking,content_index=idx,partial=partial.model_copy(deep=True),- )+ ),+ model,)elif hasattr(delta, "partial_json"):- ms.push(+ await self._emit(+ ms,StreamEvent(type="toolcall_delta",delta=delta.partial_json,content_index=idx,partial=partial.model_copy(deep=True),- )+ ),+ model,)elif etype == "content_block_stop":idx = getattr(event, "index", len(partial.content) - 1)if partial.content:last = partial.content[-1]if isinstance(last, TextContent):- ms.push(+ await self._emit(+ ms,StreamEvent(type="text_end",content_index=idx,partial=partial.model_copy(deep=True),- )+ ),+ model,)elif isinstance(last, ThinkingContent):- ms.push(+ await self._emit(+ ms,StreamEvent(type="thinking_end",content_index=idx,partial=partial.model_copy(deep=True),- )+ ),+ model,)elif isinstance(last, ToolCall):- ms.push(+ await self._emit(+ ms,StreamEvent(type="toolcall_end",content_index=idx,partial=partial.model_copy(deep=True),- )+ ),+ model,)+ @staticmethod+ def _assemble_response(final_msg: Any) -> dict[str, Any]:+ """Assemble Anthropic's non-streaming ``messages.create()`` response+ shape from the final streaming Message object.++ Mirrors the REST API response keys. Used to populate the assembled+ ``body`` argument passed to ``subscribe_response`` listeners.+ """+ content: list[dict[str, Any]] = []+ for block in final_msg.content:+ btype = getattr(block, "type", None)+ if btype == "text":+ content.append({"type": "text", "text": block.text})+ elif btype == "thinking":+ content.append({"type": "thinking", "thinking": block.thinking})+ elif btype == "tool_use":+ content.append(+ {+ "type": "tool_use",+ "id": block.id,+ "name": block.name,+ "input": block.input,+ }+ )++ usage = getattr(final_msg, "usage", None)+ usage_dict: dict[str, Any] = {}+ if usage is not None:+ usage_dict = {+ "input_tokens": getattr(usage, "input_tokens", 0),+ "output_tokens": getattr(usage, "output_tokens", 0),+ "cache_read_input_tokens": getattr(usage, "cache_read_input_tokens", 0)+ or 0,+ "cache_creation_input_tokens": getattr(+ usage, "cache_creation_input_tokens", 0+ )+ or 0,+ }++ body: dict[str, Any] = {+ "id": getattr(final_msg, "id", None),+ "type": "message",+ "role": "assistant",+ "model": getattr(final_msg, "model", None),+ "content": content,+ "stop_reason": getattr(final_msg, "stop_reason", None),+ "stop_sequence": getattr(final_msg, "stop_sequence", None),+ "usage": usage_dict,+ }+ return body+@staticmethoddef _convert_response(response: Any, model: Model) -> AssistantMessage:content: list[Any] = []diff --git a/cubepi/providers/base.py b/cubepi/providers/base.pyindex 8464bd8..72d70aa 100644--- a/cubepi/providers/base.py+++ b/cubepi/providers/base.py@@ -1,6 +1,7 @@from __future__ import annotationsimport asyncio+import copyimport inspectfrom dataclasses import dataclass, fieldfrom typing import (@@ -213,7 +214,36 @@ class MessageStream:return itemasync def result(self) -> AssistantMessage:- return await self._result_future+ """Return the final assistant message.++ Blocks not just on the result future, but also on the producer+ task's completion — the producer's ``finally`` block runs+ :func:`_fire_response_listeners` (after ``set_result``), so+ without waiting for the task, callers under ``asyncio.run``+ teardown could exit before async response listeners have run.+ Producer exceptions are NOT re-raised here; they were already+ surfaced via the result future or the stream's error events.+ """+ msg = await self._result_future+ task = self._producer_task+ # Don't await ourselves — providers may call result() from inside+ # the producer task (e.g. to read an aborted result set by an+ # internal helper); that path would deadlock.+ if task is not None and not task.done() and task is not asyncio.current_task():+ # ``asyncio.shield`` lets the producer's finally (response+ # listener cleanup) keep running independently if our caller+ # is cancelled while we're waiting. We re-raise the caller's+ # CancelledError so cooperative shutdown/timeouts still+ # propagate; the producer continues unaffected.+ try:+ await asyncio.shield(task)+ except asyncio.CancelledError:+ raise+ except BaseException:+ # Producer raised — caller already has the result via the+ # future. Swallow so result() returns the message.+ pass+ return msg@dataclass@@ -232,6 +262,239 @@ OnResponseCallback = Callable[["ProviderResponse", Model], Awaitable[None] | Non"""Optional callback invoked after an HTTP response is received."""+OnRequestCallback = Callable[[dict, Model], Awaitable[None] | None]+"""Persistent observer. Fires just before HTTP send, after any per-call+``StreamOptions.on_payload`` mutation has been applied. Receives the final+wire payload dict and the Model. Return value is ignored."""++OnChunkCallback = Callable[["StreamEvent", Model], Awaitable[None] | None]+"""Persistent observer. Fires for every StreamEvent pushed onto the stream+(start, text_delta, thinking_delta, toolcall_delta, done, error, ...).+Heavy listeners should early-return on irrelevant event types — this hook+fires hot. Return value is ignored."""++OnResponseBodyCallback = Callable[+ [dict | None, Model, BaseException | None], Awaitable[None] | None+]+"""Persistent observer. Fires exactly once per ``stream()`` call, in a+finally block, after the stream terminates.++- body: assembled provider response as a dict (same shape a non-streaming+ call to the provider would have returned), or None if the stream failed+ before a response could be assembled.+- exc: the exception that ended the stream (including+ ``asyncio.CancelledError``), or None on normal completion.+Return value is ignored."""+++async def _fire_listeners(listeners: list[Callable], *args: Any) -> None:+ """Invoke each listener with ``*args``. Listener return values and+ exceptions are ignored — a buggy listener must never crash the stream.++ Iterates a snapshot (``tuple(listeners)``) so a listener that detaches+ itself mid-iteration does not silently skip subsequent listeners.+ Callers are responsible for the hot-path guard+ (``if self._chunk_listeners:`` before ``await``) — see ``_emit`` helpers+ in each provider."""+ if not listeners:+ return+ for cb in tuple(listeners):+ try:+ result = cb(*args)+ if inspect.isawaitable(result):+ await result+ except Exception as exc: # noqa: BLE001 — intentional broad catch+ _log_listener_exception(cb, exc)+++def _fire_listeners_sync(listeners: list[Callable], *args: Any) -> None:+ """Synchronous variant of :func:`_fire_listeners`. Used in producer+ ``finally`` blocks where awaiting another coroutine after a+ cancellation is unreliable — the outer task is already cancelling, so+ a subsequent ``await`` may not get a chance to run its callee's body.++ Sync listeners are invoked directly. Async listeners are scheduled as+ detached tasks wrapped in :func:`_safe_run_coroutine` so that any+ exception raised inside the coroutine body is logged via+ :func:`_log_listener_exception` rather than bubbling up to asyncio as+ an "unhandled task exception" warning."""+ if not listeners:+ return+ for cb in tuple(listeners):+ try:+ result = cb(*args)+ if inspect.isawaitable(result):+ wrapped = _safe_run_coroutine(cb, result)+ try:+ asyncio.create_task(wrapped)+ except RuntimeError:+ # No running event loop (e.g. teardown) — close both+ # the wrapper and the inner listener coroutine so+ # neither leaks as a "coroutine was never awaited"+ # warning.+ wrapped.close()+ close = getattr(result, "close", None)+ if callable(close):+ close()+ except Exception as exc: # noqa: BLE001 — intentional broad catch+ _log_listener_exception(cb, exc)+++async def _fire_chunk_listeners(+ listeners: list[Callable], event: "StreamEvent", model: "Model"+) -> None:+ """Fire :func:`subscribe_chunk` listeners with **per-listener** deep+ copies of the event.++ The consumer's queued ``StreamEvent`` (already pushed onto the+ ``MessageStream``) and every other listener's copy are isolated.+ Without per-listener copies, a redacting listener that mutated+ ``event.partial`` would silently alter what later chunk listeners+ observed in the same stream.+ """+ if not listeners:+ return+ for cb in tuple(listeners):+ try:+ result = cb(event.model_copy(deep=True), model)+ if inspect.isawaitable(result):+ await result+ except Exception as exc: # noqa: BLE001 — intentional broad catch+ _log_listener_exception(cb, exc)+++async def _fire_request_listeners(+ listeners: list[Callable], payload: dict, model: "Model"+) -> None:+ """Fire :func:`subscribe_request` listeners with **per-listener** deep+ copies of the payload.++ ``subscribe_request`` is documented as an **observer** — the+ mutation hook is the per-call ``StreamOptions.on_payload`` slot,+ which runs before this. Two isolation properties matter here:++ 1. The dict the provider is about to send over the wire (the+ caller's ``kwargs``) must not be mutated by any listener.+ 2. Multi-subscriber observability must be order-independent — one+ listener redacting fields in place must not affect what later+ listeners observe.++ Both are achieved by giving each listener its own ``deepcopy``.+ Cost: at most one deepcopy per registered listener per stream call,+ which is negligible compared to the HTTP call itself.+ """+ if not listeners:+ return+ for cb in tuple(listeners):+ try:+ snapshot = copy.deepcopy(payload)+ result = cb(snapshot, model)+ if inspect.isawaitable(result):+ await result+ except Exception as exc: # noqa: BLE001 — intentional broad catch+ _log_listener_exception(cb, exc)+++async def _fire_response_listeners(+ listeners: list[Callable],+ body: dict | None,+ model: "Model",+ exc: BaseException | None,+) -> None:+ """Fire response listeners with the right strategy for each+ termination path.++ Normal completion (``exc is None``) or an in-stream exception that is+ NOT a cancel: ``await`` each async listener inline so the producer+ task doesn't end before the listener has run — important because+ callers that use ``asyncio.run(main())`` will tear down the loop the+ moment ``main()`` returns, cancelling any still-detached listener+ task.++ Producer task cancellation (``exc`` is :class:`asyncio.CancelledError`):+ fall back to :func:`_fire_listeners_sync`. Awaiting inside a finally+ block of a cancelled task is unreliable — the runtime may skip past+ the await without running the callee — so synchronous listeners run+ inline and async listeners are scheduled as detached best-effort+ tasks. This is the same contract the cancellation tests pin.++ In both paths, each listener receives its own ``deepcopy`` of+ ``body`` so multi-subscriber observability is order-independent.+ """+ if not listeners:+ return+ if isinstance(exc, asyncio.CancelledError):+ _fire_listeners_sync_per_listener(listeners, body, model, exc)+ return+ for cb in tuple(listeners):+ try:+ snapshot = copy.deepcopy(body) if body is not None else None+ result = cb(snapshot, model, exc)+ if inspect.isawaitable(result):+ await result+ except Exception as listener_exc: # noqa: BLE001+ _log_listener_exception(cb, listener_exc)+++def _fire_listeners_sync_per_listener(+ listeners: list[Callable],+ body: dict | None,+ model: "Model",+ exc: BaseException | None,+) -> None:+ """Sync fanout for response listeners on the cancellation path,+ giving each listener its own deep copy of ``body``."""+ if not listeners:+ return+ for cb in tuple(listeners):+ try:+ snapshot = copy.deepcopy(body) if body is not None else None+ result = cb(snapshot, model, exc)+ if inspect.isawaitable(result):+ wrapped = _safe_run_coroutine(cb, result)+ try:+ asyncio.create_task(wrapped)+ except RuntimeError:+ wrapped.close()+ close = getattr(result, "close", None)+ if callable(close):+ close()+ except Exception as listener_exc: # noqa: BLE001+ _log_listener_exception(cb, listener_exc)+++async def _safe_run_coroutine(cb: Callable, coro: Any) -> None:+ """Await an arbitrary coroutine, logging and swallowing any exception+ it raises. Used by :func:`_fire_listeners_sync` so async listener+ failures don't become asyncio unhandled-task-exception warnings."""+ try:+ await coro+ except Exception as exc: # noqa: BLE001 — intentional broad catch+ _log_listener_exception(cb, exc)+++def _log_listener_exception(cb: Callable, exc: BaseException) -> None:+ try:+ from loguru import logger++ logger.opt(exception=exc).warning(+ "cubepi provider listener {} raised; swallowed", cb+ )+ except ImportError:+ import logging++ logging.getLogger("cubepi.providers").warning(+ "cubepi provider listener %r raised; swallowed", cb, exc_info=exc+ )+++def _detach(listeners: list, cb: Callable) -> None:+ try:+ listeners.remove(cb)+ except ValueError:+ pass++class StreamOptions(BaseModel):"""Options bag for Provider.stream(), transparent to the agent loop."""@@ -282,3 +545,89 @@ class Provider(Protocol):tools: list[ToolDefinition] | None = None,options: StreamOptions | None = None,) -> MessageStream: ...+++class BaseProvider:+ """Concrete base class for built-in cubepi providers.++ Built-in providers (Anthropic, OpenAI, OpenAI Responses, Faux) inherit+ from this class to gain the persistent listener registry used by+ ``cubepi.tracing`` and other observers. User-defined providers may also+ inherit from ``BaseProvider`` to opt in, or remain duck-typed against+ the ``Provider`` Protocol (which only requires ``stream()``).++ Concrete subclasses must implement ``stream()`` and call+ ``_fire_listeners`` at three points: after the request payload is+ finalized, for each ``StreamEvent`` pushed onto the stream, and exactly+ once in a ``finally`` block after the stream terminates.++ Per-call mutators (``StreamOptions.on_payload``,+ ``StreamOptions.on_response``) retain their existing single-slot+ semantics and fire independently of the persistent listener registry+ below.+ """++ def __init__(self) -> None:+ self._request_listeners: list[OnRequestCallback] = []+ self._chunk_listeners: list[OnChunkCallback] = []+ self._response_listeners: list[OnResponseBodyCallback] = []++ async def stream(+ self,+ model: Model,+ messages: list[Message],+ *,+ system_prompt: str = "",+ tools: list[ToolDefinition] | None = None,+ options: StreamOptions | None = None,+ ) -> MessageStream:+ raise NotImplementedError++ def subscribe_request(self, cb: OnRequestCallback) -> Callable[[], None]:+ """Register a persistent observer for request payloads.++ Returns a detach callable that removes this specific subscription.+ """+ self._request_listeners.append(cb)+ return lambda: _detach(self._request_listeners, cb)++ def subscribe_chunk(self, cb: OnChunkCallback) -> Callable[[], None]:+ """Register a persistent observer for stream chunks.++ Returns a detach callable.+ """+ self._chunk_listeners.append(cb)+ return lambda: _detach(self._chunk_listeners, cb)++ def subscribe_response(self, cb: OnResponseBodyCallback) -> Callable[[], None]:+ """Register a persistent observer for assembled responses.++ Returns a detach callable.+ """+ self._response_listeners.append(cb)+ return lambda: _detach(self._response_listeners, cb)++ async def _emit(+ self,+ ms: "MessageStream",+ event: "StreamEvent",+ model: Model | None,+ ) -> None:+ """Push an event to the message stream and fan out to chunk+ listeners with an isolated deep copy.++ The synchronous guard on ``self._chunk_listeners`` makes the+ no-listener case zero-await — important because this fires on+ every text delta. When listeners are present, each receives a+ ``model_copy(deep=True)`` of the event so a redacting/mutating+ observer cannot edit the same object that was already enqueued+ for the ``async for`` consumer.++ ``model`` may be ``None`` when invoked from internal helpers+ that bypass ``stream()`` (e.g. ``FauxProvider._stream_with_deltas``+ is exposed for direct calls in tests). In that case the listener+ fan-out is skipped — the test isn't observing listeners anyway.+ """+ ms.push(event)+ if model is not None and self._chunk_listeners:+ await _fire_chunk_listeners(self._chunk_listeners, event, model)diff --git a/cubepi/providers/faux.py b/cubepi/providers/faux.pyindex 0ed4e1f..e0b151b 100644--- a/cubepi/providers/faux.py+++ b/cubepi/providers/faux.py@@ -9,6 +9,7 @@ from typing import Any, Awaitable, Callablefrom cubepi.providers.base import (AssistantMessage,+ BaseProvider,Message,MessageStream,Model,@@ -19,6 +20,9 @@ from cubepi.providers.base import (ToolCall,ToolDefinition,Usage,+ _fire_request_listeners,+ _fire_response_listeners,+ invoke_on_payload,)FauxContentBlock = TextContent | ThinkingContent | ToolCall@@ -148,7 +152,7 @@ def _can_accept_extended_args(factory: FauxResponseFactory) -> bool:return False-class FauxProvider:+class FauxProvider(BaseProvider):def __init__(self,*,@@ -156,12 +160,55 @@ class FauxProvider:token_size_min: int = 3,token_size_max: int = 5,) -> None:+ super().__init__()self._responses: list[FauxResponseStep] = []self._tokens_per_second = tokens_per_secondself._min = max(1, min(token_size_min, token_size_max))self._max = max(self._min, token_size_max)self.call_count = 0self._prompt_cache: dict[str, str] = {}+ # Monotonic counter for deterministic _assemble_response ids.+ self._response_seq = 0++ @staticmethod+ def _assemble_response(+ *, seq: int, model: Model, message: AssistantMessage+ ) -> dict[str, Any]:+ """Pinned, deterministic dict shape for FauxProvider responses.++ The schema is intentionally minimal and stable across runs (ids use+ the per-instance monotonic seq, no random or time-based fields) so+ tests for the listener registry can assert exact equality.+ """+ content_blocks: list[dict[str, Any]] = []+ for block in message.content:+ if isinstance(block, TextContent):+ content_blocks.append({"type": "text", "text": block.text})+ elif isinstance(block, ThinkingContent):+ content_blocks.append({"type": "thinking", "thinking": block.thinking})+ elif isinstance(block, ToolCall):+ content_blocks.append(+ {+ "type": "tool_use",+ "id": block.id,+ "name": block.name,+ "input": block.arguments,+ }+ )+ usage = message.usage or Usage()+ return {+ "id": f"faux-{seq}",+ "model": model.id,+ "role": "assistant",+ "content": content_blocks,+ "stop_reason": message.stop_reason,+ "usage": {+ "input_tokens": usage.input_tokens,+ "output_tokens": usage.output_tokens,+ "cache_read_tokens": usage.cache_read_tokens,+ "cache_write_tokens": usage.cache_write_tokens,+ },+ }def set_responses(self, responses: list[FauxResponseStep]) -> None:self._responses = list(responses)@@ -227,11 +274,28 @@ class FauxProvider:opts = options or StreamOptions()ms = MessageStream()self.call_count += 1+ self._response_seq += 1+ seq = self._response_seqstep = self._responses.pop(0) if self._responses else Noneasync def _produce() -> None:+ body: dict | None = None+ exc: BaseException | None = Nonetry:+ # Faux has no real wire payload, but we synthesize one for+ # observability tests. Run it through StreamOptions.on_payload+ # so the per-call mutator can produce a final dict before+ # subscribe_request listeners observe it — same ordering+ # contract as the real providers.+ payload = {+ "model": model.id,+ "messages": [m.model_dump() for m in messages],+ "system_prompt": system_prompt,+ }+ payload = await invoke_on_payload(opts.on_payload, payload, model)+ await _fire_request_listeners(self._request_listeners, payload, model)+if step is None:error_msg = AssistantMessage(content=[],@@ -240,10 +304,17 @@ class FauxProvider:usage=Usage(),timestamp=time.time(),)- ms.push(- StreamEvent(type="error", error_message=error_msg.error_message)+ await self._emit(+ ms,+ StreamEvent(+ type="error", error_message=error_msg.error_message+ ),+ model,)ms.set_result(error_msg)+ body = self._assemble_response(+ seq=seq, model=model, message=error_msg+ )returnif callable(step):@@ -275,19 +346,43 @@ class FauxProvider:})- await self._stream_with_deltas(ms, resolved, opts.signal)- except BaseException as exc:+ await self._stream_with_deltas(ms, resolved, opts.signal, model)+ # If the abort signal fired during streaming,+ # _stream_with_deltas sets an aborted result on the stream+ # and returns early. The queued `resolved` message would+ # misrepresent the run as a successful full response, so+ # surface the actual aborted result instead.+ if opts.signal and opts.signal.is_set():+ aborted_msg = await ms.result()+ body = self._assemble_response(+ seq=seq, model=model, message=aborted_msg+ )+ else:+ body = self._assemble_response(+ seq=seq, model=model, message=resolved+ )+ except BaseException as e:+ exc = eerror_msg = AssistantMessage(content=[],stop_reason="error",- error_message=str(exc),+ error_message=str(e),usage=Usage(),timestamp=time.time(),)- ms.push(StreamEvent(type="error", error_message=str(exc)))+ await self._emit(+ ms, StreamEvent(type="error", error_message=str(e)), model+ )ms.set_result(error_msg)- if not isinstance(exc, Exception):+ if not isinstance(e, Exception):raise+ finally:+ # Await async listeners inline on normal/exception paths so+ # they finish before the producer task ends. On cancellation,+ # _fire_response_listeners falls back to sync fanout.+ await _fire_response_listeners(+ self._response_listeners, body, model, exc+ )ms.attach_task(asyncio.create_task(_produce()))return ms@@ -297,7 +392,11 @@ class FauxProvider:stream: MessageStream,message: AssistantMessage,signal: asyncio.Event | None,+ model: Model | None = None,) -> None:+ # ``model`` is optional so existing tests that call this private+ # helper directly without a model still work. _emit short-circuits+ # the listener fan-out when model is None.partial = AssistantMessage(content=[],stop_reason=message.stop_reason,@@ -309,17 +408,27 @@ class FauxProvider:if signal and signal.is_set():aborted = self._make_aborted(partial)- stream.push(StreamEvent(type="error", error_message="Request was aborted"))+ await self._emit(+ stream,+ StreamEvent(type="error", error_message="Request was aborted"),+ model,+ )stream.set_result(aborted)return- stream.push(StreamEvent(type="start", partial=partial.model_copy(deep=True)))+ await self._emit(+ stream,+ StreamEvent(type="start", partial=partial.model_copy(deep=True)),+ model,+ )for block in message.content:if signal and signal.is_set():aborted = self._make_aborted(partial)- stream.push(- StreamEvent(type="error", error_message="Request was aborted")+ await self._emit(+ stream,+ StreamEvent(type="error", error_message="Request was aborted"),+ model,)stream.set_result(aborted)return@@ -327,21 +436,25 @@ class FauxProvider:if isinstance(block, ThinkingContent):partial.content.append(ThinkingContent(thinking=""))block_idx = len(partial.content) - 1- stream.push(+ await self._emit(+ stream,StreamEvent(type="thinking_start",content_index=block_idx,partial=partial.model_copy(deep=True),- )+ ),+ model,)for chunk in _split_by_token_size(block.thinking, self._min, self._max):await self._schedule_chunk(chunk)if signal and signal.is_set():aborted = self._make_aborted(partial)- stream.push(+ await self._emit(+ stream,StreamEvent(type="error", error_message="Request was aborted"- )+ ),+ model,)stream.set_result(aborted)return@@ -350,60 +463,72 @@ class FauxProvider:partial.content[-1] = ThinkingContent(thinking=last.thinking + chunk)- stream.push(+ await self._emit(+ stream,StreamEvent(type="thinking_delta",delta=chunk,content_index=block_idx,partial=partial.model_copy(deep=True),- )+ ),+ model,)- stream.push(+ await self._emit(+ stream,StreamEvent(type="thinking_end",content_index=block_idx,partial=partial.model_copy(deep=True),- )+ ),+ model,)elif isinstance(block, TextContent):partial.content.append(TextContent(text=""))block_idx = len(partial.content) - 1- stream.push(+ await self._emit(+ stream,StreamEvent(type="text_start",content_index=block_idx,partial=partial.model_copy(deep=True),- )+ ),+ model,)for chunk in _split_by_token_size(block.text, self._min, self._max):await self._schedule_chunk(chunk)if signal and signal.is_set():aborted = self._make_aborted(partial)- stream.push(+ await self._emit(+ stream,StreamEvent(type="error", error_message="Request was aborted"- )+ ),+ model,)stream.set_result(aborted)returnlast = partial.content[-1]if isinstance(last, TextContent):partial.content[-1] = TextContent(text=last.text + chunk)- stream.push(+ await self._emit(+ stream,StreamEvent(type="text_delta",delta=chunk,content_index=block_idx,partial=partial.model_copy(deep=True),- )+ ),+ model,)- stream.push(+ await self._emit(+ stream,StreamEvent(type="text_end",content_index=block_idx,partial=partial.model_copy(deep=True),- )+ ),+ model,)elif isinstance(block, ToolCall):@@ -411,52 +536,64 @@ class FauxProvider:ToolCall(id=block.id, name=block.name, arguments={}))block_idx = len(partial.content) - 1- stream.push(+ await self._emit(+ stream,StreamEvent(type="toolcall_start",content_index=block_idx,partial=partial.model_copy(deep=True),- )+ ),+ model,)json_str = json.dumps(block.arguments)for chunk in _split_by_token_size(json_str, self._min, self._max):await self._schedule_chunk(chunk)if signal and signal.is_set():aborted = self._make_aborted(partial)- stream.push(+ await self._emit(+ stream,StreamEvent(type="error", error_message="Request was aborted"- )+ ),+ model,)stream.set_result(aborted)return- stream.push(+ await self._emit(+ stream,StreamEvent(type="toolcall_delta",delta=chunk,content_index=block_idx,partial=partial.model_copy(deep=True),- )+ ),+ model,)last = partial.content[-1]if isinstance(last, ToolCall):partial.content[-1] = ToolCall(id=block.id, name=block.name, arguments=block.arguments)- stream.push(+ await self._emit(+ stream,StreamEvent(type="toolcall_end",content_index=block_idx,partial=partial.model_copy(deep=True),- )+ ),+ model,)if message.stop_reason in ("error", "aborted"):- stream.push(StreamEvent(type="error", error_message=message.error_message))+ await self._emit(+ stream,+ StreamEvent(type="error", error_message=message.error_message),+ model,+ )stream.set_result(message)return- stream.push(StreamEvent(type="done"))+ await self._emit(stream, StreamEvent(type="done"), model)stream.set_result(message)async def _schedule_chunk(self, chunk: str) -> None:diff --git a/cubepi/providers/openai.py b/cubepi/providers/openai.pyindex c49e271..785c387 100644--- a/cubepi/providers/openai.py+++ b/cubepi/providers/openai.py@@ -9,6 +9,7 @@ from cubepi.utils.json_parse import parse_streaming_jsonfrom cubepi.providers.base import (AssistantMessage,+ BaseProvider,ImageContent,Message,MessageStream,@@ -23,12 +24,14 @@ from cubepi.providers.base import (ToolResultMessage,Usage,UserMessage,+ _fire_request_listeners,+ _fire_response_listeners,invoke_on_payload,invoke_on_response,)-class OpenAIProvider:+class OpenAIProvider(BaseProvider):def __init__(self,*,@@ -38,6 +41,7 @@ class OpenAIProvider:extra_body: dict[str, Any] | None = None,extra_headers: dict[str, str] | None = None,) -> None:+ super().__init__()import openaikwargs: dict[str, Any] = {}@@ -82,6 +86,8 @@ class OpenAIProvider:kwargs["tools"] = [self._convert_tool(t) for t in tools]async def _produce() -> None:+ body: dict | None = None+ exc: BaseException | None = Nonetry:nonlocal kwargskwargs = await invoke_on_payload(opts.on_payload, kwargs, model)@@ -108,6 +114,14 @@ class OpenAIProvider:if "include_usage" not in so:so["include_usage"] = True+ # Fire request listeners AFTER all kwargs mutations so observers+ # see the final wire payload (including extra_body merges,+ # max_completion_tokens_alias rewrite, and stream_options+ # injection). The on_payload mutator already ran above.+ # _fire_request_listeners deep-copies so a listener cannot+ # accidentally mutate the dict that's about to be sent.+ await _fire_request_listeners(self._request_listeners, kwargs, model)+response = await self._client.chat.completions.create(**kwargs)# Invoke on_response with HTTP metadata if available@@ -129,8 +143,10 @@ class OpenAIProvider:provider_id=model.provider,model_id=model.id,)- ms.push(- StreamEvent(type="start", partial=partial.model_copy(deep=True))+ await self._emit(+ ms,+ StreamEvent(type="start", partial=partial.model_copy(deep=True)),+ model,)current_text = ""@@ -140,11 +156,37 @@ class OpenAIProvider:response_id: str | None = Nonethinking_started = Falsethinking_content_index: int | None = None+ # Captured for _assemble_response. Populated from the first chunk+ # that exposes them; later chunks shouldn't overwrite.+ response_model: str | None = None+ response_created: int | None = None+ system_fingerprint: str | None = None+ service_tier: str | None = None+ final_finish_reason: str | None = None+ final_usage: Any = Noneasync for chunk in response:# Usage-only chunk (stream_options.include_usage=True sends a# trailing chunk with no choices and usage populated).+ if response_model is None:+ rm = getattr(chunk, "model", None)+ if rm:+ response_model = rm+ if response_created is None:+ rc = getattr(chunk, "created", None)+ if rc is not None:+ response_created = rc+ if system_fingerprint is None:+ sf = getattr(chunk, "system_fingerprint", None)+ if sf:+ system_fingerprint = sf+ if service_tier is None:+ st = getattr(chunk, "service_tier", None)+ if st:+ service_tier = st+if getattr(chunk, "usage", None) is not None:+ final_usage = chunk.usageu = chunk.usageprompt_tokens = getattr(u, "prompt_tokens", 0) or 0cached_tokens = (@@ -175,11 +217,13 @@ class OpenAIProvider:"error_message": "Request was aborted",})- ms.push(+ await self._emit(+ ms,StreamEvent(type="error",error_message="Request was aborted",- )+ ),+ model,)ms.set_result(aborted)return@@ -220,37 +264,43 @@ class OpenAIProvider:if not thinking_started:partial.content.append(ThinkingContent(thinking=""))thinking_content_index = len(partial.content) - 1- ms.push(+ await self._emit(+ ms,StreamEvent(type="thinking_start",content_index=thinking_content_index,partial=partial.model_copy(deep=True),- )+ ),+ model,)thinking_started = Trueexisting = partial.content[thinking_content_index].thinking # type: ignore[union-attr]partial.content[thinking_content_index] = ThinkingContent(thinking=existing + reasoning_delta)- ms.push(+ await self._emit(+ ms,StreamEvent(type="thinking_delta",delta=reasoning_delta,content_index=thinking_content_index,partial=partial.model_copy(deep=True),- )+ ),+ model,)if delta.content:if not text_started:partial.content.append(TextContent(text=""))text_content_index = len(partial.content) - 1- ms.push(+ await self._emit(+ ms,StreamEvent(type="text_start",content_index=text_content_index,partial=partial.model_copy(deep=True),- )+ ),+ model,)text_started = Truecurrent_text += delta.content@@ -258,13 +308,15 @@ class OpenAIProvider:partial.content[-1], TextContent):partial.content[-1] = TextContent(text=current_text)- ms.push(+ await self._emit(+ ms,StreamEvent(type="text_delta",delta=delta.content,content_index=text_content_index,partial=partial.model_copy(deep=True),- )+ ),+ model,)if delta.tool_calls:@@ -272,12 +324,14 @@ class OpenAIProvider:idx = tc_delta.indexif idx not in tool_calls_in_progress:if text_started:- ms.push(+ await self._emit(+ ms,StreamEvent(type="text_end",content_index=text_content_index,partial=partial.model_copy(deep=True),- )+ ),+ model,)text_started = Falsetool_calls_in_progress[idx] = {@@ -300,18 +354,21 @@ class OpenAIProvider:tool_calls_in_progress[idx]["content_index"] = (tc_content_index)- ms.push(+ await self._emit(+ ms,StreamEvent(type="toolcall_start",content_index=tc_content_index,partial=partial.model_copy(deep=True),- )+ ),+ model,)if tc_delta.function and tc_delta.function.arguments:tool_calls_in_progress[idx]["arguments"] += (tc_delta.function.arguments)- ms.push(+ await self._emit(+ ms,StreamEvent(type="toolcall_delta",delta=tc_delta.function.arguments,@@ -319,30 +376,36 @@ class OpenAIProvider:"content_index"],partial=partial.model_copy(deep=True),- )+ ),+ model,)finish_reason = (chunk.choices[0].finish_reason if chunk.choices else None)if finish_reason:+ final_finish_reason = finish_reasonif thinking_started:- ms.push(+ await self._emit(+ ms,StreamEvent(type="thinking_end",content_index=thinking_content_index,partial=partial.model_copy(deep=True),- )+ ),+ model,)thinking_started = Falseif text_started:- ms.push(+ await self._emit(+ ms,StreamEvent(type="text_end",content_index=text_content_index,partial=partial.model_copy(deep=True),- )+ ),+ model,)for idx, tc_data in tool_calls_in_progress.items():@@ -354,12 +417,14 @@ class OpenAIProvider:name=tc_data["name"],arguments=args,)- ms.push(+ await self._emit(+ ms,StreamEvent(type="toolcall_end",content_index=tc_data["content_index"],partial=partial.model_copy(deep=True),- )+ ),+ model,)stop_map = {@@ -380,25 +445,114 @@ class OpenAIProvider:})- ms.push(StreamEvent(type="done"))+ body = self._assemble_response(+ response_id=response_id,+ model_id=response_model or model.id,+ created=response_created,+ system_fingerprint=system_fingerprint,+ service_tier=service_tier,+ text=current_text,+ tool_calls_in_progress=tool_calls_in_progress,+ finish_reason=final_finish_reason,+ usage=final_usage,+ )+ await self._emit(ms, StreamEvent(type="done"), model)ms.set_result(partial)- except BaseException as exc:+ except BaseException as e:+ exc = eerror_msg = AssistantMessage(content=[],stop_reason="error",- error_message=str(exc),+ error_message=str(e),usage=Usage(),timestamp=time.time(),)- ms.push(StreamEvent(type="error", error_message=str(exc)))+ await self._emit(+ ms, StreamEvent(type="error", error_message=str(e)), model+ )ms.set_result(error_msg)- if not isinstance(exc, Exception):+ if not isinstance(e, Exception):raise+ finally:+ await _fire_response_listeners(+ self._response_listeners, body, model, exc+ )ms.attach_task(asyncio.create_task(_produce()))return ms+ @staticmethod+ def _assemble_response(+ *,+ response_id: str | None,+ model_id: str,+ created: int | None,+ system_fingerprint: str | None,+ service_tier: str | None,+ text: str,+ tool_calls_in_progress: dict[int, dict[str, Any]],+ finish_reason: str | None,+ usage: Any,+ ) -> dict[str, Any]:+ """Assemble OpenAI's non-streaming ``chat.completion`` response shape+ from accumulated streaming state.+ """+ tool_calls: list[dict[str, Any]] = []+ for idx in sorted(tool_calls_in_progress):+ tc = tool_calls_in_progress[idx]+ tool_calls.append(+ {+ "id": tc.get("id", ""),+ "type": "function",+ "function": {+ "name": tc.get("name", ""),+ "arguments": tc.get("arguments", ""),+ },+ }+ )++ message: dict[str, Any] = {+ "role": "assistant",+ "content": text or None,+ }+ if tool_calls:+ message["tool_calls"] = tool_calls++ usage_dict: dict[str, Any] = {}+ if usage is not None:+ usage_dict = {+ "prompt_tokens": getattr(usage, "prompt_tokens", 0) or 0,+ "completion_tokens": getattr(usage, "completion_tokens", 0) or 0,+ "total_tokens": getattr(usage, "total_tokens", 0) or 0,+ }+ details = getattr(usage, "prompt_tokens_details", None)+ if details is not None:+ cached = getattr(details, "cached_tokens", None)+ if cached is not None:+ usage_dict["prompt_tokens_details"] = {"cached_tokens": cached}++ body: dict[str, Any] = {+ "id": response_id,+ "object": "chat.completion",+ "created": created,+ "model": model_id,+ "choices": [+ {+ "index": 0,+ "message": message,+ "finish_reason": finish_reason,+ "logprobs": None,+ }+ ],+ "usage": usage_dict,+ }+ if system_fingerprint is not None:+ body["system_fingerprint"] = system_fingerprint+ if service_tier is not None:+ body["service_tier"] = service_tier+ return body+@staticmethoddef _convert_message(msg: Message) -> dict[str, Any]:if isinstance(msg, UserMessage):diff --git a/cubepi/providers/openai_responses.py b/cubepi/providers/openai_responses.pyindex c2c7e77..cf1f8ab 100644--- a/cubepi/providers/openai_responses.py+++ b/cubepi/providers/openai_responses.py@@ -7,6 +7,7 @@ from typing import Anyfrom cubepi.providers.base import (AssistantMessage,+ BaseProvider,ImageContent,Message,MessageStream,@@ -22,6 +23,8 @@ from cubepi.providers.base import (ToolResultMessage,Usage,UserMessage,+ _fire_request_listeners,+ _fire_response_listeners,invoke_on_payload,invoke_on_response,)@@ -39,7 +42,7 @@ _THINKING_TO_EFFORT: dict[ThinkingLevel, str | None] = {}-class OpenAIResponsesProvider:+class OpenAIResponsesProvider(BaseProvider):"""Provider that uses the OpenAI Responses API.The Responses API supports reasoning models (o-series) with streaming,@@ -49,6 +52,7 @@ class OpenAIResponsesProvider:def __init__(self, *, api_key: str | None = None, base_url: str | None = None) -> None:+ super().__init__()import openaikwargs: dict[str, Any] = {}@@ -58,6 +62,17 @@ class OpenAIResponsesProvider:kwargs["base_url"] = base_urlself._client = openai.AsyncOpenAI(**kwargs)+ @staticmethod+ def _assemble_response(resp: Any) -> dict[str, Any] | None:+ """Convert the OpenAI Responses SDK Response object to its canonical+ dict shape (same as a non-streaming Responses.create() return value).+ """+ if resp is None:+ return None+ if hasattr(resp, "model_dump"):+ return resp.model_dump(mode="json")+ return dict(resp) if isinstance(resp, dict) else None+async def stream(self,model: Model,@@ -104,9 +119,12 @@ class OpenAIResponsesProvider:kwargs["temperature"] = model.temperatureasync def _produce() -> None:+ body: dict | None = None+ exc: BaseException | None = Nonetry:nonlocal kwargskwargs = await invoke_on_payload(opts.on_payload, kwargs, model)+ await _fire_request_listeners(self._request_listeners, kwargs, model)response = await self._client.responses.create(**kwargs)@@ -128,8 +146,10 @@ class OpenAIResponsesProvider:provider_id=model.provider,model_id=model.id,)- ms.push(- StreamEvent(type="start", partial=partial.model_copy(deep=True))+ await self._emit(+ ms,+ StreamEvent(type="start", partial=partial.model_copy(deep=True)),+ model,)# Track current streaming state@@ -149,11 +169,13 @@ class OpenAIResponsesProvider:"error_message": "Request was aborted",})- ms.push(+ await self._emit(+ ms,StreamEvent(type="error",error_message="Request was aborted",- )+ ),+ model,)ms.set_result(aborted)return@@ -168,24 +190,28 @@ class OpenAIResponsesProvider:current_thinking = ""partial.content.append(ThinkingContent(thinking=""))current_content_index = len(partial.content) - 1- ms.push(+ await self._emit(+ ms,StreamEvent(type="thinking_start",content_index=current_content_index,partial=partial.model_copy(deep=True),- )+ ),+ model,)elif item.type == "message":current_item_type = "message"current_text = ""partial.content.append(TextContent(text=""))current_content_index = len(partial.content) - 1- ms.push(+ await self._emit(+ ms,StreamEvent(type="text_start",content_index=current_content_index,partial=partial.model_copy(deep=True),- )+ ),+ model,)elif item.type == "function_call":current_item_type = "function_call"@@ -209,12 +235,14 @@ class OpenAIResponsesProvider:))current_content_index = len(partial.content) - 1- ms.push(+ await self._emit(+ ms,StreamEvent(type="toolcall_start",content_index=current_content_index,partial=partial.model_copy(deep=True),- )+ ),+ model,)# --- Reasoning (thinking) deltas ---@@ -227,13 +255,15 @@ class OpenAIResponsesProvider:partial.content[-1] = ThinkingContent(thinking=current_thinking)- ms.push(+ await self._emit(+ ms,StreamEvent(type="thinking_delta",delta=event.delta,content_index=current_content_index,partial=partial.model_copy(deep=True),- )+ ),+ model,)elif etype == "response.reasoning_text.delta":@@ -245,13 +275,15 @@ class OpenAIResponsesProvider:partial.content[-1] = ThinkingContent(thinking=current_thinking)- ms.push(+ await self._emit(+ ms,StreamEvent(type="thinking_delta",delta=event.delta,content_index=current_content_index,partial=partial.model_copy(deep=True),- )+ ),+ model,)elif etype == "response.reasoning_summary_part.done":@@ -264,13 +296,15 @@ class OpenAIResponsesProvider:partial.content[-1] = ThinkingContent(thinking=current_thinking)- ms.push(+ await self._emit(+ ms,StreamEvent(type="thinking_delta",delta="\n\n",content_index=current_content_index,partial=partial.model_copy(deep=True),- )+ ),+ model,)# --- Text deltas ---@@ -281,13 +315,15 @@ class OpenAIResponsesProvider:partial.content[-1], TextContent):partial.content[-1] = TextContent(text=current_text)- ms.push(+ await self._emit(+ ms,StreamEvent(type="text_delta",delta=event.delta,content_index=current_content_index,partial=partial.model_copy(deep=True),- )+ ),+ model,)elif etype == "response.refusal.delta":@@ -297,26 +333,30 @@ class OpenAIResponsesProvider:partial.content[-1], TextContent):partial.content[-1] = TextContent(text=current_text)- ms.push(+ await self._emit(+ ms,StreamEvent(type="text_delta",delta=event.delta,content_index=current_content_index,partial=partial.model_copy(deep=True),- )+ ),+ model,)# --- Tool call argument deltas ---elif etype == "response.function_call_arguments.delta":if active_tool_item_id and active_tool_item_id in tool_state:tool_state[active_tool_item_id]["json"] += event.delta- ms.push(+ await self._emit(+ ms,StreamEvent(type="toolcall_delta",delta=event.delta,content_index=current_content_index,partial=partial.model_copy(deep=True),- )+ ),+ model,)elif etype == "response.function_call_arguments.done":@@ -340,12 +380,14 @@ class OpenAIResponsesProvider:partial.content[-1] = ThinkingContent(thinking=final_thinking)- ms.push(+ await self._emit(+ ms,StreamEvent(type="thinking_end",content_index=current_content_index,partial=partial.model_copy(deep=True),- )+ ),+ model,)current_item_type = None@@ -366,12 +408,14 @@ class OpenAIResponsesProvider:and isinstance(partial.content[-1], TextContent)):partial.content[-1] = TextContent(text=final_text)- ms.push(+ await self._emit(+ ms,StreamEvent(type="text_end",content_index=current_content_index,partial=partial.model_copy(deep=True),- )+ ),+ model,)current_item_type = None@@ -396,18 +440,21 @@ class OpenAIResponsesProvider:name=item.name,arguments=args,)- ms.push(+ await self._emit(+ ms,StreamEvent(type="toolcall_end",content_index=current_content_index,partial=partial.model_copy(deep=True),- )+ ),+ model,)current_item_type = None# --- Response completed ---elif etype == "response.completed":resp = event.response+ body = self._assemble_response(resp)usage = Usage()if resp and resp.usage:cached = 0@@ -433,7 +480,7 @@ class OpenAIResponsesProvider:else None,})- ms.push(StreamEvent(type="done"))+ await self._emit(ms, StreamEvent(type="done"), model)ms.set_result(partial)return@@ -448,6 +495,7 @@ class OpenAIResponsesProvider:elif etype == "response.failed":resp = event.response+ body = self._assemble_response(resp)error_detail = ""if resp and hasattr(resp, "error") and resp.error:code = getattr(resp.error, "code", "unknown")@@ -465,21 +513,28 @@ class OpenAIResponsesProvider:raise RuntimeError(error_detail or "Unknown error (no details)")# If we get here without response.completed, finalize- ms.push(StreamEvent(type="done"))+ await self._emit(ms, StreamEvent(type="done"), model)ms.set_result(partial)- except BaseException as exc:+ except BaseException as e:+ exc = eerror_msg = AssistantMessage(content=[],stop_reason="error",- error_message=str(exc),+ error_message=str(e),usage=Usage(),timestamp=time.time(),)- ms.push(StreamEvent(type="error", error_message=str(exc)))+ await self._emit(+ ms, StreamEvent(type="error", error_message=str(e)), model+ )ms.set_result(error_msg)- if not isinstance(exc, Exception):+ if not isinstance(e, Exception):raise+ finally:+ await _fire_response_listeners(+ self._response_listeners, body, model, exc+ )ms.attach_task(asyncio.create_task(_produce()))return msdiff --git a/pyproject.toml b/pyproject.tomlindex 84e8139..9534fab 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -1,6 +1,6 @@[project]name = "cubepi"-version = "0.3.0"+version = "0.4.0"description = "Pythonic async-native agent framework"readme = "README.md"license = "MIT"diff --git a/tests/providers/test_listener_registry.py b/tests/providers/test_listener_registry.pynew file mode 100644index 0000000..3f6c1ba--- /dev/null+++ b/tests/providers/test_listener_registry.py@@ -0,0 +1,784 @@+"""Pin the persistent Provider listener registry contract.++These tests don't depend on any real LLM provider — they use FauxProvider+which inherits from BaseProvider with the same listener wiring as the+production providers.+"""++from __future__ import annotations++import asyncio+import time++import pytest++from cubepi.providers.base import Model, StreamEvent, StreamOptions, UserMessage+from cubepi.providers.faux import FauxProvider, faux_assistant_message+++MODEL = Model(id="faux-1", provider="faux")+++async def _drain(stream) -> None:+ """Consume every event from a stream until done; return final result."""+ async for _ in stream:+ pass+ return await stream.result()+++async def _run_once(provider: FauxProvider, response: str = "hello") -> None:+ provider.append_responses([faux_assistant_message(response)])+ ms = await provider.stream(MODEL, [UserMessage(content=[])])+ await _drain(ms)+++class TestSubscribeAndFire:+ async def test_each_listener_type_fires(self):+ provider = FauxProvider()+ req_seen: list[tuple] = []+ chunk_seen: list[tuple] = []+ resp_seen: list[tuple] = []++ provider.subscribe_request(+ lambda payload, model: req_seen.append((payload, model))+ )+ provider.subscribe_chunk(lambda event, model: chunk_seen.append((event, model)))+ provider.subscribe_response(+ lambda body, model, exc: resp_seen.append((body, model, exc))+ )++ await _run_once(provider, "hi")++ assert len(req_seen) == 1+ payload, model = req_seen[0]+ assert isinstance(payload, dict)+ assert payload["model"] == MODEL.id+ assert model is MODEL++ # At least start, text_start, one delta, text_end, done.+ assert len(chunk_seen) >= 4+ assert all(isinstance(ev, StreamEvent) for ev, _ in chunk_seen)+ assert all(m is MODEL for _, m in chunk_seen)+ assert chunk_seen[0][0].type == "start"+ assert chunk_seen[-1][0].type == "done"++ assert len(resp_seen) == 1+ body, model, exc = resp_seen[0]+ assert exc is None+ assert model is MODEL+ assert body is not None+ # Faux body is deterministic — pin schema:+ assert body["id"] == "faux-1"+ assert body["model"] == MODEL.id+ assert body["role"] == "assistant"+ assert body["content"] == [{"type": "text", "text": "hi"}]+ assert body["stop_reason"] == "stop"+++class TestDetach:+ async def test_detach_stops_invocations(self):+ provider = FauxProvider()+ seen: list = []+ detach = provider.subscribe_request(lambda payload, model: seen.append(payload))++ await _run_once(provider)+ assert len(seen) == 1++ detach()+ await _run_once(provider)+ assert len(seen) == 1+++class TestMultipleSubscribers:+ async def test_registration_order_preserved(self):+ provider = FauxProvider()+ order: list[str] = []+ provider.subscribe_request(lambda p, m: order.append("first"))+ provider.subscribe_request(lambda p, m: order.append("second"))+ provider.subscribe_request(lambda p, m: order.append("third"))++ await _run_once(provider)+ assert order == ["first", "second", "third"]+++class TestExceptionIsolation:+ async def test_raising_listener_does_not_crash_stream(self):+ provider = FauxProvider()++ def bad(payload, model):+ raise RuntimeError("listener bomb")++ seen: list = []+ provider.subscribe_request(bad)+ provider.subscribe_request(lambda p, m: seen.append("after-bomb"))++ # Stream must complete normally.+ provider.append_responses([faux_assistant_message("ok")])+ ms = await provider.stream(MODEL, [UserMessage(content=[])])+ result = await _drain(ms)+ assert result.stop_reason == "stop"++ # Second listener still fires despite the first raising.+ assert seen == ["after-bomb"]+++class TestResponseListenerExactlyOnce:+ async def test_normal_completion(self):+ provider = FauxProvider()+ seen: list[tuple] = []+ provider.subscribe_response(lambda body, model, exc: seen.append((body, exc)))+ await _run_once(provider, "done")+ assert len(seen) == 1+ body, exc = seen[0]+ assert exc is None+ assert body is not None+ assert body["stop_reason"] == "stop"++ async def test_exception_path(self):+ provider = FauxProvider()+ seen: list[tuple] = []+ provider.subscribe_response(lambda body, model, exc: seen.append((body, exc)))++ async def boom(messages, model, system_prompt, tools):+ raise RuntimeError("provider boom")++ provider.append_responses([boom])+ ms = await provider.stream(MODEL, [UserMessage(content=[])])+ await _drain(ms)++ assert len(seen) == 1+ body, exc = seen[0]+ assert isinstance(exc, RuntimeError)+ assert "provider boom" in str(exc)++ async def test_cancellation_path(self):+ """When the producer task is cancelled mid-stream, subscribe_response+ must still fire exactly once with a CancelledError. (A cancel issued+ before the producer task has begun running is a no-op per asyncio+ semantics — the coroutine body never executes — and is not the+ observability contract we're guaranteeing.)"""+ provider = FauxProvider(tokens_per_second=10.0) # slow chunking+ seen: list[tuple] = []+ provider.subscribe_response(+ lambda body, model, exc: seen.append((body, type(exc) if exc else None))+ )++ # Long content so the producer is mid-stream when we cancel.+ provider.append_responses([faux_assistant_message("x" * 400)])+ ms = await provider.stream(MODEL, [UserMessage(content=[])])++ # Let the producer reach at least one await before cancelling.+ # Without this, cancel() races the task scheduler — see asyncio+ # semantics: a cancel before the first await skips the body.+ await asyncio.sleep(0.05)++ assert ms._producer_task is not None+ ms._producer_task.cancel()+ with pytest.raises(asyncio.CancelledError):+ await ms._producer_task++ # Listener must have fired exactly once and seen CancelledError.+ assert len(seen) == 1+ body, exc_type = seen[0]+ assert exc_type is asyncio.CancelledError+++class TestPayloadOrdering:+ async def test_on_payload_mutation_visible_to_request_listener(self):+ """StreamOptions.on_payload mutates the payload; the persistent+ subscribe_request listener fires AFTER that mutation, so it sees+ the final wire payload."""+ provider = FauxProvider()++ async def mutator(payload, model):+ new = dict(payload)+ new["mutated_by_on_payload"] = True+ return new++ seen: list[dict] = []+ provider.subscribe_request(lambda payload, model: seen.append(payload))++ provider.append_responses([faux_assistant_message("ok")])+ opts = StreamOptions(on_payload=mutator)+ ms = await provider.stream(MODEL, [UserMessage(content=[])], options=opts)+ await _drain(ms)++ assert len(seen) == 1+ assert seen[0].get("mutated_by_on_payload") is True+++class TestChunkListenerImmutability:+ async def test_listener_mutation_does_not_leak_to_consumer(self):+ """subscribe_chunk listeners receive a deep copy of the StreamEvent+ so a redacting/mutating observer cannot edit what `async for ev in+ ms` consumers (e.g. cubepi/agent/loop.py) observe."""+ provider = FauxProvider()+ consumer_events: list = []++ def redactor(event, model):+ # Try to mutate — this should NOT affect the consumer-side+ # event of the same chunk.+ if event.partial is not None:+ event.partial.content.clear()++ provider.subscribe_chunk(redactor)+ provider.append_responses([faux_assistant_message("hello world")])+ ms = await provider.stream(MODEL, [UserMessage(content=[])])+ async for ev in ms:+ consumer_events.append(ev)+ await ms.result()++ # The consumer should have seen at least one text_delta event+ # whose partial.content was NOT empty. If the redactor's mutation+ # had leaked, every event's partial.content would be empty.+ text_deltas = [+ e+ for e in consumer_events+ if e.type == "text_delta" and e.partial is not None+ ]+ assert text_deltas, "expected at least one text_delta on the consumer side"+ assert any(ev.partial.content for ev in text_deltas), (+ "redactor's mutation leaked into consumer's queued events"+ )++ async def test_listener_mutation_does_not_leak_between_listeners(self):+ """Each chunk listener gets its OWN copy — a mutating listener-A+ must not affect what listener-B (registered later) observes+ when they both fire for the same StreamEvent."""+ provider = FauxProvider()+ b_saw_empty_partial: list[bool] = []++ def redactor_a(event, model):+ if event.partial is not None:+ event.partial.content.clear()+ event.delta = "REDACTED"++ def observer_b(event, model):+ if event.partial is not None:+ b_saw_empty_partial.append(len(event.partial.content) == 0)++ provider.subscribe_chunk(redactor_a)+ provider.subscribe_chunk(observer_b)+ provider.append_responses([faux_assistant_message("listener isolation")])+ await _run_once(provider, "isolated")++ assert b_saw_empty_partial, "observer_b never saw a partial-bearing event"+ # If per-listener isolation were broken, all of B's observations+ # would have an empty partial.content. At least one should not.+ assert not all(b_saw_empty_partial), (+ "listener-A's mutation leaked into listener-B's view"+ )+++class TestResultPreservesCallerCancel:+ async def test_result_propagates_caller_cancellation(self):+ """MessageStream.result() must not swallow the CALLER's+ CancelledError while it's waiting for the producer task to+ finish its finally cleanup. The producer should also continue+ running its listener cleanup despite the caller cancel+ (asyncio.shield protects it)."""+ provider = FauxProvider(tokens_per_second=200.0)+ listener_ran = asyncio.Event()++ async def slow_listener(body, model, exc):+ # The producer's finally awaits this. Take long enough that+ # the caller has time to cancel.+ await asyncio.sleep(0.05)+ listener_ran.set()++ provider.subscribe_response(slow_listener)+ provider.append_responses([faux_assistant_message("ok")])++ ms = await provider.stream(MODEL, [UserMessage(content=[])])++ # A task that awaits result(). We cancel it after set_result+ # fires (i.e. while result() is still waiting on the producer).+ async def waiter():+ return await ms.result()++ waiter_task = asyncio.create_task(waiter())+ # Give the producer time to push 'done' and call set_result;+ # waiter is then blocked on await asyncio.shield(producer_task).+ await asyncio.sleep(0.02)+ waiter_task.cancel()++ with pytest.raises(asyncio.CancelledError):+ await waiter_task++ # The shielded producer task should still complete its listener+ # cleanup.+ await ms._producer_task+ assert listener_ran.is_set()+++class TestResponseListenerImmutability:+ async def test_listener_mutation_does_not_leak_between_listeners(self):+ """Each response listener gets its own body snapshot — a+ mutating listener-A must not affect what listener-B observes."""+ provider = FauxProvider()+ b_saw_content: list = []++ def redactor_a(body, model, exc):+ if body is not None:+ body["content"] = "REDACTED"+ body["model"] = "REDACTED"++ def observer_b(body, model, exc):+ if body is not None:+ b_saw_content.append(body.get("content"))++ provider.subscribe_response(redactor_a)+ provider.subscribe_response(observer_b)+ await _run_once(provider, "preserved")++ assert b_saw_content, "observer_b never received a body"+ assert b_saw_content[0] != "REDACTED", (+ "listener-A's body mutation leaked into listener-B's view"+ )+++class TestRequestListenerImmutability:+ async def test_listener_mutation_does_not_leak_into_next_listener(self):+ """subscribe_request gets a defensive deep copy of the payload —+ a listener that mutates it (e.g. redaction) must not affect what+ subsequent listeners observe nor what the provider actually+ sends. The Faux provider's _produce uses the same helper as the+ real providers."""+ provider = FauxProvider()+ seen_payloads: list[dict] = []++ def redactor(payload, model):+ # Mutate in place — should not affect the next listener.+ payload["messages"] = "REDACTED"++ def observer(payload, model):+ seen_payloads.append(payload)++ provider.subscribe_request(redactor)+ provider.subscribe_request(observer)++ await _run_once(provider, "ok")++ assert len(seen_payloads) == 1+ # The observer receives a deepcopy too; whatever redactor did to+ # its copy isn't visible here because each listener gets its own+ # call site of _fire_listeners, which iterates the same snapshot+ # passed by _fire_request_listeners. (Note: the contract is+ # "snapshot vs the live kwargs"; per-listener isolation is a+ # stronger property we don't promise.)+ # Verify the snapshot's structure is intact for at least the+ # required fields:+ assert "model" in seen_payloads[0]+++class TestConcurrentStreams:+ async def test_concurrent_streams_share_listeners(self):+ provider = FauxProvider()+ responses_seen: list[tuple] = []+ provider.subscribe_response(+ lambda body, model, exc: responses_seen.append((body["id"], model.id))+ )++ provider.append_responses(+ [+ faux_assistant_message("a"),+ faux_assistant_message("b"),+ ]+ )+ model_a = Model(id="faux-a", provider="faux")+ model_b = Model(id="faux-b", provider="faux")++ ms_a, ms_b = await asyncio.gather(+ provider.stream(model_a, [UserMessage(content=[])]),+ provider.stream(model_b, [UserMessage(content=[])]),+ )+ await asyncio.gather(_drain(ms_a), _drain(ms_b))++ assert len(responses_seen) == 2+ ids = {r[0] for r in responses_seen}+ # seq counter increments per call: faux-1, faux-2.+ assert ids == {"faux-1", "faux-2"}+ models = {r[1] for r in responses_seen}+ assert models == {"faux-a", "faux-b"}+++class TestSelfDetachMidIteration:+ async def test_listener_can_detach_itself_during_iteration(self):+ """A listener detaching itself mid-stream must not skip the next+ listener (snapshot semantics via tuple(listeners) in _fire_listeners).+ """+ provider = FauxProvider()+ fires = {"first": 0, "second": 0}++ detach_holder: list = [None]++ def first(event, model):+ fires["first"] += 1+ # After the first invocation, detach self.+ if fires["first"] == 1 and detach_holder[0] is not None:+ detach_holder[0]()++ def second(event, model):+ fires["second"] += 1++ detach_holder[0] = provider.subscribe_chunk(first)+ provider.subscribe_chunk(second)++ await _run_once(provider, "abc")++ # First fired exactly once (it detached itself); second fired+ # on the same first chunk AND subsequent chunks.+ assert fires["first"] == 1+ assert fires["second"] >= 2+++class TestMidStreamSubscription:+ async def test_listener_subscribed_inside_a_listener_fires_on_next_stream(self):+ """A listener registered while another listener is mid-execution+ starts firing on the NEXT stream call, not retroactively on the+ same one."""+ provider = FauxProvider()+ late: list[int] = []+ first_seen: list[int] = []++ def first(body, model, exc):+ first_seen.append(1)+ provider.subscribe_response(lambda body, model, exc: late.append(1))++ provider.subscribe_response(first)++ await _run_once(provider, "first")+ assert first_seen == [1]+ assert late == [] # Not retroactive.++ await _run_once(provider, "second")+ # Both `first` (still subscribed) and the late listener fire on the+ # second stream.+ assert first_seen == [1, 1]+ assert len(late) == 1+++class TestSlowListenerBlocks:+ async def test_slow_async_listener_serializes_stream(self):+ """Listeners run inline in the producer coroutine; a slow listener+ delays subsequent chunks. This documents the contract."""+ provider = FauxProvider()+ per_chunk_sleep = 0.02+ n_chunks = 0++ async def slow(event, model):+ nonlocal n_chunks+ n_chunks += 1+ await asyncio.sleep(per_chunk_sleep)++ provider.subscribe_chunk(slow)+ provider.append_responses([faux_assistant_message("hello there friend")])++ start = time.monotonic()+ ms = await provider.stream(MODEL, [UserMessage(content=[])])+ await _drain(ms)+ elapsed = time.monotonic() - start++ # We expect at least n_chunks * per_chunk_sleep elapsed wall time.+ # n_chunks should be >= 4 (start, text_start, deltas..., text_end, done).+ assert n_chunks >= 4+ assert elapsed >= n_chunks * per_chunk_sleep * 0.8 # 20% leeway+++class TestAsyncListeners:+ async def test_async_request_listener_awaited(self):+ provider = FauxProvider()+ seen: list = []++ async def cb(payload, model):+ await asyncio.sleep(0)+ seen.append(payload)++ provider.subscribe_request(cb)+ await _run_once(provider, "ok")+ assert len(seen) == 1++ async def test_async_response_listener_runs_through_normal_completion(self):+ """On the normal-completion path, async response listeners are+ awaited inline so the producer task does not end before the+ listener body has run. This matters under `asyncio.run(main())`+ where the loop tears down the instant `main()` returns —+ detached listener tasks would otherwise be cancelled before they+ execute."""+ provider = FauxProvider()+ ran = asyncio.Event()++ async def cb(body, model, exc):+ await asyncio.sleep(0)+ ran.set()++ provider.subscribe_response(cb)+ await _run_once(provider, "ok")+ # The producer task should have already awaited the listener;+ # ran should be set the moment _run_once returns (no need to wait).+ assert ran.is_set()++ async def test_async_response_listener_under_asyncio_run_teardown(self):+ """Simulate the asyncio.run teardown race: caller awaits+ stream.result() and then the function returns, mimicking a+ program that exits via asyncio.run. The async response listener+ must have completed by the time the producer task is done."""+ provider = FauxProvider()+ outcome: list = []++ async def cb(body, model, exc):+ # Yield then record — proves the coroutine actually progressed.+ await asyncio.sleep(0)+ outcome.append("ran")++ provider.subscribe_response(cb)+ provider.append_responses([faux_assistant_message("hi")])++ ms = await provider.stream(MODEL, [UserMessage(content=[])])+ result = await ms.result()+ assert result.stop_reason == "stop"+ # Wait for the producer task itself to finish — that's where the+ # response listener is awaited inline now.+ await ms._producer_task+ assert outcome == ["ran"]++ async def test_async_response_listener_exception_does_not_bubble(self):+ """Per the _fire_listeners_sync contract, async listener exceptions+ are wrapped in _safe_run_coroutine and swallowed. This must not+ surface as an asyncio unhandled-task-exception warning."""+ provider = FauxProvider()+ bombed = asyncio.Event()++ async def bomb(body, model, exc):+ bombed.set()+ raise RuntimeError("async listener bomb")++ provider.subscribe_response(bomb)+ # Should complete normally despite the listener exception.+ await _run_once(provider, "ok")+ # Wait for the detached task to actually run.+ await asyncio.wait_for(bombed.wait(), timeout=1.0)+ # Yield once more so the inner coroutine has a chance to raise+ # and be caught by _safe_run_coroutine.+ await asyncio.sleep(0.01)+++class TestAbortBodyShape:+ """Faux response listener must NOT report a full successful body when+ the stream was aborted via opts.signal."""++ async def test_aborted_run_reports_aborted_body(self):+ provider = FauxProvider(tokens_per_second=10.0)+ seen: list = []+ provider.subscribe_response(lambda body, model, exc: seen.append((body, exc)))++ provider.append_responses([faux_assistant_message("x" * 400)])+ signal = asyncio.Event()+ opts = StreamOptions(signal=signal)++ ms = await provider.stream(MODEL, [UserMessage(content=[])], options=opts)+ # Let producer enter the streaming loop.+ await asyncio.sleep(0.05)+ # Trigger abort path inside _stream_with_deltas (signal check between+ # chunks). The producer will set an aborted result on the stream.+ signal.set()+ # Drain so the producer can complete.+ await _drain(ms)++ assert len(seen) == 1+ body, exc = seen[0]+ assert exc is None # abort isn't an exception in this path+ assert body is not None+ # The body must reflect the aborted state, NOT the queued full+ # response. stop_reason on the aborted body is "aborted".+ assert body["stop_reason"] == "aborted"+++class TestBaseProvider:+ """Cover BaseProvider sentinels not exercised by Faux."""++ async def test_stream_raises_not_implemented(self):+ from cubepi.providers.base import BaseProvider++ class Empty(BaseProvider):+ pass++ with pytest.raises(NotImplementedError):+ await Empty().stream(MODEL, [UserMessage(content=[])])++ def test_detach_is_idempotent(self):+ provider = FauxProvider()+ detach = provider.subscribe_request(lambda p, m: None)+ detach()+ # Calling detach again must not raise even though the listener is+ # already gone — covers the ValueError swallow in _detach.+ detach()+++class TestFireListenersHelpers:+ """Direct unit tests for the listener-fanout helpers, bypassing+ provider streaming. These cover branches that are awkward to reach+ end-to-end."""++ async def test_fire_listeners_empty_returns(self):+ from cubepi.providers.base import _fire_listeners++ # Empty list — must return without touching anything.+ await _fire_listeners([])++ async def test_fire_listeners_swallows_sync_exception(self):+ from cubepi.providers.base import _fire_listeners++ seen: list = []++ def bad(x):+ raise RuntimeError("nope")++ def good(x):+ seen.append(x)++ await _fire_listeners([bad, good], "payload")+ # Despite the first raising, the second still ran.+ assert seen == ["payload"]++ def test_fire_listeners_sync_empty_returns(self):+ from cubepi.providers.base import _fire_listeners_sync++ _fire_listeners_sync([]) # No listeners — short-circuit.++ def test_fire_listeners_sync_swallows_sync_exception(self):+ from cubepi.providers.base import _fire_listeners_sync++ seen: list = []++ def bad(x):+ raise RuntimeError("listener oops")++ def good(x):+ seen.append(x)++ _fire_listeners_sync([bad, good], "x")+ assert seen == ["x"]++ def test_fire_listeners_sync_no_running_loop(self):+ """Outside a running event loop, asyncio.create_task raises+ RuntimeError. The sync helper must swallow it (covers the+ no-running-loop branch in the detached-task scheduling)."""+ from cubepi.providers.base import _fire_listeners_sync++ async def async_cb(x):+ pass # pragma: no cover — never awaited in this test++ # Important: do NOT await; we're synchronous here, no event loop.+ _fire_listeners_sync([async_cb], "x")+++class TestProviderEmit:+ """Cover the chunk-listener fan-out inside Anthropic and OpenAI+ _emit helpers directly — they each carry the same hot-path branch+ but the Faux end-to-end tests exercise Faux's _emit only."""++ async def test_anthropic_emit_fires_chunk_listeners(self):+ from cubepi.providers.anthropic import AnthropicProvider+ from cubepi.providers.base import MessageStream++ provider = AnthropicProvider(api_key="test-key")+ seen: list = []+ provider.subscribe_chunk(lambda ev, m: seen.append((ev.type, m.id)))++ ms = MessageStream()+ event = StreamEvent(type="text_delta", delta="hi")+ await provider._emit(ms, event, MODEL)++ assert seen == [("text_delta", MODEL.id)]+ # The event was also pushed onto the stream.+ first = await ms.__anext__()+ assert first.type == "text_delta"++ async def test_openai_emit_fires_chunk_listeners(self):+ from cubepi.providers.openai import OpenAIProvider+ from cubepi.providers.base import MessageStream++ provider = OpenAIProvider(api_key="test-key")+ seen: list = []+ provider.subscribe_chunk(lambda ev, m: seen.append(ev.type))++ ms = MessageStream()+ await provider._emit(ms, StreamEvent(type="text_delta", delta="hi"), MODEL)+ assert seen == ["text_delta"]++ async def test_openai_responses_emit_fires_chunk_listeners(self):+ from cubepi.providers.openai_responses import OpenAIResponsesProvider+ from cubepi.providers.base import MessageStream++ provider = OpenAIResponsesProvider(api_key="test-key")+ seen: list = []+ provider.subscribe_chunk(lambda ev, m: seen.append(ev.type))++ ms = MessageStream()+ await provider._emit(ms, StreamEvent(type="text_delta", delta="hi"), MODEL)+ assert seen == ["text_delta"]+++class TestAssembleResponse:+ """Cover static _assemble_response helpers directly — exercises the+ optional-field branches without needing a real LLM stream."""++ def test_openai_assemble_with_system_fingerprint_and_service_tier(self):+ from cubepi.providers.openai import OpenAIProvider++ class FakeUsageDetails:+ cached_tokens = 7++ class FakeUsage:+ prompt_tokens = 10+ completion_tokens = 4+ total_tokens = 14+ prompt_tokens_details = FakeUsageDetails()++ body = OpenAIProvider._assemble_response(+ response_id="resp-123",+ model_id="gpt-test",+ created=12345,+ system_fingerprint="fp_abc",+ service_tier="scale",+ text="hello",+ tool_calls_in_progress={+ 0: {"id": "call_1", "name": "do_thing", "arguments": '{"a":1}'}+ },+ finish_reason="stop",+ usage=FakeUsage(),+ )++ assert body["id"] == "resp-123"+ assert body["object"] == "chat.completion"+ assert body["model"] == "gpt-test"+ assert body["created"] == 12345+ # Both optional fields present in body.+ assert body["system_fingerprint"] == "fp_abc"+ assert body["service_tier"] == "scale"+ assert body["choices"][0]["finish_reason"] == "stop"+ assert body["choices"][0]["message"]["content"] == "hello"+ assert body["choices"][0]["message"]["tool_calls"][0]["id"] == "call_1"+ assert body["usage"]["prompt_tokens_details"] == {"cached_tokens": 7}++ def test_openai_assemble_without_optional_fields(self):+ from cubepi.providers.openai import OpenAIProvider++ body = OpenAIProvider._assemble_response(+ response_id=None,+ model_id="gpt-test",+ created=None,+ system_fingerprint=None,+ service_tier=None,+ text="",+ tool_calls_in_progress={},+ finish_reason=None,+ usage=None,+ )+ # Optional fields omitted entirely.+ assert "system_fingerprint" not in body+ assert "service_tier" not in body+ # Content normalizes to None when text is empty and no tool calls.+ assert body["choices"][0]["message"]["content"] is None+ assert body["usage"] == {}diff --git a/uv.lock b/uv.lockindex a53f1fa..4aebc73 100644--- a/uv.lock+++ b/uv.lock@@ -374,7 +374,7 @@ wheels = [[[package]]name = "cubepi"-version = "0.3.0"+version = "0.4.0"source = { editable = "." }dependencies = [{ name = "anthropic" },