Skip to main content

base/telemetry/
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/// Where a session's telemetry events go. Never blocks, never fails the caller.
32pub trait TelemetrySink: Send + Sync {
33    fn record(&self, event: TelemetryEvent);
34}
35
36/// A build without the `telemetry` unit, or a session that records nothing.
37pub struct NoTelemetry;
38
39impl TelemetrySink for NoTelemetry {
40    fn record(&self, _: TelemetryEvent) {}
41}
42
43/// The version of the record shape.
44pub const SCHEMA_VERSION: u32 = 2;
45
46/// 一个遥测事件(转成 JSON 时展平 `event_id`/`session_id`/`timestamp` 在顶层)。
47#[derive(Debug, Clone, Serialize)]
48pub struct TelemetryEvent {
49    /// UUID v4,client 生成。
50    pub event_id: Uuid,
51    /// 关联 session。
52    pub session_id: String,
53    /// 当前 turn 编号(从 0 计)。
54    pub turn_no: u32,
55    /// 关联 turn 的 ID。None = 会话级事件(无 turn 关联)。
56    #[serde(skip_serializing_if = "Option::is_none")]
57    pub turn_id: Option<String>,
58    /// Client 本地 Unix 毫秒。
59    pub timestamp_ms: i64,
60    /// [`SCHEMA_VERSION`].
61    pub schema_version: u32,
62    /// 事件体。
63    #[serde(flatten)]
64    pub payload: EventPayload,
65}
66
67/// One line per event kind: when it is emitted, the constructor, the
68/// variant, its payload, and which file records it. The constructor's name is
69/// the kind the event serializes to; the doc line is the "when" column of the
70/// inventory in `docs/telemetry.md`.
71macro_rules! event_kinds {
72    ($($(#[doc = $doc:literal])+ $kind:ident => $variant:ident($payload:ty) in $recorded:ident;)*) => {
73        /// 事件体枚举 —— 每种变体序列化为 `type` discriminator + 字段。
74        #[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            /// Every kind, in declaration order.
82            pub const KINDS: &'static [&'static str] = &[$(stringify!($kind),)*];
83
84            /// Stable discriminator, identical to the `type` field this payload
85            /// serializes to. Used as the config key for per-event-type toggles
86            /// (see `TelemetryConfig::event_toggles`).
87            pub fn kind(&self) -> &'static str {
88                match self {
89                    $(EventPayload::$variant(_) => stringify!($kind),)*
90                }
91            }
92
93            /// Every kind with what the inventory says about it, in
94            /// declaration order.
95            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    /// daemon 建好一个会话之后、它的第一轮之前;新建与按 id 重建都算。
123    session_start => SessionStart(SessionStartPayload) in Session;
124    /// 会话的主循环退出(关闭、输入通道关闭、被取消);合计是这次载入以来的。
125    session_end => SessionEnd(SessionEndPayload) in Session;
126    /// daemon 启动完成、开始接请求时,一次。
127    startup_timing => StartupTiming(StartupTimingPayload) in Pool;
128    /// 每次模型调用完成。一轮里的调用不带 `purpose`;辅助调用带:`compact`、`memory`、`title`、`hook`、`team_judge`、`web_search`、`web_fetch`。
129    api_request => ApiRequest(ApiRequestPayload) in Session;
130    /// 一轮里的一次模型调用失败:请求被拒,或流在回复完整之前断了。每次失败的尝试一条,不论这一轮后来恢复没有;取消不算。
131    api_error => ApiError(ApiErrorPayload) in Session;
132    /// 一次模型调用去了与本会话上一次调用不同的 provider:排在前面的配额用完、没有密钥、密钥被拒、连不上或重试用尽,或排在前面的又能用了。
133    provider_switched => ProviderSwitched(ProviderSwitchedPayload) in Session;
134    /// 工具开始执行:PreToolUse hook、输入校验、权限都放行之后。
135    tool_start => ToolStart(ToolStartPayload) in Session;
136    /// 工具执行结束,成功或失败;工具自己报告的失败(如 Bash 非零退出)算失败。
137    tool_execution => ToolExecution(ToolExecutionPayload) in Session;
138    /// 一次工具调用在等权限回答时会话被关闭。
139    tool_cancelled => ToolCancelled(ToolCancelledPayload) in Session;
140    /// 会话的权限检查对一次工具调用作出判定,在询问任何人之前。
141    permission_decision => PermissionDecision(PermissionDecisionPayload) in Session;
142    /// 一轮开始,紧接 `turn_start`:开这一轮的用户消息,只记大小。
143    user_prompt_submit => UserPromptSubmit(UserPromptSubmitPayload) in Session;
144    /// 开一轮的消息是斜杠命令。
145    slash_command_used => SlashCommandUsed(SlashCommandUsedPayload) in Session;
146    /// 一轮开始,UserPromptSubmit hook 放行之后。
147    turn_start => TurnStart(TurnStartPayload) in Session;
148    /// 一轮结束,`stop_reason` 说怎么结束的。
149    turn_complete => TurnComplete(TurnCompletePayload) in Session;
150    /// 会话 token 预算到 90% 注入收尾提醒,或到 100% 中止这一轮。
151    budget_enforced => BudgetEnforced(BudgetEnforcedPayload) in Session;
152    /// 一次压缩完成或失败,或一次修剪(`kind` 为 `trim`:只清旧工具结果,不改写历史)。
153    compact_action => CompactAction(CompactActionPayload) in Session;
154    /// 一个事件的 hooks 跑完一次;没配 hook 的事件不记。`turn_no` 恒为 0,按 `turn_id` 关联。
155    hook_run => HookRun(HookRunPayload) in Session;
156    /// 会话从日志重建(会话文件);恢复请求落到已在内存里、找不到、已结束的侧链会话上(池文件);团队从 scratchpad 接上(会话文件)。
157    resume_action => ResumeAction(ResumeActionPayload) in Both;
158    /// 一个 MCP server 连上:启动时、重载时、新增时。
159    mcp_server_connected => McpServerConnected(McpServerConnectedPayload) in Pool;
160    /// 一个要连的 MCP server 没连上:起不来、握手失败或超时、配置被拒。
161    mcp_connection_error => McpConnectionError(McpConnectionErrorPayload) in Pool;
162    /// 子 Agent 开始:`Agent` 工具起的(前台、后台)、常驻团队成员、`TeamCreate` 流水线的成员。
163    agent_spawned => AgentSpawned(AgentSpawnedPayload) in Session;
164    /// 子 Agent 结束;常驻团队成员在被停下时。
165    agent_completed => AgentCompleted(AgentCompletedPayload) in Session;
166    /// `TeamCreate` 流水线的一个阶段跑完。
167    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/// 单轮开始事件的载荷。
181#[derive(Debug, Clone, Serialize, schemars::JsonSchema)]
182pub struct TurnStartPayload {
183    pub resumed: bool,
184    pub is_retry: bool,
185}
186
187/// 单轮完成事件的载荷。
188#[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/// 改写历史的压缩,还是只清旧工具结果的修剪。
200#[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/// 压缩行为事件的载荷。
209#[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/// Resume / replay 结果。Payload 只记录结构化类别和计数,不包含 transcript 内容。
222#[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/// The message a user turn opens with — its size, never its text.
236#[derive(Debug, Clone, Serialize, schemars::JsonSchema)]
237pub struct UserPromptSubmitPayload {
238    pub char_count: u32,
239    pub attachment_count: u32,
240}
241
242/// A turn whose message is a slash command.
243#[derive(Debug, Clone, Serialize, schemars::JsonSchema)]
244pub struct SlashCommandUsedPayload {
245    /// The command's name, without the leading `/`.
246    pub command: String,
247    /// `local` (run by the engine), `prompt` (a skill or command file
248    /// expanded into the turn), `mcp_prompt`, or `unknown` (sent to the model
249    /// as typed).
250    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    /// 事件类型的稳定标识(等同序列化后的 `type` 字段),用于按点过滤配置。
268    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        // 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}