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(tracing): record compaction summarizer's LLM call
xf gongd64b28f0a8b4
diff --git a/cubepi/agent/agent.py b/cubepi/agent/agent.pyindex 9e557ee..497dc26 100644--- a/cubepi/agent/agent.py+++ b/cubepi/agent/agent.py@@ -162,6 +162,11 @@ class Agent(Generic[TMessage]):if tools:self._state.tools = toolsmiddleware = middleware or []+ # Retain the list so observers (e.g. cubepi.tracing.Recorder) can+ # walk it after construction — they need to reach attributes like+ # ``Middleware.providers()`` that aren't captured by the composed+ # hook callables below.+ self._middleware: list[Middleware] = list(middleware)middleware_tools: list[AgentTool] = []for mw in middleware:middleware_tools.extend(getattr(mw, "tools", []) or [])diff --git a/cubepi/middleware/base.py b/cubepi/middleware/base.pyindex 8a52bcd..f955312 100644--- a/cubepi/middleware/base.py+++ b/cubepi/middleware/base.py@@ -1,7 +1,7 @@from __future__ import annotationsfrom dataclasses import dataclass, field-from typing import Callable, Literal+from typing import Callable, Iterable, Literalimport asyncio@@ -12,7 +12,7 @@ from cubepi.agent.types import (BeforeToolCallContext,BeforeToolCallResult,)-from cubepi.providers.base import AssistantMessage, Message+from cubepi.providers.base import AssistantMessage, Message, Providerfrom cubepi.types import JsonObject, StructuredObject@@ -90,6 +90,18 @@ class Middleware:) -> list[Message] | None:raise NotImplementedError+ def providers(self) -> Iterable[Provider]:+ """Return any extra LLM providers this middleware drives directly.++ Some middlewares (e.g. ``CompactionMiddleware``) make their own LLM+ calls outside the agent's main provider. Returning those providers+ here lets ``cubepi.tracing.Recorder`` wire its listeners so the+ resulting calls show up in the trace tree alongside the agent's own+ chat spans. Default is empty — middlewares that do not call any+ LLM directly need not override.+ """+ return ()+def _has_method(middleware: Middleware, name: str) -> bool:method = getattr(type(middleware), name, None)diff --git a/cubepi/middleware/compaction/__init__.py b/cubepi/middleware/compaction/__init__.pyindex ff2f4de..f654d6a 100644--- a/cubepi/middleware/compaction/__init__.py+++ b/cubepi/middleware/compaction/__init__.py@@ -133,6 +133,13 @@ class CompactionMiddleware(Middleware):ctx.extra["compaction_until_msg_index"] = new_boundaryreturn _compressed_view(messages, new_state, new_boundary)+ def providers(self) -> tuple[Provider, ...]:+ # Surface the summary provider so ``cubepi.tracing.Recorder`` can+ # wire its listeners — without this the summarizer's LLM call is+ # invisible to the trace, even though the rest of the turn is+ # recorded.+ return (self._summary_provider,)+__all__ = ["CompactionMiddleware",diff --git a/cubepi/middleware/compaction/summarizer.py b/cubepi/middleware/compaction/summarizer.pyindex e4c4e62..fdc1440 100644--- a/cubepi/middleware/compaction/summarizer.py+++ b/cubepi/middleware/compaction/summarizer.py@@ -1,6 +1,7 @@from __future__ import annotationsimport asyncio+import contextlibfrom cubepi.middleware.compaction.state import CompactionState, message_refsfrom cubepi.providers.base import (@@ -13,6 +14,48 @@ from cubepi.providers.base import (UserMessage,)++def _compaction_summary_span(message_count: int):+ """Open a parent span for the summarizer's LLM call.++ Without this wrapper the summarizer's chat span — emitted automatically+ once :class:`cubepi.tracing.Recorder` is wired to the summary provider —+ sits flat under ``cubepi.turn`` and is hard to tell apart from the+ agent's own chat span. The wrapping name makes the role obvious and+ tags it with the number of messages being summarised.++ Resolves the tracer via ``cubepi.mcp._tracing._get_tracer`` so the span+ routes through whichever :class:`cubepi.tracing.Tracer` is currently+ attached to the running agent. Without that lookup the OTel global+ provider is a no-op unless the user called ``set_tracer_provider``,+ which cubepi deliberately doesn't do. Falls back to a no-op context+ manager if neither OpenTelemetry nor an attached Tracer is available.+ """+ try:+ from cubepi.mcp._tracing import _get_tracer+ except ImportError:+ return contextlib.nullcontext()++ try:+ tracer = _get_tracer("cubepi.middleware.compaction")+ except Exception:+ return contextlib.nullcontext()++ cm = tracer.start_as_current_span("cubepi.compaction.summarize")++ @contextlib.contextmanager+ def _wrapped():+ with cm as span:+ try:+ if span is not None:+ span.set_attribute("cubepi.compaction.message_count", message_count)+ except Exception:+ pass+ yield span++ return _wrapped()++SUMMARIZER_SYSTEM_PROMPT = """\You compress a chat transcript into a brief, faithful narrative for an AI assistantthat is continuing the conversation. Rules:@@ -64,19 +107,22 @@ async def summarize(if existing and existing.summary:system_prompt += "\n\n" + EXISTING_SUMMARY_SUFFIX.format(prev=existing.summary)- response = await provider.generate(- model=model,- messages=[- UserMessage(- content=[TextContent(text=_format_transcript(messages_to_summarize))]- )- ],- system_prompt=system_prompt,- options=StreamOptions(signal=abort_signal),- max_output_tokens=max_summary_tokens,- temperature=0.0,- thinking="off",- )+ with _compaction_summary_span(len(messages_to_summarize)):+ response = await provider.generate(+ model=model,+ messages=[+ UserMessage(+ content=[+ TextContent(text=_format_transcript(messages_to_summarize))+ ]+ )+ ],+ system_prompt=system_prompt,+ options=StreamOptions(signal=abort_signal),+ max_output_tokens=max_summary_tokens,+ temperature=0.0,+ thinking="off",+ )text = "".join(block.text for block in response.content if isinstance(block, TextContent)diff --git a/cubepi/tracing/recorder.py b/cubepi/tracing/recorder.pyindex 9c5caee..8b55569 100644--- a/cubepi/tracing/recorder.py+++ b/cubepi/tracing/recorder.py@@ -233,21 +233,37 @@ class Recorder:# alias should one be added later.provider = getattr(agent, "_provider", None) or getattr(agent, "provider", None)provider_detachers: list[Callable[[], None]] = []++ def _subscribe(p: Any) -> None:+ if not isinstance(p, BaseProvider):+ return+ provider_detachers.append(p.subscribe_request(self._on_provider_request))+ provider_detachers.append(p.subscribe_chunk(self._on_provider_chunk))+ provider_detachers.append(p.subscribe_response(self._on_provider_response))+# Attach must be all-or-nothing: if a later subscription raises, unwind# the ones already registered (incl. the agent listener) and re-raise,# so a failed attach() leaves no dangling listeners. The caller never# gets a ``detach`` callable on this path, so we cannot defer cleanup.try:- if isinstance(provider, BaseProvider):- provider_detachers.append(- provider.subscribe_request(self._on_provider_request)- )- provider_detachers.append(- provider.subscribe_chunk(self._on_provider_chunk)- )- provider_detachers.append(- provider.subscribe_response(self._on_provider_response)- )+ _subscribe(provider)+ # Middlewares may drive their own LLM providers (e.g.+ # ``CompactionMiddleware``'s summary provider) — wire them too+ # so those calls show up in the trace tree instead of+ # silently bypassing it. ``Middleware.providers()`` returns+ # an empty iterable by default, so middlewares that don't+ # touch an LLM directly cost nothing here.+ seen: set[int] = {id(provider)} if provider is not None else set()+ for mw in getattr(agent, "_middleware", []) or []:+ try:+ extra = list(mw.providers())+ except Exception:+ extra = []+ for p in extra:+ if id(p) in seen:+ continue+ seen.add(id(p))+ _subscribe(p)except BaseException:for d in provider_detachers:try:diff --git a/tests/tracing/test_recorder.py b/tests/tracing/test_recorder.pyindex 5a4ff6b..2175ad4 100644--- a/tests/tracing/test_recorder.py+++ b/tests/tracing/test_recorder.py@@ -494,6 +494,78 @@ class TestErrorAndAbort:assert fallback_chat.status.status_code == StatusCode.UNSET+class TestMiddlewareProviders:+ """Recorder must also wire listeners for any provider a middleware drives+ directly (e.g. CompactionMiddleware.summary_provider) — without this the+ summarizer LLM call is invisible to the trace, even though the rest of the+ turn is recorded."""++ async def test_compaction_summary_provider_emits_chat_span(self):+ from cubepi.checkpointer.memory import MemoryCheckpointer+ from cubepi.middleware.compaction import CompactionMiddleware+ from cubepi.providers.base import UserMessage++ main = FauxProvider()+ summarizer = FauxProvider()+ # Cap at near-zero so transform_context triggers immediately.+ mw = CompactionMiddleware(+ summary_provider=summarizer,+ summary_model=Model(id="summary-1", provider="faux"),+ max_tokens_before_compact=1,+ keep_recent_messages=1,+ max_summary_tokens=128,+ min_compact_messages=2,+ )+ # Pre-seed history via a checkpointer so transform_context sees a+ # message list above the compaction boundary on the first prompt.+ cp = MemoryCheckpointer()+ thread_id = "t-compaction-trace"+ await cp.append(+ thread_id,+ [+ UserMessage(content=[TextContent(text="first")]),+ faux_assistant_message("first reply"),+ UserMessage(content=[TextContent(text="second")]),+ faux_assistant_message("second reply"),+ ],+ )++ agent = Agent(+ provider=main,+ model=MODEL,+ system_prompt="test",+ middleware=[mw],+ checkpointer=cp,+ thread_id=thread_id,+ )+ exporter = InMemoryExporter()+ tracer = Tracer(+ service_name="test-svc",+ agent_name="test-agent",+ exporters=[exporter],+ )+ tracer.attach(agent)++ summarizer.append_responses([faux_assistant_message("a brief summary")])+ main.append_responses([faux_assistant_message("ok")])++ await agent.prompt("third")+ await agent.wait_for_idle()+ await tracer.shutdown()++ chats = [s for s in exporter.spans if s.name.startswith("chat ")]+ # One chat from the summarizer, one from the agent's main turn.+ chat_models = sorted(_attrs(c).get("gen_ai.request.model") for c in chats)+ assert chat_models == ["faux-1", "summary-1"], chat_models++ # The C-step parent span wraps the summarizer's chat.+ summary_spans = [+ s for s in exporter.spans if s.name == "cubepi.compaction.summarize"+ ]+ assert len(summary_spans) == 1+ assert _attrs(summary_spans[0])["cubepi.compaction.message_count"] >= 1++class TestSafeToolName:"""``_safe_tool_name`` must handle all three tool payload shapes:Anthropic/cubepi top-level ``name``, OpenAI Responses top-level