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
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
// Copyright (c) 2024-2026 Nervosys LLC
// SPDX-License-Identifier: AGPL-3.0-only
//! Data models for VS Code chat sessions

use chrono::{DateTime, Utc};
use serde::{Deserialize, Serialize};
use std::collections::HashMap;

/// VS Code workspace information
#[derive(Debug, Clone)]
pub struct Workspace {
    /// Workspace hash (folder name in workspaceStorage)
    pub hash: String,
    /// Associated project path
    pub project_path: Option<String>,
    /// Full path to workspace directory
    pub workspace_path: std::path::PathBuf,
    /// Path to chatSessions directory
    pub chat_sessions_path: std::path::PathBuf,
    /// Number of chat session files
    pub chat_session_count: usize,
    /// Whether chatSessions directory exists
    pub has_chat_sessions: bool,
    /// Last modified timestamp
    #[allow(dead_code)]
    pub last_modified: Option<DateTime<Utc>>,
}

/// VS Code workspace.json structure
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct WorkspaceJson {
    pub folder: Option<String>,
}

/// VS Code Chat Session (version 3 format)
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ChatSession {
    /// Session format version
    #[serde(default = "default_version")]
    pub version: u32,

    /// Unique session identifier (may not be present in file, use filename)
    #[serde(default)]
    pub session_id: Option<String>,

    /// Creation timestamp (milliseconds)
    #[serde(default)]
    pub creation_date: i64,

    /// Last message timestamp (milliseconds)
    #[serde(default)]
    pub last_message_date: i64,

    /// Whether this session was imported
    #[serde(default)]
    pub is_imported: bool,

    /// Initial location (panel, terminal, notebook, editor)
    #[serde(default = "default_location")]
    pub initial_location: String,

    /// Custom title set by user
    #[serde(default)]
    pub custom_title: Option<String>,

    /// Requester username
    #[serde(default)]
    pub requester_username: Option<String>,

    /// Requester avatar URI
    #[serde(default)]
    pub requester_avatar_icon_uri: Option<serde_json::Value>,

    /// Responder username
    #[serde(default)]
    pub responder_username: Option<String>,

    /// Responder avatar URI
    #[serde(default)]
    pub responder_avatar_icon_uri: Option<serde_json::Value>,

    /// Chat requests/messages
    #[serde(default)]
    pub requests: Vec<ChatRequest>,
}

impl ChatSession {
    /// Collect all text content from the session (user messages and responses)
    pub fn collect_all_text(&self) -> String {
        self.requests
            .iter()
            .flat_map(|req| {
                let mut texts = Vec::new();
                if let Some(msg) = &req.message {
                    if let Some(text) = &msg.text {
                        texts.push(text.clone());
                    }
                }
                if let Some(resp) = &req.response {
                    if let Some(text) = extract_response_text(resp) {
                        texts.push(text);
                    }
                }
                texts
            })
            .collect::<Vec<_>>()
            .join(" ")
    }

    /// Get user message texts
    pub fn user_messages(&self) -> Vec<&str> {
        self.requests
            .iter()
            .filter_map(|req| req.message.as_ref().and_then(|m| m.text.as_deref()))
            .collect()
    }

    /// Get assistant response texts
    pub fn assistant_responses(&self) -> Vec<String> {
        self.requests
            .iter()
            .filter_map(|req| req.response.as_ref().and_then(|r| extract_response_text(r)))
            .collect()
    }
}

fn default_version() -> u32 {
    3
}

fn default_location() -> String {
    "panel".to_string()
}

/// Default response state: Complete (1)
fn default_response_state() -> u8 {
    1
}

/// A single chat request (message + response)
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ChatRequest {
    /// Request timestamp (milliseconds)
    #[serde(default)]
    pub timestamp: Option<i64>,

    /// The user's message
    #[serde(default)]
    pub message: Option<ChatMessage>,

    /// The AI's response (complex structure - use Value for flexibility)
    #[serde(default)]
    pub response: Option<serde_json::Value>,

    /// Variable data (context, files, etc.)
    #[serde(default)]
    pub variable_data: Option<serde_json::Value>,

    /// Request ID
    #[serde(default)]
    pub request_id: Option<String>,

    /// Response ID
    #[serde(default)]
    pub response_id: Option<String>,

    /// Model ID
    #[serde(default)]
    pub model_id: Option<String>,

    /// Agent information
    #[serde(default)]
    pub agent: Option<serde_json::Value>,

    /// Result metadata
    #[serde(default)]
    pub result: Option<serde_json::Value>,

    /// Follow-up suggestions
    #[serde(default)]
    pub followups: Option<Vec<serde_json::Value>>,

    /// Whether canceled
    #[serde(default)]
    pub is_canceled: Option<bool>,

    /// Content references
    #[serde(default)]
    pub content_references: Option<Vec<serde_json::Value>>,

    /// Code citations
    #[serde(default)]
    pub code_citations: Option<Vec<serde_json::Value>>,

    /// Response markdown info
    #[serde(default)]
    pub response_markdown_info: Option<Vec<serde_json::Value>>,

    /// Source session for merged requests
    #[serde(rename = "_sourceSession", skip_serializing_if = "Option::is_none")]
    pub source_session: Option<String>,

    /// Model state tracking (VS Code 1.109+ / Copilot Chat 0.37+)
    /// Object with `value` (0=Pending, 1=Complete, 2=Cancelled) and optional `completedAt`
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub model_state: Option<serde_json::Value>,

    /// Time spent waiting for response (milliseconds)
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub time_spent_waiting: Option<i64>,
}

/// User message in a chat request
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ChatMessage {
    /// Message text
    #[serde(alias = "content")]
    pub text: Option<String>,

    /// Message parts (for complex messages)
    #[serde(default)]
    pub parts: Option<Vec<serde_json::Value>>,
}

impl ChatMessage {
    /// Get the text content of this message
    pub fn get_text(&self) -> String {
        self.text.clone().unwrap_or_default()
    }
}

/// Extract text from various response formats.
///
/// Handles three formats:
/// 1. **New array format (VS Code Copilot Chat 0.37+)**: response is a JSON array of
///    response parts, each with an optional `kind` field. Markdown content parts have
///    `kind: ""` (or absent) and a `value` field containing the text.
/// 2. **Legacy object format**: response is `{"value": [{"value": "text"}, ...]}`.
/// 3. **Simple formats**: response has `"text"` or `"content"` string fields.
pub fn extract_response_text(response: &serde_json::Value) -> Option<String> {
    // New format: response is an array of response parts
    if let Some(parts) = response.as_array() {
        let texts: Vec<&str> = parts
            .iter()
            .filter_map(|part| {
                let kind = part.get("kind").and_then(|k| k.as_str()).unwrap_or("");
                match kind {
                    // Markdown content: kind is "" or absent
                    "" => part.get("value").and_then(|v| v.as_str()),
                    // Thinking blocks
                    "thinking" => part.get("value").and_then(|v| v.as_str()),
                    // Skip tool invocations, MCP server starts, etc.
                    _ => None,
                }
            })
            .collect();
        if !texts.is_empty() {
            return Some(texts.join("\n"));
        }
    }

    // Legacy object format: {"value": [{"value": "text"}, ...]}
    if let Some(value) = response.get("value").and_then(|v| v.as_array()) {
        let parts: Vec<String> = value
            .iter()
            .filter_map(|v| v.get("value").and_then(|v| v.as_str()))
            .map(String::from)
            .collect();
        if !parts.is_empty() {
            return Some(parts.join("\n"));
        }
    }

    // Try direct text field
    if let Some(text) = response.get("text").and_then(|v| v.as_str()) {
        return Some(text.to_string());
    }

    // Try result field (legacy)
    if let Some(result) = response.get("result").and_then(|v| v.as_str()) {
        return Some(result.to_string());
    }

    // Try content field (OpenAI format)
    if let Some(content) = response.get("content").and_then(|v| v.as_str()) {
        return Some(content.to_string());
    }

    None
}

/// AI response in a chat request
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
#[allow(dead_code)]
pub struct ChatResponse {
    /// Response text
    #[serde(alias = "content")]
    pub text: Option<String>,

    /// Response parts
    #[serde(default)]
    pub parts: Option<Vec<serde_json::Value>>,

    /// Result metadata
    #[serde(default)]
    pub result: Option<serde_json::Value>,
}

/// VS Code chat session index (stored in state.vscdb)
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ChatSessionIndex {
    /// Index version
    #[serde(default = "default_index_version")]
    pub version: u32,

    /// Session entries keyed by session ID.
    /// Handles both old format (array of UUID strings) and new format (map of UUID → entry).
    #[serde(default, deserialize_with = "deserialize_index_entries")]
    pub entries: HashMap<String, ChatSessionIndexEntry>,
}

/// Custom deserializer that handles both index formats:
/// - Old: `{"entries": ["uuid1", "uuid2", ...]}`
/// - New: `{"entries": {"uuid1": {...}, "uuid2": {...}, ...}}`
fn deserialize_index_entries<'de, D>(
    deserializer: D,
) -> std::result::Result<HashMap<String, ChatSessionIndexEntry>, D::Error>
where
    D: serde::Deserializer<'de>,
{
    use serde::de;

    struct EntriesVisitor;

    impl<'de> de::Visitor<'de> for EntriesVisitor {
        type Value = HashMap<String, ChatSessionIndexEntry>;

        fn expecting(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
            f.write_str("a map of session entries or an array of session ID strings")
        }

        // New format: {"uuid": {entry}, ...}
        fn visit_map<M>(self, mut access: M) -> std::result::Result<Self::Value, M::Error>
        where
            M: de::MapAccess<'de>,
        {
            let mut map = HashMap::new();
            while let Some((key, value)) = access.next_entry::<String, ChatSessionIndexEntry>()? {
                map.insert(key, value);
            }
            Ok(map)
        }

        // Old format: ["uuid1", "uuid2", ...]
        fn visit_seq<S>(self, mut seq: S) -> std::result::Result<Self::Value, S::Error>
        where
            S: de::SeqAccess<'de>,
        {
            let mut map = HashMap::new();
            while let Some(id) = seq.next_element::<String>()? {
                let entry = ChatSessionIndexEntry {
                    session_id: id.clone(),
                    title: String::new(),
                    last_message_date: 0,
                    timing: None,
                    last_response_state: 0,
                    initial_location: "panel".to_string(),
                    is_empty: false,
                    is_imported: None,
                    has_pending_edits: None,
                    is_external: None,
                };
                map.insert(id, entry);
            }
            Ok(map)
        }
    }

    deserializer.deserialize_any(EntriesVisitor)
}

fn default_index_version() -> u32 {
    1
}

impl Default for ChatSessionIndex {
    fn default() -> Self {
        Self {
            version: 1,
            entries: HashMap::new(),
        }
    }
}

/// Session timing information (VS Code 1.109+)
/// Supports both old format (startTime/endTime) and new format (created/lastRequestStarted/lastRequestEnded)
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ChatSessionTiming {
    /// When the session was created (ms since epoch)
    /// Old format used "startTime", new format uses "created"
    #[serde(default, alias = "startTime")]
    pub created: i64,

    /// When the most recent request started (ms since epoch)
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub last_request_started: Option<i64>,

    /// When the most recent request completed (ms since epoch)
    /// Old format used "endTime", new format uses "lastRequestEnded"
    #[serde(default, skip_serializing_if = "Option::is_none", alias = "endTime")]
    pub last_request_ended: Option<i64>,
}

/// Entry in the chat session index
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ChatSessionIndexEntry {
    /// Session ID
    pub session_id: String,

    /// Session title
    pub title: String,

    /// Last message timestamp (milliseconds)
    pub last_message_date: i64,

    /// Session timing (VS Code 1.109+)
    #[serde(default)]
    pub timing: Option<ChatSessionTiming>,

    /// Last response state: 0=Pending, 1=Complete, 2=Cancelled, 3=Failed, 4=NeedsInput
    #[serde(default = "default_response_state")]
    pub last_response_state: u8,

    /// Initial location (panel, terminal, etc.)
    #[serde(default = "default_location")]
    pub initial_location: String,

    /// Whether the session is empty
    #[serde(default)]
    pub is_empty: bool,

    /// Whether the session was imported
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub is_imported: Option<bool>,

    /// Whether the session has pending edits
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub has_pending_edits: Option<bool>,

    /// Whether the session is from an external source
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub is_external: Option<bool>,
}

/// Entry in the `agentSessions.model.cache` DB key.
/// This cache drives the Chat panel sidebar in VS Code — sessions *must* have
/// a model cache entry to be visible in the UI.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ModelCacheEntry {
    /// Always "local" for local sessions
    #[serde(default)]
    pub provider_type: String,

    /// Always "Local" for local sessions
    #[serde(default)]
    pub provider_label: String,

    /// Resource URI: `vscode-chat-session://local/{base64(sessionId)}`
    pub resource: String,

    /// Icon identifier (typically "vm")
    #[serde(default)]
    pub icon: String,

    /// Session title (display label)
    #[serde(default)]
    pub label: String,

    /// Status: 1 = valid
    #[serde(default)]
    pub status: u8,

    /// Session timing information
    #[serde(default)]
    pub timing: ChatSessionTiming,

    /// Initial location (panel, terminal, etc.)
    #[serde(default)]
    pub initial_location: String,

    /// Whether the session has pending edits
    #[serde(default)]
    pub has_pending_edits: bool,

    /// Whether the session is empty (no requests)
    #[serde(default)]
    pub is_empty: bool,

    /// Whether the session is from an external source
    #[serde(default)]
    pub is_external: bool,

    /// Last response state: 0=Pending, 1=Complete, 2=Cancelled, 3=Failed, 4=NeedsInput
    #[serde(default)]
    pub last_response_state: u8,
}

/// Entry in the `agentSessions.state.cache` DB key.
/// Tracks read timestamps per session for UI state (e.g., unread indicators).
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct StateCacheEntry {
    /// Resource URI: `vscode-chat-session://local/{base64(sessionId)}`
    pub resource: String,

    /// Timestamp of last read (ms since epoch)
    #[serde(default)]
    pub read: Option<i64>,
}

/// Session with its file path for internal processing
#[derive(Debug, Clone)]
pub struct SessionWithPath {
    pub path: std::path::PathBuf,
    pub session: ChatSession,
}

impl SessionWithPath {
    /// Get the session ID from the session data or from the filename
    #[allow(dead_code)]
    pub fn get_session_id(&self) -> String {
        self.session.session_id.clone().unwrap_or_else(|| {
            self.path
                .file_stem()
                .map(|s| s.to_string_lossy().to_string())
                .unwrap_or_else(|| uuid::Uuid::new_v4().to_string())
        })
    }
}

impl ChatSession {
    /// Get the session ID (from field or will need to be set from filename)
    #[allow(dead_code)]
    pub fn get_session_id(&self) -> String {
        self.session_id
            .clone()
            .unwrap_or_else(|| "unknown".to_string())
    }

    /// Get the title for this session (from custom_title or first message)
    pub fn title(&self) -> String {
        // First try custom_title
        if let Some(title) = &self.custom_title {
            if !title.is_empty() {
                return title.clone();
            }
        }

        // Try to extract from first message
        if let Some(first_req) = self.requests.first() {
            if let Some(msg) = &first_req.message {
                if let Some(text) = &msg.text {
                    // Truncate to first 50 chars
                    let title: String = text.chars().take(50).collect();
                    if !title.is_empty() {
                        if title.len() < text.len() {
                            return format!("{}...", title);
                        }
                        return title;
                    }
                }
            }
        }

        "Untitled".to_string()
    }

    /// Check if this session is empty
    pub fn is_empty(&self) -> bool {
        self.requests.is_empty()
    }

    /// Get the request count
    pub fn request_count(&self) -> usize {
        self.requests.len()
    }

    /// Get the timestamp range of requests
    pub fn timestamp_range(&self) -> Option<(i64, i64)> {
        if self.requests.is_empty() {
            return None;
        }

        let timestamps: Vec<i64> = self.requests.iter().filter_map(|r| r.timestamp).collect();

        if timestamps.is_empty() {
            return None;
        }

        let min = *timestamps.iter().min().unwrap();
        let max = *timestamps.iter().max().unwrap();
        Some((min, max))
    }
}