1use serde::Serialize;
7use time::OffsetDateTime;
8use uuid::Uuid;
9
10mod hook;
11pub mod inventory;
12mod mcp;
13mod model;
14mod session;
15mod team;
16mod tool;
17
18pub use hook::HookRunPayload;
19pub use mcp::{McpConnectionErrorPayload, McpServerConnectedPayload};
20pub use model::{
21 ApiErrorPayload, ApiRequestPayload, BudgetEnforcedAction, BudgetEnforcedPayload,
22 ProviderSwitchedPayload,
23};
24pub use session::{SessionEndPayload, SessionStartPayload, StartupTimingPayload};
25pub use team::{AgentCompletedPayload, AgentSpawnedPayload, TeamStageCompletePayload};
26pub use tool::{
27 PermissionDecisionOutcome, PermissionDecisionPayload, ToolCancelledPayload,
28 ToolExecutionPayload, ToolOutcome, ToolStartPayload,
29};
30
31pub const SCHEMA_VERSION: u32 = 2;
33
34#[derive(Debug, Clone, Serialize)]
36pub struct TelemetryEvent {
37 pub event_id: Uuid,
39 pub session_id: String,
41 pub turn_no: u32,
43 #[serde(skip_serializing_if = "Option::is_none")]
45 pub turn_id: Option<String>,
46 pub timestamp_ms: i64,
48 pub schema_version: u32,
50 #[serde(flatten)]
52 pub payload: EventPayload,
53}
54
55macro_rules! event_kinds {
60 ($($(#[doc = $doc:literal])+ $kind:ident => $variant:ident($payload:ty) in $recorded:ident;)*) => {
61 #[derive(Debug, Clone, Serialize)]
63 #[serde(tag = "type", rename_all = "snake_case")]
64 pub enum EventPayload {
65 $($variant($payload),)*
66 }
67
68 impl EventPayload {
69 pub const KINDS: &'static [&'static str] = &[$(stringify!($kind),)*];
71
72 pub fn kind(&self) -> &'static str {
76 match self {
77 $(EventPayload::$variant(_) => stringify!($kind),)*
78 }
79 }
80
81 pub fn inventory() -> Vec<inventory::KindInfo> {
84 vec![$(inventory::KindInfo {
85 kind: stringify!($kind),
86 when: concat!($($doc),+),
87 recorded: inventory::Recorded::$recorded,
88 schema: || schemars::schema_for!($payload),
89 },)*]
90 }
91 }
92
93 impl TelemetryEvent {
94 $(
95 $(#[doc = $doc])+
96 pub fn $kind(
97 session_id: &str,
98 turn_no: u32,
99 turn_id: Option<String>,
100 p: $payload,
101 ) -> Self {
102 Self::new(session_id, turn_no, turn_id, EventPayload::$variant(p))
103 }
104 )*
105 }
106 };
107}
108
109event_kinds! {
110 session_start => SessionStart(SessionStartPayload) in Session;
112 session_end => SessionEnd(SessionEndPayload) in Session;
114 startup_timing => StartupTiming(StartupTimingPayload) in Pool;
116 api_request => ApiRequest(ApiRequestPayload) in Session;
118 api_error => ApiError(ApiErrorPayload) in Session;
120 provider_switched => ProviderSwitched(ProviderSwitchedPayload) in Session;
122 tool_start => ToolStart(ToolStartPayload) in Session;
124 tool_execution => ToolExecution(ToolExecutionPayload) in Session;
126 tool_cancelled => ToolCancelled(ToolCancelledPayload) in Session;
128 permission_decision => PermissionDecision(PermissionDecisionPayload) in Session;
130 user_prompt_submit => UserPromptSubmit(UserPromptSubmitPayload) in Session;
132 slash_command_used => SlashCommandUsed(SlashCommandUsedPayload) in Session;
134 turn_start => TurnStart(TurnStartPayload) in Session;
136 turn_complete => TurnComplete(TurnCompletePayload) in Session;
138 budget_enforced => BudgetEnforced(BudgetEnforcedPayload) in Session;
140 compact_action => CompactAction(CompactActionPayload) in Session;
142 hook_run => HookRun(HookRunPayload) in Session;
144 resume_action => ResumeAction(ResumeActionPayload) in Both;
146 mcp_server_connected => McpServerConnected(McpServerConnectedPayload) in Pool;
148 mcp_connection_error => McpConnectionError(McpConnectionErrorPayload) in Pool;
150 agent_spawned => AgentSpawned(AgentSpawnedPayload) in Session;
152 agent_completed => AgentCompleted(AgentCompletedPayload) in Session;
154 team_stage_complete => TeamStageComplete(TeamStageCompletePayload) in Session;
156}
157
158#[derive(Debug, Clone, Copy, Serialize, PartialEq, Eq, schemars::JsonSchema)]
159#[serde(rename_all = "snake_case")]
160pub enum ResumeOutcome {
161 Succeeded,
162 Partial,
163 Degraded,
164 Failed,
165}
166
167#[derive(Debug, Clone, Serialize, schemars::JsonSchema)]
169pub struct TurnStartPayload {
170 pub resumed: bool,
171 pub is_retry: bool,
172}
173
174#[derive(Debug, Clone, Serialize, schemars::JsonSchema)]
176pub struct TurnCompletePayload {
177 pub stop_reason: String,
178 pub api_calls: u32,
179 pub tool_calls: u32,
180 pub permission_denials: u32,
181 pub last_tool_name: Option<String>,
182 pub last_tool_was_error: bool,
183 pub turn_duration_ms: u64,
184}
185
186#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, schemars::JsonSchema)]
188#[serde(rename_all = "snake_case")]
189pub enum CompactKind {
190 Compact,
191 Trim,
192}
193
194#[derive(Debug, Clone, Serialize, schemars::JsonSchema)]
196pub struct CompactActionPayload {
197 pub kind: CompactKind,
198 pub strategy: String,
199 pub before_tokens: u64,
200 pub after_tokens: u64,
201 pub before_message_count: usize,
202 pub after_message_count: usize,
203 pub success: bool,
204 pub latency_ms: u64,
205}
206
207#[derive(Debug, Clone, Serialize, schemars::JsonSchema)]
209pub struct ResumeActionPayload {
210 pub outcome: ResumeOutcome,
211 pub source: String,
212 pub entry_count: usize,
213 pub projected_message_count: usize,
214 pub compact_boundary_count: usize,
215 pub sidechain_entry_count: usize,
216 #[serde(skip_serializing_if = "Option::is_none")]
217 pub warning_kind: Option<String>,
218 pub latency_ms: u64,
219}
220
221#[derive(Debug, Clone, Serialize, schemars::JsonSchema)]
223pub struct UserPromptSubmitPayload {
224 pub char_count: u32,
225 pub attachment_count: u32,
226}
227
228#[derive(Debug, Clone, Serialize, schemars::JsonSchema)]
230pub struct SlashCommandUsedPayload {
231 pub command: String,
233 pub kind: String,
237 pub has_arg: bool,
238}
239
240impl TelemetryEvent {
241 fn new(session_id: &str, turn_no: u32, turn_id: Option<String>, payload: EventPayload) -> Self {
242 Self {
243 event_id: Uuid::new_v4(),
244 session_id: session_id.to_string(),
245 turn_no,
246 turn_id,
247 timestamp_ms: (OffsetDateTime::now_utc().unix_timestamp_nanos() / 1_000_000) as i64,
248 schema_version: SCHEMA_VERSION,
249 payload,
250 }
251 }
252
253 pub fn kind(&self) -> &'static str {
255 self.payload.kind()
256 }
257
258 pub fn redact(self, policy: &crate::RedactionPolicy) -> Self {
261 let payload = match self.payload {
262 EventPayload::ApiError(p) => EventPayload::ApiError(p.redact(policy)),
263 EventPayload::ToolExecution(p) => EventPayload::ToolExecution(p.redact(policy)),
264 EventPayload::McpConnectionError(p) => {
265 EventPayload::McpConnectionError(p.redact(policy))
266 }
267 other => other,
268 };
269 Self { payload, ..self }
270 }
271}
272
273#[cfg(test)]
274mod tests {
275 use super::*;
276 use std::collections::HashSet;
277
278 fn object_keys_are_unique(json: &str) -> bool {
279 let mut depth = 0usize;
282 let mut keys = HashSet::new();
283 let mut chars = json.chars().peekable();
284 let mut expecting_key = false;
285 while let Some(c) = chars.next() {
286 match c {
287 '{' => {
288 depth += 1;
289 expecting_key = depth == 1;
290 }
291 '}' | ']' => depth -= 1,
292 '[' => depth += 1,
293 ',' if depth == 1 => expecting_key = true,
294 '"' => {
295 let mut text = String::new();
296 while let Some(c) = chars.next() {
297 match c {
298 '\\' => {
299 chars.next();
300 }
301 '"' => break,
302 c => text.push(c),
303 }
304 }
305 if expecting_key && depth == 1 && !keys.insert(text) {
306 return false;
307 }
308 expecting_key = false;
309 }
310 _ => {}
311 }
312 }
313 true
314 }
315
316 #[test]
317 fn no_event_repeats_an_envelope_key() {
318 let events = [
319 TelemetryEvent::turn_start(
320 "sess",
321 3,
322 Some("t".into()),
323 TurnStartPayload {
324 resumed: false,
325 is_retry: false,
326 },
327 ),
328 TelemetryEvent::turn_complete(
329 "sess",
330 3,
331 Some("t".into()),
332 TurnCompletePayload {
333 stop_reason: "end_turn".into(),
334 api_calls: 1,
335 tool_calls: 0,
336 permission_denials: 0,
337 last_tool_name: None,
338 last_tool_was_error: false,
339 turn_duration_ms: 1,
340 },
341 ),
342 TelemetryEvent::user_prompt_submit(
343 "sess",
344 3,
345 Some("t".into()),
346 UserPromptSubmitPayload {
347 char_count: 5,
348 attachment_count: 0,
349 },
350 ),
351 ];
352 for event in events {
353 let json = serde_json::to_string(&event).unwrap();
354 assert!(object_keys_are_unique(&json), "{json}");
355 assert!(json.contains("\"schema_version\":2"), "{json}");
356 }
357 }
358
359 #[test]
360 fn the_duplicate_key_check_sees_a_duplicate() {
361 assert!(!object_keys_are_unique(
362 r#"{"turn_no":1,"x":{"turn_no":2},"turn_no":1}"#
363 ));
364 assert!(object_keys_are_unique(r#"{"turn_no":1,"x":{"turn_no":2}}"#));
365 }
366
367 #[test]
368 fn kinds_are_unique_and_match_kind() {
369 let unique: HashSet<_> = EventPayload::KINDS.iter().collect();
370 assert_eq!(unique.len(), EventPayload::KINDS.len());
371 let event = TelemetryEvent::slash_command_used(
372 "sess",
373 1,
374 None,
375 SlashCommandUsedPayload {
376 command: "help".into(),
377 kind: "local".into(),
378 has_arg: false,
379 },
380 );
381 assert!(EventPayload::KINDS.contains(&event.kind()));
382 let v = serde_json::to_value(event).unwrap();
383 assert_eq!(v["type"], "slash_command_used");
384 assert_eq!(v["command"], "help");
385 }
386
387 #[test]
388 fn resume_action_uses_stable_outcome_taxonomy() {
389 for (outcome, expected) in [
390 (ResumeOutcome::Succeeded, "succeeded"),
391 (ResumeOutcome::Partial, "partial"),
392 (ResumeOutcome::Degraded, "degraded"),
393 (ResumeOutcome::Failed, "failed"),
394 ] {
395 let event = TelemetryEvent::resume_action(
396 "sess",
397 3,
398 None,
399 ResumeActionPayload {
400 outcome,
401 source: "jsonl".into(),
402 entry_count: 12,
403 projected_message_count: 7,
404 compact_boundary_count: 1,
405 sidechain_entry_count: 2,
406 warning_kind: Some("missing_sidecar".into()),
407 latency_ms: 9,
408 },
409 );
410 assert_eq!(event.kind(), "resume_action");
411 let value = serde_json::to_value(event).unwrap();
412 assert_eq!(value["outcome"], expected);
413 assert_eq!(value["warning_kind"], "missing_sidecar");
414 }
415 }
416
417 #[test]
418 fn compact_action_serializes() {
419 let event = TelemetryEvent::compact_action(
420 "sess",
421 5,
422 None,
423 CompactActionPayload {
424 kind: CompactKind::Compact,
425 strategy: "auto".into(),
426 before_tokens: 1000,
427 after_tokens: 200,
428 before_message_count: 20,
429 after_message_count: 5,
430 success: true,
431 latency_ms: 50,
432 },
433 );
434 let v = serde_json::to_value(event).unwrap();
435 assert_eq!(v["type"], "compact_action");
436 assert_eq!(v["before_tokens"], 1000);
437 }
438}