Repository navigation
Expand file tree
/
Copy pathexport.rs
More file actions
395 lines (338 loc) · 11.4 KB
/
Copy pathexport.rs
File metadata and controls
395 lines (338 loc) · 11.4 KB
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
//! Session export functionality.
//!
//! Supports exporting sessions to various formats:
//! - Markdown
//! - JSON
//! - Plain text
use anyhow::Result;
use chrono::Local;
use super::manager::CortexSession;
use super::types::StoredMessage;
// ============================================================
// EXPORT FORMAT
// ============================================================
/// Export format options.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ExportFormat {
/// Markdown format with syntax highlighting.
Markdown,
/// JSON format (full data).
Json,
/// Plain text format.
Text,
}
impl ExportFormat {
/// Gets the file extension for this format.
pub fn extension(&self) -> &'static str {
match self {
ExportFormat::Markdown => "md",
ExportFormat::Json => "json",
ExportFormat::Text => "txt",
}
}
/// Gets the display name for this format.
pub fn name(&self) -> &'static str {
match self {
ExportFormat::Markdown => "Markdown",
ExportFormat::Json => "JSON",
ExportFormat::Text => "Text",
}
}
/// Parses a format from string.
pub fn parse(s: &str) -> Option<Self> {
match s.to_lowercase().as_str() {
"md" | "markdown" => Some(ExportFormat::Markdown),
"json" => Some(ExportFormat::Json),
"txt" | "text" => Some(ExportFormat::Text),
_ => None,
}
}
}
// ============================================================
// EXPORT FUNCTION
// ============================================================
/// Exports a session to the specified format.
pub fn export_session(session: &CortexSession, format: ExportFormat) -> Result<String> {
match format {
ExportFormat::Markdown => export_markdown(session),
ExportFormat::Json => export_json(session),
ExportFormat::Text => export_text(session),
}
}
/// Exports a session to Markdown format.
fn export_markdown(session: &CortexSession) -> Result<String> {
let mut output = String::new();
// Header
output.push_str(&format!("# {}\n\n", session.title()));
output.push_str(&format!(
"**Model:** {} / {}\n\n",
session.meta.provider, session.meta.model
));
output.push_str(&format!(
"**Created:** {}\n\n",
session
.meta
.created_at
.with_timezone(&Local)
.format("%Y-%m-%d %H:%M")
));
output.push_str(&format!(
"**Messages:** {} | **Tokens:** {}\n\n",
session.message_count(),
session.format_tokens()
));
output.push_str("---\n\n");
// Messages
for message in session.messages() {
output.push_str(&format_message_markdown(message));
output.push('\n');
}
Ok(output)
}
/// Escape nested code blocks in content by using different fence styles.
/// If content contains ```, use ~~~~ as the outer fence.
fn escape_nested_code_blocks(content: &str) -> (String, &'static str) {
// Count the maximum number of consecutive backticks in the content
let max_backticks = content.split("```").count().saturating_sub(1);
if max_backticks > 0 || content.contains("```") {
// Use tildes as outer fence when content has backticks
("~~~~".to_string(), "~~~~")
} else {
("```".to_string(), "```")
}
}
/// Formats a single message as Markdown.
fn format_message_markdown(message: &StoredMessage) -> String {
let mut output = String::new();
// Role header
let role_icon = match message.role.as_str() {
"user" => ">",
"assistant" => "",
"system" => "[System]",
_ => "",
};
if message.role == "user" {
output.push_str(&format!("### {} User\n\n", role_icon));
} else if message.role == "assistant" {
output.push_str("### Assistant\n\n");
} else if message.role == "system" {
output.push_str(&format!("### {}\n\n", role_icon));
}
// Reasoning (if present)
if let Some(reasoning) = &message.reasoning {
output.push_str("<details>\n<summary>Thinking</summary>\n\n");
output.push_str(reasoning);
output.push_str("\n\n</details>\n\n");
}
// Content
output.push_str(&message.content);
output.push_str("\n\n");
// Tool calls
for tool_call in &message.tool_calls {
output.push_str(&format!("**Tool:** `{}`\n", tool_call.name));
output.push_str("```json\n");
output.push_str(&serde_json::to_string_pretty(&tool_call.input).unwrap_or_default());
output.push_str("\n```\n");
if let Some(result) = &tool_call.output {
let status = if tool_call.success {
"Success"
} else {
"Error"
};
output.push_str(&format!("**Result ({}):**\n", status));
// Use appropriate fence style based on content
let (fence_open, fence_close) = escape_nested_code_blocks(result);
output.push_str(&fence_open);
output.push('\n');
// Truncate long outputs
if result.len() > 1000 {
output.push_str(&result[..1000]);
output.push_str("\n... (truncated)");
} else {
output.push_str(result);
}
output.push('\n');
output.push_str(fence_close);
output.push('\n');
}
output.push('\n');
}
// Token usage
if let Some(tokens) = &message.tokens {
output.push_str(&format!(
"*Tokens: {} in, {} out*\n\n",
tokens.input_tokens, tokens.output_tokens
));
}
output
}
/// Exports a session to JSON format.
fn export_json(session: &CortexSession) -> Result<String> {
#[derive(serde::Serialize)]
struct ExportedSession<'a> {
meta: &'a super::types::SessionMeta,
messages: &'a [StoredMessage],
}
let exported = ExportedSession {
meta: &session.meta,
messages: session.messages(),
};
Ok(serde_json::to_string_pretty(&exported)?)
}
/// Exports a session to plain text format.
fn export_text(session: &CortexSession) -> Result<String> {
let mut output = String::new();
// Header
output.push_str(&format!("{}\n", session.title()));
output.push_str(&format!(
"Model: {} / {}\n",
session.meta.provider, session.meta.model
));
output.push_str(&format!(
"Created: {}\n",
session
.meta
.created_at
.with_timezone(&Local)
.format("%Y-%m-%d %H:%M")
));
output.push_str(&format!(
"Messages: {} | Tokens: {}\n",
session.message_count(),
session.format_tokens()
));
output.push_str(&"=".repeat(60));
output.push_str("\n\n");
// Messages
for message in session.messages() {
output.push_str(&format_message_text(message));
output.push('\n');
}
Ok(output)
}
/// Formats a single message as plain text.
fn format_message_text(message: &StoredMessage) -> String {
let mut output = String::new();
// Role
let role = match message.role.as_str() {
"user" => "> User",
"assistant" => "Assistant",
"system" => "[System]",
_ => &message.role,
};
output.push_str(&format!("{}\n", role));
output.push_str(&"-".repeat(40));
output.push('\n');
// Content
output.push_str(&message.content);
output.push_str("\n\n");
// Tool calls (simplified)
for tool_call in &message.tool_calls {
let status = if tool_call.success { "OK" } else { "ERROR" };
output.push_str(&format!("[Tool: {} - {}]\n", tool_call.name, status));
}
output
}
// ============================================================
// FILE EXPORT
// ============================================================
/// Exports a session to a file.
pub fn export_to_file(
session: &CortexSession,
format: ExportFormat,
path: &std::path::Path,
) -> Result<()> {
let content = export_session(session, format)?;
std::fs::write(path, content)?;
Ok(())
}
/// Generates a default filename for export.
pub fn default_export_filename(session: &CortexSession, format: ExportFormat) -> String {
let title = session
.meta
.title
.clone()
.unwrap_or_else(|| session.meta.short_id().to_string());
// Sanitize title for filename
let safe_title: String = title
.chars()
.map(|c| {
if c.is_alphanumeric() || c == '-' || c == '_' {
c
} else {
'_'
}
})
.collect();
let timestamp = session.meta.created_at.format("%Y%m%d");
format!("cortex_{}_{}.{}", safe_title, timestamp, format.extension())
}
// ============================================================
// TESTS
// ============================================================
#[cfg(test)]
mod tests {
use super::*;
use crate::session::storage::SessionStorage;
use cortex_engine::client::TokenUsage;
use tempfile::TempDir;
fn create_test_session_with_messages() -> (CortexSession, TempDir) {
let temp_dir = TempDir::new().unwrap();
let storage = SessionStorage::with_dir(temp_dir.path().to_path_buf());
let mut session =
CortexSession::with_storage("cortex", "anthropic/claude-opus-4", storage).unwrap();
session.add_user_message("What is 2 + 2?");
session.add_assistant_message(
"2 + 2 = 4",
TokenUsage {
input_tokens: 10,
output_tokens: 5,
total_tokens: 15,
},
);
(session, temp_dir)
}
#[test]
fn test_export_markdown() {
let (session, _temp) = create_test_session_with_messages();
let md = export_session(&session, ExportFormat::Markdown).unwrap();
assert!(md.contains("# "));
assert!(md.contains("cortex"));
assert!(md.contains("What is 2 + 2?"));
assert!(md.contains("2 + 2 = 4"));
}
#[test]
fn test_export_json() {
let (session, _temp) = create_test_session_with_messages();
let json = export_session(&session, ExportFormat::Json).unwrap();
// Should be valid JSON
let _: serde_json::Value = serde_json::from_str(&json).unwrap();
assert!(json.contains("\"provider\""));
assert!(json.contains("\"messages\""));
}
#[test]
fn test_export_text() {
let (session, _temp) = create_test_session_with_messages();
let text = export_session(&session, ExportFormat::Text).unwrap();
assert!(text.contains("> User"));
assert!(text.contains("Assistant"));
assert!(text.contains("What is 2 + 2?"));
}
#[test]
fn test_format_extension() {
assert_eq!(ExportFormat::Markdown.extension(), "md");
assert_eq!(ExportFormat::Json.extension(), "json");
assert_eq!(ExportFormat::Text.extension(), "txt");
}
#[test]
fn test_format_from_str() {
assert_eq!(ExportFormat::parse("md"), Some(ExportFormat::Markdown));
assert_eq!(
ExportFormat::parse("markdown"),
Some(ExportFormat::Markdown)
);
assert_eq!(ExportFormat::parse("json"), Some(ExportFormat::Json));
assert_eq!(ExportFormat::parse("txt"), Some(ExportFormat::Text));
assert_eq!(ExportFormat::parse("unknown"), None);
}
}