Skip to main content

base/telemetry/
tool.rs

1//! Tool execution and permission events.
2
3use serde::Serialize;
4
5/// 工具开始执行事件的载荷(在 ToolExecution 之前发出)。
6#[derive(Debug, Clone, Serialize, schemars::JsonSchema)]
7pub struct ToolStartPayload {
8    pub tool_name: String,
9    pub tool_use_id: String,
10    pub input_json_size: u64,
11    pub destructive: bool,
12    pub deferred: bool,
13    /// An MCP server's or a plugin's tool, not one of the engine's own.
14    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
15    pub extension: bool,
16}
17
18/// 工具执行事件的载荷。
19#[derive(Debug, Clone, Serialize, schemars::JsonSchema)]
20pub struct ToolExecutionPayload {
21    pub tool_name: String,
22    pub tool_use_id: String,
23    /// Unified outcome taxonomy: Succeeded / Failed / Timeout / etc.
24    pub outcome: ToolOutcome,
25    pub is_error: bool,
26    #[serde(skip_serializing_if = "Option::is_none")]
27    pub error_message: Option<String>,
28    pub latency_ms: u64,
29    pub input_json_size: u64,
30    pub result_content_size: u64,
31    pub user_approved: bool,
32}
33
34/// 工具被取消事件的载荷。
35#[derive(Debug, Clone, Serialize, schemars::JsonSchema)]
36pub struct ToolCancelledPayload {
37    pub tool_name: String,
38    pub reason: String,
39    pub elapsed_ms: u64,
40}
41
42/// What became of one tool call's permission: the conclusion, after whoever
43/// could answer the session's question did.
44#[derive(Debug, Clone, Serialize, schemars::JsonSchema)]
45pub struct PermissionDecisionPayload {
46    pub tool_name: String,
47    pub outcome: PermissionDecisionOutcome,
48    pub permission_mode: String,
49    pub destructive: bool,
50    pub latency_ms: u64,
51    /// On whose word the call ran: `rule`, `contained`, `accept_edits`,
52    /// `bypass`, `hook_approved`, `unattended_confined`, `host_declared` or
53    /// `person`.
54    #[serde(skip_serializing_if = "Option::is_none")]
55    pub basis: Option<String>,
56    /// Where the call was refused, or asked about before a person refused it.
57    #[serde(skip_serializing_if = "Option::is_none")]
58    pub stage: Option<String>,
59}
60
61#[derive(Debug, Clone, Copy, Serialize, PartialEq, Eq, schemars::JsonSchema)]
62#[serde(rename_all = "snake_case")]
63#[non_exhaustive]
64pub enum ToolOutcome {
65    Approved,
66    Denied,
67    Succeeded,
68    Failed,
69    Timeout,
70    Cancelled,
71}
72
73#[derive(Debug, Clone, Copy, Serialize, PartialEq, Eq, schemars::JsonSchema)]
74#[serde(rename_all = "snake_case")]
75#[non_exhaustive]
76pub enum PermissionDecisionOutcome {
77    AutoAllow,
78    /// A person approved it when asked.
79    UserAllow,
80    Deny,
81}
82
83#[cfg(test)]
84mod tests {
85    use super::*;
86    use crate::telemetry::TelemetryEvent;
87    use serde_json::json;
88
89    #[test]
90    fn permission_decision_redacts_inputs_by_shape() {
91        let event = TelemetryEvent::permission_decision(
92            "sess",
93            1,
94            None,
95            PermissionDecisionPayload {
96                tool_name: "bash".into(),
97                outcome: PermissionDecisionOutcome::Deny,
98                permission_mode: "default".into(),
99                destructive: true,
100                latency_ms: 4,
101                basis: None,
102                stage: Some("mode_default".into()),
103            },
104        );
105
106        assert_eq!(event.kind(), "permission_decision");
107        let value =
108            serde_json::to_value(event).expect("serialization of telemetry event should not fail");
109        assert_eq!(value["type"], "permission_decision");
110        assert_eq!(value["outcome"], "deny");
111        assert_eq!(value["stage"], "mode_default");
112        assert!(value.get("basis").is_none());
113        assert_eq!(value["tool_name"], "bash");
114        assert_eq!(value.get("input").unwrap_or(&json!(null)), &json!(null));
115        assert_eq!(value.get("prompt").unwrap_or(&json!(null)), &json!(null));
116    }
117
118    #[test]
119    fn tool_outcome_all_variants() {
120        for (outcome, expected) in [
121            (ToolOutcome::Approved, "approved"),
122            (ToolOutcome::Denied, "denied"),
123            (ToolOutcome::Succeeded, "succeeded"),
124            (ToolOutcome::Failed, "failed"),
125            (ToolOutcome::Timeout, "timeout"),
126            (ToolOutcome::Cancelled, "cancelled"),
127        ] {
128            let payload = ToolExecutionPayload {
129                tool_name: "Bash".into(),
130                tool_use_id: "tu_01".into(),
131                outcome,
132                is_error: matches!(outcome, ToolOutcome::Failed | ToolOutcome::Timeout),
133                error_message: None,
134                latency_ms: 100,
135                input_json_size: 42,
136                result_content_size: 128,
137                user_approved: true,
138            };
139            let event = TelemetryEvent::tool_execution("sess", 1, None, payload);
140            assert_eq!(event.kind(), "tool_execution");
141            let v = serde_json::to_value(event)
142                .expect("serialization of telemetry event should not fail");
143            assert_eq!(v["type"], "tool_execution");
144            assert_eq!(v["outcome"], expected);
145            assert_eq!(v["tool_name"], "Bash");
146        }
147    }
148
149    #[test]
150    fn permission_decision_all_outcomes() {
151        for (outcome, expected) in [
152            (PermissionDecisionOutcome::AutoAllow, "auto_allow"),
153            (PermissionDecisionOutcome::UserAllow, "user_allow"),
154            (PermissionDecisionOutcome::Deny, "deny"),
155        ] {
156            let payload = PermissionDecisionPayload {
157                tool_name: "Read".into(),
158                outcome,
159                permission_mode: "default".into(),
160                destructive: false,
161                latency_ms: 3,
162                basis: None,
163                stage: None,
164            };
165            let event = TelemetryEvent::permission_decision("sess", 2, None, payload);
166            let v = serde_json::to_value(event)
167                .expect("serialization of telemetry event should not fail");
168            assert_eq!(v["type"], "permission_decision");
169            assert_eq!(v["outcome"], expected);
170        }
171    }
172
173    #[test]
174    fn tool_start_serializes() {
175        let event = TelemetryEvent::tool_start(
176            "sess",
177            5,
178            None,
179            ToolStartPayload {
180                tool_name: "Bash".into(),
181                tool_use_id: "tu_01".into(),
182                input_json_size: 128,
183                destructive: true,
184                deferred: false,
185                extension: false,
186            },
187        );
188        assert_eq!(event.kind(), "tool_start");
189        let v =
190            serde_json::to_value(event).expect("serialization of telemetry event should not fail");
191        assert_eq!(v["type"], "tool_start");
192        assert_eq!(v["tool_name"], "Bash");
193        assert_eq!(v["destructive"], true);
194    }
195
196    #[test]
197    fn tool_cancelled_serializes() {
198        let event = TelemetryEvent::tool_cancelled(
199            "sess",
200            3,
201            None,
202            ToolCancelledPayload {
203                tool_name: "Read".into(),
204                reason: "user_interrupt".into(),
205                elapsed_ms: 500,
206            },
207        );
208        assert_eq!(event.kind(), "tool_cancelled");
209        let v =
210            serde_json::to_value(event).expect("serialization of telemetry event should not fail");
211        assert_eq!(v["type"], "tool_cancelled");
212        assert_eq!(v["reason"], "user_interrupt");
213    }
214}