ai-session 0.5.0

AI-optimized terminal session management library
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
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
//! AI Session CLI - Terminal session management optimized for AI agents

use ai_session::SessionConfig;
use anyhow::Result;
use clap::{Parser, Subcommand};
use serde::{Deserialize, Serialize};
use std::io::{self, Write};
use std::path::PathBuf;

use ai_session::session_persistence::get_session_manager;

#[derive(Parser)]
#[command(name = "ai-session")]
#[command(about = "AI-optimized terminal session management")]
#[command(version)]
struct Cli {
    #[command(subcommand)]
    command: Commands,
}

#[derive(Subcommand)]
enum Commands {
    /// Create a new session
    Create {
        /// Session name
        #[arg(short, long)]
        name: Option<String>,

        /// Working directory
        #[arg(short, long)]
        dir: Option<PathBuf>,

        /// Enable AI context management
        #[arg(long)]
        ai_context: bool,

        /// Token limit for context
        #[arg(long, default_value = "4096")]
        token_limit: usize,
    },

    /// List active sessions
    List {
        /// Show detailed information
        #[arg(short, long)]
        detailed: bool,
    },

    /// Attach to a session
    Attach {
        /// Session ID or name
        session: String,
    },

    /// Execute command in session
    Exec {
        /// Session ID or name
        session: String,

        /// Command to execute
        command: Vec<String>,

        /// Capture output for AI analysis
        #[arg(long)]
        capture: bool,
    },

    /// Kill a session
    Kill {
        /// Session ID or name
        session: String,

        /// Force kill without cleanup
        #[arg(short, long)]
        force: bool,
    },

    /// Show session context and history
    Context {
        /// Session ID or name
        session: String,

        /// Number of recent entries to show
        #[arg(short, long, default_value = "10")]
        lines: usize,
    },

    /// Migrate from tmux
    Migrate {
        /// Tmux session name
        #[arg(short, long)]
        tmux_session: Option<String>,

        /// Migrate all tmux sessions
        #[arg(long)]
        all: bool,
    },

    /// Remote session management via HTTP API
    Remote {
        #[command(subcommand)]
        command: RemoteCommands,
    },

    /// Interactive mode for continuous conversation
    Interactive {
        /// Session name
        name: String,

        /// Server URL (default: http://localhost:3000)
        #[arg(long, default_value = "http://localhost:3000")]
        server: String,

        /// Show raw output
        #[arg(long)]
        raw: bool,
    },

    /// Quick chat with Claude Code (convenience command)
    ClaudeChat {
        /// Server URL (default: http://localhost:4000 for Claude)
        #[arg(long, default_value = "http://localhost:4000")]
        server: String,

        /// Session name (default: claude-code)
        #[arg(long, default_value = "claude-code")]
        session: String,

        /// Show raw output
        #[arg(long)]
        raw: bool,

        /// Auto-create session if not exists
        #[arg(long, default_value = "true")]
        auto_create: bool,
    },

    /// Resume a Claude Code session by session ID
    ClaudeResume {
        /// Claude session ID to resume (UUID format)
        session_id: String,

        /// Working directory for the session
        #[arg(short, long)]
        dir: Option<PathBuf>,

        /// Optional prompt to send after resuming
        #[arg(short, long)]
        prompt: Option<String>,

        /// Maximum conversation turns (when using --prompt)
        #[arg(long, default_value = "3")]
        max_turns: u32,
    },

    /// Start a new Claude Code session with a specific session ID
    ClaudeStart {
        /// Prompt to send to Claude
        prompt: String,

        /// Session ID to use (will be auto-generated if not specified)
        #[arg(long)]
        session_id: Option<String>,

        /// Working directory
        #[arg(short, long)]
        dir: Option<PathBuf>,

        /// Maximum conversation turns
        #[arg(long, default_value = "3")]
        max_turns: u32,
    },
}

#[derive(Subcommand)]
enum RemoteCommands {
    /// Create a new remote session
    Create {
        /// Session name
        name: String,

        /// Enable AI features
        #[arg(long)]
        ai_features: bool,

        /// Server URL (default: http://localhost:3000)
        #[arg(long, default_value = "http://localhost:3000")]
        server: String,
    },

    /// List remote sessions
    List {
        /// Server URL
        #[arg(long, default_value = "http://localhost:3000")]
        server: String,
    },

    /// Execute command in remote session
    Exec {
        /// Session name
        name: String,

        /// Command to execute
        command: Vec<String>,

        /// Server URL
        #[arg(long, default_value = "http://localhost:3000")]
        server: String,

        /// Show raw output
        #[arg(long)]
        raw: bool,
    },

    /// Get remote session output
    Output {
        /// Session name
        name: String,

        /// Server URL
        #[arg(long, default_value = "http://localhost:3000")]
        server: String,

        /// Show raw output
        #[arg(long)]
        raw: bool,
    },

    /// Get remote session status
    Status {
        /// Session name
        name: String,

        /// Server URL
        #[arg(long, default_value = "http://localhost:3000")]
        server: String,
    },

    /// Delete remote session
    Delete {
        /// Session name
        name: String,

        /// Server URL
        #[arg(long, default_value = "http://localhost:3000")]
        server: String,
    },

    /// Check server health
    Health {
        /// Server URL
        #[arg(long, default_value = "http://localhost:3000")]
        server: String,
    },
}

// API Response types
#[derive(Deserialize)]
struct SessionResponse {
    id: String,
    name: String,
    status: String,
    #[allow(dead_code)]
    created_at: String,
}

#[derive(Deserialize)]
struct SessionListResponse {
    sessions: Vec<SessionSummary>,
    total: usize,
}

#[derive(Deserialize)]
struct SessionSummary {
    id: String,
    name: String,
    status: String,
    created_at: String,
    last_activity: String,
}

#[derive(Deserialize)]
struct CommandResponse {
    success: bool,
    output: String,
    error: Option<String>,
    execution_time_ms: u64,
}

#[derive(Deserialize)]
struct OutputResponse {
    session_name: String,
    output: String,
    raw_output: String,
    timestamp: String,
    size_bytes: usize,
}

#[derive(Serialize)]
struct CreateSessionRequest {
    name: String,
    enable_ai_features: bool,
}

#[derive(Serialize)]
struct ExecuteCommandRequest {
    command: String,
}

#[tokio::main]
async fn main() -> Result<()> {
    // Initialize logging
    tracing_subscriber::fmt()
        .with_env_filter("ai_session=debug")
        .init();

    let cli = Cli::parse();

    match cli.command {
        Commands::Create {
            name,
            dir,
            ai_context,
            token_limit,
        } => create_session(name, dir, ai_context, token_limit).await?,
        Commands::List { detailed } => list_sessions(detailed).await?,
        Commands::Attach { session } => attach_session(session).await?,
        Commands::Exec {
            session,
            command,
            capture,
        } => exec_command(session, command, capture).await?,
        Commands::Kill { session, force } => kill_session(session, force).await?,
        Commands::Context { session, lines } => show_context(session, lines).await?,
        Commands::Migrate { tmux_session, all } => migrate_tmux(tmux_session, all).await?,
        Commands::Remote { command } => handle_remote_command(command).await?,
        Commands::Interactive { name, server, raw } => interactive_mode(name, server, raw).await?,
        Commands::ClaudeChat {
            server,
            session,
            raw,
            auto_create,
        } => claude_chat_mode(server, session, raw, auto_create).await?,

        Commands::ClaudeResume {
            session_id,
            dir,
            prompt,
            max_turns,
        } => claude_resume_session(session_id, dir, prompt, max_turns).await?,

        Commands::ClaudeStart {
            prompt,
            session_id,
            dir,
            max_turns,
        } => claude_start_session(prompt, session_id, dir, max_turns).await?,
    }

    Ok(())
}

async fn create_session(
    name: Option<String>,
    dir: Option<PathBuf>,
    ai_context: bool,
    token_limit: usize,
) -> Result<()> {
    let manager = get_session_manager().await?;

    let mut config = SessionConfig::default();
    if let Some(n) = name.clone() {
        config.name = Some(n);
    }
    if let Some(d) = dir {
        config.working_directory = d;
    }
    if ai_context {
        config.enable_ai_features = true;
        config.context_config.max_tokens = token_limit;
    }

    let session = manager.create_session_with_config(config).await?;

    // Session is automatically started and persisted by the PersistentSessionManager

    println!("Created session: {}", session.id);
    if let Some(n) = name {
        println!("Name: {}", n);
    }
    println!(
        "Working directory: {}",
        session.config.working_directory.display()
    );
    if ai_context {
        println!("AI context enabled with {} token limit", token_limit);
    }

    Ok(())
}

async fn list_sessions(detailed: bool) -> Result<()> {
    let manager = get_session_manager().await?;
    let session_ids = manager.list_all_sessions().await?;

    if session_ids.is_empty() {
        println!("No active sessions");
        return Ok(());
    }

    println!("Active sessions ({} total):", session_ids.len());
    for session_id in session_ids {
        if let Some(session) = manager.get_session(&session_id).await {
            if detailed {
                println!("\n  ID: {}", session.id);
                if let Some(name) = &session.config.name {
                    println!("  Name: {}", name);
                }
                println!(
                    "  Created: {}",
                    session.created_at.format("%Y-%m-%d %H:%M:%S")
                );
                println!(
                    "  Directory: {}",
                    session.config.working_directory.display()
                );
                println!("  Status: {:?}", session.status().await);
                if session.config.enable_ai_features {
                    println!("  AI Features: Enabled");
                    println!(
                        "  Context Size: {} tokens",
                        session.config.context_config.max_tokens
                    );
                }
            } else {
                let id_str = session.id.to_string();
                let short_id = id_str.split('-').next().unwrap_or("unknown");
                let name_str = session.config.name.as_deref().unwrap_or(short_id);
                println!(
                    "  {} - {} ({}) [{}]",
                    short_id,
                    name_str,
                    session.created_at.format("%H:%M:%S"),
                    match session.status().await {
                        ai_session::core::SessionStatus::Running => "running",
                        ai_session::core::SessionStatus::Paused => "paused",
                        ai_session::core::SessionStatus::Terminated => "terminated",
                        _ => "unknown",
                    }
                );
            }
        }
    }

    Ok(())
}

async fn attach_session(session: String) -> Result<()> {
    let manager = get_session_manager().await?;
    let session_id = ai_session::core::SessionId::parse_str(&session)?;

    if let Some(session) = manager.get_session(&session_id).await {
        println!("Attaching to session: {}", session_id);
        println!("Session status: {:?}", session.status().await);
        println!(
            "Working directory: {}",
            session.config.working_directory.display()
        );

        // For now, just demonstrate that we can interact with the session
        println!(
            "\n(Interactive mode would start here. For now, use 'ai-session exec' to run commands)"
        );
    } else {
        eprintln!("Session not found: {}", session_id);
        std::process::exit(1);
    }

    Ok(())
}

async fn exec_command(session: String, command: Vec<String>, capture: bool) -> Result<()> {
    let manager = get_session_manager().await?;
    let session_id = ai_session::core::SessionId::parse_str(&session)?;

    let cmd = command.join(" ");
    println!("Executing in session {}: {}", session, cmd);

    let output_str = if let Some(session) = manager.get_session(&session_id).await {
        session.send_input(&cmd).await?;
        let output = session.read_output().await?;
        let result = String::from_utf8_lossy(&output);
        println!("{}", result);
        result.to_string()
    } else {
        eprintln!("Session not found: {}", session_id);
        std::process::exit(1);
    };

    if capture {
        println!("\nCaptured output:");
        println!("{}", output_str);
        println!("\n(Output saved for AI analysis)");
    }

    Ok(())
}

async fn kill_session(session: String, force: bool) -> Result<()> {
    let manager = get_session_manager().await?;
    let session_id = ai_session::core::SessionId::parse_str(&session)?;

    if force {
        println!("Force killing session: {}", session);
    } else {
        println!("Gracefully terminating session: {}", session);
    }

    manager.remove_session(&session_id).await?;
    println!("Session terminated");

    Ok(())
}

async fn show_context(session: String, lines: usize) -> Result<()> {
    println!("Session context for: {}", session);
    println!("Last {} context entries:", lines);
    println!("\n  [Context display not implemented in demo]");
    println!("  Would show:");
    println!("  - Command history");
    println!("  - AI conversation context");
    println!("  - Token usage statistics");
    println!("  - Performance metrics");

    Ok(())
}

async fn migrate_tmux(tmux_session: Option<String>, all: bool) -> Result<()> {
    use ai_session::integration::TmuxCompatLayer;

    let tmux = TmuxCompatLayer::new();

    if all {
        println!("Migrating all tmux sessions...");
        let sessions = tmux.list_tmux_sessions().await?;
        println!("Found {} tmux sessions", sessions.len());

        for session in sessions {
            println!("  - {} (created: {})", session.name, session.created);
        }

        println!("\n(Migration would convert these to AI sessions)");
    } else if let Some(name) = tmux_session {
        println!("Migrating tmux session: {}", name);
        println!("(Would capture state and create equivalent AI session)");
    } else {
        println!("Please specify --tmux-session or --all");
    }

    Ok(())
}

// Remote command handlers
async fn handle_remote_command(command: RemoteCommands) -> Result<()> {
    match command {
        RemoteCommands::Create {
            name,
            ai_features,
            server,
        } => remote_create_session(name, ai_features, server).await?,
        RemoteCommands::List { server } => remote_list_sessions(server).await?,
        RemoteCommands::Exec {
            name,
            command,
            server,
            raw,
        } => remote_exec_command(name, command, server, raw).await?,
        RemoteCommands::Output { name, server, raw } => {
            remote_get_output(name, server, raw).await?
        }
        RemoteCommands::Status { name, server } => remote_get_status(name, server).await?,
        RemoteCommands::Delete { name, server } => remote_delete_session(name, server).await?,
        RemoteCommands::Health { server } => remote_health_check(server).await?,
    }
    Ok(())
}

async fn remote_create_session(name: String, ai_features: bool, server: String) -> Result<()> {
    let client = reqwest::Client::new();
    let request = CreateSessionRequest {
        name: name.clone(),
        enable_ai_features: ai_features,
    };

    let response = client
        .post(format!("{}/sessions", server))
        .json(&request)
        .send()
        .await?;

    if response.status().is_success() {
        let session: SessionResponse = response.json().await?;
        println!("✅ Created remote session: {}", session.name);
        println!("   ID: {}", session.id);
        println!("   Status: {}", session.status);
        println!(
            "   AI Features: {}",
            if ai_features { "Enabled" } else { "Disabled" }
        );
    } else {
        let error_text = response.text().await?;
        eprintln!("❌ Failed to create session: {}", error_text);
        std::process::exit(1);
    }

    Ok(())
}

async fn remote_list_sessions(server: String) -> Result<()> {
    let client = reqwest::Client::new();
    let response = client.get(format!("{}/sessions", server)).send().await?;

    if response.status().is_success() {
        let list: SessionListResponse = response.json().await?;
        if list.sessions.is_empty() {
            println!("No remote sessions found");
        } else {
            println!("Remote sessions ({} total):", list.total);
            for session in list.sessions {
                println!(
                    "  {} - {} (Status: {})",
                    session.name,
                    session.id.split('-').next().unwrap_or(""),
                    session.status
                );
                println!("    Created: {}", session.created_at);
                println!("    Last Activity: {}", session.last_activity);
            }
        }
    } else {
        eprintln!("❌ Failed to list sessions: {}", response.status());
        std::process::exit(1);
    }

    Ok(())
}

async fn remote_exec_command(
    name: String,
    command: Vec<String>,
    server: String,
    raw: bool,
) -> Result<()> {
    let client = reqwest::Client::new();
    let cmd = command.join(" ");
    let request = ExecuteCommandRequest {
        command: cmd.clone(),
    };

    println!("💬 Executing: {}", cmd);

    let response = client
        .post(format!("{}/sessions/{}/execute", server, name))
        .json(&request)
        .send()
        .await?;

    if response.status().is_success() {
        let result: CommandResponse = response.json().await?;
        if result.success {
            println!(
                "✅ Command executed successfully ({}ms)",
                result.execution_time_ms
            );
            if raw {
                println!("{}", result.output);
            } else {
                // Clean output for display
                let clean_output = clean_terminal_output(&result.output);
                if !clean_output.trim().is_empty() {
                    println!("\n📤 Output:");
                    println!("{}", clean_output);
                }
            }
        } else {
            eprintln!("❌ Command failed");
            if let Some(error) = result.error {
                eprintln!("   Error: {}", error);
            }
        }
    } else {
        let error_text = response.text().await?;
        eprintln!("❌ Failed to execute command: {}", error_text);
        std::process::exit(1);
    }

    Ok(())
}

async fn remote_get_output(name: String, server: String, raw: bool) -> Result<()> {
    let client = reqwest::Client::new();
    let response = client
        .get(format!("{}/sessions/{}/output", server, name))
        .send()
        .await?;

    if response.status().is_success() {
        let output: OutputResponse = response.json().await?;
        println!(
            "📤 Session output for '{}' ({} bytes):",
            output.session_name, output.size_bytes
        );
        println!("   Timestamp: {}", output.timestamp);
        println!();

        if raw {
            println!("{}", output.raw_output);
        } else {
            println!("{}", output.output);
        }
    } else {
        eprintln!("❌ Failed to get output: {}", response.status());
        std::process::exit(1);
    }

    Ok(())
}

async fn remote_get_status(name: String, server: String) -> Result<()> {
    let client = reqwest::Client::new();
    let response = client
        .get(format!("{}/sessions/{}/status", server, name))
        .send()
        .await?;

    if response.status().is_success() {
        let status_text = response.text().await?;
        let status: serde_json::Value = serde_json::from_str(&status_text)?;
        println!("📊 Session Status for '{}':", name);
        println!("{}", serde_json::to_string_pretty(&status)?);
    } else {
        eprintln!("❌ Failed to get status: {}", response.status());
        std::process::exit(1);
    }

    Ok(())
}

async fn remote_delete_session(name: String, server: String) -> Result<()> {
    let client = reqwest::Client::new();

    println!("🗑️  Deleting session '{}'...", name);

    let response = client
        .delete(format!("{}/sessions/{}", server, name))
        .send()
        .await?;

    if response.status().is_success() {
        println!("✅ Session '{}' deleted successfully", name);
    } else {
        let error_text = response.text().await?;
        eprintln!("❌ Failed to delete session: {}", error_text);
        std::process::exit(1);
    }

    Ok(())
}

async fn remote_health_check(server: String) -> Result<()> {
    let client = reqwest::Client::new();
    let response = client.get(format!("{}/health", server)).send().await?;

    if response.status().is_success() {
        let health: serde_json::Value = response.json().await?;
        println!("🏥 Server Health Check:");
        println!("{}", serde_json::to_string_pretty(&health)?);
    } else {
        eprintln!("❌ Server is not healthy: {}", response.status());
        std::process::exit(1);
    }

    Ok(())
}

fn clean_terminal_output(output: &str) -> String {
    // Simple cleaning - remove ANSI escape sequences
    let ansi_escape = regex::Regex::new(r"\x1b\[[0-9;]*[mK]").unwrap();
    let control_chars = regex::Regex::new(r"[\x00-\x1f\x7f]").unwrap();

    let cleaned = ansi_escape.replace_all(output, "");
    let cleaned = control_chars.replace_all(&cleaned, " ");

    // Remove excessive whitespace and empty lines
    cleaned
        .lines()
        .filter(|line| !line.trim().is_empty())
        .map(|line| line.trim())
        .take(20) // Show first 20 lines
        .collect::<Vec<_>>()
        .join("\n")
}

// Interactive mode for continuous conversation
async fn interactive_mode(name: String, server: String, raw: bool) -> Result<()> {
    println!("🤖 AI-Session Interactive Mode");
    println!("   Session: {}", name);
    println!("   Server: {}", server);
    println!("   Commands:");
    println!("     /exit or /quit - Exit interactive mode");
    println!("     /status - Show session status");
    println!("     /output - Get latest output");
    println!("     /clear - Clear screen");
    println!("     /help - Show this help");
    println!("   Type your message and press Enter to send to the session");
    println!();

    let client = reqwest::Client::new();
    let stdin = io::stdin();
    let mut stdout = io::stdout();

    loop {
        // Show prompt
        print!("💬 > ");
        stdout.flush()?;

        // Read input
        let mut input = String::new();
        stdin.read_line(&mut input)?;
        let input = input.trim();

        // Handle special commands
        if input.is_empty() {
            continue;
        }

        match input {
            "/exit" | "/quit" => {
                println!("👋 Exiting interactive mode...");
                break;
            }
            "/status" => {
                match get_session_status(&client, &name, &server).await {
                    Ok(status) => println!("{}", status),
                    Err(e) => eprintln!("❌ Error getting status: {}", e),
                }
                continue;
            }
            "/output" => {
                match get_session_output(&client, &name, &server, raw).await {
                    Ok(output) => println!("{}", output),
                    Err(e) => eprintln!("❌ Error getting output: {}", e),
                }
                continue;
            }
            "/clear" => {
                print!("\x1B[2J\x1B[1;1H");
                continue;
            }
            "/help" => {
                println!("📖 Interactive Mode Commands:");
                println!("   /exit or /quit - Exit interactive mode");
                println!("   /status - Show session status");
                println!("   /output - Get latest output");
                println!("   /clear - Clear screen");
                println!("   /help - Show this help");
                continue;
            }
            _ if input.starts_with('/') => {
                println!("❓ Unknown command: {}. Type /help for commands.", input);
                continue;
            }
            _ => {
                // Send regular message to session
                match send_command_to_session(&client, &name, &server, input, raw).await {
                    Ok(output) => {
                        if !output.trim().is_empty() {
                            println!("\n📤 Response:");
                            println!("{}", output);
                        }
                    }
                    Err(e) => eprintln!("❌ Error: {}", e),
                }
            }
        }

        println!(); // Empty line for readability
    }

    Ok(())
}

// Helper function to send command and get response
async fn send_command_to_session(
    client: &reqwest::Client,
    name: &str,
    server: &str,
    command: &str,
    raw: bool,
) -> Result<String> {
    let request = ExecuteCommandRequest {
        command: command.to_string(),
    };

    let response = client
        .post(format!("{}/sessions/{}/execute", server, name))
        .json(&request)
        .send()
        .await?;

    if response.status().is_success() {
        let result: CommandResponse = response.json().await?;
        if result.success {
            if raw {
                Ok(result.output)
            } else {
                Ok(clean_terminal_output(&result.output))
            }
        } else {
            Err(anyhow::anyhow!("Command failed: {:?}", result.error))
        }
    } else {
        let error_text = response.text().await?;
        Err(anyhow::anyhow!("Request failed: {}", error_text))
    }
}

// Helper function to get session status
async fn get_session_status(client: &reqwest::Client, name: &str, server: &str) -> Result<String> {
    let response = client
        .get(format!("{}/sessions/{}/status", server, name))
        .send()
        .await?;

    if response.status().is_success() {
        let status_text = response.text().await?;
        let status: serde_json::Value = serde_json::from_str(&status_text)?;
        Ok(serde_json::to_string_pretty(&status)?)
    } else {
        Err(anyhow::anyhow!("Failed to get status"))
    }
}

// Helper function to get session output
async fn get_session_output(
    client: &reqwest::Client,
    name: &str,
    server: &str,
    raw: bool,
) -> Result<String> {
    let response = client
        .get(format!("{}/sessions/{}/output", server, name))
        .send()
        .await?;

    if response.status().is_success() {
        let output: OutputResponse = response.json().await?;
        if raw {
            Ok(output.raw_output)
        } else {
            Ok(output.output)
        }
    } else {
        Err(anyhow::anyhow!("Failed to get output"))
    }
}

// Claude chat mode - convenience wrapper
async fn claude_chat_mode(
    server: String,
    session: String,
    raw: bool,
    auto_create: bool,
) -> Result<()> {
    let client = reqwest::Client::new();

    println!("🤖 Claude Code Chat");
    println!("   Checking session...");

    // Check if session exists
    let session_exists = check_session_exists(&client, &session, &server).await?;

    if !session_exists && auto_create {
        println!("   Creating session '{}'...", session);

        // Create session
        let request = CreateSessionRequest {
            name: session.clone(),
            enable_ai_features: true,
        };

        let response = client
            .post(format!("{}/sessions", server))
            .json(&request)
            .send()
            .await?;

        if !response.status().is_success() {
            let error_text = response.text().await?;
            eprintln!("❌ Failed to create session: {}", error_text);
            std::process::exit(1);
        }

        println!("✅ Session created");

        // Start Claude in the session
        println!("   Starting Claude Code...");
        let start_request = ExecuteCommandRequest {
            command: "claude".to_string(),
        };

        let response = client
            .post(format!("{}/sessions/{}/execute", server, session))
            .json(&start_request)
            .send()
            .await?;

        if response.status().is_success() {
            println!("✅ Claude Code started");
            // Wait for Claude to initialize
            tokio::time::sleep(tokio::time::Duration::from_secs(2)).await;
        } else {
            eprintln!("⚠️  Could not start Claude Code automatically");
        }
    } else if !session_exists {
        eprintln!(
            "❌ Session '{}' does not exist. Use --auto-create to create it.",
            session
        );
        std::process::exit(1);
    }

    println!("\n🎯 Ready for chat!");
    println!("   💡 Tip: You can directly ask questions about code, programming, etc.");
    println!("   💡 Type /help for commands, /exit to quit\n");

    // Launch interactive mode
    interactive_mode(session, server, raw).await
}

// Helper to check if session exists
async fn check_session_exists(client: &reqwest::Client, name: &str, server: &str) -> Result<bool> {
    let response = client.get(format!("{}/sessions", server)).send().await?;

    if response.status().is_success() {
        let list: SessionListResponse = response.json().await?;
        Ok(list.sessions.iter().any(|s| s.name == name))
    } else {
        Ok(false)
    }
}

/// Resume a Claude Code session by its session ID
///
/// This uses Claude's native `--resume` flag to continue a previous conversation.
async fn claude_resume_session(
    session_id: String,
    dir: Option<PathBuf>,
    prompt: Option<String>,
    max_turns: u32,
) -> Result<()> {
    use ai_session::PtyHandle;

    let working_dir = dir.unwrap_or_else(|| std::env::current_dir().unwrap_or_default());

    println!("🔄 Resuming Claude session: {}", session_id);
    println!("   Working directory: {}", working_dir.display());

    let pty = PtyHandle::new(24, 80)?;

    if let Some(p) = prompt {
        println!("   Prompt: {}", p);
        println!("   Max turns: {}", max_turns);
        pty.resume_claude_with_prompt(&session_id, &p, &working_dir, Some(max_turns))
            .await?;
    } else {
        // Interactive resume
        pty.resume_claude(&session_id, &working_dir).await?;
    }

    println!("✅ Claude session resumed successfully");

    // Read and display output
    let output = pty.read_with_timeout(30000).await?;
    if !output.is_empty() {
        println!("\n📤 Output:");
        println!("{}", String::from_utf8_lossy(&output));
    }

    Ok(())
}

/// Start a new Claude Code session with a specific session ID
///
/// This allows you to specify a session ID upfront so you can resume it later.
async fn claude_start_session(
    prompt: String,
    session_id: Option<String>,
    dir: Option<PathBuf>,
    max_turns: u32,
) -> Result<()> {
    use ai_session::PtyHandle;

    let working_dir = dir.unwrap_or_else(|| std::env::current_dir().unwrap_or_default());
    let session_id = session_id.unwrap_or_else(|| uuid::Uuid::new_v4().to_string());

    println!("🚀 Starting Claude session with ID: {}", session_id);
    println!("   Working directory: {}", working_dir.display());
    println!("   Prompt: {}", prompt);
    println!("   Max turns: {}", max_turns);
    println!();
    println!("💡 To resume this session later, run:");
    println!("   ai-session claude-resume {}", session_id);
    println!();

    let pty = PtyHandle::new(24, 80)?;
    pty.spawn_claude_with_session(&prompt, &working_dir, &session_id, Some(max_turns))
        .await?;

    println!("✅ Claude session started");

    // Read and display output
    let output = pty.read_with_timeout(60000).await?;
    if !output.is_empty() {
        println!("\n📤 Output:");
        println!("{}", String::from_utf8_lossy(&output));
    }

    Ok(())
}