-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathimport_cmd.rs
More file actions
484 lines (418 loc) · 16.9 KB
/
import_cmd.rs
File metadata and controls
484 lines (418 loc) · 16.9 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
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
//! Session import command for Cortex CLI.
//!
//! Imports a session from a portable JSON format (exported or shared).
use anyhow::{Context, Result, bail};
use clap::Parser;
use std::collections::HashSet;
use std::path::PathBuf;
use cortex_engine::rollout::recorder::{RolloutRecorder, SessionMeta};
use cortex_engine::rollout::{SESSIONS_SUBDIR, get_rollout_path};
use cortex_protocol::{
AgentMessageEvent, ConversationId, Event, EventMsg, ExecCommandEndEvent, ExecCommandSource,
ParsedCommand, UserMessageEvent,
};
use crate::export_cmd::{ExportMessage, SessionExport};
/// Maximum depth for processing messages to prevent stack overflow from deeply nested structures.
const MAX_PROCESSING_DEPTH: usize = 10000;
/// Import a session from JSON format.
#[derive(Debug, Parser)]
pub struct ImportCommand {
/// Path to the JSON file to import, or URL to fetch
#[arg(value_name = "FILE_OR_URL")]
pub source: String,
/// Force import even if session already exists
#[arg(short, long, default_value_t = false)]
pub force: bool,
/// Resume the imported session after import
#[arg(long, default_value_t = false)]
pub resume: bool,
}
impl ImportCommand {
/// Run the import command.
pub async fn run(self) -> Result<()> {
// Validate source argument is not empty
if self.source.trim().is_empty() {
bail!("Error: Source path cannot be empty\n\nUsage: cortex import <FILE_OR_URL>");
}
let cortex_home = dirs::home_dir()
.map(|h| h.join(".cortex"))
.ok_or_else(|| anyhow::anyhow!("Could not determine home directory"))?;
// Read the export data
let (json_content, is_from_url) =
if self.source.starts_with("http://") || self.source.starts_with("https://") {
// Fetch from URL
(fetch_url(&self.source).await?, true)
} else {
// Read from local file
let path = PathBuf::from(&self.source);
let content = std::fs::read_to_string(&path)
.with_context(|| format!("Failed to read file: {}", path.display()))?;
(content, false)
};
// Parse the export with helpful error messages
let export: SessionExport = serde_json::from_str(&json_content).map_err(|e| {
// Create a helpful error message with content preview
let preview_len = json_content.len().min(200);
let content_preview = &json_content[..preview_len];
let truncated = if json_content.len() > 200 {
"..."
} else {
""
};
let source_type = if is_from_url { "URL" } else { "file" };
// Detect common non-JSON content types
let hint = if content_preview.trim_start().starts_with("<!DOCTYPE")
|| content_preview.trim_start().starts_with("<html")
{
"\nHint: The URL returned HTML content, not JSON. Make sure the URL points directly to a JSON export file."
} else if content_preview.trim_start().starts_with("<?xml") {
"\nHint: The URL returned XML content, not JSON. Make sure the URL points directly to a JSON export file."
} else if content_preview.is_empty() {
"\nHint: The response was empty. Make sure the URL is accessible and returns JSON content."
} else {
"\nHint: Ensure the file contains valid JSON. Check for syntax errors like missing commas, unclosed brackets, or invalid characters."
};
anyhow::anyhow!(
"Failed to parse JSON from {}: {}\n\nReceived content (first {} bytes):\n{}{}\n{}",
source_type,
e,
preview_len,
content_preview,
truncated,
hint
)
})?;
// Validate version
if export.version != 1 {
bail!(
"Unsupported export version: {}. This CLI supports version 1.",
export.version
);
}
// Generate a new session ID (we always create a new session on import)
let new_conversation_id = ConversationId::new();
// Check if a session with the original ID already exists
let original_id: Result<ConversationId, _> = export.session.id.parse();
if let Ok(orig_id) = original_id {
let existing_path = get_rollout_path(&cortex_home, &orig_id);
if existing_path.exists() && !self.force {
eprintln!(
"Warning: Original session {} already exists locally.",
export.session.id
);
eprintln!("Creating new session with ID: {new_conversation_id}");
}
}
// Create sessions directory if needed
let sessions_dir = cortex_home.join(SESSIONS_SUBDIR);
std::fs::create_dir_all(&sessions_dir)?;
// Initialize rollout recorder for the new session
let mut recorder = RolloutRecorder::new(&cortex_home, new_conversation_id)?;
recorder.init()?;
// Record session metadata
let cwd = export
.session
.cwd
.map(PathBuf::from)
.unwrap_or_else(|| std::env::current_dir().unwrap_or_default());
let meta = SessionMeta {
id: new_conversation_id,
parent_id: None,
fork_point: None,
timestamp: export.session.created_at.clone(),
cwd: cwd.clone(),
model: export
.session
.model
.clone()
.unwrap_or_else(|| "unknown".to_string()),
cli_version: env!("CARGO_PKG_VERSION").to_string(),
instructions: None,
};
recorder.record_meta(&meta)?;
// Validate message count to prevent infinite loop on malicious input
if export.messages.len() > MAX_PROCESSING_DEPTH {
bail!(
"Error: Session contains too many messages ({} > {}). \
This may indicate a malformed or malicious session file.",
export.messages.len(),
MAX_PROCESSING_DEPTH
);
}
// Check for circular message references if messages have IDs and reply_to fields
// This prevents infinite loops when processing message chains
validate_no_circular_references(&export.messages)?;
// Record messages as events
let mut turn_id = 0u64;
for message in &export.messages {
let event = message_to_event(message, &mut turn_id, &cwd)?;
recorder.record_event(&event)?;
}
recorder.flush()?;
println!("Imported session as: {new_conversation_id}");
println!(" Original ID: {}", export.session.id);
if let Some(title) = &export.session.title {
println!(" Title: {title}");
}
println!(" Messages: {}", export.messages.len());
println!("\nTo resume: cortex resume {new_conversation_id}");
if self.resume {
// Launch resume
println!("\nResuming session...");
let config = cortex_engine::Config::default();
#[cfg(feature = "cortex-tui")]
{
cortex_tui::resume(config, new_conversation_id).await?;
}
#[cfg(not(feature = "cortex-tui"))]
{
compile_error!("The 'cortex-tui' feature must be enabled");
}
}
Ok(())
}
}
/// Fetch content from a URL.
async fn fetch_url(url: &str) -> Result<String> {
// Use reqwest if available, otherwise fall back to curl
#[cfg(feature = "reqwest")]
{
let response = reqwest::get(url).await?;
if !response.status().is_success() {
bail!("Failed to fetch URL: HTTP {}", response.status());
}
// Check content-type header to warn about non-JSON content
if let Some(content_type) = response.headers().get(reqwest::header::CONTENT_TYPE) {
let content_type_str = content_type.to_str().unwrap_or("");
if !content_type_str.contains("application/json")
&& !content_type_str.contains("text/plain")
&& !content_type_str.is_empty()
{
eprintln!(
"Warning: URL returned Content-Type '{}', expected 'application/json'",
content_type_str
);
eprintln!("The import may fail if the content is not valid JSON.");
}
}
Ok(response.text().await?)
}
#[cfg(not(feature = "reqwest"))]
{
// Simple curl-based fallback
use std::process::Command;
let output = Command::new("curl")
.args(["-sSL", url])
.output()
.with_context(|| "Failed to run curl. Install curl or use a local file.")?;
if !output.status.success() {
let stderr = String::from_utf8_lossy(&output.stderr);
bail!("Failed to fetch URL: {stderr}");
}
Ok(String::from_utf8_lossy(&output.stdout).to_string())
}
}
/// Validate that there are no circular message references.
///
/// This function checks for potential circular references in message chains.
/// While the current ExportMessage struct doesn't have a reply_to field,
/// this validation protects against malformed input that could cause
/// infinite loops during processing.
fn validate_no_circular_references(messages: &[ExportMessage]) -> Result<()> {
// Build a map of message IDs to their indices for reference checking
// If tool_call_id references form a cycle, detect it
let mut seen_tool_call_ids: HashSet<String> = HashSet::new();
let mut referenced_ids: HashSet<String> = HashSet::new();
for (idx, message) in messages.iter().enumerate() {
// Track tool call IDs to detect duplicates (potential for circular references)
if let Some(ref tool_call_id) = message.tool_call_id {
if !seen_tool_call_ids.insert(tool_call_id.clone()) {
bail!(
"Error: Duplicate tool_call_id '{}' detected at message index {}. \
This may indicate circular message references.",
tool_call_id,
idx
);
}
referenced_ids.insert(tool_call_id.clone());
}
// Track tool calls made to ensure they reference unique IDs
if let Some(ref tool_calls) = message.tool_calls {
for tc in tool_calls {
if !seen_tool_call_ids.insert(tc.id.clone()) {
bail!(
"Error: Duplicate tool call id '{}' detected at message index {}. \
This may indicate circular message references.",
tc.id,
idx
);
}
}
}
}
Ok(())
}
/// Convert an export message to a protocol event.
fn message_to_event(message: &ExportMessage, turn_id: &mut u64, cwd: &PathBuf) -> Result<Event> {
let event_msg = match message.role.as_str() {
"user" => {
*turn_id += 1;
EventMsg::UserMessage(UserMessageEvent {
id: None,
parent_id: None,
message: message.content.clone(),
images: None,
})
}
"assistant" => EventMsg::AgentMessage(AgentMessageEvent {
id: None,
parent_id: None,
message: message.content.clone(),
}),
"tool" => {
// Reconstruct tool result as ExecCommandEnd
EventMsg::ExecCommandEnd(Box::new(ExecCommandEndEvent {
call_id: message.tool_call_id.clone().unwrap_or_default(),
turn_id: turn_id.to_string(),
command: vec!["imported_tool".to_string()],
cwd: cwd.clone(),
parsed_cmd: vec![ParsedCommand {
program: "imported_tool".to_string(),
args: vec![],
}],
source: ExecCommandSource::Agent,
interaction_input: None,
stdout: message.content.clone(),
stderr: String::new(),
aggregated_output: message.content.clone(),
exit_code: 0,
duration_ms: 0,
formatted_output: message.content.clone(),
metadata: None,
}))
}
"system" => {
// System messages are typically not replayed, skip or handle specially
EventMsg::AgentMessage(AgentMessageEvent {
id: None,
parent_id: None,
message: format!("[System] {}", message.content),
})
}
other => {
// Unknown role, treat as assistant message
EventMsg::AgentMessage(AgentMessageEvent {
id: None,
parent_id: None,
message: format!("[{other}] {}", message.content),
})
}
};
Ok(Event {
id: turn_id.to_string(),
msg: event_msg,
})
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_parse_export_json() {
let json = r#"{
"version": 1,
"session": {
"id": "test-123",
"title": "Test Session",
"created_at": "2024-01-01T00:00:00Z"
},
"messages": [
{"role": "user", "content": "Hello"},
{"role": "assistant", "content": "Hi there!"}
]
}"#;
let export: SessionExport = serde_json::from_str(json).unwrap();
assert_eq!(export.version, 1);
assert_eq!(export.session.id, "test-123");
assert_eq!(export.messages.len(), 2);
}
#[test]
fn test_message_to_event() {
let mut turn_id = 0u64;
let cwd = PathBuf::from("/tmp");
let user_msg = ExportMessage {
role: "user".to_string(),
content: "Hello".to_string(),
tool_calls: None,
tool_call_id: None,
timestamp: None,
};
let event = message_to_event(&user_msg, &mut turn_id, &cwd).unwrap();
assert_eq!(turn_id, 1);
assert!(matches!(event.msg, EventMsg::UserMessage(_)));
let assistant_msg = ExportMessage {
role: "assistant".to_string(),
content: "Hi".to_string(),
tool_calls: None,
tool_call_id: None,
timestamp: None,
};
let event = message_to_event(&assistant_msg, &mut turn_id, &cwd).unwrap();
assert!(matches!(event.msg, EventMsg::AgentMessage(_)));
}
#[tokio::test]
async fn test_import_empty_source_validation() {
let cmd = ImportCommand {
source: String::new(),
force: false,
resume: false,
};
let result = cmd.run().await;
assert!(result.is_err());
let err_msg = result.unwrap_err().to_string();
assert!(err_msg.contains("Source path cannot be empty"));
}
#[tokio::test]
async fn test_import_whitespace_source_validation() {
let cmd = ImportCommand {
source: " ".to_string(),
force: false,
resume: false,
};
let result = cmd.run().await;
assert!(result.is_err());
let err_msg = result.unwrap_err().to_string();
assert!(err_msg.contains("Source path cannot be empty"));
}
#[test]
fn test_parse_html_provides_helpful_error() {
let html_content = "<!DOCTYPE html><html><head><title>Not JSON</title></head></html>";
let result: Result<SessionExport, _> = serde_json::from_str(html_content);
assert!(result.is_err());
// Verify that our error handling would detect this as HTML
assert!(html_content.trim_start().starts_with("<!DOCTYPE"));
}
#[test]
fn test_parse_xml_provides_helpful_error() {
let xml_content = r#"<?xml version="1.0"?><root><data>Not JSON</data></root>"#;
let result: Result<SessionExport, _> = serde_json::from_str(xml_content);
assert!(result.is_err());
// Verify that our error handling would detect this as XML
assert!(xml_content.trim_start().starts_with("<?xml"));
}
#[test]
fn test_parse_empty_content_error() {
let empty_content = "";
let result: Result<SessionExport, _> = serde_json::from_str(empty_content);
assert!(result.is_err());
// Verify that our error handling would detect this as empty
assert!(empty_content.is_empty());
}
#[test]
fn test_content_preview_truncation() {
// Test that preview logic correctly truncates long content
let long_content = "a".repeat(500);
let preview_len = long_content.len().min(200);
assert_eq!(preview_len, 200);
assert_eq!(&long_content[..preview_len].len(), &200);
}
}