matrixcode-core 0.4.22

MatrixCode Agent Core - Pure logic, no UI
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
//! MatrixCode Event Protocol

use serde::{Deserialize, Serialize};
use std::time::{SystemTime, UNIX_EPOCH};

/// Agent event
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct AgentEvent {
    pub event_type: EventType,
    pub timestamp: u64,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub data: Option<EventData>,
}

/// Event types
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "snake_case")]
pub enum EventType {
    TextStart,
    TextDelta,
    TextEnd,
    ThinkingStart,
    ThinkingDelta,
    ThinkingEnd,
    ToolUseStart,
    ToolUseInputDelta,
    ToolUseInputEnd,
    ToolResult,
    SessionStarted,
    SessionEnded,
    SessionRestored, // Session loaded from file with token stats
    NewSession,
    CompressionTriggered,
    CompressionCompleted,
    MemoryLoaded,
    MemoryDetected,    // Memory extracted from conversation
    KeywordsExtracted, // Keywords extracted from context (for debug)
    Error,
    Usage,
    Progress,
    ContextSize, // Update context window size from provider
    AskQuestion, // Ask tool: waiting for user input
    ProxyToolRequest, // Proxy tool: request external execution
    ProxyToolResponse, // Proxy tool: external execution result
    DebugLog,    // Debug log entry for TUI debug panel
    SkillsLoaded,   // Skills loaded notification
    WorkflowsLoaded, // Workflows loaded notification
}

/// Event data
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "snake_case")]
pub enum EventData {
    Text {
        delta: String,
    },
    Thinking {
        delta: String,
        signature: Option<String>,
    },
    ToolUse {
        id: String,
        name: String,
        input: Option<serde_json::Value>,
    },
    ToolUseInput {
        id: String,
        delta: String,
    },
    ToolResult {
        tool_use_id: String,
        name: String,
        detail: Option<String>,
        content: String,
        is_error: bool,
    },
    Error {
        message: String,
        code: Option<String>,
        source: Option<String>,
    },
    Usage {
        input_tokens: u64,
        output_tokens: u64,
        cache_creation_input_tokens: Option<u64>,
        cache_read_input_tokens: Option<u64>,
    },
    SessionRestore {
        input_tokens: u64,
        total_output_tokens: u64,
        message_count: usize,
    },
    Progress {
        message: String,
        percentage: Option<u8>,
    },
    ContextSize {
        context_size: u64,
    },
    Compression {
        original_tokens: u64,
        compressed_tokens: u64,
        ratio: f32,
    },
    Memory {
        summary: String,
        entries_count: usize,
    },
    Keywords {
        keywords: Vec<String>,
        source: String,
    }, // Extracted keywords
    AskQuestion {
        question: String,
        options: Option<serde_json::Value>,
    },
    /// Proxy tool request - needs external execution
    ProxyToolRequest {
        request_id: String,
        tool_name: String,
        tool_input: serde_json::Value,
        metadata: crate::tools::toolproxy::ProxyMetadata,
    },
    /// Proxy tool response - external execution result
    ProxyToolResponse {
        request_id: String,
        result: String,
        is_error: bool,
    },
    DebugLog {
        category: String,
        message: String,
    }, // Debug log entry
    SkillsLoaded {
        names: Vec<String>,
    },
    WorkflowsLoaded {
        names: Vec<String>,
    },
}

impl AgentEvent {
    pub fn new(event_type: EventType) -> Self {
        Self {
            event_type,
            timestamp: current_timestamp(),
            data: None,
        }
    }

    pub fn with_data(event_type: EventType, data: EventData) -> Self {
        Self {
            event_type,
            timestamp: current_timestamp(),
            data: Some(data),
        }
    }

    pub fn text_delta(delta: impl Into<String>) -> Self {
        Self::with_data(
            EventType::TextDelta,
            EventData::Text {
                delta: delta.into(),
            },
        )
    }

    pub fn text_start() -> Self {
        Self::new(EventType::TextStart)
    }
    pub fn text_end() -> Self {
        Self::new(EventType::TextEnd)
    }
    pub fn thinking_start() -> Self {
        Self::new(EventType::ThinkingStart)
    }
    pub fn thinking_end() -> Self {
        Self::new(EventType::ThinkingEnd)
    }
    pub fn session_started() -> Self {
        Self::new(EventType::SessionStarted)
    }
    pub fn session_ended() -> Self {
        Self::new(EventType::SessionEnded)
    }
    pub fn session_restored(
        input_tokens: u64,
        total_output_tokens: u64,
        message_count: usize,
    ) -> Self {
        Self::with_data(
            EventType::SessionRestored,
            EventData::SessionRestore {
                input_tokens,
                total_output_tokens,
                message_count,
            },
        )
    }

    pub fn thinking_delta(delta: impl Into<String>, signature: Option<String>) -> Self {
        Self::with_data(
            EventType::ThinkingDelta,
            EventData::Thinking {
                delta: delta.into(),
                signature,
            },
        )
    }

    pub fn tool_use_start(
        id: impl Into<String>,
        name: impl Into<String>,
        input: Option<serde_json::Value>,
    ) -> Self {
        Self::with_data(
            EventType::ToolUseStart,
            EventData::ToolUse {
                id: id.into(),
                name: name.into(),
                input,
            },
        )
    }

    pub fn tool_result(
        tool_use_id: impl Into<String>,
        name: impl Into<String>,
        detail: Option<String>,
        content: impl Into<String>,
        is_error: bool,
    ) -> Self {
        Self::with_data(
            EventType::ToolResult,
            EventData::ToolResult {
                tool_use_id: tool_use_id.into(),
                name: name.into(),
                detail,
                content: content.into(),
                is_error,
            },
        )
    }

    pub fn error(message: impl Into<String>, code: Option<String>, source: Option<String>) -> Self {
        Self::with_data(
            EventType::Error,
            EventData::Error {
                message: message.into(),
                code,
                source,
            },
        )
    }

    pub fn progress(message: impl Into<String>, percentage: Option<u8>) -> Self {
        Self::with_data(
            EventType::Progress,
            EventData::Progress {
                message: message.into(),
                percentage,
            },
        )
    }

    pub fn usage(input_tokens: u64, output_tokens: u64) -> Self {
        Self::with_data(
            EventType::Usage,
            EventData::Usage {
                input_tokens,
                output_tokens,
                cache_creation_input_tokens: None,
                cache_read_input_tokens: None,
            },
        )
    }

    pub fn usage_with_cache(
        input_tokens: u64,
        output_tokens: u64,
        cache_read: u64,
        cache_created: u64,
    ) -> Self {
        Self::with_data(
            EventType::Usage,
            EventData::Usage {
                input_tokens,
                output_tokens,
                cache_creation_input_tokens: if cache_created > 0 {
                    Some(cache_created)
                } else {
                    None
                },
                cache_read_input_tokens: if cache_read > 0 {
                    Some(cache_read)
                } else {
                    None
                },
            },
        )
    }

    pub fn debug_log(category: impl Into<String>, message: impl Into<String>) -> Self {
        Self::with_data(
            EventType::DebugLog,
            EventData::DebugLog {
                category: category.into(),
                message: message.into(),
            },
        )
    }

    pub fn skills_loaded(names: Vec<String>) -> Self {
        Self::with_data(
            EventType::SkillsLoaded,
            EventData::SkillsLoaded { names },
        )
    }

    pub fn workflows_loaded(names: Vec<String>) -> Self {
        Self::with_data(
            EventType::WorkflowsLoaded,
            EventData::WorkflowsLoaded { names },
        )
    }

    /// 创建代理工具请求事件
    pub fn proxy_tool_request(
        request_id: impl Into<String>,
        tool_name: impl Into<String>,
        tool_input: serde_json::Value,
        metadata: crate::tools::toolproxy::ProxyMetadata,
    ) -> Self {
        Self::with_data(
            EventType::ProxyToolRequest,
            EventData::ProxyToolRequest {
                request_id: request_id.into(),
                tool_name: tool_name.into(),
                tool_input,
                metadata,
            },
        )
    }
    
    /// 创建代理工具响应事件
    pub fn proxy_tool_response(
        request_id: impl Into<String>,
        result: impl Into<String>,
        is_error: bool,
    ) -> Self {
        Self::with_data(
            EventType::ProxyToolResponse,
            EventData::ProxyToolResponse {
                request_id: request_id.into(),
                result: result.into(),
                is_error,
            },
        )
    }

    pub fn to_json(&self) -> Result<String, serde_json::Error> {
        serde_json::to_string(self)
    }
    pub fn from_json(json: &str) -> Result<Self, serde_json::Error> {
        serde_json::from_str(json)
    }
}

fn current_timestamp() -> u64 {
    SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .unwrap_or_default()
        .as_millis() as u64
}

#[derive(Debug, Default)]
pub struct EventCollector {
    events: Vec<AgentEvent>,
}

impl EventCollector {
    pub fn new() -> Self {
        Self::default()
    }
    pub fn push(&mut self, event: AgentEvent) {
        self.events.push(event);
    }
    pub fn events(&self) -> &[AgentEvent] {
        &self.events
    }
    pub fn len(&self) -> usize {
        self.events.len()
    }
    pub fn is_empty(&self) -> bool {
        self.events.is_empty()
    }
    pub fn clear(&mut self) {
        self.events.clear();
    }
    pub fn to_json_lines(&self) -> Result<Vec<String>, serde_json::Error> {
        self.events.iter().map(|e| e.to_json()).collect()
    }
    pub fn output_json_lines(&self) -> Result<String, serde_json::Error> {
        Ok(self.to_json_lines()?.join("\n"))
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    #[test]
    fn test_event() {
        let e = AgentEvent::text_delta("Hello");
        assert!(e.to_json().unwrap().contains("Hello"));
    }
}