claudy 0.3.3

Modern multi-provider launcher for Claude CLI
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
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
use std::sync::Arc;

use crate::domain::channel_events::{
    ChannelIdentity, ConversationId, IncomingEvent, InteractionButtons, InteractionEvent,
    OutboundMessage, Platform, TextMessage,
};

use super::{AppState, THINKING_MESSAGES, TypingGuard, is_authorized, spawn_process_event};
use crate::adapters::channel::retry::{RetryPolicy, retry_send};
use crate::adapters::channel::state::{scope_key, with_write};

/// Validate a stored session ID by checking if the session file still exists on disk.
/// Clears stale session state and returns `None` if the file is missing.
async fn validate_resume_session(
    state: &Arc<AppState>,
    scope: &str,
    session_id: Option<String>,
) -> Option<String> {
    let sid = session_id?;
    let projects_dir = crate::adapters::channel::sessions::claude_projects_dir();
    let found = projects_dir
        .as_ref()
        .is_some_and(|dir| crate::adapters::channel::sessions::session_file_exists(dir, &sid));
    if !found {
        tracing::info!(session_id = %sid, "Stored session not found on disk, starting fresh");
        let mut cs = state.channel_state.write().await;
        cs.clear_session(scope);
        if let Err(e) = cs.save() {
            tracing::error!(error = %e, "Failed to persist cleared session state");
        }
        None
    } else {
        Some(sid)
    }
}

/// Start a Claude subprocess, register its PID for cancellation, and spawn a stderr monitor.
async fn start_claude_and_track(
    state: &Arc<AppState>,
    scope: &str,
    config: &crate::adapters::channel::claude_process::SessionConfig<'_>,
) -> anyhow::Result<crate::adapters::channel::claude_process::ClaudeProcess> {
    let mut claude = crate::adapters::channel::claude_process::start_claude_session(
        &state.paths,
        &state.config,
        &state.secrets,
        &state.catalog,
        config,
    )?;

    // Store child PID for /cancel
    if let Some(pid) = claude.child_id() {
        state
            .active_claude
            .lock()
            .await
            .insert(scope.to_string(), pid);
    }

    // Spawn stderr reader to detect stale session errors
    if let Some(stderr) = claude.take_stderr() {
        let stderr_state = state.channel_state.clone();
        let stderr_scope = scope.to_string();
        tokio::spawn(async move {
            use tokio::io::AsyncBufReadExt;
            let mut reader = tokio::io::BufReader::new(stderr);
            let mut line = String::new();
            loop {
                line.clear();
                match reader.read_line(&mut line).await {
                    Ok(0) => break,
                    Ok(_) => {
                        let trimmed = line.trim();
                        tracing::warn!(stderr = trimmed, "Claude stderr");
                        if trimmed.contains("No conversation found with session ID")
                            || trimmed.contains("Invalid `signature` in `thinking` block")
                            || trimmed.contains("Invalid signature in thinking block")
                        {
                            tracing::info!(
                                stderr = trimmed,
                                "Clearing session due to resume incompatibility"
                            );
                            let mut cs = stderr_state.write().await;
                            cs.clear_session(&stderr_scope);
                            if let Err(e) = cs.save() {
                                tracing::error!(error = %e, "Failed to clear session after resume error");
                            }
                        }
                    }
                    Err(_) => break,
                }
            }
        });
    }

    Ok(claude)
}

/// Process the streamed response: update message, handle interactive buttons,
/// YOLO auto-continue, and capture session metadata.
async fn process_stream_result(
    state: &Arc<AppState>,
    scope: &str,
    channel: &dyn crate::ports::channel_ports::ChannelPort,
    msg: &TextMessage,
    delivery: &crate::domain::channel_events::MessageDelivery,
    result: crate::adapters::channel::stream_handler::StreamResult,
    yolo: bool,
) -> anyhow::Result<()> {
    // Clear active process for this scope
    state.active_claude.lock().await.remove(scope);

    if !result.has_content {
        let _ = channel
            .edit_message(&OutboundMessage {
                conversation_id: msg.conversation_id.clone(),
                channel: msg.channel.clone(),
                text: "No response".to_string(),
                message_ref: Some(delivery.platform_message_id.clone()),
                interaction: None,
            })
            .await;
    } else if !result.accumulated_text.is_empty() {
        let analysis =
            crate::adapters::channel::response_analyzer::analyze_response(&result.accumulated_text);
        if analysis.needs_interaction {
            let max_len = msg.channel.platform.max_message_length();
            let text = crate::adapters::channel::stream_handler::truncate_message(
                &result.accumulated_text,
                max_len,
            );
            let _ = channel
                .edit_message(&OutboundMessage {
                    conversation_id: msg.conversation_id.clone(),
                    channel: msg.channel.clone(),
                    text,
                    message_ref: Some(delivery.platform_message_id.clone()),
                    interaction: Some(InteractionButtons {
                        prompt_text: "Choose or type your response".into(),
                        buttons: analysis.buttons,
                    }),
                })
                .await;

            if yolo
                && crate::adapters::channel::response_analyzer::is_auto_continuable(
                    &result.accumulated_text,
                )
            {
                schedule_yolo_auto_continue(state, scope, &msg.channel, &msg.conversation_id);
            }
        }
    }

    if let Some(ref sid) = result.session_id {
        let mut cs = state.channel_state.write().await;
        cs.set_session_id(scope, sid);
        if let Some(ref c) = result.cwd {
            cs.set_working_dir(scope, c);
        }
        if let Some(ref b) = result.branch {
            cs.set_branch(scope, b);
        }
        if let Some(ref m) = result.model {
            cs.set_last_model(scope, m);
        }
        if result.input_tokens > 0 || result.output_tokens > 0 {
            cs.add_tokens(scope, result.input_tokens, result.output_tokens);
        }
        if let Err(e) = cs.save() {
            tracing::error!(error = %e, "Failed to persist session capture");
        }
        tracing::info!(session_id = %sid, cwd = ?result.cwd, "Session captured");
    }

    Ok(())
}

fn schedule_yolo_auto_continue(
    state: &Arc<AppState>,
    scope: &str,
    channel_id: &ChannelIdentity,
    conversation_id: &ConversationId,
) {
    let spawn_state = state.clone();
    let ac_state = state.clone();
    let channel_id = channel_id.clone();
    let conversation_id = conversation_id.clone();
    let scope = scope.to_string();
    let handle = tokio::spawn(async move {
        tokio::time::sleep(std::time::Duration::from_secs(60)).await;
        tracing::info!("YOLO auto-continue: sending 'proceed'");
        let synthetic = IncomingEvent::TextMessage(TextMessage {
            conversation_id,
            channel: channel_id,
            text: "proceed".to_string(),
            reply_to_id: None,
        });
        spawn_process_event(spawn_state, synthetic);
    });
    // Cancel old timer + store new one in a single lock scope
    let ac_state_clone = ac_state.clone();
    std::mem::drop(tokio::spawn(async move {
        let mut ac = ac_state_clone.auto_continue.lock().await;
        if let Some(h) = ac.remove(&scope) {
            h.abort();
        }
        ac.insert(scope, handle);
    }));
}

pub(super) async fn handle_text_message(
    state: &Arc<AppState>,
    msg: TextMessage,
) -> anyhow::Result<()> {
    let platform = msg.channel.platform;
    let channel = state
        .channels
        .get(&platform)
        .ok_or_else(|| anyhow::anyhow!("{platform:?} adapter not registered"))?;

    let scope = scope_key(
        msg.channel.platform.as_str(),
        &msg.channel.channel_id,
        &msg.channel.user_id,
    );

    // Handle "waiting for directory input" state (from New project flow)
    {
        let waiting = {
            let cs = state.channel_state.read().await;
            cs.waiting_for_dir(&scope)
        };
        if waiting {
            let path = msg.text.trim();
            if std::path::Path::new(path).is_dir() {
                with_write(&state.channel_state, |cs| {
                    cs.set_working_dir(&scope, path);
                    cs.clear_session(&scope);
                    cs.clear_waiting_for_dir(&scope);
                })
                .await;
                let display = std::path::Path::new(path)
                    .file_name()
                    .map(|n| n.to_string_lossy().to_string())
                    .unwrap_or_else(|| path.to_string());
                let _ = channel
                    .send_message(&OutboundMessage {
                        conversation_id: msg.conversation_id.clone(),
                        channel: msg.channel.clone(),
                        text: format!("New session started.\nProject: {}", display),
                        message_ref: None,
                        interaction: None,
                    })
                    .await;
            } else {
                let _ = channel
                    .send_message(&OutboundMessage {
                        conversation_id: msg.conversation_id.clone(),
                        channel: msg.channel.clone(),
                        text: "Directory not found. Try again or type /cancel.".to_string(),
                        message_ref: None,
                        interaction: None,
                    })
                    .await;
            }
            return Ok(());
        }
    }

    // Reject if a Claude process is already running for this scope,
    // but clean up stale PIDs where the process has already exited.
    {
        let mut active = state.active_claude.lock().await;
        if let Some(&pid) = active.get(&scope) {
            if is_pid_alive(pid) {
                drop(active);
                let _ = channel
                    .send_message(&OutboundMessage {
                        conversation_id: msg.conversation_id.clone(),
                        channel: msg.channel.clone(),
                        text: "Busy — type /cancel first, then retry.".to_string(),
                        message_ref: None,
                        interaction: None,
                    })
                    .await;
                return Ok(());
            }
            tracing::warn!(pid, scope = %scope, "Cleaning up stale Claude PID");
            active.remove(&scope);
        }
    }

    let profile = state.channel_config.profile_for_channel(
        platform.as_str(),
        &msg.channel.channel_id,
        msg.channel.guild_id.as_deref(),
    );
    let mode = state.channel_config.mode_for_channel(
        platform.as_str(),
        &msg.channel.channel_id,
        msg.channel.guild_id.as_deref(),
    );
    let config_project = state.channel_config.project_for_channel(
        platform.as_str(),
        &msg.channel.channel_id,
        msg.channel.guild_id.as_deref(),
    );

    let _typing = TypingGuard::start(channel.clone(), msg.channel.clone());

    // Read current session state for resume
    let (resume_session, working_dir, model, yolo) = {
        let cs = state.channel_state.read().await;
        let session = cs.session_id(&scope).map(|s| s.to_string());
        let cwd = cs
            .working_dir(&scope)
            .map(|s| s.to_string())
            .or(config_project);
        let m = cs.model(&scope).map(|s| s.to_string());
        let y = cs.yolo(&scope);
        (session, cwd, m, y)
    };

    let resume_session = validate_resume_session(state, &scope, resume_session).await;

    // Strip thinking blocks with empty/invalid signatures written by non-Anthropic
    // providers (e.g. ZAI/GLM). The Anthropic API rejects these with HTTP 400 when
    // the session is resumed. Sanitization is a no-op when the file is already clean.
    if let (Some(sid), Some(projects_dir)) = (
        resume_session.as_deref(),
        crate::adapters::channel::sessions::claude_projects_dir(),
    ) {
        match crate::adapters::channel::sessions::sanitize_session_thinking_blocks(
            &projects_dir,
            sid,
        ) {
            Ok(0) => {}
            Ok(n) => tracing::info!(
                count = n,
                session_id = %sid,
                "Stripped invalid thinking blocks before resume"
            ),
            Err(e) => tracing::warn!(
                error = %e,
                session_id = %sid,
                "Could not sanitize thinking blocks; resume may fail"
            ),
        }
    }

    let mut claude = match start_claude_and_track(
        state,
        &scope,
        &crate::adapters::channel::claude_process::SessionConfig {
            profile: &profile,
            mode: mode.as_deref(),
            resume_session: resume_session.as_deref(),
            working_dir: working_dir.as_deref(),
            model: model.as_deref(),
            yolo,
        },
    )
    .await
    {
        Ok(p) => p,
        Err(e) => {
            tracing::error!(error = %e, "Failed to start Claude session");
            let err_msg = OutboundMessage {
                conversation_id: msg.conversation_id.clone(),
                channel: msg.channel.clone(),
                text: format!("Failed to start Claude session: {}", e),
                message_ref: None,
                interaction: None,
            };
            let policy = RetryPolicy::for_platform(msg.channel.platform);
            let _ = retry_send(channel.as_ref(), &err_msg, &policy).await;
            return Err(e);
        }
    };

    {
        use tokio::io::AsyncWriteExt;
        if let Some(mut stdin) = claude.take_stdin() {
            stdin.write_all(msg.text.as_bytes()).await?;
            stdin.write_all(b"\n").await?;
            // Drop stdin to send EOF — Claude CLI --print mode waits for
            // stdin EOF before processing. Keeping it open causes an
            // indefinite hang.
            drop(stdin);
        }
    }

    let thinking_msg = OutboundMessage {
        conversation_id: msg.conversation_id.clone(),
        channel: msg.channel.clone(),
        text: THINKING_MESSAGES[rand::random_range(0..THINKING_MESSAGES.len())].to_string(),
        message_ref: None,
        interaction: None,
    };
    let policy = RetryPolicy::for_platform(msg.channel.platform);
    let delivery = retry_send(channel.as_ref(), &thinking_msg, &policy).await?;

    let stdout = claude.stdout();
    let stream_result = crate::adapters::channel::stream_handler::stream_response(
        stdout,
        channel.as_ref(),
        &msg.channel,
        &delivery.platform_message_id,
        state.channel_config.stream_timeout_secs,
    )
    .await;

    match stream_result {
        Ok(result) => {
            // R1/R3: If context window limit was detected, attempt auto-compact
            let ctx_limit = result.context_limit.clone();
            if let Some(ref ctx_err) = ctx_limit {
                tracing::warn!(
                    error = %ctx_err.message,
                    "Context window limit detected — attempting auto-compact recovery"
                );
                // Skip process_stream_result — sending the error text to the channel
                // before the recovery message would confuse the user. Just clean up
                // the PID and proceed to recovery.
                state.active_claude.lock().await.remove(&scope);

                return handle_context_limit_recovery(state, &scope, channel.as_ref(), &msg, yolo)
                    .await;
            }

            clear_recovery_depth(state, &scope).await;

            process_stream_result(
                state,
                &scope,
                channel.as_ref(),
                &msg,
                &delivery,
                result,
                yolo,
            )
            .await?;
        }
        Err(e) => {
            let err_str = e.to_string();
            // R1: Detect context limit in generic stream errors too
            if crate::adapters::channel::stream_handler::is_context_limit_error(&err_str) {
                tracing::warn!(
                    error = %err_str,
                    "Context window limit in stream error — attempting recovery"
                );
                state.active_claude.lock().await.remove(&scope);

                return handle_context_limit_recovery(state, &scope, channel.as_ref(), &msg, yolo)
                    .await;
            }

            clear_recovery_depth(state, &scope).await;

            tracing::error!(error = %e, "Stream error");
            state.active_claude.lock().await.remove(&scope);
            let err_msg = OutboundMessage {
                conversation_id: msg.conversation_id.clone(),
                channel: msg.channel.clone(),
                text: format!("Error: {}", e),
                message_ref: None,
                interaction: None,
            };
            let policy = RetryPolicy::for_platform(msg.channel.platform);
            let _ = retry_send(channel.as_ref(), &err_msg, &policy).await;
            return Err(e);
        }
    }

    Ok(())
}

pub(super) async fn handle_interaction(
    state: &Arc<AppState>,
    inter: InteractionEvent,
) -> anyhow::Result<()> {
    let platform = inter.channel.platform;

    // Defense-in-depth: authorize_and_spawn checks at the entry point,
    // but reject here if somehow bypassed.
    if !is_authorized(state, platform, &inter.channel.user_id) {
        tracing::warn!(
            user_id = %inter.channel.user_id,
            "Interaction reached handler without authorization"
        );
        return Ok(());
    }

    let channel = state
        .channels
        .get(&platform)
        .ok_or_else(|| anyhow::anyhow!("{platform:?} adapter not registered"))?;

    // Acknowledge the callback immediately (stops loading spinner)
    if let Some(ref query_id) = inter.callback_query_id
        && let Err(e) = channel.ack_interaction(&inter.channel, query_id).await
    {
        tracing::warn!(error = %e, "Failed to ack callback (may have expired)");
    }

    let action = &inter.action_id;
    if action.starts_with("allow") || action.starts_with("deny") {
        // Permission buttons are no longer interactive (stdin is closed
        // for --print mode). Ack and ignore.
        return Ok(());
    }

    let scope = scope_key(
        inter.channel.platform.as_str(),
        &inter.channel.channel_id,
        &inter.channel.user_id,
    );

    // Cancel auto-continue timer on any button press
    {
        let mut ac = state.auto_continue.lock().await;
        if let Some(h) = ac.remove(&scope) {
            h.abort();
        }
    }

    crate::adapters::channel::commands::handle_callback(
        crate::adapters::channel::commands::CallbackContext {
            channel: channel.clone(),
            channel_id: inter.channel.clone(),
            action: inter.action_id.clone(),
            data: inter.message_ref.clone(),
            callback_message_id: inter.callback_message_id,
            original_text: inter.original_text,
            scope,
            channel_state: state.channel_state.clone(),
            app_state: state.clone(),
        },
    )
    .await
}

pub(super) async fn handle_bot_command(
    state: &Arc<AppState>,
    command: &str,
    args: &str,
    bot_channel: ChannelIdentity,
) -> anyhow::Result<()> {
    let platform = bot_channel.platform;
    let adapter = state
        .channels
        .get(&platform)
        .ok_or_else(|| anyhow::anyhow!("{platform:?} adapter not registered"))?;

    let scope = scope_key(
        bot_channel.platform.as_str(),
        &bot_channel.channel_id,
        &bot_channel.user_id,
    );

    match command {
        "/start" => {
            // Set up Telegram persistent bottom keyboard
            if platform == Platform::Telegram
                && let Some(tg) = adapter
                    .as_any()
                    .downcast_ref::<super::super::telegram::TelegramAdapter>()
                && let Err(e) = tg.send_reply_keyboard(&bot_channel.channel_id).await
            {
                tracing::warn!(error = %e, "Failed to send Telegram reply keyboard");
            }
            crate::adapters::channel::commands::handle_help(adapter.as_ref(), &bot_channel).await
        }
        "/help" => {
            crate::adapters::channel::commands::handle_help(adapter.as_ref(), &bot_channel).await
        }
        "/cancel" | "/stop" => {
            crate::adapters::channel::commands::handle_cancel(
                adapter.as_ref(),
                &bot_channel,
                &scope,
                &state.active_claude,
            )
            .await
        }
        "/yolo" => {
            crate::adapters::channel::commands::handle_yolo(
                adapter.as_ref(),
                &bot_channel,
                &scope,
                &state.channel_state,
            )
            .await
        }
        "/model" => {
            crate::adapters::channel::commands::handle_model(
                adapter.as_ref(),
                &bot_channel,
                args,
                &scope,
                &state.channel_state,
            )
            .await
        }
        "/status" => {
            let cs = state.channel_state.read().await;
            let active_session = cs.session_id(&scope);
            let active_cwd = cs.working_dir(&scope);
            let active_model = cs.model(&scope).map(|s| s.to_string());
            let yolo = cs.yolo(&scope);
            let branch = cs.branch(&scope).map(|s| s.to_string());
            let input_tokens = cs.input_tokens(&scope);
            let output_tokens = cs.output_tokens(&scope);
            let last_model = cs.last_model(&scope).map(|s| s.to_string());
            let resolved_project = state.channel_config.project_for_channel(
                platform.as_str(),
                &bot_channel.channel_id,
                bot_channel.guild_id.as_deref(),
            );
            crate::adapters::channel::commands::handle_status(
                adapter.as_ref(),
                &bot_channel,
                &state.channel_config,
                crate::adapters::channel::commands::SessionStatus {
                    session_id: active_session,
                    cwd: active_cwd,
                    model: active_model.as_deref(),
                    yolo,
                    branch: branch.as_deref(),
                    input_tokens,
                    output_tokens,
                    last_model: last_model.as_deref(),
                    project: resolved_project.as_deref(),
                },
            )
            .await
        }
        "/sessions" => {
            crate::adapters::channel::commands::handle_sessions(adapter.as_ref(), &bot_channel)
                .await
        }
        "/projects" => {
            crate::adapters::channel::commands::handle_projects(adapter.as_ref(), &bot_channel)
                .await
        }
        "/new" => {
            crate::adapters::channel::commands::handle_new(
                adapter.as_ref(),
                &bot_channel,
                &scope,
                &state.channel_state,
            )
            .await
        }
        "/history" => {
            crate::adapters::channel::commands::handle_history(
                adapter.as_ref(),
                &bot_channel,
                &scope,
                &state.channel_state,
            )
            .await
        }
        "/compact" => {
            let has_session = {
                let cs = state.channel_state.read().await;
                cs.session_id(&scope).is_some()
            };
            if !has_session {
                crate::adapters::channel::commands::handle_help(adapter.as_ref(), &bot_channel)
                    .await?;
                return Ok(());
            }
            handle_manual_compact(state, &scope, adapter.as_ref(), &bot_channel).await
        }
        _ => {
            adapter
                .send_message(&OutboundMessage {
                    conversation_id: ConversationId::new(),
                    channel: bot_channel.clone(),
                    text: format!("Unknown command: {}", command),
                    message_ref: None,
                    interaction: None,
                })
                .await?;
            Ok(())
        }
    }
}

/// Send a simple text message to a channel with retry and error logging.
async fn send_channel_text(
    channel: &dyn crate::ports::channel_ports::ChannelPort,
    channel_id: &ChannelIdentity,
    text: impl Into<String>,
) {
    let msg = OutboundMessage {
        conversation_id: ConversationId::new(),
        channel: channel_id.clone(),
        text: text.into(),
        message_ref: None,
        interaction: None,
    };
    let policy = RetryPolicy::for_platform(channel_id.platform);
    if let Err(e) = retry_send(channel, &msg, &policy).await {
        tracing::warn!(error = %e, "Failed to send channel message");
    }
}

/// Handle a manual `/compact` command: run compaction and report token savings.
async fn handle_manual_compact(
    state: &Arc<AppState>,
    scope: &str,
    channel: &dyn crate::ports::channel_ports::ChannelPort,
    bot_channel: &ChannelIdentity,
) -> anyhow::Result<()> {
    let (session_id, working_dir, model, yolo) = {
        let cs = state.channel_state.read().await;
        let sid = cs.session_id(scope).map(|s| s.to_string());
        let cwd = cs.working_dir(scope).map(|s| s.to_string());
        let m = cs.model(scope).map(|s| s.to_string());
        let y = cs.yolo(scope);
        (sid, cwd, m, y)
    };

    if let Some(ref sid) = session_id {
        let before_tokens = {
            let cs = state.channel_state.read().await;
            cs.input_tokens(scope)
        };

        let result = CompactParams {
            state,
            scope,
            channel,
            channel_id: bot_channel,
            session_id: sid,
            working_dir: working_dir.as_deref(),
            model: model.as_deref(),
            yolo,
        }
        .run()
        .await;

        match result {
            Ok(Some(r)) => {
                let after_tokens = r.input_tokens;
                if let Some(ref new_sid) = r.session_id {
                    with_write(&state.channel_state, |cs| {
                        cs.set_session_id(scope, new_sid);
                        if r.input_tokens > 0 || r.output_tokens > 0 {
                            cs.add_tokens(scope, r.input_tokens, r.output_tokens);
                        }
                        cs.reset_recovery_depth(scope);
                    })
                    .await;
                }
                let text = match (before_tokens, after_tokens) {
                    (0, 0) => "Compaction complete.".to_string(),
                    (b, a) => format!("Compaction complete ({} -> {} tokens).", b, a),
                };
                send_channel_text(channel, bot_channel, text).await;
            }
            Ok(None) | Err(_) => {
                send_channel_text(
                    channel,
                    bot_channel,
                    "Compaction failed. Try /new to start a fresh session.",
                )
                .await;
            }
        }
    } else {
        send_channel_text(
            channel,
            bot_channel,
            "No active session to compact. Start a conversation first.",
        )
        .await;
    }
    Ok(())
}

/// Clear the recovery depth counter after a successful non-recovery message.
async fn clear_recovery_depth(state: &Arc<AppState>, scope: &str) {
    with_write(&state.channel_state, |cs| {
        if cs.recovery_depth(scope) > 0 {
            cs.reset_recovery_depth(scope);
        }
    })
    .await;
}

/// Check if a process with the given PID is still alive (signal-0 probe / OpenProcess).
/// Returns `true` if the process exists (including the EPERM case where it is
/// alive but owned by another user). Returns `false` only on ESRCH (no such process).
#[cfg(unix)]
fn is_pid_alive(pid: u32) -> bool {
    unsafe {
        if libc::kill(pid as i32, 0) == 0 {
            return true;
        }
        // EPERM means the process exists but we lack permission to signal it.
        std::io::Error::last_os_error().raw_os_error() != Some(libc::ESRCH)
    }
}

#[cfg(windows)]
fn is_pid_alive(pid: u32) -> bool {
    std::process::Command::new("tasklist")
        .args(["/FI", &format!("PID eq {}", pid), "/NH", "/FO", "CSV"])
        .output()
        .map(|o| String::from_utf8_lossy(&o.stdout).contains(&pid.to_string()))
        .unwrap_or(false)
}

/// Maximum number of context-limit recovery attempts before giving up.
const MAX_RECOVERY_DEPTH: u8 = 1;

/// R3/R4/R5: Attempt recovery from a context window limit error.
///
/// Strategy:
/// 1. If recovery depth exceeded, report failure (prevents infinite loops)
/// 2. Try sending `/compact` to reduce context, then replay the original message
/// 3. If compaction fails, start a completely new session and replay
async fn handle_context_limit_recovery(
    state: &Arc<AppState>,
    scope: &str,
    channel: &dyn crate::ports::channel_ports::ChannelPort,
    original_msg: &TextMessage,
    yolo: bool,
) -> anyhow::Result<()> {
    let current_depth = {
        let cs = state.channel_state.read().await;
        cs.recovery_depth(scope)
    };

    if current_depth >= MAX_RECOVERY_DEPTH {
        tracing::warn!(
            depth = current_depth,
            "Recovery depth exceeded — reporting failure to user"
        );
        with_write(&state.channel_state, |cs| {
            cs.clear_session(scope);
        })
        .await;

        send_channel_text(
            channel,
            &original_msg.channel,
            "Context recovery failed. New session started — please resend your message.",
        )
        .await;

        return Ok(());
    }

    // Increment recovery depth
    with_write(&state.channel_state, |cs| {
        cs.increment_recovery_depth(scope);
    })
    .await;

    // Notify user that compaction is being attempted
    send_channel_text(
        channel,
        &original_msg.channel,
        "Context limit reached. Compacting conversation...",
    )
    .await;

    // Get current session info for resume
    let (resume_session, working_dir, model) = {
        let cs = state.channel_state.read().await;
        let session = cs.session_id(scope).map(|s| s.to_string());
        let cwd = cs.working_dir(scope).map(|s| s.to_string());
        let m = cs.model(scope).map(|s| s.to_string());
        (session, cwd, m)
    };

    let resume_session = validate_resume_session(state, scope, resume_session).await;

    // Phase 1: Try compaction
    if let Some(ref sid) = resume_session {
        tracing::info!(session_id = %sid, "Attempting compact for context limit recovery");
        let compact_result = CompactParams {
            state,
            scope,
            channel,
            channel_id: &original_msg.channel,
            session_id: sid,
            working_dir: working_dir.as_deref(),
            model: model.as_deref(),
            yolo,
        }
        .run()
        .await;

        match compact_result {
            Ok(Some(result)) => {
                return update_and_replay_after_compact(
                    state,
                    scope,
                    channel,
                    original_msg,
                    &result,
                )
                .await;
            }
            Ok(None) => {
                tracing::warn!("Compact produced no result — falling back to new session");
            }
            Err(e) => {
                tracing::warn!(error = %e, "Compact failed — falling back to new session");
            }
        }
    } else {
        tracing::info!("No resumable session — skipping compact, starting fresh session");
    }

    // Phase 2: Fallback — new session + replay
    start_fresh_session_and_replay(state, scope, channel, original_msg).await
}

/// Update session state after a successful compaction, then replay the original
/// message in the compacted session.
async fn update_and_replay_after_compact(
    state: &Arc<AppState>,
    scope: &str,
    channel: &dyn crate::ports::channel_ports::ChannelPort,
    original_msg: &TextMessage,
    compact_result: &crate::adapters::channel::stream_handler::StreamResult,
) -> anyhow::Result<()> {
    let before_tokens = {
        let cs = state.channel_state.read().await;
        cs.input_tokens(scope)
    };
    let after_tokens = compact_result.input_tokens;

    let text = match (before_tokens, after_tokens) {
        (0, 0) => "Compaction complete. Retrying your message...".to_string(),
        (b, a) => format!(
            "Compaction complete ({} -> {} tokens). Retrying your message...",
            b, a
        ),
    };
    send_channel_text(channel, &original_msg.channel, text).await;

    if let Some(ref new_sid) = compact_result.session_id {
        // DO NOT reset recovery_depth here — keep it at the current value so
        // that if the replayed message also hits the context limit, the guard
        // in handle_context_limit_recovery catches it and falls back to a new
        // session instead of looping. The counter is cleared only after a
        // successful non-recovery message completes (manual /compact or the
        // replayed message succeeding without context-limit errors).
        with_write(&state.channel_state, |cs| {
            cs.set_session_id(scope, new_sid);
            if compact_result.input_tokens > 0 || compact_result.output_tokens > 0 {
                cs.add_tokens(
                    scope,
                    compact_result.input_tokens,
                    compact_result.output_tokens,
                );
            }
        })
        .await;
    } else {
        // Compact produced no new session ID — replaying into the old
        // context-limited session would be pointless. Fall back to fresh session.
        tracing::warn!(
            "Compact succeeded but produced no session ID — falling back to new session"
        );
        return start_fresh_session_and_replay(state, scope, channel, original_msg).await;
    }

    // Pin the future so the compiler can determine its size —
    // handle_text_message is recursive through the recovery path.
    Box::pin(handle_text_message(
        state,
        TextMessage {
            conversation_id: original_msg.conversation_id.clone(),
            channel: original_msg.channel.clone(),
            text: original_msg.text.clone(),
            reply_to_id: None,
        },
    ))
    .await
}

/// Clear the current session and replay the original message in a fresh one.
async fn start_fresh_session_and_replay(
    state: &Arc<AppState>,
    scope: &str,
    channel: &dyn crate::ports::channel_ports::ChannelPort,
    original_msg: &TextMessage,
) -> anyhow::Result<()> {
    tracing::info!("Starting new session as context limit fallback");
    with_write(&state.channel_state, |cs| {
        cs.clear_session(scope);
    })
    .await;

    send_channel_text(
        channel,
        &original_msg.channel,
        "Context could not be recovered. New session started — retrying your message...",
    )
    .await;

    // Pin the future so the compiler can determine its size —
    // handle_text_message is recursive through the recovery path.
    Box::pin(handle_text_message(
        state,
        TextMessage {
            conversation_id: original_msg.conversation_id.clone(),
            channel: original_msg.channel.clone(),
            text: original_msg.text.clone(),
            reply_to_id: None,
        },
    ))
    .await
}

/// Parameters for launching a compaction command against an existing session.
struct CompactParams<'a> {
    state: &'a Arc<AppState>,
    scope: &'a str,
    channel: &'a dyn crate::ports::channel_ports::ChannelPort,
    channel_id: &'a ChannelIdentity,
    session_id: &'a str,
    working_dir: Option<&'a str>,
    model: Option<&'a str>,
    yolo: bool,
}

impl CompactParams<'_> {
    /// Kill the tracked Claude process for this scope (best-effort).
    async fn kill_tracked_process(&self) {
        if let Some(pid) = self.state.active_claude.lock().await.remove(self.scope) {
            let kill_result = tokio::process::Command::new("kill")
                .arg("-TERM")
                .arg(pid.to_string())
                .output()
                .await;
            if let Err(e) = kill_result {
                tracing::warn!(
                    pid,
                    error = %e,
                    "Failed to kill Claude process during compact cleanup"
                );
            }
        }
    }

    /// Run a `/compact` command against an existing session by launching a new
    /// Claude process with `--resume` and sending the compact text.
    async fn run(
        self,
    ) -> anyhow::Result<Option<crate::adapters::channel::stream_handler::StreamResult>> {
        // Kill any active process for this scope first
        {
            let mut active = self.state.active_claude.lock().await;
            if let Some(pid) = active.remove(self.scope) {
                let kill_result = tokio::process::Command::new("kill")
                    .arg("-TERM")
                    .arg(pid.to_string())
                    .output()
                    .await;
                if let Err(e) = kill_result {
                    tracing::warn!(
                        pid,
                        error = %e,
                        "Failed to send SIGTERM to active Claude process before compact"
                    );
                }
            }
        }

        let profile = self.state.channel_config.profile_for_channel(
            self.channel_id.platform.as_str(),
            &self.channel_id.channel_id,
            self.channel_id.guild_id.as_deref(),
        );
        let mode = self.state.channel_config.mode_for_channel(
            self.channel_id.platform.as_str(),
            &self.channel_id.channel_id,
            self.channel_id.guild_id.as_deref(),
        );

        let mut claude = start_claude_and_track(
            self.state,
            self.scope,
            &crate::adapters::channel::claude_process::SessionConfig {
                profile: &profile,
                mode: mode.as_deref(),
                resume_session: Some(self.session_id),
                working_dir: self.working_dir,
                model: self.model,
                yolo: self.yolo,
            },
        )
        .await?;

        // Send /compact and stream the response. On any failure after the
        // process is spawned, ensure the process is killed before returning.
        use tokio::io::AsyncWriteExt;
        let mut stdin = match claude.take_stdin() {
            Some(s) => s,
            None => {
                self.kill_tracked_process().await;
                return Err(anyhow::anyhow!(
                    "Claude stdin unavailable — cannot send /compact"
                ));
            }
        };
        if let Err(e) = stdin.write_all(b"/compact\n").await {
            self.kill_tracked_process().await;
            return Err(e.into());
        }
        drop(stdin);

        let stdout = claude.stdout();
        let result = crate::adapters::channel::stream_handler::stream_response(
            stdout,
            self.channel,
            self.channel_id,
            "compact",
            self.state.channel_config.stream_timeout_secs,
        )
        .await;

        self.kill_tracked_process().await;

        match result {
            Ok(r) => Ok(Some(r)),
            Err(e) => {
                tracing::warn!(error = %e, "Compact stream failed");
                Err(e)
            }
        }
    }
}

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

    #[test]
    fn is_pid_alive_returns_true_for_current_process() {
        let pid = std::process::id();
        assert!(is_pid_alive(pid), "Current process PID should be alive");
    }

    #[test]
    fn is_pid_alive_returns_false_for_nonexistent_pid() {
        assert!(!is_pid_alive(99_999_999), "Very large PID should not exist");
    }
}