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): Phase 2 — record_content=True + redaction hook (#83)
Chris96146e74e77b
diff --git a/cubepi/tracing/content.py b/cubepi/tracing/content.pynew file mode 100644index 0000000..4ea2da2--- /dev/null+++ b/cubepi/tracing/content.py@@ -0,0 +1,172 @@+"""Convert cubepi messages and tool definitions into the OpenTelemetry+GenAI semconv ``gen_ai.input.messages`` / ``gen_ai.output.messages`` /+``gen_ai.tool.definitions`` JSON shapes.++The OTel SDK only accepts simple attribute types (str, bool, int, float+and sequences thereof) on :meth:`Span.set_attribute`, so structured+content is serialized to a JSON **string** here. Backends that parse+``gen_ai.input.messages`` follow this convention.+"""++from __future__ import annotations++import json+from typing import Any++from cubepi.providers.base import (+ AssistantMessage,+ Message,+ TextContent,+ ThinkingContent,+ ToolCall,+ ToolResultMessage,+ UserMessage,+)+++def messages_to_semconv(messages: list[Message]) -> list[dict[str, Any]]:+ """Translate a list of cubepi messages into the GenAI semconv shape.++ Returns a list of ``{"role": ..., "parts": [...]}`` dicts. Note+ that ``"reasoning"`` is a cubepi extension to the standard semconv+ part-type set; see the spec.+ """+ out: list[dict[str, Any]] = []+ for msg in messages:+ if isinstance(msg, UserMessage):+ out.append(+ {"role": "user", "parts": _user_or_tool_content_to_parts(msg.content)}+ )+ elif isinstance(msg, AssistantMessage):+ out.append(+ {"role": "assistant", "parts": _assistant_content_to_parts(msg.content)}+ )+ elif isinstance(msg, ToolResultMessage):+ out.append(+ {+ "role": "tool",+ "parts": [+ {+ "type": "tool_call_response",+ "id": msg.tool_call_id,+ "result": _text_of(msg.content),+ }+ ],+ }+ )+ return out+++def system_instructions_to_semconv(system_prompt: str | None) -> list[dict[str, Any]]:+ """Wrap a system prompt string in the semconv messages-array shape.++ Per the spec §10.5, ``gen_ai.system_instructions`` follows the same+ structure as ``gen_ai.input.messages`` but with a single+ ``role: "system"`` entry.+ """+ if not system_prompt:+ return []+ return [+ {+ "role": "system",+ "parts": [{"type": "text", "content": system_prompt}],+ }+ ]+++def tool_definitions_to_semconv(payload: dict) -> list[dict[str, Any]]:+ """Pull tool schemas out of the provider's wire payload.++ Each provider shapes ``tools`` differently:+ - Anthropic: ``[{"name", "description", "input_schema"}]``+ - OpenAI chat: ``[{"type": "function", "function": {"name", "description", "parameters"}}]``+ - OpenAI Responses: same as chat but flattened+ - Faux: doesn't emit a tools key (handled by absence)++ Normalize all to ``[{"name", "description", "parameters"}]`` so a+ single backend renderer can show them consistently.+ """+ tools = payload.get("tools")+ if not isinstance(tools, list):+ return []+ out: list[dict[str, Any]] = []+ for t in tools:+ if not isinstance(t, dict):+ continue+ if "function" in t and isinstance(t["function"], dict):+ fn = t["function"]+ out.append(+ {+ "name": fn.get("name") or "",+ "description": fn.get("description") or "",+ "parameters": fn.get("parameters") or {},+ }+ )+ else:+ out.append(+ {+ "name": t.get("name") or "",+ "description": t.get("description") or "",+ "parameters": t.get("input_schema") or t.get("parameters") or {},+ }+ )+ return out+++def serialize_for_attribute(value: Any) -> str:+ """JSON-encode an arbitrary value for placement on a span attribute.++ Falls back to ``str(value)`` for objects without a JSON+ representation (rare, since we control the inputs).+ """+ try:+ return json.dumps(value, ensure_ascii=False, default=str)+ except Exception:+ return str(value)+++def _user_or_tool_content_to_parts(content: list[Any]) -> list[dict[str, Any]]:+ parts: list[dict[str, Any]] = []+ for block in content:+ if isinstance(block, TextContent):+ parts.append({"type": "text", "content": block.text})+ else:+ # Other UserMessage content types (e.g. ImageContent) — record+ # the type marker so a downstream backend can display a+ # placeholder; binary payloads are NOT emitted.+ type_marker = getattr(block, "type", "unknown")+ parts.append({"type": str(type_marker)})+ return parts+++def _assistant_content_to_parts(content: list[Any]) -> list[dict[str, Any]]:+ parts: list[dict[str, Any]] = []+ for block in content:+ if isinstance(block, TextContent):+ parts.append({"type": "text", "content": block.text})+ elif isinstance(block, ThinkingContent):+ # ``reasoning`` is a cubepi extension to the semconv parts+ # vocabulary; see docs/specs/2026-05-18-cubepi-tracing-design.md §10.5.+ parts.append({"type": "reasoning", "content": block.thinking})+ elif isinstance(block, ToolCall):+ parts.append(+ {+ "type": "tool_call",+ "id": block.id,+ "name": block.name,+ "arguments": block.arguments,+ }+ )+ else:+ type_marker = getattr(block, "type", "unknown")+ parts.append({"type": str(type_marker)})+ return parts+++def _text_of(content: list[Any]) -> str:+ """Concatenate text-typed content blocks into a single string."""+ parts: list[str] = []+ for block in content:+ if isinstance(block, TextContent):+ parts.append(block.text)+ return "".join(parts)diff --git a/cubepi/tracing/recorder.py b/cubepi/tracing/recorder.pyindex 84c5dda..1cdd2f1 100644--- a/cubepi/tracing/recorder.py+++ b/cubepi/tracing/recorder.py@@ -43,12 +43,20 @@ from cubepi.providers.base import (ToolResultMessage,UserMessage,)+from cubepi.tracing.content import (+ messages_to_semconv,+ serialize_for_attribute,+ system_instructions_to_semconv,+ tool_definitions_to_semconv,+)from cubepi.tracing.errors import cubepi_error_type_forfrom cubepi.tracing.schema import (CUBEPI_ABORTED,CUBEPI_AGENT_SYSTEM_PROMPT_SHA256,CUBEPI_AGENT_TOOLS,CUBEPI_INPUT_MESSAGES_COUNT,+ CUBEPI_LLM_RAW_REQUEST,+ CUBEPI_LLM_RAW_RESPONSE,CUBEPI_LLM_THINKING_LEVEL,CUBEPI_OUTPUT_MESSAGES_COUNT,CUBEPI_RUN_ID,@@ -63,6 +71,12 @@ from cubepi.tracing.schema import (CUBEPI_TURN_TOOL_CALLS_COUNT,ERROR_TYPE,EVENT_GEN_AI_EXCEPTION,+ GEN_AI_INPUT_MESSAGES,+ GEN_AI_OUTPUT_MESSAGES,+ GEN_AI_SYSTEM_INSTRUCTIONS,+ GEN_AI_TOOL_CALL_ARGUMENTS,+ GEN_AI_TOOL_CALL_RESULT,+ GEN_AI_TOOL_DEFINITIONS,GEN_AI_OPERATION_NAME,GEN_AI_PROVIDER_NAME,GEN_AI_REQUEST_MAX_TOKENS,@@ -117,6 +131,26 @@ class _RunState:new_message_count: int = 0# Whether any tool reported terminate=True in the current turn.turn_terminated_by_tool: bool = False+ # Content recording (only used when record_content=True).+ system_prompt: str | None = None+ # input_messages: user / tool_result messages — used by the root+ # span's ``gen_ai.input.messages``. Pure caller-provided input.+ input_messages: list[Any] = field(default_factory=list)+ # output_messages: assistant + tool_result messages produced+ # during the run — used by the root span's ``gen_ai.output.messages``.+ output_messages: list[Any] = field(default_factory=list)+ # transcript: ALL messages in chronological order, including prior+ # assistant turns. Used as the chat span's ``gen_ai.input.messages``+ # so multi-turn tool-using runs reconstruct correctly — the second+ # chat call's request includes the prior assistant tool-call+ # message plus the tool_result, and so must its input.messages+ # attribute.+ transcript: list[Any] = field(default_factory=list)+ # Per-turn message accumulators (cleared at TurnStart).+ turn_input_messages: list[Any] = field(default_factory=list)+ turn_output_messages: list[Any] = field(default_factory=list)+ # Chat-span specific tool_definitions captured at request time.+ chat_tool_definitions: list[dict] | None = Noneclass Recorder:@@ -127,9 +161,16 @@ class Recorder:agent can host many sequential runs over the recorder's lifetime."""- def __init__(self, tracer: "Tracer", *, record_content: bool = False) -> None:+ def __init__(+ self,+ tracer: "Tracer",+ *,+ record_content: bool = False,+ redact: "Callable[[str, Any], Any] | None" = None,+ ) -> None:self._tracer = tracerself._record_content = record_content+ self._redact = redact# Active run state. cubepi agents serialize runs (one# ``agent.run()`` at a time per Agent), so a single slot is# enough — but defensively key by AgentStartEvent identity@@ -254,6 +295,31 @@ class Recorder:run.agent_span.set_attribute(CUBEPI_OUTPUT_MESSAGES_COUNT, run.new_message_count)+ if self._record_content:+ if run.system_prompt:+ self._set_content_attr(+ run.agent_span,+ GEN_AI_SYSTEM_INSTRUCTIONS,+ system_instructions_to_semconv(run.system_prompt),+ )+ if run.input_messages:+ self._set_content_attr(+ run.agent_span,+ GEN_AI_INPUT_MESSAGES,+ messages_to_semconv(run.input_messages),+ )+ # ``event.messages`` is the run's full new_messages list —+ # for a normal ``agent.prompt(...)`` it includes the user+ # prompt(s) as well as the generated assistant/tool replies.+ # ``gen_ai.output.messages`` should be model output only, so+ # use the accumulator that tracks just assistant + tool+ # results.+ if run.output_messages:+ self._set_content_attr(+ run.agent_span,+ GEN_AI_OUTPUT_MESSAGES,+ messages_to_semconv(run.output_messages),+ )run.agent_span.end()self._run = None@@ -280,12 +346,20 @@ class Recorder:},)run.turn_terminated_by_tool = False+ run.turn_input_messages = []+ run.turn_output_messages = []def _on_turn_end(self, event: TurnEndEvent) -> None:run = self._runif run is None or run.turn_span is None:returnmsg = event.message+ # Track output messages: assistant + any tool_results from this turn.+ run.turn_output_messages.append(msg)+ run.output_messages.append(msg)+ for tr in getattr(event, "tool_results", []) or []:+ run.turn_output_messages.append(tr)+ run.output_messages.append(tr)# Map cubepi stop_reason to gen_ai.response.finish_reasons on# the chat span — already done in _on_provider_response. Here we# record the cubepi-normalized stop_reason on the turn span.@@ -300,6 +374,20 @@ class Recorder:run.turn_span.set_attribute(CUBEPI_TURN_TOOL_CALLS_COUNT, tool_calls_count)if run.turn_terminated_by_tool:run.turn_span.set_attribute(CUBEPI_TURN_TERMINATED_BY_TOOL, True)+ # Content: record per-turn input/output messages if enabled.+ if self._record_content:+ if run.turn_input_messages:+ self._set_content_attr(+ run.turn_span,+ GEN_AI_INPUT_MESSAGES,+ messages_to_semconv(run.turn_input_messages),+ )+ if run.turn_output_messages:+ self._set_content_attr(+ run.turn_span,+ GEN_AI_OUTPUT_MESSAGES,+ messages_to_semconv(run.turn_output_messages),+ )# Error handling on the turn: if assistant message stopped with# "error", mark turn ERROR. Abort path leaves UNSET + sets# cubepi.aborted on the invoke_agent root.@@ -330,6 +418,9 @@ class Recorder:# Per-span run_id so JsonlSpanExporter shards correctly.CUBEPI_RUN_ID: run.run_id,}+ # NOTE: gen_ai.tool.call.arguments is opt-in content recorded+ # after start_span so the redaction hook can run before the+ # attribute is committed.# Lookup AgentTool for description + execution_mode.tool_obj = self._find_tool(event.tool_name)if tool_obj is not None:@@ -344,6 +435,10 @@ class Recorder:attributes=attrs,)run.tool_spans[event.tool_call_id] = span+ if self._record_content and event.args is not None:+ self._set_content_attr(+ span, GEN_AI_TOOL_CALL_ARGUMENTS, _coerce_dict(event.args)+ )def _on_tool_exec_end(self, event: ToolExecutionEndEvent) -> None:run = self._run@@ -353,6 +448,10 @@ class Recorder:if span is None:returnspan.set_attribute(CUBEPI_TOOL_IS_ERROR, event.is_error)+ if self._record_content and event.result is not None:+ self._set_content_attr(+ span, GEN_AI_TOOL_CALL_RESULT, _coerce_dict(event.result)+ )if event.terminate:span.set_attribute(CUBEPI_TOOL_TERMINATE, True)run.turn_terminated_by_tool = True@@ -380,7 +479,9 @@ class Recorder:if run is None:returnmsg = event.message- # Count user-provided + tool-result messages as input.+ # Count user-provided + tool-result messages as input. We also+ # accumulate them for content recording (only emitted on spans+ # when ``record_content=True``).if isinstance(msg, (UserMessage, ToolResultMessage)):run.agent_span.set_attribute(CUBEPI_INPUT_MESSAGES_COUNT,@@ -391,12 +492,24 @@ class Recorder:)+ 1,)+ run.input_messages.append(msg)+ run.turn_input_messages.append(msg)+ run.transcript.append(msg)def _on_message_end(self, event: MessageEndEvent) -> None:- # Reserved for future use. Currently no-op — chat span is- # closed by the provider response listener, and turn span- # gets its stop_reason from TurnEndEvent.- del event+ run = self._run+ if run is None:+ return+ # Append assistant / tool_result messages to the transcript so+ # later chat spans see them in their ``gen_ai.input.messages``.+ # Note: ``output_messages`` accumulation happens at TurnEnd+ # (since it includes the synthesized turn snapshot); here we+ # only update the chronological transcript that drives chat+ # span input.+ msg = event.message+ msg_role = getattr(msg, "role", None)+ if msg_role in ("assistant", "tool_result"):+ run.transcript.append(msg)# ------------------------------------------------------------------# Provider listeners — drive the chat span lifetime@@ -461,7 +574,33 @@ class Recorder:run.chat_span = chat_spanrun.chat_open_ns = time.time_ns()run.chat_first_chunk_recorded = False- # cubepi.llm.raw_request is content; MVP is record_content=False.++ # Content (record_content=True): record system instructions,+ # input messages, tool definitions, and the raw wire payload.+ if self._record_content:+ sys_prompt = _extract_system_prompt(payload)+ if sys_prompt:+ run.system_prompt = sys_prompt+ sys_payload = system_instructions_to_semconv(sys_prompt)+ if sys_payload:+ self._set_content_attr(+ chat_span, GEN_AI_SYSTEM_INSTRUCTIONS, sys_payload+ )+ if run.transcript:+ # chat input = full chronological context the provider+ # is about to receive (user prompts + earlier+ # assistant/tool-result turns).+ self._set_content_attr(+ chat_span,+ GEN_AI_INPUT_MESSAGES,+ messages_to_semconv(run.transcript),+ )+ tool_defs = tool_definitions_to_semconv(payload)+ if tool_defs:+ run.chat_tool_definitions = tool_defs+ self._set_content_attr(chat_span, GEN_AI_TOOL_DEFINITIONS, tool_defs)+ # Raw wire payload — large; gated by record_content.+ self._set_content_attr(chat_span, CUBEPI_LLM_RAW_REQUEST, payload)def _on_provider_chunk(self, event: StreamEvent, model: "Model") -> None:del model@@ -493,6 +632,12 @@ class Recorder:try:if body is not None:self._record_chat_response_attrs(span, body)+ if self._record_content:+ # Output messages on chat span: the assembled body+ # itself (provider-shaped). Record both the raw+ # response (JSON dict) for backends that prefer it,+ # and the normalized output messages where derivable.+ self._set_content_attr(span, CUBEPI_LLM_RAW_RESPONSE, body)# Cooperative abort: providers may finish the response# listener with ``exc is None`` and a body whose finish# reason is ``"aborted"`` (faux + the agent's signal path).@@ -532,6 +677,29 @@ class Recorder:# helpers# ------------------------------------------------------------------+ def _set_content_attr(self, span: Any, key: str, value: Any) -> None:+ """Set a content attribute on ``span`` with optional redaction.++ ``value`` is JSON-serialized (OTel attribute values can only be+ simple scalars/sequences, not dicts/lists-of-dicts). When the+ Tracer has a ``redact`` hook, the raw value is passed through+ it first; returning ``None`` skips the attribute entirely.+ """+ if not self._record_content:+ return+ if self._redact is not None:+ try:+ value = self._redact(key, value)+ except Exception:+ # Redactor must never crash the recorder.+ return+ if value is None:+ return+ if isinstance(value, str):+ span.set_attribute(key, value)+ else:+ span.set_attribute(key, serialize_for_attribute(value))+def _find_tool(self, name: str):"""Look up an :class:`AgentTool` by name on the attached agent.@@ -707,6 +875,24 @@ def _safe_tool_name(t: Any) -> str:return str(name) if name else ""+def _coerce_dict(value: Any) -> Any:+ """Coerce a pydantic model or arbitrary object into a JSON-safe+ structure. Returns the value as-is if already a dict/list/scalar.+ """+ if hasattr(value, "model_dump"):+ try:+ return value.model_dump()+ except Exception:+ pass+ if hasattr(value, "__dict__") and not isinstance(value, type):+ # Best-effort dataclass-like coercion.+ try:+ return dict(vars(value))+ except Exception:+ pass+ return value++def _is_cancelled_error(exc: BaseException) -> bool:import asynciodiff --git a/cubepi/tracing/schema.py b/cubepi/tracing/schema.pyindex e622abb..23c3f04 100644--- a/cubepi/tracing/schema.py+++ b/cubepi/tracing/schema.py@@ -67,6 +67,14 @@ GEN_AI_TOOL_CALL_ID = "gen_ai.tool.call.id"GEN_AI_TOOL_TYPE = "gen_ai.tool.type"GEN_AI_TOOL_DESCRIPTION = "gen_ai.tool.description"+# Content (opt-in — only emitted when ``Tracer(record_content=True)``)+GEN_AI_INPUT_MESSAGES = "gen_ai.input.messages"+GEN_AI_OUTPUT_MESSAGES = "gen_ai.output.messages"+GEN_AI_SYSTEM_INSTRUCTIONS = "gen_ai.system_instructions"+GEN_AI_TOOL_DEFINITIONS = "gen_ai.tool.definitions"+GEN_AI_TOOL_CALL_ARGUMENTS = "gen_ai.tool.call.arguments"+GEN_AI_TOOL_CALL_RESULT = "gen_ai.tool.call.result"+# Network (recommended on CLIENT spans)SERVER_ADDRESS = "server.address"SERVER_PORT = "server.port"diff --git a/cubepi/tracing/tracer.py b/cubepi/tracing/tracer.pyindex 276ca95..6839755 100644--- a/cubepi/tracing/tracer.py+++ b/cubepi/tracing/tracer.py@@ -69,15 +69,11 @@ class Tracer:agent_version: str | None = None,exporters: list[SpanExporter] | None = None,record_content: bool = False,+ redact: "Callable[[str, Any], Any] | None" = None,resource: Resource | None = None,) -> None:- if record_content:- raise NotImplementedError(- "record_content=True is Phase 2 of cubepi.tracing. "- "Construct with record_content=False (default) for MVP."- )-self._record_content = record_content+ self._redact = redactself._resource = resource or _build_resource(service_name=service_name,service_version=service_version,@@ -120,6 +116,18 @@ class Tracer:"""return self._otel_tracer+ @property+ def redact(self) -> "Callable[[str, Any], Any] | None":+ """Optional ``(key, value) -> value`` filter applied at every+ ``set_attribute`` site for content attributes.++ Return ``None`` to drop the attribute entirely. Return a value+ of the same type to substitute. Useful for redacting PII inside+ ``gen_ai.input.messages`` and friends before they leave the+ process.+ """+ return self._redact+def attach(self, agent: "Agent") -> Callable[[], None]:"""Wire the cubepi recorder to ``agent``.@@ -130,7 +138,11 @@ class Tracer:"""from cubepi.tracing.recorder import Recorder- recorder = Recorder(self, record_content=self._record_content)+ recorder = Recorder(+ self,+ record_content=self._record_content,+ redact=self._redact,+ )return recorder.attach(agent)async def force_flush(self, timeout_seconds: float = 30.0) -> bool:diff --git a/tests/tracing/test_content_recording.py b/tests/tracing/test_content_recording.pynew file mode 100644index 0000000..58ec746--- /dev/null+++ b/tests/tracing/test_content_recording.py@@ -0,0 +1,460 @@+"""Phase 2: pin record_content=True attribute emissions + redaction hook.++When ``Tracer(record_content=True)``, the recorder emits opt-in content+attrs on each span layer per the OTel GenAI semconv:++- ``invoke_agent`` (root): gen_ai.input.messages / gen_ai.output.messages+ / gen_ai.system_instructions+- ``cubepi.turn``: gen_ai.input.messages / gen_ai.output.messages+- ``chat``: gen_ai.system_instructions / gen_ai.input.messages /+ gen_ai.tool.definitions / cubepi.llm.raw_request / cubepi.llm.raw_response+- ``execute_tool``: gen_ai.tool.call.arguments / gen_ai.tool.call.result++Plus a ``redact`` hook on the Tracer for per-attribute filtering.+"""++from __future__ import annotations++import json+from typing import Any++from opentelemetry.sdk.trace import ReadableSpan+from opentelemetry.sdk.trace.export import SpanExporter, SpanExportResult+from pydantic import BaseModel++from cubepi.agent.agent import Agent+from cubepi.agent.types import AgentTool, AgentToolResult+from cubepi.providers.base import Model, TextContent, ToolCall+from cubepi.providers.faux import FauxProvider, faux_assistant_message+from cubepi.tracing import Tracer+++MODEL = Model(id="faux-1", provider="faux")+++class _Capture(SpanExporter):+ def __init__(self) -> None:+ self.spans: list[ReadableSpan] = []++ def export(self, spans): # noqa: ANN001+ self.spans.extend(spans)+ return SpanExportResult.SUCCESS++ def shutdown(self) -> None:+ pass++ def force_flush(self, timeout_millis: int = 30_000) -> bool:+ return True+++def _attrs(span: ReadableSpan) -> dict[str, Any]:+ return dict(span.attributes or {})+++def _json_attr(span: ReadableSpan, key: str) -> Any:+ raw = _attrs(span).get(key)+ if raw is None:+ return None+ return json.loads(raw)+++async def _build(*, record_content: bool, redact=None, tools=None):+ provider = FauxProvider()+ agent = Agent(+ provider=provider,+ model=MODEL,+ system_prompt="be helpful, be careful",+ tools=tools,+ )+ exporter = _Capture()+ tracer = Tracer(+ service_name="t",+ agent_name="a",+ exporters=[exporter],+ record_content=record_content,+ redact=redact,+ )+ tracer.attach(agent)+ return agent, provider, exporter, tracer+++class TestContentDisabled:+ async def test_no_content_attrs_when_record_content_false(self):+ agent, provider, exporter, tracer = await _build(record_content=False)+ provider.append_responses([faux_assistant_message("hello")])++ await agent.prompt("hi")+ await agent.wait_for_idle()+ await tracer.shutdown()++ for span in exporter.spans:+ attrs = _attrs(span)+ for forbidden in (+ "gen_ai.input.messages",+ "gen_ai.output.messages",+ "gen_ai.system_instructions",+ "gen_ai.tool.definitions",+ "gen_ai.tool.call.arguments",+ "gen_ai.tool.call.result",+ "cubepi.llm.raw_request",+ "cubepi.llm.raw_response",+ ):+ assert forbidden not in attrs, (+ f"{span.name} should not carry {forbidden} with record_content=False"+ )+++class TestRootContent:+ async def test_invoke_agent_records_input_output_system(self):+ agent, provider, exporter, tracer = await _build(record_content=True)+ provider.append_responses([faux_assistant_message("hi back")])++ await agent.prompt("hello there")+ await agent.wait_for_idle()+ await tracer.shutdown()++ root = [s for s in exporter.spans if s.name == "invoke_agent"][0]+ sys_msgs = _json_attr(root, "gen_ai.system_instructions")+ assert sys_msgs == [+ {+ "role": "system",+ "parts": [{"type": "text", "content": "be helpful, be careful"}],+ }+ ]+ inp = _json_attr(root, "gen_ai.input.messages")+ assert isinstance(inp, list)+ assert inp[0]["role"] == "user"+ assert inp[0]["parts"][0] == {"type": "text", "content": "hello there"}+ out = _json_attr(root, "gen_ai.output.messages")+ assert isinstance(out, list)+ assert any(+ m.get("role") == "assistant"+ and any(p.get("content") == "hi back" for p in m.get("parts", []))+ for m in out+ )+++class TestChatContent:+ async def test_chat_span_carries_system_input_and_raw_payload(self):+ agent, provider, exporter, tracer = await _build(record_content=True)+ provider.append_responses([faux_assistant_message("hi")])++ await agent.prompt("x")+ await agent.wait_for_idle()+ await tracer.shutdown()++ chat = next(s for s in exporter.spans if s.name.startswith("chat "))+ attrs = _attrs(chat)+ assert "gen_ai.system_instructions" in attrs+ assert "gen_ai.input.messages" in attrs+ raw = json.loads(attrs["cubepi.llm.raw_request"])+ assert raw["model"] == MODEL.id+ assert "messages" in raw+ resp = json.loads(attrs["cubepi.llm.raw_response"])+ assert resp["id"] == "faux-1"+ assert resp["role"] == "assistant"+++class TestToolContent:+ async def test_execute_tool_carries_arguments_and_result(self):+ class Params(BaseModel):+ value: str++ async def run(tool_call_id, params, *, signal=None, on_update=None):+ return AgentToolResult(+ content=[TextContent(text=f"echoed: {params.value}")]+ )++ tool = AgentTool(+ name="echo", description="echo a thing", parameters=Params, execute=run+ )++ agent, provider, exporter, tracer = await _build(+ record_content=True, tools=[tool]+ )+ provider.append_responses(+ [+ faux_assistant_message(+ [ToolCall(id="t1", name="echo", arguments={"value": "X"})],+ stop_reason="tool_use",+ ),+ faux_assistant_message("done"),+ ]+ )++ await agent.prompt("x")+ await agent.wait_for_idle()+ await tracer.shutdown()++ t_span = next(s for s in exporter.spans if s.name.startswith("execute_tool "))+ attrs = _attrs(t_span)+ args = json.loads(attrs["gen_ai.tool.call.arguments"])+ assert args == {"value": "X"}+ result = json.loads(attrs["gen_ai.tool.call.result"])+ assert "content" in result+ assert any(+ isinstance(c, dict) and c.get("text") == "echoed: X"+ for c in result.get("content", [])+ )+++class TestTurnContent:+ async def test_turn_records_per_turn_input_and_output(self):+ agent, provider, exporter, tracer = await _build(record_content=True)+ provider.append_responses([faux_assistant_message("hello back")])++ await agent.prompt("hi")+ await agent.wait_for_idle()+ await tracer.shutdown()++ turn = next(s for s in exporter.spans if s.name == "cubepi.turn")+ inp = _json_attr(turn, "gen_ai.input.messages")+ assert inp[0]["parts"][0]["content"] == "hi"+ out = _json_attr(turn, "gen_ai.output.messages")+ assert out[0]["role"] == "assistant"+++class TestRootOutputIsOnlyGenerated:+ async def test_root_output_excludes_user_prompts(self):+ """The root invoke_agent's gen_ai.output.messages must be model+ output only (assistant + tool_result), NOT include the caller's+ user prompts — codex round-1 finding on PR #83."""+ agent, provider, exporter, tracer = await _build(record_content=True)+ provider.append_responses([faux_assistant_message("hello back")])+ await agent.prompt("hi there")+ await agent.wait_for_idle()+ await tracer.shutdown()++ root = next(s for s in exporter.spans if s.name == "invoke_agent")+ out = _json_attr(root, "gen_ai.output.messages")+ # No user-role messages must appear in output.+ for m in out:+ assert m["role"] != "user", (+ f"root gen_ai.output.messages must not include user prompts; got {m}"+ )+ # An assistant message with the model output IS expected.+ assert any(+ m["role"] == "assistant"+ and any(p.get("content") == "hello back" for p in m.get("parts", []))+ for m in out+ )+++class TestChatInputIncludesPriorAssistant:+ async def test_second_chat_input_includes_prior_assistant_turn(self):+ """In a tool-using multi-turn run, the second chat span's+ gen_ai.input.messages must include the prior assistant+ (tool-call) message + the tool_result so consumers can+ reconstruct the prompt — codex round-1 finding on PR #83."""++ class P(BaseModel):+ pass++ async def run(tool_call_id, params, *, signal=None, on_update=None):+ return AgentToolResult(content=[TextContent(text="tool-output")])++ tool = AgentTool(name="t", description="t", parameters=P, execute=run)++ agent, provider, exporter, tracer = await _build(+ record_content=True, tools=[tool]+ )+ provider.append_responses(+ [+ faux_assistant_message(+ [ToolCall(id="c1", name="t", arguments={})],+ stop_reason="tool_use",+ ),+ faux_assistant_message("final answer"),+ ]+ )++ await agent.prompt("kick off")+ await agent.wait_for_idle()+ await tracer.shutdown()++ chats = sorted(+ [s for s in exporter.spans if s.name.startswith("chat ")],+ key=lambda s: s.start_time or 0,+ )+ assert len(chats) == 2+ second = chats[1]+ inp = _json_attr(second, "gen_ai.input.messages")+ roles = [m["role"] for m in inp]+ # Must include the original user prompt, the assistant tool-call+ # message, and the tool result — in that order.+ assert roles.count("user") == 1+ assert "assistant" in roles+ assert "tool" in roles+ # The assistant message must carry the tool_call part.+ asst = next(m for m in inp if m["role"] == "assistant")+ assert any(p.get("type") == "tool_call" for p in asst.get("parts", []))+++class TestRedaction:+ async def test_redact_can_substitute(self):+ seen_keys: list[str] = []++ def redact(key: str, value: Any) -> Any:+ seen_keys.append(key)+ if key == "gen_ai.input.messages":+ return [+ {+ "role": "user",+ "parts": [{"type": "text", "content": "<REDACTED>"}],+ }+ ]+ return value++ agent, provider, exporter, tracer = await _build(+ record_content=True, redact=redact+ )+ provider.append_responses([faux_assistant_message("ok")])+ await agent.prompt("secret prompt")+ await agent.wait_for_idle()+ await tracer.shutdown()++ assert "gen_ai.input.messages" in seen_keys+ chat = next(s for s in exporter.spans if s.name.startswith("chat "))+ inp = _json_attr(chat, "gen_ai.input.messages")+ assert inp == [+ {"role": "user", "parts": [{"type": "text", "content": "<REDACTED>"}]}+ ]++ async def test_redact_can_drop_attribute(self):+ def redact(key: str, value: Any) -> Any:+ if key == "cubepi.llm.raw_request":+ return None+ return value++ agent, provider, exporter, tracer = await _build(+ record_content=True, redact=redact+ )+ provider.append_responses([faux_assistant_message("ok")])+ await agent.prompt("x")+ await agent.wait_for_idle()+ await tracer.shutdown()++ chat = next(s for s in exporter.spans if s.name.startswith("chat "))+ assert "cubepi.llm.raw_request" not in _attrs(chat)+ assert "gen_ai.input.messages" in _attrs(chat)++ async def test_redact_exception_is_swallowed(self):+ def redact(key: str, value: Any) -> Any:+ raise RuntimeError("bad redactor")++ agent, provider, exporter, tracer = await _build(+ record_content=True, redact=redact+ )+ provider.append_responses([faux_assistant_message("ok")])+ await agent.prompt("x")+ await agent.wait_for_idle()+ await tracer.shutdown()++ assert any(s.name == "invoke_agent" for s in exporter.spans)+ chat = next(s for s in exporter.spans if s.name.startswith("chat "))+ assert "gen_ai.input.messages" not in _attrs(chat)+++class TestContentHelpers:+ def test_messages_to_semconv_handles_all_block_types(self):+ from cubepi.providers.base import (+ AssistantMessage,+ ThinkingContent,+ )+ from cubepi.providers.base import ToolCall as _ToolCall+ from cubepi.providers.base import (+ ToolResultMessage,+ UserMessage,+ )+ from cubepi.tracing.content import messages_to_semconv++ msgs = [+ UserMessage(content=[TextContent(text="hi")]),+ AssistantMessage(+ content=[+ TextContent(text="ok"),+ ThinkingContent(thinking="planning..."),+ _ToolCall(id="c1", name="t", arguments={"a": 1}),+ ],+ stop_reason="tool_use",+ ),+ ToolResultMessage(+ tool_call_id="c1",+ tool_name="t",+ content=[TextContent(text="done")],+ ),+ ]+ out = messages_to_semconv(msgs)+ assert out[0]["role"] == "user"+ assert out[1]["role"] == "assistant"+ assert out[1]["parts"][0] == {"type": "text", "content": "ok"}+ assert out[1]["parts"][1] == {+ "type": "reasoning",+ "content": "planning...",+ }+ assert out[1]["parts"][2] == {+ "type": "tool_call",+ "id": "c1",+ "name": "t",+ "arguments": {"a": 1},+ }+ assert out[2]["role"] == "tool"+ assert out[2]["parts"][0] == {+ "type": "tool_call_response",+ "id": "c1",+ "result": "done",+ }++ def test_tool_definitions_anthropic_shape(self):+ from cubepi.tracing.content import tool_definitions_to_semconv++ payload = {+ "tools": [+ {+ "name": "fetch",+ "description": "fetch a url",+ "input_schema": {"type": "object"},+ }+ ]+ }+ out = tool_definitions_to_semconv(payload)+ assert out == [+ {+ "name": "fetch",+ "description": "fetch a url",+ "parameters": {"type": "object"},+ }+ ]++ def test_tool_definitions_openai_chat_shape(self):+ from cubepi.tracing.content import tool_definitions_to_semconv++ payload = {+ "tools": [+ {+ "type": "function",+ "function": {+ "name": "fetch",+ "description": "fetch a url",+ "parameters": {"type": "object"},+ },+ }+ ]+ }+ out = tool_definitions_to_semconv(payload)+ assert out == [+ {+ "name": "fetch",+ "description": "fetch a url",+ "parameters": {"type": "object"},+ }+ ]++ def test_serialize_for_attribute_fallback(self):+ from cubepi.tracing.content import serialize_for_attribute++ class NotJsonable:+ pass++ out = serialize_for_attribute(NotJsonable())+ assert isinstance(out, str)diff --git a/tests/tracing/test_recorder.py b/tests/tracing/test_recorder.pyindex 322432a..7f57d5a 100644--- a/tests/tracing/test_recorder.py+++ b/tests/tracing/test_recorder.py@@ -9,7 +9,6 @@ from __future__ import annotationsimport asynciofrom typing import Any-import pytestfrom opentelemetry.sdk.trace import ReadableSpanfrom opentelemetry.sdk.trace.export import SpanExporter, SpanExportResultfrom opentelemetry.trace import SpanKind, StatusCode@@ -402,9 +401,10 @@ class TestLifecycle:await tracer.shutdown()await tracer.shutdown()- async def test_record_content_true_is_not_yet_supported(self):- with pytest.raises(NotImplementedError):- Tracer(service_name="s", record_content=True)+ async def test_record_content_true_is_accepted(self):+ # Phase 2: record_content=True is supported. No exception.+ tracer = Tracer(service_name="s", record_content=True, exporters=[])+ assert tracer is not Noneclass TestJsonlExporter: