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 trait TelemetrySink: Send + Sync {
33 fn record(&self, event: TelemetryEvent);
34}
35
36pub struct NoTelemetry;
38
39impl TelemetrySink for NoTelemetry {
40 fn record(&self, _: TelemetryEvent) {}
41}
42
43pub const SCHEMA_VERSION: u32 = 2;
45
46#[derive(Debug, Clone, Serialize)]
48pub struct TelemetryEvent {
49 pub event_id: Uuid,
51 pub session_id: String,
53 pub turn_no: u32,
55 #[serde(skip_serializing_if = "Option::is_none")]
57 pub turn_id: Option<String>,
58 pub timestamp_ms: i64,
60 pub schema_version: u32,
62 #[serde(flatten)]
64 pub payload: EventPayload,
65}
66
67macro_rules! event_kinds {
72 ($($(#[doc = $doc:literal])+ $kind:ident => $variant:ident($payload:ty) in $recorded:ident;)*) => {
73 #[derive(Debug, Clone, Serialize)]
75 #[serde(tag = "type", rename_all = "snake_case")]
76 pub enum EventPayload {
77 $($variant($payload),)*
78 }
79
80 impl EventPayload {
81 pub const KINDS: &'static [&'static str] = &[$(stringify!($kind),)*];
83
84 pub fn kind(&self) -> &'static str {
88 match self {
89 $(EventPayload::$variant(_) => stringify!($kind),)*
90 }
91 }
92
93 pub fn inventory() -> Vec<inventory::KindInfo> {
96 vec![$(inventory::KindInfo {
97 kind: stringify!($kind),
98 when: concat!($($doc),+),
99 recorded: inventory::Recorded::$recorded,
100 schema: || schemars::schema_for!($payload),
101 },)*]
102 }
103 }
104
105 impl TelemetryEvent {
106 $(
107 $(#[doc = $doc])+
108 pub fn $kind(
109 session_id: &str,
110 turn_no: u32,
111 turn_id: Option<String>,
112 p: $payload,
113 ) -> Self {
114 Self::new(session_id, turn_no, turn_id, EventPayload::$variant(p))
115 }
116 )*
117 }
118 };
119}
120
121event_kinds! {
122 session_start => SessionStart(SessionStartPayload) in Session;
124 session_end => SessionEnd(SessionEndPayload) in Session;
126 startup_timing => StartupTiming(StartupTimingPayload) in Pool;
128 api_request => ApiRequest(ApiRequestPayload) in Session;
130 api_error => ApiError(ApiErrorPayload) in Session;
132 provider_switched => ProviderSwitched(ProviderSwitchedPayload) in Session;
134 tool_start => ToolStart(ToolStartPayload) in Session;
136 tool_execution => ToolExecution(ToolExecutionPayload) in Session;
138 tool_cancelled => ToolCancelled(ToolCancelledPayload) in Session;
140 permission_decision => PermissionDecision(PermissionDecisionPayload) in Session;
142 user_prompt_submit => UserPromptSubmit(UserPromptSubmitPayload) in Session;
144 slash_command_used => SlashCommandUsed(SlashCommandUsedPayload) in Session;
146 turn_start => TurnStart(TurnStartPayload) in Session;
148 turn_complete => TurnComplete(TurnCompletePayload) in Session;
150 budget_enforced => BudgetEnforced(BudgetEnforcedPayload) in Session;
152 compact_action => CompactAction(CompactActionPayload) in Session;
154 hook_run => HookRun(HookRunPayload) in Session;
156 resume_action => ResumeAction(ResumeActionPayload) in Both;
158 mcp_server_connected => McpServerConnected(McpServerConnectedPayload) in Pool;
160 mcp_connection_error => McpConnectionError(McpConnectionErrorPayload) in Pool;
162 agent_spawned => AgentSpawned(AgentSpawnedPayload) in Session;
164 agent_completed => AgentCompleted(AgentCompletedPayload) in Session;
166 team_stage_complete => TeamStageComplete(TeamStageCompletePayload) in Session;
168}
169
170#[derive(Debug, Clone, Copy, Serialize, PartialEq, Eq, schemars::JsonSchema)]
171#[serde(rename_all = "snake_case")]
172#[non_exhaustive]
173pub enum ResumeOutcome {
174 Succeeded,
175 Partial,
176 Degraded,
177 Failed,
178}
179
180#[derive(Debug, Clone, Serialize, schemars::JsonSchema)]
182pub struct TurnStartPayload {
183 pub resumed: bool,
184 pub is_retry: bool,
185}
186
187#[derive(Debug, Clone, Serialize, schemars::JsonSchema)]
189pub struct TurnCompletePayload {
190 pub stop_reason: String,
191 pub api_calls: u32,
192 pub tool_calls: u32,
193 pub permission_denials: u32,
194 pub last_tool_name: Option<String>,
195 pub last_tool_was_error: bool,
196 pub turn_duration_ms: u64,
197}
198
199#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, schemars::JsonSchema)]
201#[serde(rename_all = "snake_case")]
202#[non_exhaustive]
203pub enum CompactKind {
204 Compact,
205 Trim,
206}
207
208#[derive(Debug, Clone, Serialize, schemars::JsonSchema)]
210pub struct CompactActionPayload {
211 pub kind: CompactKind,
212 pub strategy: String,
213 pub before_tokens: u64,
214 pub after_tokens: u64,
215 pub before_message_count: usize,
216 pub after_message_count: usize,
217 pub success: bool,
218 pub latency_ms: u64,
219}
220
221#[derive(Debug, Clone, Serialize, schemars::JsonSchema)]
223pub struct ResumeActionPayload {
224 pub outcome: ResumeOutcome,
225 pub source: String,
226 pub entry_count: usize,
227 pub projected_message_count: usize,
228 pub compact_boundary_count: usize,
229 pub sidechain_entry_count: usize,
230 #[serde(skip_serializing_if = "Option::is_none")]
231 pub warning_kind: Option<String>,
232 pub latency_ms: u64,
233}
234
235#[derive(Debug, Clone, Serialize, schemars::JsonSchema)]
237pub struct UserPromptSubmitPayload {
238 pub char_count: u32,
239 pub attachment_count: u32,
240}
241
242#[derive(Debug, Clone, Serialize, schemars::JsonSchema)]
244pub struct SlashCommandUsedPayload {
245 pub command: String,
247 pub kind: String,
251 pub has_arg: bool,
252}
253
254impl TelemetryEvent {
255 fn new(session_id: &str, turn_no: u32, turn_id: Option<String>, payload: EventPayload) -> Self {
256 Self {
257 event_id: Uuid::new_v4(),
258 session_id: session_id.to_string(),
259 turn_no,
260 turn_id,
261 timestamp_ms: (OffsetDateTime::now_utc().unix_timestamp_nanos() / 1_000_000) as i64,
262 schema_version: SCHEMA_VERSION,
263 payload,
264 }
265 }
266
267 pub fn kind(&self) -> &'static str {
269 self.payload.kind()
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}