feat(telemetry): record per-agent usage for mission turns
deploy / test (push) Successful in 4m31s
deploy / build (push) Successful in 5m23s

The command centre's SPEND, ACTIVITY and THROUGHPUT cards read `usage_events`,
and nothing on the mission path ever wrote a row: `cm_billing::charge` was
called only from the agent-run path. Measured mid-mission with 14 agents live,
`usage_events` was 0 while a crew had just burned 15k tokens — so an agent that
had done real work reported zero cost and zero activity.

The worker already knew everything needed: it logs node, role and token count
per step, and the node's `attrs.agent` carries the `claw_<uuid>` binding the
runtime dispatches on. This routes that to the ledger.

`charge`'s run_id is now Option. `usage_events.run_id` references `agent_runs`,
and a topology turn has no row there — passing its `topology_runs` id was a
foreign-key violation, which is exactly what the first attempt hit. NULL is the
honest value; the agent-run caller still passes its real id.

The executor reports one total rather than an in/out split, so the cost is right
(credits price the sum) and the columns record it as output rather than
inventing a split.

Verified end to end on a real mission: 4 agents, 1046-8670 tokens each, credits
attributed per agent, and the SPEND/ACTIVITY queries now return real numbers.

Co-Authored-By: Claude Opus 5 <[email protected]>
This commit is contained in:
Omar Sobh
2026-08-15 05:09:56 -07:00
co-authored by Claude Opus 5
parent 8ef7067467
commit 8be7b3c9b2
4 changed files with 99 additions and 21 deletions
+5 -1
View File
@@ -29,7 +29,11 @@ pub async fn charge(
pool: &PgPool,
workspace_id: WorkspaceId,
agent_id: AgentId,
run_id: Uuid,
// Optional: `usage_events.run_id` references `agent_runs`, and a topology
// turn has no row there — its id lives in `topology_runs`. Passing that id
// was a foreign-key violation, so mission usage went unrecorded. NULL is
// the honest value for a charge that is not an agent_run.
run_id: Option<Uuid>,
input_tokens: u64,
output_tokens: u64,
) -> Result<i64, BillingError> {