chasm-cli 2.0.0

Universal chat session manager - harvest, merge, and analyze AI chat history from VS Code, Cursor, and other editors
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
// Copyright (c) 2024-2026 Nervosys LLC
// SPDX-License-Identifier: AGPL-3.0-only
//! Session format conversion utilities
//!
//! Converts between different chat session formats:
//! - VS Code Copilot Chat format
//! - OpenAI API format
//! - Ollama format
//! - Generic markdown format

use crate::models::{extract_response_text, ChatMessage, ChatRequest, ChatSession};
use serde::{Deserialize, Serialize};

/// Generic message format for import/export
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct GenericMessage {
    pub role: String,
    pub content: String,
    #[serde(default)]
    pub timestamp: Option<i64>,
    #[serde(default)]
    pub model: Option<String>,
}

/// Generic session format for import/export
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct GenericSession {
    pub id: String,
    pub title: Option<String>,
    pub messages: Vec<GenericMessage>,
    #[serde(default)]
    pub created_at: Option<i64>,
    #[serde(default)]
    pub updated_at: Option<i64>,
    #[serde(default)]
    pub provider: Option<String>,
    #[serde(default)]
    pub model: Option<String>,
}

impl From<ChatSession> for GenericSession {
    fn from(session: ChatSession) -> Self {
        let mut messages = Vec::new();

        for request in session.requests {
            // Add user message
            if let Some(msg) = &request.message {
                if let Some(text) = &msg.text {
                    messages.push(GenericMessage {
                        role: "user".to_string(),
                        content: text.clone(),
                        timestamp: request.timestamp,
                        model: request.model_id.clone(),
                    });
                }
            }

            // Add assistant response
            if let Some(response) = &request.response {
                if let Some(text) = extract_response_text(response) {
                    messages.push(GenericMessage {
                        role: "assistant".to_string(),
                        content: text,
                        timestamp: request.timestamp,
                        model: request.model_id.clone(),
                    });
                }
            }
        }

        GenericSession {
            id: session
                .session_id
                .unwrap_or_else(|| uuid::Uuid::new_v4().to_string()),
            title: session.custom_title,
            messages,
            created_at: Some(session.creation_date),
            updated_at: Some(session.last_message_date),
            provider: session.responder_username,
            model: None,
        }
    }
}

impl From<GenericSession> for ChatSession {
    fn from(generic: GenericSession) -> Self {
        let now = chrono::Utc::now().timestamp_millis();

        let mut requests = Vec::new();
        let mut user_msg: Option<(String, Option<i64>, Option<String>)> = None;

        for msg in generic.messages {
            match msg.role.as_str() {
                "user" => {
                    user_msg = Some((msg.content, msg.timestamp, msg.model));
                }
                "assistant" => {
                    if let Some((user_text, timestamp, model)) = user_msg.take() {
                        requests.push(ChatRequest {
                            timestamp: timestamp.or(Some(now)),
                            message: Some(ChatMessage {
                                text: Some(user_text),
                                parts: None,
                            }),
                            response: Some(serde_json::json!(
                                [{"value": msg.content}]
                            )),
                            variable_data: None,
                            request_id: Some(uuid::Uuid::new_v4().to_string()),
                            response_id: Some(uuid::Uuid::new_v4().to_string()),
                            model_id: model.or(msg.model),
                            agent: None,
                            result: None,
                            followups: None,
                            is_canceled: Some(false),
                            content_references: None,
                            code_citations: None,
                            response_markdown_info: None,
                            source_session: None,
                            model_state: None,
                            time_spent_waiting: None,
                        });
                    }
                }
                _ => {}
            }
        }

        ChatSession {
            version: 3,
            session_id: Some(generic.id),
            creation_date: generic.created_at.unwrap_or(now),
            last_message_date: generic.updated_at.unwrap_or(now),
            is_imported: true,
            initial_location: "imported".to_string(),
            custom_title: generic.title,
            requester_username: Some("user".to_string()),
            requester_avatar_icon_uri: None,
            responder_username: generic.provider,
            responder_avatar_icon_uri: None,
            requests,
        }
    }
}

/// Convert a session to markdown format
pub fn session_to_markdown(session: &ChatSession) -> String {
    let mut md = String::new();

    // Header
    md.push_str(&format!("# {}\n\n", session.title()));

    if let Some(id) = &session.session_id {
        md.push_str(&format!("Session ID: `{}`\n\n", id));
    }

    md.push_str(&format!(
        "Created: {}\n",
        format_timestamp(session.creation_date)
    ));
    md.push_str(&format!(
        "Last Updated: {}\n\n",
        format_timestamp(session.last_message_date)
    ));

    md.push_str("---\n\n");

    // Messages
    for (i, request) in session.requests.iter().enumerate() {
        // User message
        if let Some(msg) = &request.message {
            if let Some(text) = &msg.text {
                md.push_str(&format!("## User ({})\n\n", i + 1));
                md.push_str(text);
                md.push_str("\n\n");
            }
        }

        // Assistant response
        if let Some(response) = &request.response {
            if let Some(text) = extract_response_text(response) {
                let model = request.model_id.as_deref().unwrap_or("Assistant");
                md.push_str(&format!("## {} ({})\n\n", model, i + 1));
                md.push_str(&text);
                md.push_str("\n\n");
            }
        }

        md.push_str("---\n\n");
    }

    md
}

/// Parse a markdown file into a session
pub fn markdown_to_session(markdown: &str, title: Option<String>) -> ChatSession {
    let now = chrono::Utc::now().timestamp_millis();
    let session_id = uuid::Uuid::new_v4().to_string();

    // Simple parsing - look for ## User and ## Assistant sections
    let mut requests = Vec::new();
    let mut current_user: Option<String> = None;
    let mut current_assistant: Option<String> = None;
    let mut in_user = false;
    let mut in_assistant = false;
    let mut content = String::new();

    for line in markdown.lines() {
        if line.starts_with("## User") {
            // Save previous pair
            if let Some(user) = current_user.take() {
                requests.push(create_request(
                    user,
                    current_assistant.take().unwrap_or_default(),
                    now,
                    None,
                ));
            }
            in_user = true;
            in_assistant = false;
            content.clear();
        } else if line.starts_with("## ") && !line.starts_with("## User") {
            // Assistant or model response
            if in_user {
                current_user = Some(content.trim().to_string());
            }
            in_user = false;
            in_assistant = true;
            content.clear();
        } else if line == "---" {
            if in_assistant {
                current_assistant = Some(content.trim().to_string());
            }
            // Save pair
            if let Some(user) = current_user.take() {
                requests.push(create_request(
                    user,
                    current_assistant.take().unwrap_or_default(),
                    now,
                    None,
                ));
            }
            in_user = false;
            in_assistant = false;
            content.clear();
        } else {
            content.push_str(line);
            content.push('\n');
        }
    }

    // Handle final pair
    if in_user {
        current_user = Some(content.trim().to_string());
    } else if in_assistant {
        current_assistant = Some(content.trim().to_string());
    }
    if let Some(user) = current_user.take() {
        requests.push(create_request(
            user,
            current_assistant.take().unwrap_or_default(),
            now,
            None,
        ));
    }

    ChatSession {
        version: 3,
        session_id: Some(session_id),
        creation_date: now,
        last_message_date: now,
        is_imported: true,
        initial_location: "markdown".to_string(),
        custom_title: title,
        requester_username: Some("user".to_string()),
        requester_avatar_icon_uri: None,
        responder_username: Some("Imported".to_string()),
        responder_avatar_icon_uri: None,
        requests,
    }
}

/// Create a ChatRequest from user/assistant text
fn create_request(
    user_text: String,
    assistant_text: String,
    timestamp: i64,
    model: Option<String>,
) -> ChatRequest {
    ChatRequest {
        timestamp: Some(timestamp),
        message: Some(ChatMessage {
            text: Some(user_text),
            parts: None,
        }),
        response: Some(serde_json::json!(
            [{"value": assistant_text}]
        )),
        variable_data: None,
        request_id: Some(uuid::Uuid::new_v4().to_string()),
        response_id: Some(uuid::Uuid::new_v4().to_string()),
        model_id: model,
        agent: None,
        result: None,
        followups: None,
        is_canceled: Some(false),
        content_references: None,
        code_citations: None,
        response_markdown_info: None,
        source_session: None,
        model_state: None,
        time_spent_waiting: None,
    }
}

/// Extract text from various response formats
/// NOTE: This is now delegated to crate::models::extract_response_text.
/// This wrapper is kept for backward compatibility with in-module callers.
fn _extract_response_text_legacy(response: &serde_json::Value) -> Option<String> {
    extract_response_text(response)
}

/// Format a timestamp for display
fn format_timestamp(timestamp: i64) -> String {
    use chrono::{TimeZone, Utc};

    if timestamp == 0 {
        return "Unknown".to_string();
    }

    let dt = Utc.timestamp_millis_opt(timestamp);
    match dt {
        chrono::LocalResult::Single(dt) => dt.format("%Y-%m-%d %H:%M:%S").to_string(),
        _ => "Invalid".to_string(),
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_session_to_markdown() {
        let session = ChatSession {
            version: 3,
            session_id: Some("test-123".to_string()),
            creation_date: 1700000000000,
            last_message_date: 1700000000000,
            is_imported: false,
            initial_location: "panel".to_string(),
            custom_title: Some("Test Session".to_string()),
            requester_username: Some("user".to_string()),
            requester_avatar_icon_uri: None,
            responder_username: Some("assistant".to_string()),
            responder_avatar_icon_uri: None,
            requests: vec![ChatRequest {
                timestamp: Some(1700000000000),
                message: Some(ChatMessage {
                    text: Some("Hello".to_string()),
                    parts: None,
                }),
                response: Some(serde_json::json!({
                    "value": [{"value": "Hi there!"}]
                })),
                variable_data: None,
                request_id: None,
                response_id: None,
                model_id: Some("gpt-4".to_string()),
                agent: None,
                result: None,
                followups: None,
                is_canceled: None,
                content_references: None,
                code_citations: None,
                response_markdown_info: None,
                source_session: None,
                model_state: None,
                time_spent_waiting: None,
            }],
        };

        let md = session_to_markdown(&session);
        assert!(md.contains("# Test Session"));
        assert!(md.contains("Hello"));
        assert!(md.contains("Hi there!"));
    }

    #[test]
    fn test_generic_session_conversion() {
        let session = ChatSession {
            version: 3,
            session_id: Some("test-123".to_string()),
            creation_date: 1700000000000,
            last_message_date: 1700000000000,
            is_imported: false,
            initial_location: "panel".to_string(),
            custom_title: Some("Test".to_string()),
            requester_username: None,
            requester_avatar_icon_uri: None,
            responder_username: Some("Copilot".to_string()),
            responder_avatar_icon_uri: None,
            requests: vec![],
        };

        let generic: GenericSession = session.clone().into();
        assert_eq!(generic.id, "test-123");
        assert_eq!(generic.title, Some("Test".to_string()));

        let back: ChatSession = generic.into();
        assert_eq!(back.session_id, Some("test-123".to_string()));
    }
}