Skip to main content

telemetry/events/
mod.rs

1//! `TelemetryEvent` 枚举 + 各 payload 结构化定义。
2//!
3//! 每一种事件都有生产者:`tests/guards/tests/wiring.rs` 逐个 kind 查
4//! 工作区里有没有构造它的地方,没有就失败。加一种事件要连同发它的地方一起加。
5
6use 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
31/// The version of the record shape.
32pub const SCHEMA_VERSION: u32 = 2;
33
34/// 一个遥测事件(转成 JSON 时展平 `event_id`/`session_id`/`timestamp` 在顶层)。
35#[derive(Debug, Clone, Serialize)]
36pub struct TelemetryEvent {
37    /// UUID v4,client 生成。
38    pub event_id: Uuid,
39    /// 关联 session。
40    pub session_id: String,
41    /// 当前 turn 编号(从 0 计)。
42    pub turn_no: u32,
43    /// 关联 turn 的 ID。None = 会话级事件(无 turn 关联)。
44    #[serde(skip_serializing_if = "Option::is_none")]
45    pub turn_id: Option<String>,
46    /// Client 本地 Unix 毫秒。
47    pub timestamp_ms: i64,
48    /// [`SCHEMA_VERSION`].
49    pub schema_version: u32,
50    /// 事件体。
51    #[serde(flatten)]
52    pub payload: EventPayload,
53}
54
55/// One line per event kind: when it is emitted, the constructor, the
56/// variant, its payload, and which file records it. The constructor's name is
57/// the kind the event serializes to; the doc line is the "when" column of the
58/// inventory in `docs/telemetry.md`.
59macro_rules! event_kinds {
60    ($($(#[doc = $doc:literal])+ $kind:ident => $variant:ident($payload:ty) in $recorded:ident;)*) => {
61        /// 事件体枚举 —— 每种变体序列化为 `type` discriminator + 字段。
62        #[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            /// Every kind, in declaration order.
70            pub const KINDS: &'static [&'static str] = &[$(stringify!($kind),)*];
71
72            /// Stable discriminator, identical to the `type` field this payload
73            /// serializes to. Used as the config key for per-event-type toggles
74            /// (see `TelemetryConfig::event_toggles`).
75            pub fn kind(&self) -> &'static str {
76                match self {
77                    $(EventPayload::$variant(_) => stringify!($kind),)*
78                }
79            }
80
81            /// Every kind with what the inventory says about it, in
82            /// declaration order.
83            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    /// daemon 建好一个会话之后、它的第一轮之前;新建与按 id 重建都算。
111    session_start => SessionStart(SessionStartPayload) in Session;
112    /// 会话的主循环退出(关闭、输入通道关闭、被取消);合计是这次载入以来的。
113    session_end => SessionEnd(SessionEndPayload) in Session;
114    /// daemon 启动完成、开始接请求时,一次。
115    startup_timing => StartupTiming(StartupTimingPayload) in Pool;
116    /// 每次模型调用完成。一轮里的调用不带 `purpose`;辅助调用带:`compact`、`memory`、`title`、`hook`、`team_judge`、`web_search`、`web_fetch`。
117    api_request => ApiRequest(ApiRequestPayload) in Session;
118    /// 一轮里的一次模型调用失败:请求被拒,或流在回复完整之前断了。每次失败的尝试一条,不论这一轮后来恢复没有;取消不算。
119    api_error => ApiError(ApiErrorPayload) in Session;
120    /// 一次模型调用去了与本会话上一次调用不同的 provider:排在前面的配额用完、没有密钥、密钥被拒、连不上或重试用尽,或排在前面的又能用了。
121    provider_switched => ProviderSwitched(ProviderSwitchedPayload) in Session;
122    /// 工具开始执行:PreToolUse hook、输入校验、权限都放行之后。
123    tool_start => ToolStart(ToolStartPayload) in Session;
124    /// 工具执行结束,成功或失败;工具自己报告的失败(如 Bash 非零退出)算失败。
125    tool_execution => ToolExecution(ToolExecutionPayload) in Session;
126    /// 一次工具调用在等权限回答时会话被关闭。
127    tool_cancelled => ToolCancelled(ToolCancelledPayload) in Session;
128    /// 会话的权限检查对一次工具调用作出判定,在询问任何人之前。
129    permission_decision => PermissionDecision(PermissionDecisionPayload) in Session;
130    /// 一轮开始,紧接 `turn_start`:开这一轮的用户消息,只记大小。
131    user_prompt_submit => UserPromptSubmit(UserPromptSubmitPayload) in Session;
132    /// 开一轮的消息是斜杠命令。
133    slash_command_used => SlashCommandUsed(SlashCommandUsedPayload) in Session;
134    /// 一轮开始,UserPromptSubmit hook 放行之后。
135    turn_start => TurnStart(TurnStartPayload) in Session;
136    /// 一轮结束,`stop_reason` 说怎么结束的。
137    turn_complete => TurnComplete(TurnCompletePayload) in Session;
138    /// 会话 token 预算到 90% 注入收尾提醒,或到 100% 中止这一轮。
139    budget_enforced => BudgetEnforced(BudgetEnforcedPayload) in Session;
140    /// 一次压缩完成或失败,或一次修剪(`kind` 为 `trim`:只清旧工具结果,不改写历史)。
141    compact_action => CompactAction(CompactActionPayload) in Session;
142    /// 一个事件的 hooks 跑完一次;没配 hook 的事件不记。`turn_no` 恒为 0,按 `turn_id` 关联。
143    hook_run => HookRun(HookRunPayload) in Session;
144    /// 会话从日志重建(会话文件);恢复请求落到已在内存里、找不到、已结束的侧链会话上(池文件);团队从 scratchpad 接上(会话文件)。
145    resume_action => ResumeAction(ResumeActionPayload) in Both;
146    /// 一个 MCP server 连上:启动时、重载时、新增时。
147    mcp_server_connected => McpServerConnected(McpServerConnectedPayload) in Pool;
148    /// 一个要连的 MCP server 没连上:起不来、握手失败或超时、配置被拒。
149    mcp_connection_error => McpConnectionError(McpConnectionErrorPayload) in Pool;
150    /// 子 Agent 开始:`Agent` 工具起的(前台、后台)、常驻团队成员、`TeamCreate` 流水线的成员。
151    agent_spawned => AgentSpawned(AgentSpawnedPayload) in Session;
152    /// 子 Agent 结束;常驻团队成员在被停下时。
153    agent_completed => AgentCompleted(AgentCompletedPayload) in Session;
154    /// `TeamCreate` 流水线的一个阶段跑完。
155    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/// 单轮开始事件的载荷。
168#[derive(Debug, Clone, Serialize, schemars::JsonSchema)]
169pub struct TurnStartPayload {
170    pub resumed: bool,
171    pub is_retry: bool,
172}
173
174/// 单轮完成事件的载荷。
175#[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/// 改写历史的压缩,还是只清旧工具结果的修剪。
187#[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/// 压缩行为事件的载荷。
195#[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/// Resume / replay 结果。Payload 只记录结构化类别和计数,不包含 transcript 内容。
208#[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/// The message a user turn opens with — its size, never its text.
222#[derive(Debug, Clone, Serialize, schemars::JsonSchema)]
223pub struct UserPromptSubmitPayload {
224    pub char_count: u32,
225    pub attachment_count: u32,
226}
227
228/// A turn whose message is a slash command.
229#[derive(Debug, Clone, Serialize, schemars::JsonSchema)]
230pub struct SlashCommandUsedPayload {
231    /// The command's name, without the leading `/`.
232    pub command: String,
233    /// `local` (run by the engine), `prompt` (a skill or command file
234    /// expanded into the turn), `mcp_prompt`, or `unknown` (sent to the model
235    /// as typed).
236    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    /// 事件类型的稳定标识(等同序列化后的 `type` 字段),用于按点过滤配置。
254    pub fn kind(&self) -> &'static str {
255        self.payload.kind()
256    }
257
258    /// Scrub the free-text fields (error messages) as `policy` says. No
259    /// event carries a prompt or a tool's input or output.
260    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        // A flattened payload with a field named like an envelope field
280        // serializes the key twice; serde_json::Value would keep only one.
281        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}