use serde::Serialize;
use time::OffsetDateTime;
use uuid::Uuid;
mod hook;
pub mod inventory;
mod mcp;
mod model;
mod session;
mod team;
mod tool;
pub use hook::HookRunPayload;
pub use mcp::{McpConnectionErrorPayload, McpServerConnectedPayload};
pub use model::{
ApiErrorPayload, ApiRequestPayload, BudgetEnforcedAction, BudgetEnforcedPayload,
ProviderSwitchedPayload,
};
pub use session::{SessionEndPayload, SessionStartPayload, StartupTimingPayload};
pub use team::{AgentCompletedPayload, AgentSpawnedPayload, TeamStageCompletePayload};
pub use tool::{
PermissionDecisionOutcome, PermissionDecisionPayload, ToolCancelledPayload,
ToolExecutionPayload, ToolOutcome, ToolStartPayload,
};
pub trait TelemetrySink: Send + Sync {
fn record(&self, event: TelemetryEvent);
}
pub struct NoTelemetry;
impl TelemetrySink for NoTelemetry {
fn record(&self, _: TelemetryEvent) {}
}
pub const SCHEMA_VERSION: u32 = 2;
#[derive(Debug, Clone, Serialize)]
pub struct TelemetryEvent {
pub event_id: Uuid,
pub session_id: String,
pub turn_no: u32,
#[serde(skip_serializing_if = "Option::is_none")]
pub turn_id: Option<String>,
pub timestamp_ms: i64,
pub schema_version: u32,
#[serde(flatten)]
pub payload: EventPayload,
}
macro_rules! event_kinds {
($($(#[doc = $doc:literal])+ $kind:ident => $variant:ident($payload:ty) in $recorded:ident;)*) => {
#[derive(Debug, Clone, Serialize)]
#[serde(tag = "type", rename_all = "snake_case")]
pub enum EventPayload {
$($variant($payload),)*
}
impl EventPayload {
pub const KINDS: &'static [&'static str] = &[$(stringify!($kind),)*];
pub fn kind(&self) -> &'static str {
match self {
$(EventPayload::$variant(_) => stringify!($kind),)*
}
}
pub fn inventory() -> Vec<inventory::KindInfo> {
vec![$(inventory::KindInfo {
kind: stringify!($kind),
when: concat!($($doc),+),
recorded: inventory::Recorded::$recorded,
schema: || schemars::schema_for!($payload),
},)*]
}
}
impl TelemetryEvent {
$(
$(#[doc = $doc])+
pub fn $kind(
session_id: &str,
turn_no: u32,
turn_id: Option<String>,
p: $payload,
) -> Self {
Self::new(session_id, turn_no, turn_id, EventPayload::$variant(p))
}
)*
}
};
}
event_kinds! {
session_start => SessionStart(SessionStartPayload) in Session;
session_end => SessionEnd(SessionEndPayload) in Session;
startup_timing => StartupTiming(StartupTimingPayload) in Pool;
api_request => ApiRequest(ApiRequestPayload) in Session;
api_error => ApiError(ApiErrorPayload) in Session;
provider_switched => ProviderSwitched(ProviderSwitchedPayload) in Session;
tool_start => ToolStart(ToolStartPayload) in Session;
tool_execution => ToolExecution(ToolExecutionPayload) in Session;
tool_cancelled => ToolCancelled(ToolCancelledPayload) in Session;
permission_decision => PermissionDecision(PermissionDecisionPayload) in Session;
user_prompt_submit => UserPromptSubmit(UserPromptSubmitPayload) in Session;
slash_command_used => SlashCommandUsed(SlashCommandUsedPayload) in Session;
turn_start => TurnStart(TurnStartPayload) in Session;
turn_complete => TurnComplete(TurnCompletePayload) in Session;
budget_enforced => BudgetEnforced(BudgetEnforcedPayload) in Session;
compact_action => CompactAction(CompactActionPayload) in Session;
hook_run => HookRun(HookRunPayload) in Session;
resume_action => ResumeAction(ResumeActionPayload) in Both;
mcp_server_connected => McpServerConnected(McpServerConnectedPayload) in Pool;
mcp_connection_error => McpConnectionError(McpConnectionErrorPayload) in Pool;
agent_spawned => AgentSpawned(AgentSpawnedPayload) in Session;
agent_completed => AgentCompleted(AgentCompletedPayload) in Session;
team_stage_complete => TeamStageComplete(TeamStageCompletePayload) in Session;
}
#[derive(Debug, Clone, Copy, Serialize, PartialEq, Eq, schemars::JsonSchema)]
#[serde(rename_all = "snake_case")]
#[non_exhaustive]
pub enum ResumeOutcome {
Succeeded,
Partial,
Degraded,
Failed,
}
#[derive(Debug, Clone, Serialize, schemars::JsonSchema)]
pub struct TurnStartPayload {
pub resumed: bool,
pub is_retry: bool,
}
#[derive(Debug, Clone, Serialize, schemars::JsonSchema)]
pub struct TurnCompletePayload {
pub stop_reason: String,
pub api_calls: u32,
pub tool_calls: u32,
pub permission_denials: u32,
pub last_tool_name: Option<String>,
pub last_tool_was_error: bool,
pub turn_duration_ms: u64,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, schemars::JsonSchema)]
#[serde(rename_all = "snake_case")]
#[non_exhaustive]
pub enum CompactKind {
Compact,
Trim,
}
#[derive(Debug, Clone, Serialize, schemars::JsonSchema)]
pub struct CompactActionPayload {
pub kind: CompactKind,
pub strategy: String,
pub before_tokens: u64,
pub after_tokens: u64,
pub before_message_count: usize,
pub after_message_count: usize,
pub success: bool,
pub latency_ms: u64,
}
#[derive(Debug, Clone, Serialize, schemars::JsonSchema)]
pub struct ResumeActionPayload {
pub outcome: ResumeOutcome,
pub source: String,
pub entry_count: usize,
pub projected_message_count: usize,
pub compact_boundary_count: usize,
pub sidechain_entry_count: usize,
#[serde(skip_serializing_if = "Option::is_none")]
pub warning_kind: Option<String>,
pub latency_ms: u64,
}
#[derive(Debug, Clone, Serialize, schemars::JsonSchema)]
pub struct UserPromptSubmitPayload {
pub char_count: u32,
pub attachment_count: u32,
}
#[derive(Debug, Clone, Serialize, schemars::JsonSchema)]
pub struct SlashCommandUsedPayload {
pub command: String,
pub kind: String,
pub has_arg: bool,
}
impl TelemetryEvent {
fn new(session_id: &str, turn_no: u32, turn_id: Option<String>, payload: EventPayload) -> Self {
Self {
event_id: Uuid::new_v4(),
session_id: session_id.to_string(),
turn_no,
turn_id,
timestamp_ms: (OffsetDateTime::now_utc().unix_timestamp_nanos() / 1_000_000) as i64,
schema_version: SCHEMA_VERSION,
payload,
}
}
pub fn kind(&self) -> &'static str {
self.payload.kind()
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::collections::HashSet;
fn object_keys_are_unique(json: &str) -> bool {
let mut depth = 0usize;
let mut keys = HashSet::new();
let mut chars = json.chars().peekable();
let mut expecting_key = false;
while let Some(c) = chars.next() {
match c {
'{' => {
depth += 1;
expecting_key = depth == 1;
}
'}' | ']' => depth -= 1,
'[' => depth += 1,
',' if depth == 1 => expecting_key = true,
'"' => {
let mut text = String::new();
while let Some(c) = chars.next() {
match c {
'\\' => {
chars.next();
}
'"' => break,
c => text.push(c),
}
}
if expecting_key && depth == 1 && !keys.insert(text) {
return false;
}
expecting_key = false;
}
_ => {}
}
}
true
}
#[test]
fn no_event_repeats_an_envelope_key() {
let events = [
TelemetryEvent::turn_start(
"sess",
3,
Some("t".into()),
TurnStartPayload {
resumed: false,
is_retry: false,
},
),
TelemetryEvent::turn_complete(
"sess",
3,
Some("t".into()),
TurnCompletePayload {
stop_reason: "end_turn".into(),
api_calls: 1,
tool_calls: 0,
permission_denials: 0,
last_tool_name: None,
last_tool_was_error: false,
turn_duration_ms: 1,
},
),
TelemetryEvent::user_prompt_submit(
"sess",
3,
Some("t".into()),
UserPromptSubmitPayload {
char_count: 5,
attachment_count: 0,
},
),
];
for event in events {
let json = serde_json::to_string(&event).unwrap();
assert!(object_keys_are_unique(&json), "{json}");
assert!(json.contains("\"schema_version\":2"), "{json}");
}
}
#[test]
fn the_duplicate_key_check_sees_a_duplicate() {
assert!(!object_keys_are_unique(
r#"{"turn_no":1,"x":{"turn_no":2},"turn_no":1}"#
));
assert!(object_keys_are_unique(r#"{"turn_no":1,"x":{"turn_no":2}}"#));
}
#[test]
fn kinds_are_unique_and_match_kind() {
let unique: HashSet<_> = EventPayload::KINDS.iter().collect();
assert_eq!(unique.len(), EventPayload::KINDS.len());
let event = TelemetryEvent::slash_command_used(
"sess",
1,
None,
SlashCommandUsedPayload {
command: "help".into(),
kind: "local".into(),
has_arg: false,
},
);
assert!(EventPayload::KINDS.contains(&event.kind()));
let v = serde_json::to_value(event).unwrap();
assert_eq!(v["type"], "slash_command_used");
assert_eq!(v["command"], "help");
}
#[test]
fn resume_action_uses_stable_outcome_taxonomy() {
for (outcome, expected) in [
(ResumeOutcome::Succeeded, "succeeded"),
(ResumeOutcome::Partial, "partial"),
(ResumeOutcome::Degraded, "degraded"),
(ResumeOutcome::Failed, "failed"),
] {
let event = TelemetryEvent::resume_action(
"sess",
3,
None,
ResumeActionPayload {
outcome,
source: "jsonl".into(),
entry_count: 12,
projected_message_count: 7,
compact_boundary_count: 1,
sidechain_entry_count: 2,
warning_kind: Some("missing_sidecar".into()),
latency_ms: 9,
},
);
assert_eq!(event.kind(), "resume_action");
let value = serde_json::to_value(event).unwrap();
assert_eq!(value["outcome"], expected);
assert_eq!(value["warning_kind"], "missing_sidecar");
}
}
#[test]
fn compact_action_serializes() {
let event = TelemetryEvent::compact_action(
"sess",
5,
None,
CompactActionPayload {
kind: CompactKind::Compact,
strategy: "auto".into(),
before_tokens: 1000,
after_tokens: 200,
before_message_count: 20,
after_message_count: 5,
success: true,
latency_ms: 50,
},
);
let v = serde_json::to_value(event).unwrap();
assert_eq!(v["type"], "compact_action");
assert_eq!(v["before_tokens"], 1000);
}
}