Skip to content

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

docs(tracing): add trace CLI guide + fix middleware hook count (#123)

Chris561e94cb67b6
diff --git a/README.md b/README.md
index 6716fc2..fa4adde 100644
--- a/README.md
+++ b/README.md
@@ -24,7 +24,7 @@ A Pythonic, async-native agent framework — a leaner, more readable take on age
| **Dependencies** | Pulls in langchain-core, langgraph-sdk, and transitive deps | 3 core deps: `pydantic`, `anthropic`, `openai` |
| **Tool execution** | Tools are graph nodes with manual wiring | Declare tools as functions, framework handles routing and parallel execution |
| **Multi-provider** | Via langchain chat model adapters | Native `Provider` protocol — Anthropic, OpenAI built in, add your own with one class |
-| **Middleware** | Graph-level middleware on node entry/exit | Agent-level middleware with 5 typed hooks and declarative composition rules |
+| **Middleware** | Graph-level middleware on node entry/exit | Agent-level middleware with 7 typed hooks and declarative composition rules |
| **Observability** | LangSmith / Langfuse integration, full trace visualization | Native OpenTelemetry — `Tracer`, `Meter`, GenAI semconv, OTLP / JSONL exporters built in |
## Install
@@ -105,7 +105,7 @@ cubepi/
│ ├── tools.py # Tool execution engine (sequential + parallel)
│ └── types.py # Events, AgentTool, AgentContext, hook types
├── middleware/ # Composable middleware protocol
-│ └── base.py # 5 hooks with distinct composition rules
+│ └── base.py # 7 hooks with distinct composition rules
├── checkpointer/ # Persistence
│ ├── base.py # Checkpointer protocol
│ ├── memory.py # In-memory (dev/test)
diff --git a/skills/cubepi-trace/SKILL.md b/skills/cubepi-trace/SKILL.md
index 1202633..02e9198 100644
--- a/skills/cubepi-trace/SKILL.md
+++ b/skills/cubepi-trace/SKILL.md
@@ -34,8 +34,11 @@ inspect. In cubebox it's config-driven (dynaconf):
Env override form: `CUBEBOX_TRACING__ENABLED=true`,
`CUBEBOX_TRACING__RECORD_CONTENT=true`, `CUBEBOX_TRACING__DIRECTORY=...`.
cubebox's `config.development` already enables this. Files land at
-`<directory>/<YYYY-MM-DD>/<run_id>.jsonl` (a run that crosses UTC midnight is
-split across two date dirs; the CLI merges them).
+`<directory>/<YYYY-MM-DD>/<trace_id>.jsonl` — sharded by `trace_id`, so one
+file holds the whole trace, including any nested subagent runs (they inherit
+the parent's trace). A trace that crosses UTC midnight is split across two date
+dirs; the CLI merges them. (`cubepi.run_id` is still recorded as a per-span
+attribute if you need to distinguish individual runs within a trace.)
Run the CLI from the cubebox backend dir so it picks up the venv that has
cubepi installed (the `trace-cli` extra provides it):
@@ -50,33 +53,43 @@ elsewhere (e.g. a worktree).
## The fast path (this is 90% of debugging)
```bash
-# 1. List recent runs, newest first. The `input` column shows the user's
-# message so you can find the right run; `status` flags errors.
+# 1. List recent traces, newest first. The `trace_id` column is the id you
+# pass to `view`; the `input` column shows the user's message so you can
+# find the right one; `status` flags errors.
uv run cubepi trace ls
-# 2. View one run as a span tree. A run id PREFIX is enough (ls truncates ids).
-# Errors are printed inline under the failing span — no flags needed.
-uv run cubepi trace view 66f1806f
+# 2. View one trace as a span tree. A trace id PREFIX is enough (ls truncates
+# ids). Errors are printed inline under the failing span — no flags needed.
+uv run cubepi trace view 1cd97cdb
```
-`view` output looks like:
+`view` output looks like (each node ends with a short `span_id` for locating
+the raw span in the JSONL):
```
trace
-└── invoke_agent 14425.8ms
- ├── cubepi.turn 1283.1ms
- │ ├── chat deepseek-v4-flash 1208.7ms tok 6845/68
- │ └── execute_tool datetime 0.3ms datetime
- └── cubepi.turn 491.9ms ERROR
- └── chat deepseek-v4-flash 427.2ms ERROR
+└── invoke_agent 14425.8ms [0x1cd97cdb]
+ ├── cubepi.turn 1283.1ms [0x5cfda93e]
+ │ ├── chat deepseek-v4-flash 1208.7ms tok 6845/68 [0x0d130229]
+ │ └── execute_tool subagent 9610.2ms subagent [0x38bdd10a]
+ │ └── invoke_agent 9601.0ms [0x8094f99b] ← subagent run, nested
+ │ └── cubepi.turn 9598.4ms [0x57c5cfc7]
+ │ ├── chat deepseek-v4-flash 1190.3ms [0x8205ca6b]
+ │ └── execute_tool web_search 6500.2ms web_search [0xca4e59fc]
+ └── cubepi.turn 491.9ms ERROR [0xce25f242]
+ └── chat deepseek-v4-flash 427.2ms ERROR [0x0bff68ec]
└── error: Error code: 400 - ... `tool_use` ids were found without
`tool_result` blocks immediately after: call_01_...
```
-Read the tree top-down: `invoke_agent` (whole run) → `cubepi.turn` (one
-agent loop turn) → `chat <model>` (an LLM call, with `tok <input>/<output>`)
-and `execute_tool <name>` (a tool call). An `ERROR` marker plus the inline
-`error:` line usually tells you the root cause directly.
+Read the tree top-down: `invoke_agent` (one run) → `cubepi.turn` (one agent
+loop turn) → `chat <model>` (an LLM call, with `tok <input>/<output>`) and
+`execute_tool <name>` (a tool call). A **subagent** appears as
+`execute_tool subagent` with the subagent's own `invoke_agent → cubepi.turn →
+…` nested directly beneath it — its chat and tool spans live inside that
+subtree, not flat under the parent turn. The `[0x…]` suffix is the span_id
+(grep it in the raw JSONL to inspect that exact span). An `ERROR` marker plus
+the inline `error:` line usually tells you the root cause directly.
## Going deeper
@@ -128,9 +141,14 @@ Mind the convention — it differs between the trace and cubebox's UI:
## Tips
-- **Prefix match**: `view`/`follow`/`stats` accept a unique run-id prefix;
- copy the visible chars from `ls`. An ambiguous prefix lists candidates.
-- **Find the run** by the `input` column in `ls` rather than guessing ids.
+- **Prefix match**: `view`/`follow`/`stats` accept a unique trace-id prefix;
+ copy the visible chars from the `trace_id` column in `ls`. An ambiguous
+ prefix lists candidates.
+- **Find the trace** by the `input` column in `ls` rather than guessing ids.
+- **Subagent missing from the tree?** It should nest under
+ `execute_tool subagent`. If a subagent's spans look absent, confirm the run
+ was recorded with a cubepi new enough to shard by `trace_id` (older runs
+ sharded by `run_id`, so a subagent's spans landed in a separate file).
- **Backend vs frontend**: the trace shows what the backend/agent did. If the
trace shows correct data but the UI is wrong, the bug is in the frontend
(SSE handling / rendering) — the trace won't see that; use a browser instead.
diff --git a/website/docs/guides/tracing/cli.md b/website/docs/guides/tracing/cli.md
new file mode 100644
index 0000000..1d103e0
--- /dev/null
+++ b/website/docs/guides/tracing/cli.md
@@ -0,0 +1,102 @@
+---
+title: The trace CLI
+---
+
+# Inspecting traces with `cubepi trace`
+
+The `JsonlSpanExporter` writes one file per trace under
+`./cubepi-traces/<date>/<trace_id>.jsonl`. The `cubepi trace` CLI (provided by
+the `trace-cli` extra) reads those files so you can see exactly what a run did
+— which LLM and tool calls fired, in what order, what each returned, where it
+errored, and the token counts — without re-running it.
+
+```bash
+pip install 'cubepi[trace-cli]' # or: uv sync --extra trace-cli
+cubepi trace --help
+```
+
+`--dir` defaults to `./cubepi-traces`; pass `--dir <path>` if your traces live
+elsewhere. Each file is one **trace**: the run plus any nested subagent runs,
+which inherit the parent's `trace_id` and so land in the same file.
+
+## `ls` — list recent traces
+
+```bash
+cubepi trace ls # newest first; -n N to limit
+```
+
+| column | meaning |
+|---|---|
+| `started` | trace start time (UTC) |
+| `trace_id` | the id you pass to `view` / `follow` / `stats` |
+| `spans` | span count for the whole trace (incl. subagents) |
+| `status` | `ok` or `error` |
+| `duration` | wall-clock span of the trace |
+| `input` | the user's prompt, to identify the run |
+
+## `view` — render a trace as a span tree
+
+A trace-id **prefix** is enough (the table truncates ids); an ambiguous prefix
+lists candidates.
+
+```bash
+cubepi trace view 1cd97cdb
+```
+
+```
+trace
+└── invoke_agent 14425.8ms [0x1cd97cdb]
+ ├── cubepi.turn 1283.1ms [0x5cfda93e]
+ │ ├── chat claude-sonnet-4-5 1208.7ms tok 6845/68 [0x0d130229]
+ │ └── execute_tool subagent 9610.2ms subagent [0x38bdd10a]
+ │ └── invoke_agent 9601.0ms [0x8094f99b] ← subagent run, nested
+ │ └── cubepi.turn 9598.4ms [0x57c5cfc7]
+ │ ├── chat claude-sonnet-4-5 1190.3ms [0x8205ca6b]
+ │ └── execute_tool web_search 6500.2ms web_search [0xca4e59fc]
+ └── cubepi.turn 491.9ms [0xce25f242]
+ └── chat claude-sonnet-4-5 427.2ms [0x0bff68ec]
+```
+
+Read it top-down: `invoke_agent` (a run) → `cubepi.turn` (one agent-loop turn)
+→ `chat <model>` (an LLM call, with `tok <input>/<output>`) and
+`execute_tool <name>` (a tool call). A **subagent** shows up as
+`execute_tool subagent` with its own `invoke_agent → cubepi.turn → …` nested
+directly beneath it. The `[0x…]` suffix on each node is the span's `span_id` —
+grep it in the raw JSONL to inspect that exact span. Errors print inline under
+the failing span.
+
+Flags:
+
+```bash
+cubepi trace view <id> --content # expand gen_ai prompts / tool args / results
+cubepi trace view <id> -v # expand ALL span attributes (verbose, large)
+```
+
+`--content` requires the run to have been recorded with
+`record_content=True` (see [Content & Redaction](./content-recording)).
+
+## `follow` — watch a trace live
+
+```bash
+cubepi trace follow <id> # polls as spans complete; good for a run in progress
+```
+
+## `stats` — aggregate across traces
+
+```bash
+cubepi trace stats --by model # latency p50/p95, error rate, tokens
+cubepi trace stats --by tool --since 2026-05-20
+```
+
+## Beyond the CLI
+
+The files are plain JSONL — one span per line — so you can parse them directly
+(`jq`, `python -c`) to pull a specific attribute (`gen_ai.usage.*`,
+`gen_ai.tool.call.result`, `gen_ai.input.messages`, …). Error detail lives in a
+span **event** named `gen_ai.client.operation.exception`.
+
+:::tip For AI agents
+A bundled `cubepi-trace` skill drives this CLI for debugging ("why did the run
+end with no reply?", "the tool result is wrong"). It encodes the fast path
+(`ls` → `view <prefix>`) and the token/cache-rate conventions.
+:::
diff --git a/website/docs/guides/tracing/getting-started.md b/website/docs/guides/tracing/getting-started.md
index a68387a..0634a04 100644
--- a/website/docs/guides/tracing/getting-started.md
+++ b/website/docs/guides/tracing/getting-started.md
@@ -77,14 +77,18 @@ safety net while you're still building. (Doesn't run on `SIGKILL` or
`os._exit`; for guaranteed delivery there, use the synchronous
`SimpleSpanProcessor` from OTel.)
-The run produces one JSONL file per agent run:
+The run produces one JSONL file per trace (sharded by `trace_id`):
```text
./cubepi-traces/
2026-05-19/
- 8e1c…-…-…-….jsonl ← one run, one file, one span per line
+ 8e1c9a3f4b2d…d976a.jsonl ← one trace, one file, one span per line
```
+A trace is the whole run, including any nested subagent runs (they inherit the
+parent's `trace_id`, so they land in the same file). Each span still carries
+`cubepi.run_id` as an attribute if you want to filter by individual run.
+
Open it with any tool that reads OTLP/JSON or with `jq` directly:
```bash
diff --git a/website/docs/guides/tracing/overview.md b/website/docs/guides/tracing/overview.md
index 09e8a97..ad0ba3b 100644
--- a/website/docs/guides/tracing/overview.md
+++ b/website/docs/guides/tracing/overview.md
@@ -33,8 +33,11 @@ Each layer carries standard `gen_ai.*` attributes — `gen_ai.operation.name`,
`gen_ai.client.operation.duration`, `gen_ai.client.operation.time_to_first_chunk`,
`gen_ai.client.token.usage`.
- **JsonlSpanExporter** — write one JSON line per span to
- `./cubepi-traces/<date>/<run_id>.jsonl`. Useful for local dev and offline
- debugging; works with any OTel viewer that reads JSONL.
+ `./cubepi-traces/<date>/<trace_id>.jsonl`. Files are sharded by `trace_id`,
+ so one file holds a whole trace — the run plus any nested subagent runs
+ (which inherit the trace). Useful for local dev and offline debugging; works
+ with any OTel viewer that reads JSONL, and with the [`cubepi trace`
+ CLI](./cli).
- **OTLP** — bring your own exporter via `opentelemetry-exporter-otlp-proto-http`
(HTTP) or `…-grpc` and hand it to `Tracer(exporters=[…])`.
- **W3C trace context propagation** — outgoing MCP calls inject the active
diff --git a/website/docs/intro.mdx b/website/docs/intro.mdx
index 139d8f8..e7317ab 100644
--- a/website/docs/intro.mdx
+++ b/website/docs/intro.mdx
@@ -35,9 +35,10 @@ working tool-using agent in under five minutes.
conversation length — SQLite for laptops, Postgres for production.
- **Native multi-provider.** Anthropic and OpenAI ship in the box,
through a `Provider` Protocol. Add a new provider in one class.
-- **Five-hook middleware.** `transform_context`, `convert_to_llm`,
- `before_tool_call`, `after_tool_call`, `should_stop_after_turn` —
- each with explicit composition rules. No mystery node ordering.
+- **Seven-hook middleware.** `transform_context`, `convert_to_llm`,
+ `transform_system_prompt`, `before_tool_call`, `after_tool_call`,
+ `should_stop_after_turn`, `after_model_response` — each with explicit
+ composition rules. No mystery node ordering.
- **MCP loaders.** Point at any
[Model Context Protocol](https://modelcontextprotocol.io) server
(HTTP or stdio) and get back a list of `AgentTool`s.
diff --git a/website/sidebars.ts b/website/sidebars.ts
index 4adc035..1a1571c 100644
--- a/website/sidebars.ts
+++ b/website/sidebars.ts
@@ -46,6 +46,7 @@ const sidebars: SidebarsConfig = {
{ type: 'category', label: 'Tracing', items: [
'guides/tracing/overview',
'guides/tracing/getting-started',
+ 'guides/tracing/cli',
'guides/tracing/otlp',
'guides/tracing/content-recording',
'guides/tracing/metrics',
diff --git a/website/src/components/Home/WhyTable.tsx b/website/src/components/Home/WhyTable.tsx
index d3b8b79..433eb9a 100644
--- a/website/src/components/Home/WhyTable.tsx
+++ b/website/src/components/Home/WhyTable.tsx
@@ -8,7 +8,7 @@ const ROWS: { label: string; langgraph: string; cubepi: string }[] = [
{ label: 'Dependencies', langgraph: 'langchain-core, langgraph-sdk, and transitive deps', cubepi: '3 core deps: pydantic, anthropic, openai' },
{ label: 'Tool execution', langgraph: 'Tools are graph nodes with manual wiring', cubepi: 'Declare tools as functions; framework routes and parallelizes' },
{ label: 'Multi-provider', langgraph: 'Via langchain chat model adapters', cubepi: 'Native Provider protocol — Anthropic, OpenAI built in' },
- { label: 'Middleware', langgraph: 'Graph-level middleware on node entry/exit', cubepi: '5 typed hooks with declarative composition rules' },
+ { label: 'Middleware', langgraph: 'Graph-level middleware on node entry/exit', cubepi: '7 typed hooks with declarative composition rules' },
{ label: 'Observability', langgraph: 'LangSmith / Langfuse integration', cubepi: 'Native OpenTelemetry — Tracer, Meter, GenAI semconv, OTLP / JSONL out of the box' },
];