1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
use std::cell::RefCell;
/// A single LLM call trace entry.
#[derive(Debug, Clone)]
pub struct LlmTraceEntry {
pub model: String,
/// Provider that served the call. Carried alongside `model` because
/// catalog pricing resolves on the (provider, model) pair, and a trace
/// summary that priced by model alone would silently misprice every model
/// served by more than one provider.
pub provider: String,
pub input_tokens: i64,
pub output_tokens: i64,
/// The price of this exact call, as computed by the one owner of per-call
/// cost (`LlmResult::priced_cost_usd`). Carried rather than recomputed
/// because re-pricing from `(provider, model, input, output)` alone cannot
/// see prompt-cache accounting or the accelerated-serving tier, so a
/// summary that re-priced would disagree with the run's own total.
///
/// `None` means the catalog prices no rate for this pair — which is not
/// the same as a call that cost nothing.
pub cost_usd: Option<f64>,
pub duration_ms: u64,
}
thread_local! {
static LLM_TRACE: RefCell<Vec<LlmTraceEntry>> = const { RefCell::new(Vec::new()) };
static LLM_TRACING_ENABLED: RefCell<bool> = const { RefCell::new(false) };
}
/// Enable LLM tracing for the current thread.
pub fn enable_tracing() {
LLM_TRACING_ENABLED.with(|v| *v.borrow_mut() = true);
}
/// Get and clear the trace log.
pub fn take_trace() -> Vec<LlmTraceEntry> {
LLM_TRACE.with(|v| std::mem::take(&mut *v.borrow_mut()))
}
/// Clone the current trace log without consuming it.
pub fn peek_trace() -> Vec<LlmTraceEntry> {
LLM_TRACE.with(|v| v.borrow().clone())
}
/// Summarize trace usage without consuming entries.
pub fn peek_trace_summary() -> (i64, i64, i64, i64) {
LLM_TRACE.with(|v| {
let entries = v.borrow();
let mut input = 0i64;
let mut output = 0i64;
let mut duration = 0i64;
let count = entries.len() as i64;
for e in entries.iter() {
input += e.input_tokens;
output += e.output_tokens;
duration += e.duration_ms as i64;
}
(input, output, duration, count)
})
}
/// Reset thread-local trace state. Call between test runs.
pub(crate) fn reset_trace_state() {
LLM_TRACE.with(|v| v.borrow_mut().clear());
LLM_TRACING_ENABLED.with(|v| *v.borrow_mut() = false);
}
pub(crate) fn trace_llm_call(entry: LlmTraceEntry) {
LLM_TRACING_ENABLED.with(|enabled| {
if *enabled.borrow() {
LLM_TRACE.with(|v| v.borrow_mut().push(entry));
}
});
}
/// Fine-grained event emitted during agent loop execution. Captures tool
/// calls, LLM calls, interventions, compaction, and phase changes so
/// downstream consumers (portal, IDE hosts, cloud runners) can display
/// execution traces without reconstructing them from raw JSON.
#[derive(Debug, Clone, serde::Serialize)]
#[serde(tag = "type", rename_all = "snake_case")]
pub enum AgentTraceEvent {
LlmCall {
call_id: String,
model: String,
input_tokens: i64,
output_tokens: i64,
cache_tokens: i64,
duration_ms: u64,
iteration: usize,
},
ToolExecution {
tool_name: String,
tool_use_id: String,
duration_ms: u64,
status: String,
classification: String,
iteration: usize,
},
ToolRejected {
tool_name: String,
reason: String,
iteration: usize,
},
LoopIntervention {
tool_name: String,
kind: String,
count: usize,
iteration: usize,
},
ContextCompaction {
archived_messages: usize,
new_summary_len: usize,
iteration: usize,
},
PhaseChange {
from_phase: String,
to_phase: String,
iteration: usize,
},
LoopComplete {
status: String,
iterations: usize,
total_duration_ms: u64,
tools_used: Vec<String>,
successful_tools: Vec<String>,
},
/// Emitted when `llm_call` re-prompts the model after the previous
/// response failed `output_schema` validation. One event per retry;
/// `attempt` counts retries (the initial call is attempt 0 and
/// produces no event; the first retry emits `attempt: 1`).
///
/// The retry does **not** persist the invalid response — the
/// original messages are replayed with a single appended user-role
/// correction that cites the validation errors and schema. That
/// correction text is surfaced here as `correction_prompt` so
/// transcripts show both why the retry happened and what was sent.
SchemaRetry {
attempt: usize,
errors: Vec<String>,
nudge_used: bool,
correction_prompt: String,
},
/// Emitted when `llm_call` aborts a streaming provider response
/// because the partial JSON content can no longer satisfy
/// `output_schema`. `chunks_consumed` counts text-delta chunks seen
/// before the abort; `provider` / `model` track the route that fired
/// so cost dashboards can attribute the savings.
SchemaStreamAborted {
provider: String,
model: String,
reason: String,
path: String,
chunks_consumed: usize,
},
TypedCheckpoint {
name: String,
status: String,
checkpoint_attempts: usize,
llm_attempts: usize,
error_category: Option<String>,
errors: Vec<String>,
repaired: bool,
final_accepted: bool,
raw_text: String,
},
NativeToolFallback {
iteration: usize,
accepted: bool,
policy: String,
fallback_index: usize,
tool_call_count: usize,
},
EmptyCompletionRetry {
iteration: usize,
attempt: usize,
provider: String,
model: String,
reason: String,
duration_ms: u64,
error: String,
},
/// Emitted when a `models:`/`ladder:` model ladder advances from one rung
/// to the next because the current rung hit a transport-class failure
/// (connection/timeout/429/5xx/circuit_open). Schema-validation failures
/// never emit this — they re-ask the SAME rung's model. `from_index` is
/// the 0-based ladder position that failed; `category` is the failover
/// error category that drove the advance.
ModelsAdvance {
from_index: usize,
from_model: String,
to_model: String,
category: String,
},
}
thread_local! {
static AGENT_TRACE: RefCell<Vec<AgentTraceEvent>> = const { RefCell::new(Vec::new()) };
}
/// Emit an agent trace event.
pub(crate) fn emit_agent_event(event: AgentTraceEvent) {
AGENT_TRACE.with(|v| v.borrow_mut().push(event));
}
/// Get and clear the agent trace log.
pub fn take_agent_trace() -> Vec<AgentTraceEvent> {
AGENT_TRACE.with(|v| std::mem::take(&mut *v.borrow_mut()))
}
/// Clone the current agent trace log without consuming it.
pub fn peek_agent_trace() -> Vec<AgentTraceEvent> {
AGENT_TRACE.with(|v| v.borrow().clone())
}
/// Produce a rolled-up summary of agent trace events as JSON.
pub fn agent_trace_summary() -> serde_json::Value {
AGENT_TRACE.with(|v| {
let events = v.borrow();
let mut llm_calls = 0usize;
let mut tool_executions = 0usize;
let mut tool_rejections = 0usize;
let mut interventions = 0usize;
let mut compactions = 0usize;
let mut native_text_tool_fallbacks = 0usize;
let mut native_text_tool_fallback_rejections = 0usize;
let mut empty_completion_retries = 0usize;
let mut models_advances = 0usize;
let mut schema_stream_aborts = 0usize;
let mut typed_checkpoints = 0usize;
let mut typed_checkpoint_failures = 0usize;
let mut total_input_tokens = 0i64;
let mut total_output_tokens = 0i64;
let mut total_llm_duration_ms = 0u64;
let mut total_tool_duration_ms = 0u64;
let mut tools_used: Vec<String> = Vec::new();
let mut status = "unknown".to_string();
let mut iterations = 0usize;
let mut total_duration_ms = 0u64;
for event in events.iter() {
match event {
AgentTraceEvent::LlmCall {
input_tokens,
output_tokens,
duration_ms,
..
} => {
llm_calls += 1;
total_input_tokens += input_tokens;
total_output_tokens += output_tokens;
total_llm_duration_ms += duration_ms;
}
AgentTraceEvent::ToolExecution {
tool_name,
duration_ms,
..
} => {
tool_executions += 1;
total_tool_duration_ms += duration_ms;
if !tools_used.contains(tool_name) {
tools_used.push(tool_name.clone());
}
}
AgentTraceEvent::ToolRejected { .. } => {
tool_rejections += 1;
}
AgentTraceEvent::LoopIntervention { .. } => {
interventions += 1;
}
AgentTraceEvent::ContextCompaction { .. } => {
compactions += 1;
}
AgentTraceEvent::PhaseChange { .. } => {}
AgentTraceEvent::LoopComplete {
status: s,
iterations: i,
total_duration_ms: d,
..
} => {
status = s.clone();
iterations = *i;
total_duration_ms = *d;
}
AgentTraceEvent::SchemaRetry { .. } => {}
AgentTraceEvent::SchemaStreamAborted { .. } => {
schema_stream_aborts += 1;
}
AgentTraceEvent::TypedCheckpoint { final_accepted, .. } => {
typed_checkpoints += 1;
if !final_accepted {
typed_checkpoint_failures += 1;
}
}
AgentTraceEvent::NativeToolFallback { accepted, .. } => {
native_text_tool_fallbacks += 1;
if !accepted {
native_text_tool_fallback_rejections += 1;
}
}
AgentTraceEvent::EmptyCompletionRetry { .. } => {
empty_completion_retries += 1;
}
AgentTraceEvent::ModelsAdvance { .. } => {
models_advances += 1;
}
}
}
serde_json::json!({
"status": status,
"iterations": iterations,
"total_duration_ms": total_duration_ms,
"llm_calls": llm_calls,
"tool_executions": tool_executions,
"tool_rejections": tool_rejections,
"interventions": interventions,
"compactions": compactions,
"native_text_tool_fallbacks": native_text_tool_fallbacks,
"native_text_tool_fallback_rejections": native_text_tool_fallback_rejections,
"empty_completion_retries": empty_completion_retries,
"models_advances": models_advances,
"schema_stream_aborts": schema_stream_aborts,
"typed_checkpoints": typed_checkpoints,
"typed_checkpoint_failures": typed_checkpoint_failures,
"total_input_tokens": total_input_tokens,
"total_output_tokens": total_output_tokens,
"total_llm_duration_ms": total_llm_duration_ms,
"total_tool_duration_ms": total_tool_duration_ms,
"tools_used": tools_used,
})
})
}
/// Reset agent trace state. Call between test runs.
pub(crate) fn reset_agent_trace_state() {
AGENT_TRACE.with(|v| v.borrow_mut().clear());
}