aboutsummaryrefslogtreecommitdiffstats
path: root/crates/atuin-ai/src/fsm/mod.rs
blob: 3d72a3ae084f5b1bfe6c255c83c4e4ffee0640ba (plain) (blame)
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
//! Agent conversation FSM.
//!
//! Pure state machine that returns effects as data.
//! The driver is responsible for executing effects and feeding events back.
//!
//! The FSM owns the conversation event log and tool lifecycle state.
//! It never performs IO directly.

pub(crate) mod effects;
pub(crate) mod events;
pub(crate) mod tools;

#[cfg(test)]
mod tests;

use std::collections::HashMap;

use serde_json::Value;

use crate::context_window::ContextWindowBuilder;
use crate::tui::state::ConversationEvent;

use effects::{Effect, ExitAction, PermissionTarget, TimeoutKind};
use events::{Event, PermissionChoice, PermissionResponse};
use tools::{ToolManager, ToolState};

// ============================================================================
// State
// ============================================================================

/// The discrete states of the agent FSM.
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) enum AgentState {
    /// Waiting for user input.
    Idle {
        confirmation: Option<PendingConfirmation>,
    },

    /// A conversation turn is in progress.
    Turn { stream: StreamPhase },

    /// Unrecoverable error. User can retry or exit.
    Error(String),
}

/// Stream connection lifecycle within a Turn.
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) enum StreamPhase {
    /// Request sent, awaiting first stream frame.
    Connecting,
    /// Actively receiving streamed response.
    Streaming { status: Option<StreamingStatus> },
    /// Stream connection has ended (Done received).
    Done,
}

/// Streaming status indicators from server.
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) enum StreamingStatus {
    Processing,
    Searching,
    Thinking,
    WaitingForTools,
}

impl StreamingStatus {
    pub(crate) fn from_str(s: &str) -> Self {
        match s {
            "processing" => Self::Processing,
            "searching" => Self::Searching,
            "waiting_for_tools" => Self::WaitingForTools,
            _ => Self::Thinking,
        }
    }
}

/// Pending dangerous command confirmation state.
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct PendingConfirmation {
    pub command: String,
    pub timeout_id: u64,
}

// ============================================================================
// Context
// ============================================================================

/// Shared context owned by the FSM.
#[derive(Debug, Clone)]
pub(crate) struct AgentContext {
    /// The full conversation event log (source of truth for API + persistence).
    pub events: Vec<ConversationEvent>,
    /// Server-assigned session ID.
    pub session_id: Option<String>,
    /// Accumulated text from current stream (committed to events on tool call or stream end).
    pub current_response: String,
    /// Per-tool lifecycle state and cached render data.
    /// Tools persist across turns for rendering history.
    pub tools: ToolManager,
    /// Tool IDs that belong to the current turn. Cleared on continuation start.
    /// Used to determine whether a turn needs continuation (has unprocessed results).
    current_turn_tool_ids: Vec<String>,
    /// Maps timeout_id → tool_id for active tool execution timeouts.
    /// Cleaned up when a tool completes naturally, so stale timeouts are ignored.
    tool_timeout_ids: HashMap<u64, String>,
    /// Counter for generating unique timeout IDs.
    next_timeout_id: u64,
    /// Capabilities advertised to the server.
    pub capabilities: Vec<String>,
    /// Unique invocation ID for this CLI invocation.
    pub invocation_id: String,

    // ─── View state (owned by FSM for atomic transitions) ───────
    /// Index into events where the current TUI invocation starts.
    /// Events before this are context for the API but not rendered.
    pub view_start_index: usize,
    /// Whether this session was resumed from a prior invocation.
    pub is_resumed: bool,
    /// Time of the last event from a previous invocation.
    pub last_event_time: Option<chrono::DateTime<chrono::Utc>>,
    /// Events from archived sessions (/new) still rendered on screen.
    pub archived_events: Vec<ConversationEvent>,
}

impl AgentContext {
    fn next_timeout_id(&mut self) -> u64 {
        let id = self.next_timeout_id;
        self.next_timeout_id += 1;
        id
    }
}

// ============================================================================
// The Agent FSM
// ============================================================================

/// The agent finite state machine.
///
/// Pure state machine — `handle()` takes an event, mutates internal state,
/// and returns effects as data for the driver to execute.
#[derive(Debug, Clone)]
pub(crate) struct AgentFsm {
    pub state: AgentState,
    pub ctx: AgentContext,
}

impl AgentFsm {
    /// Create a new FSM in Idle state.
    pub fn new(capabilities: Vec<String>, invocation_id: String) -> Self {
        Self {
            state: AgentState::Idle { confirmation: None },
            ctx: AgentContext {
                events: Vec::new(),
                session_id: None,
                current_response: String::new(),
                tools: ToolManager::new(),
                current_turn_tool_ids: Vec::new(),
                tool_timeout_ids: HashMap::new(),
                next_timeout_id: 0,
                capabilities,
                invocation_id,
                view_start_index: 0,
                is_resumed: false,
                last_event_time: None,
                archived_events: Vec::new(),
            },
        }
    }

    /// Create an FSM from saved session state (for resume).
    pub fn from_session(
        events: Vec<ConversationEvent>,
        session_id: Option<String>,
        capabilities: Vec<String>,
        invocation_id: String,
        view_start_index: usize,
        is_resumed: bool,
        last_event_time: Option<chrono::DateTime<chrono::Utc>>,
    ) -> Self {
        Self {
            state: AgentState::Idle { confirmation: None },
            ctx: AgentContext {
                events,
                session_id,
                current_response: String::new(),
                tools: ToolManager::new(),
                current_turn_tool_ids: Vec::new(),
                tool_timeout_ids: HashMap::new(),
                next_timeout_id: 0,
                capabilities,
                invocation_id,
                view_start_index,
                is_resumed,
                last_event_time,
                archived_events: Vec::new(),
            },
        }
    }

    /// Handle an event, returning effects to execute.
    pub fn handle(&mut self, event: Event) -> Vec<Effect> {
        match (&self.state, event) {
            // ================================================================
            // Idle state
            // ================================================================
            (AgentState::Idle { confirmation: None }, Event::UserSubmit(msg)) => {
                self.start_turn(msg)
            }

            (
                AgentState::Idle {
                    confirmation: Some(_),
                },
                Event::UserSubmit(msg),
            ) => self.start_turn(msg),

            (AgentState::Idle { confirmation: None }, Event::ExecuteCommand) => {
                let cmd = self.current_command();
                let Some(cmd) = cmd else {
                    // No command suggested — exit
                    return vec![Effect::ExitApp(ExitAction::Cancel)];
                };
                if self.is_current_command_dangerous() {
                    let timeout_id = self.ctx.next_timeout_id();
                    self.state = AgentState::Idle {
                        confirmation: Some(PendingConfirmation {
                            command: cmd,
                            timeout_id,
                        }),
                    };
                    vec![Effect::ScheduleTimeout {
                        timeout_id,
                        duration: std::time::Duration::from_secs(5),
                        kind: TimeoutKind::Confirmation,
                    }]
                } else {
                    vec![Effect::ExitApp(ExitAction::Execute(cmd))]
                }
            }

            (
                AgentState::Idle {
                    confirmation: Some(_),
                },
                Event::ExecuteCommand,
            ) => {
                let confirm = self.state_confirmation().unwrap().clone();
                self.state = AgentState::Idle { confirmation: None };
                vec![Effect::ExitApp(ExitAction::Execute(confirm.command))]
            }

            (AgentState::Idle { .. }, Event::InsertCommand) => {
                let cmd = self.current_command();
                match cmd {
                    Some(cmd) => vec![Effect::ExitApp(ExitAction::Insert(cmd))],
                    None => vec![],
                }
            }

            (
                AgentState::Idle {
                    confirmation: Some(_),
                },
                Event::Cancel,
            ) => {
                self.state = AgentState::Idle { confirmation: None };
                vec![]
            }

            (AgentState::Idle { confirmation: None }, Event::Cancel) => {
                vec![Effect::ExitApp(ExitAction::Cancel)]
            }

            (AgentState::Idle { .. }, Event::ConfirmationTimeout { timeout_id }) => {
                if self
                    .state_confirmation()
                    .is_some_and(|c| c.timeout_id == timeout_id)
                {
                    self.state = AgentState::Idle { confirmation: None };
                }
                vec![]
            }

            (AgentState::Idle { .. }, Event::NewSession) => {
                // Archive visible events so they remain on screen but aren't
                // sent to the API. Tools persist for rendering.
                let visible = self.ctx.events[self.ctx.view_start_index..].to_vec();
                self.ctx.archived_events.extend(visible);

                self.ctx.events.clear();
                self.ctx.session_id = None;
                self.ctx.current_turn_tool_ids.clear();
                self.ctx.view_start_index = 0;
                self.ctx.is_resumed = false;

                // Add OOB indicator for the new session
                self.ctx.events.push(ConversationEvent::OutOfBandOutput {
                    name: "System".to_string(),
                    command: Some("/new".to_string()),
                    content: "Started a new session.".to_string(),
                });

                self.state = AgentState::Idle { confirmation: None };
                vec![Effect::ArchiveSession, Effect::Persist]
            }

            (AgentState::Idle { .. }, Event::SlashCommand { command, content }) => {
                self.handle_slash_command(&command, &content);
                vec![]
            }

            (
                AgentState::Idle { .. },
                Event::SkillLoaded {
                    name,
                    arguments,
                    content,
                },
            ) => {
                self.ctx.events.push(ConversationEvent::SkillInvocation {
                    name,
                    arguments,
                    content,
                });
                self.ctx.current_response.clear();
                self.ctx.current_turn_tool_ids.clear();

                let messages = self.build_messages();
                let session_id = self.ctx.session_id.clone();
                self.state = AgentState::Turn {
                    stream: StreamPhase::Connecting,
                };
                vec![Effect::StartStream {
                    messages,
                    session_id,
                }]
            }

            // ================================================================
            // Turn — stream lifecycle
            // ================================================================
            (
                AgentState::Turn {
                    stream: StreamPhase::Connecting,
                },
                Event::StreamStarted,
            ) => {
                self.state = AgentState::Turn {
                    stream: StreamPhase::Streaming { status: None },
                };
                vec![]
            }

            (
                AgentState::Turn {
                    stream: StreamPhase::Connecting,
                },
                Event::StreamError(e),
            ) => {
                self.state = AgentState::Error(e);
                vec![]
            }

            (
                AgentState::Turn {
                    stream: StreamPhase::Streaming { .. },
                },
                Event::StreamChunk(text),
            ) => {
                self.ctx.current_response.push_str(&text);
                vec![]
            }

            (
                AgentState::Turn {
                    stream: StreamPhase::Streaming { .. },
                },
                Event::StreamStatusChanged(status),
            ) => {
                self.state = AgentState::Turn {
                    stream: StreamPhase::Streaming {
                        status: Some(StreamingStatus::from_str(&status)),
                    },
                };
                vec![]
            }

            (AgentState::Turn { .. }, Event::StreamToolCall { id, name, input }) => {
                self.commit_streaming_text();
                self.handle_stream_tool_call(id, name, input)
            }

            (AgentState::Turn { .. }, Event::SuggestCommand { id, input }) => {
                self.commit_streaming_text();
                // Push the suggest_command as a ToolCall event (protocol requirement)
                self.ctx.events.push(ConversationEvent::ToolCall {
                    id,
                    name: "suggest_command".to_string(),
                    input,
                });
                self.state = AgentState::Idle { confirmation: None };
                vec![Effect::Persist]
            }

            (
                AgentState::Turn {
                    stream: StreamPhase::Streaming { .. },
                },
                Event::StreamServerToolResult {
                    tool_use_id,
                    content,
                    is_error,
                    remote,
                    content_length,
                },
            ) => {
                self.ctx.events.push(ConversationEvent::ToolResult {
                    tool_use_id,
                    content,
                    is_error,
                    remote,
                    content_length,
                });
                vec![]
            }

            (AgentState::Turn { .. }, Event::StreamDone { session_id }) => {
                self.commit_streaming_text();
                if !session_id.is_empty() {
                    self.ctx.session_id = Some(session_id);
                }
                self.state = AgentState::Turn {
                    stream: StreamPhase::Done,
                };
                self.check_turn_completion()
            }

            (
                AgentState::Turn {
                    stream: StreamPhase::Streaming { .. },
                },
                Event::StreamError(e),
            ) => {
                // Abort any executing tools on stream error
                let abort_effects: Vec<_> = self
                    .ctx
                    .tools
                    .executing_ids()
                    .into_iter()
                    .map(|tool_id| Effect::AbortTool { tool_id })
                    .collect();
                self.ctx.tool_timeout_ids.clear();
                self.state = AgentState::Error(e);
                abort_effects
            }

            // ================================================================
            // Turn — tool lifecycle (any stream phase)
            // ================================================================
            (AgentState::Turn { .. }, Event::PermissionResolved { tool_id, response }) => {
                self.handle_permission_resolved(tool_id, response)
            }

            (AgentState::Turn { .. }, Event::PermissionUserChoice { tool_id, choice }) => {
                self.handle_permission_choice(tool_id, choice)
            }

            (
                AgentState::Turn { .. },
                Event::ToolExecutionDone {
                    tool_id,
                    outcome,
                    preview,
                },
            ) => self.handle_tool_done(tool_id, outcome, preview),

            (
                AgentState::Turn { .. },
                Event::ToolPreviewUpdate {
                    tool_id,
                    lines,
                    exit_code,
                },
            ) => {
                if let Some(tracked) = self.ctx.tools.get_mut(&tool_id) {
                    if tracked.is_resolved() {
                        // Tool already completed — a late preview update raced with
                        // ToolExecutionDone. Update lines (they may carry the final
                        // screen) but preserve the finalized exit_code/interrupted.
                        if let Some(tools::ToolPreviewData::Shell {
                            lines: existing_lines,
                            ..
                        }) = &mut tracked.preview
                        {
                            *existing_lines = lines;
                        }
                    } else {
                        tracked.preview = Some(tools::ToolPreviewData::Shell {
                            lines,
                            exit_code,
                            interrupted: None,
                        });
                    }
                }
                vec![]
            }

            (AgentState::Turn { .. }, Event::InterruptTools) => {
                let ids = self.ctx.tools.executing_ids();
                for id in &ids {
                    if let Some(tracked) = self.ctx.tools.get_mut(id) {
                        tracked.interrupt_reason = Some(tools::InterruptReason::User);
                    }
                    // Clear any pending execution timeout for this tool
                    self.ctx.tool_timeout_ids.retain(|_, tid| tid != id);
                }
                ids.into_iter()
                    .map(|tool_id| Effect::AbortTool { tool_id })
                    .collect()
            }

            (
                AgentState::Turn { .. },
                Event::ToolExecutionTimeout {
                    timeout_id,
                    tool_id,
                },
            ) => self.handle_tool_execution_timeout(timeout_id, tool_id),

            // ─── Cancel during Turn ─────────────────────────────────────
            (AgentState::Turn { stream }, Event::Cancel) => {
                let mut effects = Vec::new();

                // Abort stream if still active
                if !matches!(stream, StreamPhase::Done) {
                    effects.push(Effect::AbortStream);
                }

                // Cancel all pending tools
                let pending = self.ctx.tools.pending_ids();
                for id in &pending {
                    if let Some(tracked) = self.ctx.tools.get_mut(id) {
                        if tracked.state == ToolState::Executing {
                            effects.push(Effect::AbortTool {
                                tool_id: id.clone(),
                            });
                        }
                        tracked.state = ToolState::Completed;
                    }
                    self.ctx.events.push(ConversationEvent::ToolResult {
                        tool_use_id: id.clone(),
                        content: "Error: user cancelled this operation".to_string(),
                        is_error: true,
                        remote: false,
                        content_length: None,
                    });
                }

                // Commit any partial streaming text
                self.commit_streaming_text_as_cancelled();

                // Add context so the LLM knows what happened
                if !pending.is_empty() {
                    self.ctx.events.push(ConversationEvent::SystemContext {
                        content: "The user cancelled the previous generation. Tool calls that were in progress have been aborted.".to_string(),
                    });
                }

                // Clear timeout mappings — stale timeouts will be ignored by the guard
                self.ctx.tool_timeout_ids.clear();

                self.state = AgentState::Idle { confirmation: None };
                effects.push(Effect::Persist);
                effects
            }

            // ================================================================
            // Error state
            // ================================================================
            (AgentState::Error(_), Event::Retry) => {
                let messages = self.build_messages();
                let session_id = self.ctx.session_id.clone();
                self.state = AgentState::Turn {
                    stream: StreamPhase::Connecting,
                };
                vec![Effect::StartStream {
                    messages,
                    session_id,
                }]
            }

            (AgentState::Error(_), Event::Cancel) => {
                vec![Effect::ExitApp(ExitAction::Cancel)]
            }

            // ================================================================
            // Fallthrough — ignore events with no valid transition
            // ================================================================

            // StreamDone can arrive after SuggestCommand (which already moved to Idle).
            // We still need to capture the session_id from it.
            (_, Event::StreamDone { session_id }) => {
                if !session_id.is_empty() {
                    self.ctx.session_id = Some(session_id);
                }
                vec![Effect::Persist]
            }

            (_, Event::SlashCommand { command, content }) => {
                self.handle_slash_command(&command, &content);
                vec![]
            }

            // RequestSkillLoad during non-idle: still emit the effect
            (_, Event::RequestSkillLoad { name, arguments }) => {
                vec![Effect::LoadSkill { name, arguments }]
            }

            // SkillLoaded during non-idle: queue so it's visible
            // in context for the next turn.
            (
                _,
                Event::SkillLoaded {
                    name,
                    arguments,
                    content,
                },
            ) => {
                self.ctx.events.push(ConversationEvent::SkillInvocation {
                    name,
                    arguments,
                    content,
                });
                vec![]
            }

            _ => vec![],
        }
    }

    // ────────────────────────────────────────────────────────────────────
    // Private helpers
    // ────────────────────────────────────────────────────────────────────

    /// Start a new turn: push user message, build messages, emit StartStream.
    fn start_turn(&mut self, msg: String) -> Vec<Effect> {
        self.ctx
            .events
            .push(ConversationEvent::UserMessage { content: msg });
        // Don't clear tools — completed tools persist for rendering history.
        // Tools are only cleared on /new (session reset).
        self.ctx.current_response.clear();
        self.ctx.current_turn_tool_ids.clear();

        let messages = self.build_messages();
        let session_id = self.ctx.session_id.clone();
        self.state = AgentState::Turn {
            stream: StreamPhase::Connecting,
        };
        vec![Effect::StartStream {
            messages,
            session_id,
        }]
    }

    /// Build API messages from the conversation event log.
    fn build_messages(&self) -> Vec<Value> {
        ContextWindowBuilder::with_default_budget().build(&self.ctx.events)
    }

    /// Commit accumulated streaming text to the event log.
    fn commit_streaming_text(&mut self) {
        let text = std::mem::take(&mut self.ctx.current_response);
        let trimmed = text.trim_start().to_string();
        if !trimmed.is_empty() {
            self.ctx
                .events
                .push(ConversationEvent::Text { content: trimmed });
        }
    }

    /// Commit streaming text with a cancellation suffix.
    fn commit_streaming_text_as_cancelled(&mut self) {
        let text = std::mem::take(&mut self.ctx.current_response);
        let trimmed = text.trim_start().to_string();
        if !trimmed.is_empty() {
            self.ctx.events.push(ConversationEvent::Text {
                content: format!("{trimmed}\n\n[User cancelled this generation]"),
            });
        }
    }

    /// Handle a client-side tool call from the stream.
    fn handle_stream_tool_call(&mut self, id: String, name: String, input: Value) -> Vec<Effect> {
        // Parse the tool call
        let tool = match crate::tools::ClientToolCall::try_from((name.as_str(), &input)) {
            Ok(tool) => tool,
            Err(_) => {
                // Unknown tool — push as event but don't track
                self.ctx
                    .events
                    .push(ConversationEvent::ToolCall { id, name, input });
                return vec![];
            }
        };

        // Capability gating
        if let Some(required_cap) = tool.descriptor().capability
            && !self.ctx.capabilities.iter().any(|c| c == required_cap)
        {
            self.ctx.events.push(ConversationEvent::ToolCall {
                id: id.clone(),
                name,
                input,
            });
            self.ctx.events.push(ConversationEvent::ToolResult {
                tool_use_id: id,
                content: format!(
                    "Tool not enabled: capability '{required_cap}' was not advertised by this client"
                ),
                is_error: true,
                remote: false,
                content_length: None,
            });
            return vec![];
        }

        // Track the tool and push ToolCall event
        let tool_for_effect = tool.clone();
        self.ctx.tools.insert(id.clone(), tool);
        self.ctx.current_turn_tool_ids.push(id.clone());
        self.ctx.events.push(ConversationEvent::ToolCall {
            id: id.clone(),
            name,
            input,
        });

        // Transition to Turn if we were Streaming
        if let AgentState::Turn {
            stream: StreamPhase::Streaming { .. },
        } = &self.state
        {
            self.state = AgentState::Turn {
                stream: StreamPhase::Streaming { status: None },
            };
        }

        vec![Effect::CheckPermission {
            tool_id: id,
            tool: tool_for_effect,
        }]
    }

    /// Handle permission resolver result.
    fn handle_permission_resolved(
        &mut self,
        tool_id: String,
        response: PermissionResponse,
    ) -> Vec<Effect> {
        let Some(tracked) = self.ctx.tools.get_mut(&tool_id) else {
            return vec![];
        };

        // If already resolved (e.g. cancelled while permission check was in flight),
        // ignore the stale result to avoid re-executing a cancelled tool.
        if tracked.is_resolved() {
            return vec![];
        }

        match response {
            PermissionResponse::Allowed | PermissionResponse::SessionGranted => {
                tracked.state = ToolState::Executing;
                let tool = tracked.tool.clone();
                self.emit_execute_tool(tool_id, tool)
            }
            PermissionResponse::Ask => {
                tracked.state = ToolState::AwaitingPermission;
                vec![]
            }
            PermissionResponse::Denied => {
                tracked.state = ToolState::Denied;
                self.ctx.events.push(ConversationEvent::ToolResult {
                    tool_use_id: tool_id,
                    content: "Permission denied on the user's system".to_string(),
                    is_error: true,
                    remote: false,
                    content_length: None,
                });
                self.check_turn_completion()
            }
        }
    }

    /// Handle user's permission choice from the dialog.
    fn handle_permission_choice(
        &mut self,
        tool_id: String,
        choice: PermissionChoice,
    ) -> Vec<Effect> {
        let Some(tracked) = self.ctx.tools.get_mut(&tool_id) else {
            return vec![];
        };

        if tracked.is_resolved() {
            return vec![];
        }

        match choice {
            PermissionChoice::Allow => {
                tracked.state = ToolState::Executing;
                let tool = tracked.tool.clone();
                self.emit_execute_tool(tool_id, tool)
            }
            PermissionChoice::AllowForSession => {
                tracked.state = ToolState::Executing;
                let tool = tracked.tool.clone();
                let mut effects = self.emit_execute_tool(tool_id, tool.clone());
                if let Some(path) = tool.resolved_file_path() {
                    effects.push(Effect::CacheSessionGrant { path });
                }
                effects
            }
            PermissionChoice::AlwaysAllowInProject => {
                tracked.state = ToolState::Executing;
                let tool = tracked.tool.clone();
                let rule = crate::permissions::rule::Rule {
                    tool: tool.rule_name().to_string(),
                    scope: None, // project file provides the scoping
                };
                let mut effects = self.emit_execute_tool(tool_id, tool);
                effects.push(Effect::WritePermissionRule {
                    target: PermissionTarget::Project,
                    rule,
                    disposition: crate::permissions::writer::RuleDisposition::Allow,
                });
                effects
            }
            PermissionChoice::AlwaysAllow => {
                tracked.state = ToolState::Executing;
                let tool = tracked.tool.clone();
                let scope = tool
                    .resolved_file_path()
                    .map(|p| p.to_string_lossy().to_string());
                let rule = crate::permissions::rule::Rule {
                    tool: tool.rule_name().to_string(),
                    scope,
                };
                let mut effects = self.emit_execute_tool(tool_id, tool);
                effects.push(Effect::WritePermissionRule {
                    target: PermissionTarget::Global,
                    rule,
                    disposition: crate::permissions::writer::RuleDisposition::Allow,
                });
                effects
            }
            PermissionChoice::Deny => {
                tracked.state = ToolState::Denied;
                self.ctx.events.push(ConversationEvent::ToolResult {
                    tool_use_id: tool_id,
                    content: "Permission denied by the user".to_string(),
                    is_error: true,
                    remote: false,
                    content_length: None,
                });
                self.check_turn_completion()
            }
        }
    }

    /// Handle tool execution completion.
    fn handle_tool_done(
        &mut self,
        tool_id: String,
        outcome: crate::tools::ToolOutcome,
        preview: Option<tools::ToolPreviewData>,
    ) -> Vec<Effect> {
        let Some(tracked) = self.ctx.tools.get_mut(&tool_id) else {
            return vec![];
        };

        // If already completed (e.g. cancelled), ignore stale result
        if tracked.is_resolved() {
            return vec![];
        }

        tracked.state = ToolState::Completed;

        // If the FSM tagged this tool with an interrupt reason (user or timeout),
        // use it; otherwise derive from the outcome's interrupted flag.
        let reason = tracked.interrupt_reason.take().or({
            if let crate::tools::ToolOutcome::Structured {
                interrupted: true, ..
            } = &outcome
            {
                Some(tools::InterruptReason::User)
            } else {
                None
            }
        });

        // Merge shell preview: the final ToolExecutionDone carries exit_code/interrupted
        // but has empty lines (the live lines were accumulated via ToolPreviewUpdate).
        // Preserve the accumulated lines and fold in the terminal metadata.
        match (&mut tracked.preview, preview) {
            (
                Some(tools::ToolPreviewData::Shell {
                    exit_code,
                    interrupted,
                    ..
                }),
                Some(tools::ToolPreviewData::Shell {
                    exit_code: final_exit,
                    ..
                }),
            ) => {
                *exit_code = final_exit;
                *interrupted = reason.clone();
            }
            (_, Some(mut p)) => {
                if let tools::ToolPreviewData::Shell {
                    ref mut interrupted,
                    ..
                } = p
                {
                    *interrupted = reason.clone();
                }
                tracked.preview = Some(p);
            }
            _ => {}
        }

        // Clean up any pending execution timeout for this tool
        self.ctx.tool_timeout_ids.retain(|_, tid| tid != &tool_id);

        let content = outcome.format_for_llm(reason.as_ref());
        let is_error = outcome.is_error();
        self.ctx.events.push(ConversationEvent::ToolResult {
            tool_use_id: tool_id,
            content,
            is_error,
            remote: false,
            content_length: None,
        });

        self.check_turn_completion()
    }

    /// Handle a tool execution timeout. Aborts the tool if it's still running.
    fn handle_tool_execution_timeout(&mut self, timeout_id: u64, tool_id: String) -> Vec<Effect> {
        // Guard: only act if this timeout is still registered (not cleaned up by natural completion)
        if self.ctx.tool_timeout_ids.remove(&timeout_id).is_none() {
            return vec![];
        }

        let Some(tracked) = self.ctx.tools.get_mut(&tool_id) else {
            return vec![];
        };

        if tracked.is_resolved() {
            return vec![];
        }

        // Tag the tool so handle_tool_done can distinguish timeout from user interrupt.
        // Only shell tools have entries in tool_timeout_ids, so this is always Shell.
        let timeout_secs = match &tracked.tool {
            crate::tools::ClientToolCall::Shell(s) => s.timeout_secs,
            _ => unreachable!("only shell tools have execution timeouts"),
        };
        tracked.interrupt_reason = Some(tools::InterruptReason::Timeout(timeout_secs));

        // Abort the tool — the driver sends the interrupt signal via oneshot,
        // and execute_shell_command_streaming returns a Structured outcome with
        // interrupted: true and partial stdout/stderr. This flows through the
        // normal ToolExecutionDone path.
        vec![Effect::AbortTool { tool_id }]
    }

    /// Emit effects to begin executing a tool. For shell commands, also schedules
    /// an execution timeout based on the LLM-specified timeout_secs.
    fn emit_execute_tool(
        &mut self,
        tool_id: String,
        tool: crate::tools::ClientToolCall,
    ) -> Vec<Effect> {
        let mut effects = vec![Effect::ExecuteTool {
            tool_id: tool_id.clone(),
            tool: tool.clone(),
        }];

        if let crate::tools::ClientToolCall::Shell(ref shell) = tool {
            let timeout_id = self.ctx.next_timeout_id();
            self.ctx
                .tool_timeout_ids
                .insert(timeout_id, tool_id.clone());
            effects.push(Effect::ScheduleTimeout {
                timeout_id,
                duration: std::time::Duration::from_secs(shell.timeout_secs),
                kind: TimeoutKind::ToolExecution { tool_id },
            });
        }

        effects
    }

    /// Check if the turn is complete (stream done + all tools resolved).
    /// If so, either continue the conversation or go Idle.
    fn check_turn_completion(&mut self) -> Vec<Effect> {
        // Stream must be done
        if !matches!(
            self.state,
            AgentState::Turn {
                stream: StreamPhase::Done
            }
        ) {
            return vec![];
        }

        // All current-turn tools must be resolved before the turn can complete
        if !self.ctx.tools.all_resolved(&self.ctx.current_turn_tool_ids) {
            return vec![];
        }

        // Turn is complete. Check if we need to continue (tool results to send back).
        // We continue if this turn had any client tool calls (the LLM needs to see
        // the results and respond).
        if !self.ctx.current_turn_tool_ids.is_empty() {
            // Continue conversation with tool results.
            // Don't clear tools — they persist for rendering history.
            // Clear turn IDs so the continuation turn doesn't loop.
            self.ctx.current_turn_tool_ids.clear();
            let messages = self.build_messages();
            let session_id = self.ctx.session_id.clone();
            self.ctx.current_response.clear();
            self.state = AgentState::Turn {
                stream: StreamPhase::Connecting,
            };
            vec![Effect::StartStream {
                messages,
                session_id,
            }]
        } else {
            // No tools — turn is done, go idle
            self.state = AgentState::Idle { confirmation: None };
            vec![Effect::Persist]
        }
    }

    /// Extract the current confirmation state (if any).
    fn state_confirmation(&self) -> Option<&PendingConfirmation> {
        if let AgentState::Idle {
            confirmation: Some(ref c),
        } = self.state
        {
            Some(c)
        } else {
            None
        }
    }

    /// Get the most recent suggested command from the conversation.
    /// Get the most recent command from the current invocation only.
    fn current_command(&self) -> Option<String> {
        self.current_invocation_events()
            .rev()
            .find_map(|e| e.as_command())
            .map(|s| s.to_string())
    }

    /// Check if the most recent command is dangerous.
    fn is_current_command_dangerous(&self) -> bool {
        self.current_invocation_events()
            .rev()
            .find_map(|e| {
                if let ConversationEvent::ToolCall { name, input, .. } = e
                    && name == "suggest_command"
                {
                    let danger = input
                        .get("danger")
                        .and_then(|v| v.as_str())
                        .unwrap_or("low");
                    Some(danger == "high" || danger == "medium" || danger == "med")
                } else {
                    None
                }
            })
            .unwrap_or(false)
    }

    /// Events from the current invocation only (from view_start_index onward).
    fn current_invocation_events(&self) -> impl DoubleEndedIterator<Item = &ConversationEvent> {
        let start = self.ctx.view_start_index.min(self.ctx.events.len());
        self.ctx.events[start..].iter()
    }

    /// Handle a slash command by pushing an OOB event.
    fn handle_slash_command(&mut self, command: &str, content: &str) {
        self.ctx.events.push(ConversationEvent::OutOfBandOutput {
            name: "System".to_string(),
            command: Some(command.to_string()),
            content: content.to_string(),
        });
    }
}