Skip to main content

microclaw_core/
runtime_event.rs

1//! Provider-neutral runtime events shared by Server, MicroClaw Code, and headless clients.
2
3use serde::{Deserialize, Serialize};
4use serde_json::Value;
5
6#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
7#[serde(rename_all = "snake_case")]
8pub enum RuntimePlanStepStatus {
9    #[default]
10    Pending,
11    InProgress,
12    Completed,
13}
14
15#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
16pub struct RuntimePlanStep {
17    pub title: String,
18    pub status: RuntimePlanStepStatus,
19}
20
21#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
22#[serde(rename_all = "snake_case")]
23pub enum RuntimeApprovalOptionKind {
24    Primary,
25    Secondary,
26    Danger,
27}
28
29#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
30#[serde(rename_all = "snake_case")]
31pub enum RuntimeApprovalDecision {
32    Approve,
33    Deny,
34}
35
36#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
37pub struct RuntimeApprovalOption {
38    pub value: String,
39    pub label: String,
40    pub kind: RuntimeApprovalOptionKind,
41    pub decision: RuntimeApprovalDecision,
42}
43
44#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
45#[serde(rename_all = "snake_case")]
46pub enum RuntimeProcessKind {
47    Command,
48    Verification,
49}
50
51/// An observable event emitted by the shared agent runtime.
52///
53/// Keep provider-specific payloads behind the runtime boundary. Consumers
54/// should be able to project this stream without knowing which LLM produced it.
55#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
56#[serde(tag = "type", rename_all = "snake_case")]
57pub enum RuntimeEvent {
58    Iteration {
59        iteration: usize,
60    },
61    ToolStart {
62        call_id: String,
63        name: String,
64        input: Value,
65    },
66    ToolResult {
67        call_id: String,
68        name: String,
69        is_error: bool,
70        preview: String,
71        duration_ms: u64,
72        status_code: Option<i32>,
73        bytes: usize,
74        error_type: Option<String>,
75    },
76    TextDelta {
77        delta: String,
78    },
79    ToolWaveStart {
80        wave: usize,
81        tool_count: usize,
82    },
83    ToolWaveComplete {
84        wave: usize,
85    },
86    Cancelled {
87        final_text: String,
88    },
89    FinalResponse {
90        text: String,
91    },
92    MidTurnInjection {
93        count: usize,
94    },
95    FileDiff {
96        path: String,
97        diff: String,
98        added: usize,
99        removed: usize,
100        truncated: bool,
101    },
102    SubagentStarted {
103        run_id: String,
104        label: String,
105    },
106    SubagentFinished {
107        run_id: String,
108        status: String,
109    },
110    ApprovalRequired {
111        approval_id: String,
112        tool: String,
113        preview: Option<String>,
114        options: Vec<RuntimeApprovalOption>,
115        advisory: Option<String>,
116    },
117    CheckpointCreated {
118        commit: String,
119        label: String,
120    },
121    PlanUpdated {
122        steps: Vec<RuntimePlanStep>,
123    },
124    /// The conversation was reduced to fit the model's context window.
125    /// `method` is `pruned` (old tool outputs cleared), `summarized` or
126    /// `fallback` (mechanical digest after the summarizer failed).
127    ContextCompacted {
128        method: String,
129        trigger: String,
130        tokens_before: u64,
131        tokens_after: u64,
132        messages_before: usize,
133        messages_after: usize,
134        duration_ms: u64,
135    },
136    ProcessOutput {
137        call_id: String,
138        command: String,
139        output: String,
140        exit_code: Option<i32>,
141        duration_ms: u64,
142        truncated: bool,
143        kind: RuntimeProcessKind,
144    },
145}
146
147/// Versioned transport envelope for replayable runtime event streams.
148#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
149pub struct RuntimeEventEnvelope {
150    pub schema_version: u32,
151    pub run_id: String,
152    pub sequence: u64,
153    pub event: RuntimeEvent,
154}
155
156impl RuntimeEventEnvelope {
157    pub const SCHEMA_VERSION: u32 = 7;
158
159    pub fn new(run_id: impl Into<String>, sequence: u64, event: RuntimeEvent) -> Self {
160        Self {
161            schema_version: Self::SCHEMA_VERSION,
162            run_id: run_id.into(),
163            sequence,
164            event,
165        }
166    }
167}
168
169#[cfg(test)]
170mod tests {
171    use super::*;
172
173    #[test]
174    fn envelope_round_trips_as_tagged_json() {
175        let expected = RuntimeEventEnvelope::new(
176            "run-1",
177            7,
178            RuntimeEvent::ToolStart {
179                call_id: "call-1".into(),
180                name: "read_file".into(),
181                input: serde_json::json!({"path": "README.md"}),
182            },
183        );
184
185        let json = serde_json::to_string(&expected).expect("serialize runtime event");
186        assert!(json.contains("\"type\":\"tool_start\""));
187        let actual: RuntimeEventEnvelope =
188            serde_json::from_str(&json).expect("deserialize runtime event");
189        assert_eq!(actual, expected);
190    }
191
192    #[test]
193    fn plan_update_round_trips_with_step_statuses() {
194        let expected = RuntimeEventEnvelope::new(
195            "run-plan",
196            2,
197            RuntimeEvent::PlanUpdated {
198                steps: vec![
199                    RuntimePlanStep {
200                        title: "Inspect the workspace".into(),
201                        status: RuntimePlanStepStatus::Completed,
202                    },
203                    RuntimePlanStep {
204                        title: "Implement the change".into(),
205                        status: RuntimePlanStepStatus::InProgress,
206                    },
207                ],
208            },
209        );
210        let json = serde_json::to_string(&expected).expect("serialize plan update");
211        let actual: RuntimeEventEnvelope =
212            serde_json::from_str(&json).expect("deserialize plan update");
213        assert_eq!(actual, expected);
214    }
215
216    #[test]
217    fn approval_options_round_trip_with_stable_values_and_intent() {
218        let expected = RuntimeEventEnvelope::new(
219            "run-approval",
220            3,
221            RuntimeEvent::ApprovalRequired {
222                approval_id: "approval-1".into(),
223                tool: "bash".into(),
224                preview: Some("cargo test".into()),
225                options: vec![RuntimeApprovalOption {
226                    value: "3".into(),
227                    label: "Deny".into(),
228                    kind: RuntimeApprovalOptionKind::Danger,
229                    decision: RuntimeApprovalDecision::Deny,
230                }],
231                advisory: Some("Review command scope".into()),
232            },
233        );
234        let json = serde_json::to_string(&expected).expect("serialize approval event");
235        let actual: RuntimeEventEnvelope =
236            serde_json::from_str(&json).expect("deserialize approval event");
237        assert_eq!(actual, expected);
238    }
239
240    #[test]
241    fn process_output_round_trips_as_bounded_execution_evidence() {
242        let expected = RuntimeEventEnvelope::new(
243            "run-process",
244            4,
245            RuntimeEvent::ProcessOutput {
246                call_id: "bash-1".into(),
247                command: "cargo test".into(),
248                output: "test result: ok".into(),
249                exit_code: Some(0),
250                duration_ms: 250,
251                truncated: false,
252                kind: RuntimeProcessKind::Verification,
253            },
254        );
255        let json = serde_json::to_string(&expected).expect("serialize process output");
256        let actual: RuntimeEventEnvelope =
257            serde_json::from_str(&json).expect("deserialize process output");
258        assert_eq!(actual, expected);
259    }
260
261    #[test]
262    fn tool_result_duration_is_json_transport_safe() {
263        let expected = RuntimeEventEnvelope::new(
264            "run-tool",
265            5,
266            RuntimeEvent::ToolResult {
267                call_id: "call-1".into(),
268                name: "bash".into(),
269                is_error: false,
270                preview: "ok".into(),
271                duration_ms: u64::MAX,
272                status_code: Some(0),
273                bytes: 2,
274                error_type: None,
275            },
276        );
277        let json = serde_json::to_string(&expected).expect("serialize tool result");
278        let actual: RuntimeEventEnvelope =
279            serde_json::from_str(&json).expect("deserialize tool result");
280        assert_eq!(actual, expected);
281    }
282}