Skip to content

CubeLoop — a Pythonic, async-native agent harness core designed for high performance, readability, and production-grade persistence.

feat(tracing): stream recording + trace convert command

xf gong4078d87ffccf
diff --git a/cubepi/cli/trace/commands.py b/cubepi/cli/trace/commands.py
index a9d46c7..2d8434f 100644
--- a/cubepi/cli/trace/commands.py
+++ b/cubepi/cli/trace/commands.py
@@ -48,6 +48,34 @@ def register(subparsers: "argparse._SubParsersAction") -> None:
)
p_follow.set_defaults(handler=cmd_follow)
+ from cubepi.cli.trace.convert import cmd_convert
+
+ p_convert = trace_sub.add_parser(
+ "convert", help="reconstruct API request body from a recorded chat span"
+ )
+ p_convert.add_argument("run", help="trace id or path to a .jsonl file")
+ _add_dir(p_convert)
+ p_convert.add_argument(
+ "--turn",
+ type=int,
+ default=None,
+ metavar="N",
+ help="select the N-th chat span (1-indexed); default: last",
+ )
+ p_convert.add_argument(
+ "--span",
+ default=None,
+ metavar="SPAN_ID",
+ help="select span by id prefix",
+ )
+ p_convert.add_argument(
+ "--format",
+ choices=("openai", "anthropic", "curl"),
+ default="openai",
+ help="output format (default: openai)",
+ )
+ p_convert.set_defaults(handler=cmd_convert)
+
p_stats = trace_sub.add_parser("stats", help="aggregate stats across runs")
p_stats.add_argument("runs", nargs="*", help="trace ids (default: whole dir)")
_add_dir(p_stats)
diff --git a/cubepi/cli/trace/convert.py b/cubepi/cli/trace/convert.py
new file mode 100644
index 0000000..791dad9
--- /dev/null
+++ b/cubepi/cli/trace/convert.py
@@ -0,0 +1,305 @@
+"""cubepi trace convert — reconstruct an API request body from a recorded chat span."""
+
+from __future__ import annotations
+
+import argparse
+import json
+from pathlib import Path
+from typing import Any
+
+from cubepi.cli.trace import loader
+from cubepi.tracing import schema
+
+
+def cmd_convert(args: argparse.Namespace) -> int:
+ directory = Path(args.dir)
+ try:
+ files = loader.resolve_run(args.run, directory)
+ except loader.RunResolutionError as exc:
+ print(str(exc))
+ return 1
+
+ spans, _skipped = loader.load_run(files)
+ chat_spans = [s for s in spans if s.is_chat]
+ if not chat_spans:
+ print("no chat spans found — was record_content=True when tracing?")
+ return 1
+
+ target = None
+ if args.span:
+ prefix = args.span
+ matches = [s for s in chat_spans if (s.span_id or "").startswith(prefix)]
+ if not matches:
+ print(f"no chat span with id prefix {prefix!r}")
+ return 1
+ if len(matches) > 1:
+ ids = ", ".join(s.span_id or "" for s in matches)
+ print(f"ambiguous span prefix {prefix!r}: {ids}")
+ return 1
+ target = matches[0]
+ elif args.turn is not None:
+ idx = args.turn - 1
+ if idx < 0 or idx >= len(chat_spans):
+ print(f"--turn {args.turn} out of range (1..{len(chat_spans)})")
+ return 1
+ target = chat_spans[idx]
+ else:
+ target = chat_spans[-1]
+
+ attrs = target.attributes
+ model_id = str(attrs.get(schema.GEN_AI_REQUEST_MODEL, ""))
+ max_tokens = attrs.get(schema.GEN_AI_REQUEST_MAX_TOKENS)
+ temperature = attrs.get(schema.GEN_AI_REQUEST_TEMPERATURE)
+
+ msgs: list[dict[str, Any]] = _parse_json_attr(
+ attrs.get(schema.GEN_AI_INPUT_MESSAGES)
+ )
+ sys_instructions: list[dict[str, Any]] = _parse_json_attr(
+ attrs.get(schema.GEN_AI_SYSTEM_INSTRUCTIONS)
+ )
+ tool_defs: list[dict[str, Any]] = _parse_json_attr(
+ attrs.get(schema.GEN_AI_TOOL_DEFINITIONS)
+ )
+
+ fmt = args.format
+ if fmt == "anthropic":
+ body = _build_anthropic(model_id, msgs, sys_instructions, tool_defs, max_tokens)
+ print(json.dumps(body, indent=2, ensure_ascii=False))
+ elif fmt == "curl":
+ print(
+ _build_curl(
+ model_id, msgs, sys_instructions, tool_defs, max_tokens, temperature
+ )
+ )
+ else:
+ body = _build_openai(
+ model_id, msgs, sys_instructions, tool_defs, max_tokens, temperature
+ )
+ print(json.dumps(body, indent=2, ensure_ascii=False))
+ return 0
+
+
+def _parse_json_attr(raw: Any) -> list[dict[str, Any]]:
+ if raw is None:
+ return []
+ if isinstance(raw, list):
+ return [x for x in raw if isinstance(x, dict)]
+ if isinstance(raw, str):
+ try:
+ parsed = json.loads(raw)
+ if isinstance(parsed, list):
+ return [x for x in parsed if isinstance(x, dict)]
+ except (json.JSONDecodeError, TypeError):
+ pass
+ return []
+
+
+def _system_text(instructions: list[dict[str, Any]]) -> str:
+ parts: list[str] = []
+ for block in instructions:
+ role = block.get("role", "")
+ if role == "system":
+ for part in block.get("parts", []) or []:
+ if isinstance(part, dict) and part.get("type") == "text":
+ text = part.get("content") or part.get("text") or ""
+ if text:
+ parts.append(str(text))
+ return "\n\n".join(parts)
+
+
+def messages_to_openai(msgs: list[dict[str, Any]]) -> list[dict[str, Any]]:
+ out: list[dict[str, Any]] = []
+ for msg in msgs:
+ role = msg.get("role", "")
+ parts = msg.get("parts") or []
+ if role == "user":
+ texts = [
+ str(p.get("content") or p.get("text") or "")
+ for p in parts
+ if isinstance(p, dict) and p.get("type") == "text"
+ ]
+ out.append({"role": "user", "content": " ".join(t for t in texts if t)})
+ elif role == "assistant":
+ tool_calls: list[dict[str, Any]] = []
+ text_parts: list[str] = []
+ for p in parts:
+ if not isinstance(p, dict):
+ continue
+ if p.get("type") == "tool_call":
+ args = p.get("arguments", {})
+ tool_calls.append(
+ {
+ "id": str(p.get("id", "")),
+ "type": "function",
+ "function": {
+ "name": str(p.get("name", "")),
+ "arguments": (
+ json.dumps(args)
+ if isinstance(args, dict)
+ else str(args)
+ ),
+ },
+ }
+ )
+ elif p.get("type") == "text":
+ t = str(p.get("content") or p.get("text") or "")
+ if t:
+ text_parts.append(t)
+ entry: dict[str, Any] = {
+ "role": "assistant",
+ "content": " ".join(text_parts) if text_parts else None,
+ }
+ if tool_calls:
+ entry["tool_calls"] = tool_calls
+ out.append(entry)
+ elif role == "tool":
+ for p in parts:
+ if isinstance(p, dict) and p.get("type") == "tool_call_response":
+ out.append(
+ {
+ "role": "tool",
+ "tool_call_id": str(p.get("id", "")),
+ "content": str(p.get("result", "")),
+ }
+ )
+ return out
+
+
+def messages_to_anthropic(msgs: list[dict[str, Any]]) -> list[dict[str, Any]]:
+ out: list[dict[str, Any]] = []
+ pending_tool_results: list[dict[str, Any]] = []
+ for msg in msgs:
+ role = msg.get("role", "")
+ parts = msg.get("parts") or []
+ if role == "tool":
+ for p in parts:
+ if isinstance(p, dict) and p.get("type") == "tool_call_response":
+ pending_tool_results.append(
+ {
+ "type": "tool_result",
+ "tool_use_id": str(p.get("id", "")),
+ "content": str(p.get("result", "")),
+ }
+ )
+ elif role == "user":
+ if pending_tool_results:
+ out.append({"role": "user", "content": list(pending_tool_results)})
+ pending_tool_results = []
+ content_blocks: list[dict[str, Any]] = []
+ for p in parts:
+ if not isinstance(p, dict):
+ continue
+ if p.get("type") == "text":
+ text = str(p.get("content") or p.get("text") or "")
+ if text:
+ content_blocks.append({"type": "text", "text": text})
+ if content_blocks:
+ out.append({"role": "user", "content": content_blocks})
+ elif role == "assistant":
+ if pending_tool_results:
+ out.append({"role": "user", "content": list(pending_tool_results)})
+ pending_tool_results = []
+ content_blocks = []
+ for p in parts:
+ if not isinstance(p, dict):
+ continue
+ if p.get("type") == "text":
+ text = str(p.get("content") or p.get("text") or "")
+ if text:
+ content_blocks.append({"type": "text", "text": text})
+ elif p.get("type") == "tool_call":
+ args = p.get("arguments", {})
+ content_blocks.append(
+ {
+ "type": "tool_use",
+ "id": str(p.get("id", "")),
+ "name": str(p.get("name", "")),
+ "input": args if isinstance(args, dict) else {},
+ }
+ )
+ if content_blocks:
+ out.append({"role": "assistant", "content": content_blocks})
+ if pending_tool_results:
+ out.append({"role": "user", "content": pending_tool_results})
+ return out
+
+
+def _build_openai(
+ model_id: str,
+ msgs: list[dict[str, Any]],
+ sys_instructions: list[dict[str, Any]],
+ tool_defs: list[dict[str, Any]],
+ max_tokens: Any,
+ temperature: Any,
+) -> dict[str, Any]:
+ openai_msgs: list[dict[str, Any]] = []
+ sys_text = _system_text(sys_instructions)
+ if sys_text:
+ openai_msgs.append({"role": "system", "content": sys_text})
+ openai_msgs.extend(messages_to_openai(msgs))
+ body: dict[str, Any] = {"model": model_id, "messages": openai_msgs, "stream": True}
+ if max_tokens is not None:
+ body["max_tokens"] = int(max_tokens)
+ if temperature is not None:
+ body["temperature"] = float(temperature)
+ if tool_defs:
+ body["tools"] = [
+ {
+ "type": "function",
+ "function": {
+ "name": str(t.get("name", "")),
+ "description": str(t.get("description", "")),
+ "parameters": t.get("parameters") or {},
+ },
+ }
+ for t in tool_defs
+ ]
+ return body
+
+
+def _build_anthropic(
+ model_id: str,
+ msgs: list[dict[str, Any]],
+ sys_instructions: list[dict[str, Any]],
+ tool_defs: list[dict[str, Any]],
+ max_tokens: Any,
+) -> dict[str, Any]:
+ sys_text = _system_text(sys_instructions)
+ body: dict[str, Any] = {
+ "model": model_id,
+ "messages": messages_to_anthropic(msgs),
+ "max_tokens": int(max_tokens) if max_tokens is not None else 4096,
+ }
+ if sys_text:
+ body["system"] = sys_text
+ if tool_defs:
+ body["tools"] = [
+ {
+ "name": str(t.get("name", "")),
+ "description": str(t.get("description", "")),
+ "input_schema": t.get("parameters") or {},
+ }
+ for t in tool_defs
+ ]
+ return body
+
+
+def _build_curl(
+ model_id: str,
+ msgs: list[dict[str, Any]],
+ sys_instructions: list[dict[str, Any]],
+ tool_defs: list[dict[str, Any]],
+ max_tokens: Any,
+ temperature: Any,
+) -> str:
+ body = _build_openai(
+ model_id, msgs, sys_instructions, tool_defs, max_tokens, temperature
+ )
+ body_json = json.dumps(body, ensure_ascii=False)
+ escaped = body_json.replace("'", "'\"'\"'")
+ return (
+ 'curl -s -X POST "${BASE_URL}/v1/chat/completions" \\\n'
+ ' -H "Authorization: Bearer ${API_KEY}" \\\n'
+ ' -H "Content-Type: application/json" \\\n'
+ f" -d '{escaped}'"
+ )
diff --git a/cubepi/tracing/recorder.py b/cubepi/tracing/recorder.py
index 5996fde..344d5ff 100644
--- a/cubepi/tracing/recorder.py
+++ b/cubepi/tracing/recorder.py
@@ -20,11 +20,13 @@ from __future__ import annotations
import contextvars
import hashlib
+import json
import time
import traceback
import uuid
from dataclasses import dataclass, field
-from typing import TYPE_CHECKING, Any, Callable
+from pathlib import Path
+from typing import IO, TYPE_CHECKING, Any, Callable
from opentelemetry import trace
from opentelemetry.trace import SpanKind, Status, StatusCode
@@ -41,6 +43,7 @@ from cubepi.agent.types import (
)
from cubepi.providers.base import (
StreamEvent,
+ ToolCall,
ToolResultMessage,
UserMessage,
)
@@ -173,6 +176,10 @@ class _RunState:
turn_output_messages: list[Any] = field(default_factory=list)
# Chat-span specific tool_definitions captured at request time.
chat_tool_definitions: list[dict] | None = None
+ # Stream recording (only used when record_stream=True).
+ stream_file: IO[str] | None = None
+ stream_start_time: float | None = None
+ stream_tool_accumulated: dict[int, int] = field(default_factory=dict)
class Recorder:
@@ -188,10 +195,14 @@ class Recorder:
tracer: "Tracer",
*,
record_content: bool = False,
+ record_stream: bool = False,
+ stream_dir: "Path | None" = None,
redact: "Callable[[str, Any], Any] | None" = None,
) -> None:
self._tracer = tracer
self._record_content = record_content
+ self._record_stream = record_stream
+ self._stream_dir = stream_dir
self._redact = redact
# Active run state. cubepi agents serialize runs (one
# ``agent.run()`` at a time per Agent), so a single slot is
@@ -451,6 +462,13 @@ class Recorder:
except Exception:
pass
# Don't null agent_span — _RunState gets dropped wholesale.
+ # Close stream file on cancellation — normal end is handled in _on_agent_end.
+ if run.stream_file is not None:
+ try:
+ run.stream_file.close()
+ except Exception:
+ pass
+ run.stream_file = None
# Release the per-task active-run gate. A cancelled run never
# reaches _on_agent_end, so the only reset opportunity is here
# (detach always calls _close_open_spans). Without this a stale
@@ -502,6 +520,15 @@ class Recorder:
# Resource carries gen_ai.agent.name at process level — agents
# that vary per-run set their own value via _ensure_agent_name.
self._run = _RunState(run_id=run_id, agent_span=span)
+ # Open stream file when record_stream is enabled.
+ if self._record_stream and self._stream_dir is not None:
+ try:
+ self._stream_dir.mkdir(parents=True, exist_ok=True)
+ stream_path = self._stream_dir / f"{run_id}.stream.jsonl"
+ self._run.stream_file = stream_path.open("w", encoding="utf-8")
+ self._run.stream_start_time = time.time()
+ except Exception:
+ pass
# Claim the per-task active-run gate for this run so this
# recorder's provider listeners act only for LLM calls made on
# the task that owns this run (not for an inner subagent sharing
@@ -609,6 +636,12 @@ class Recorder:
# ``_sweep_tool_span_tokens`` docstring.
self._sweep_tool_span_tokens(run)
run.agent_span.end()
+ if run.stream_file is not None:
+ try:
+ run.stream_file.close()
+ except Exception:
+ pass
+ run.stream_file = None
self._reset_active_run()
self._run = None
@@ -939,20 +972,88 @@ class Recorder:
def _on_provider_chunk(self, event: StreamEvent, model: "Model") -> None:
del model
run = self._run
- if run is None or run.chat_span is None or run.chat_first_chunk_recorded:
+ if run is None:
return
if _active_run.get() is not run:
return
- # Only count "content" chunks for time-to-first-chunk (not 'start').
- if event.type in (
- "text_delta",
- "thinking_delta",
- "toolcall_delta",
+ # TTFT: record once per chat span for the first content chunk.
+ if (
+ run.chat_span is not None
+ and not run.chat_first_chunk_recorded
+ and event.type in ("text_delta", "thinking_delta", "toolcall_delta")
):
opened = run.chat_open_ns or time.time_ns()
ttft_s = (time.time_ns() - opened) / 1e9
run.chat_span.set_attribute(GEN_AI_RESPONSE_TIME_TO_FIRST_CHUNK, ttft_s)
run.chat_first_chunk_recorded = True
+ # Stream recording: write every semantically interesting event.
+ if self._record_stream and run.stream_file is not None:
+ self._write_stream_event(run, event)
+
+ def _write_stream_event(self, run: "_RunState", event: StreamEvent) -> None:
+ if event.type in (
+ "start",
+ "text_start",
+ "text_end",
+ "thinking_start",
+ "thinking_end",
+ "done",
+ ):
+ return
+ elapsed = round(time.time() - (run.stream_start_time or time.time()), 3)
+ rec: dict[str, Any] = {"t": elapsed, "type": event.type}
+ ci = event.content_index if event.content_index is not None else 0
+
+ if event.type == "toolcall_start":
+ id_, name = "", ""
+ if event.partial is not None and ci < len(event.partial.content):
+ block = event.partial.content[ci]
+ if isinstance(block, ToolCall):
+ id_, name = block.id, block.name
+ rec.update({"ci": ci, "id": id_, "name": name})
+
+ elif event.type == "toolcall_delta":
+ delta = event.delta or ""
+ run.stream_tool_accumulated[ci] = run.stream_tool_accumulated.get(
+ ci, 0
+ ) + len(delta)
+ rec.update(
+ {
+ "ci": ci,
+ "chars": len(delta),
+ "accumulated": run.stream_tool_accumulated[ci],
+ "preview": delta[:60],
+ }
+ )
+
+ elif event.type == "toolcall_end":
+ id_, name, args_str = "", "", ""
+ if event.partial is not None and ci < len(event.partial.content):
+ block = event.partial.content[ci]
+ if isinstance(block, ToolCall):
+ id_, name = block.id, block.name
+ args_str = json.dumps(block.arguments)
+ total = run.stream_tool_accumulated.pop(ci, len(args_str))
+ rec.update(
+ {
+ "ci": ci,
+ "id": id_,
+ "name": name,
+ "args_chars": total,
+ "args_preview": args_str[:80],
+ }
+ )
+
+ elif event.type in ("text_delta", "thinking_delta"):
+ rec["chars"] = len(event.delta or "")
+
+ elif event.type == "error":
+ rec["error_message"] = event.error_message or ""
+
+ try:
+ run.stream_file.write(json.dumps(rec) + "\n") # type: ignore[union-attr]
+ except Exception:
+ pass
def _on_provider_response(
self,
diff --git a/cubepi/tracing/tracer.py b/cubepi/tracing/tracer.py
index c46d674..cca2171 100644
--- a/cubepi/tracing/tracer.py
+++ b/cubepi/tracing/tracer.py
@@ -12,6 +12,7 @@ import atexit
import contextlib
import logging
import uuid
+from pathlib import Path
from typing import TYPE_CHECKING, Any, AsyncIterator, Callable
from opentelemetry.sdk.resources import Resource
@@ -72,12 +73,18 @@ class Tracer:
agent_version: str | None = None,
exporters: list[SpanExporter] | None = None,
record_content: bool = False,
+ record_stream: bool = False,
+ stream_dir: "str | Path | None" = None,
redact: "Callable[[str, Any], Any] | None" = None,
resource: Resource | None = None,
atexit_flush: bool = True,
atexit_flush_timeout_seconds: float = 5.0,
) -> None:
self._record_content = record_content
+ self._record_stream = record_stream
+ self._stream_dir = (
+ Path(stream_dir) if isinstance(stream_dir, str) else stream_dir
+ )
self._redact = redact
self._resource = resource or _build_resource(
service_name=service_name,
@@ -177,6 +184,8 @@ class Tracer:
recorder = Recorder(
self,
record_content=self._record_content,
+ record_stream=self._record_stream,
+ stream_dir=self._stream_dir,
redact=self._redact,
)
recorder_detach = recorder.attach(agent)