pi-core 0.1.0

Pure synchronous agent-core state machine. No async, no I/O.
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
use ts_rs::TS;
use serde::{Deserialize, Serialize};
use std::collections::HashMap;

use crate::context::LlmContext;
use crate::events::{AgentAction, AgentEvent, CancelReason, ContentDelta, QueueMode, ThinkingLevel, ToolExecutionUpdate, WaitMode};
use crate::llm::{LlmChunk, LlmResult, Model};
use crate::message::{AgentMessage, Content, StopReason, ToolCall, ToolResultMessage};
use crate::tool::{ToolDefinition, ToolError, ToolExecutionMode, ToolResult};
use crate::types::{SessionId, ToolCallId};
use tracing::{debug, trace, warn};

/// Public agent state.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, TS)]
#[ts(export)]
pub struct AgentState {
    pub system_prompt: String,
    pub model: Model,
    pub thinking_level: ThinkingLevel,
    pub tools: Vec<ToolDefinition>,
    pub messages: Vec<AgentMessage>,
    pub is_streaming: bool,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub streaming_message: Option<AgentMessage>,
    pub pending_tool_calls: Vec<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub error_message: Option<String>,
}

/// Options for constructing an Agent.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, TS)]
pub struct AgentOptions {
    pub system_prompt: String,
    pub model: Model,
    #[serde(default)]
    pub thinking_level: ThinkingLevel,
    #[serde(default)]
    pub tools: Vec<ToolDefinition>,
    #[serde(default)]
    pub steering_mode: QueueMode,
    #[serde(default)]
    pub follow_up_mode: QueueMode,
    #[serde(default)]
    pub tool_execution_mode: ToolExecutionMode,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub session_id: Option<SessionId>,
    #[serde(default)]
    pub messages: Vec<AgentMessage>,
}

/// Internal phase of the agent state machine.
#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize, TS)]
#[serde(rename_all = "snake_case")]
pub enum Phase {
    Idle,
    Streaming,
    ExecutingTools,
    WaitForInput,
}

/// The agent state machine. Purely synchronous; the host drives progress.
pub struct Agent {
    state: AgentState,
    steering_queue: Vec<AgentMessage>,
    follow_up_queue: Vec<AgentMessage>,
    pub phase: Phase,
    pending_tool_calls: HashMap<ToolCallId, ToolCall>,
    completed_tool_results: Vec<ToolResultMessage>,
    completed_tool_terminations: Vec<bool>,
    steering_mode: QueueMode,
    follow_up_mode: QueueMode,
    #[allow(dead_code)]
    tool_execution_mode: ToolExecutionMode,
    session_id: Option<SessionId>,
}

impl Agent {
    pub fn new(options: AgentOptions) -> Self {
        Self {
            state: AgentState {
                system_prompt: options.system_prompt,
                model: options.model,
                thinking_level: options.thinking_level,
                tools: options.tools,
                messages: options.messages,
                is_streaming: false,
                streaming_message: None,
                pending_tool_calls: Vec::new(),
                error_message: None,
            },
            steering_queue: Vec::new(),
            follow_up_queue: Vec::new(),
            phase: Phase::Idle,
            pending_tool_calls: HashMap::new(),
            completed_tool_results: Vec::new(),
            completed_tool_terminations: Vec::new(),
            steering_mode: options.steering_mode,
            follow_up_mode: options.follow_up_mode,
            tool_execution_mode: options.tool_execution_mode,
            session_id: options.session_id,
        }
    }

    /// Start processing a new prompt.
    pub fn start_turn(&mut self, prompt: AgentMessage) -> (Vec<AgentEvent>, Vec<AgentAction>) {
        if self.phase != Phase::Idle {
            warn!(phase = ?self.phase, "start_turn requested while agent is not idle");
            return (
                vec![AgentEvent::AgentStart],
                vec![AgentAction::WaitForInput {
                    mode: WaitMode::Any,
                }],
            );
        }

        self.state.messages.push(prompt.clone());
        debug!(
            message_count = self.state.messages.len(),
            "agent turn started"
        );
        let events = vec![
            AgentEvent::AgentStart,
            AgentEvent::TurnStart,
            AgentEvent::MessageStart { message: prompt },
            AgentEvent::MessageEnd {
                message: self.state.messages.last().unwrap().clone(),
            },
        ];

        self.phase = Phase::Streaming;
        self.state.is_streaming = true;

        let actions = vec![AgentAction::StreamLlm {
            context: self.build_llm_context(),
            session_id: self.session_id.clone(),
        }];

        (events, actions)
    }

    /// Continue from the current transcript without adding a new message.
    pub fn continue_turn(&mut self) -> (Vec<AgentEvent>, Vec<AgentAction>) {
        if self.phase != Phase::Idle {
            warn!(phase = ?self.phase, "continue_turn requested while agent is not idle");
            return (vec![], vec![]);
        }

        let last = self.state.messages.last();
        if let Some(AgentMessage::Assistant(_)) = last {
            // Check steering queue first
            let drained = self.drain_steering();
            if !drained.is_empty() {
                return self.inject_messages_and_stream(drained);
            }

            let follow = self.drain_follow_up();
            if !follow.is_empty() {
                return self.inject_messages_and_stream(follow);
            }

            return (
                vec![],
                vec![AgentAction::WaitForInput {
                    mode: WaitMode::Any,
                }],
            );
        }

        self.phase = Phase::Streaming;
        self.state.is_streaming = true;

        let events = vec![AgentEvent::AgentStart, AgentEvent::TurnStart];
        let actions = vec![AgentAction::StreamLlm {
            context: self.build_llm_context(),
            session_id: self.session_id.clone(),
        }];

        (events, actions)
    }

    /// Feed a streaming chunk from the LLM.
    pub fn feed_llm_chunk(&mut self, chunk: LlmChunk) -> Vec<AgentEvent> {
        if self.phase != Phase::Streaming {
            trace!(phase = ?self.phase, "ignored llm chunk outside streaming phase");
            return vec![];
        }

        let mut events = Vec::new();

        match chunk {
            LlmChunk::Start { mut partial } => {
                trace!("llm stream started");
                partial.timestamp = current_timestamp();
                let msg = AgentMessage::Assistant(partial.clone());
                self.state.messages.push(msg.clone());
                self.state.streaming_message = Some(msg.clone());
                events.push(AgentEvent::MessageStart { message: msg });
            }
            LlmChunk::TextDelta { text } => {
                trace!(bytes = text.len(), "llm text delta");
                if let Some(AgentMessage::Assistant(ref mut a)) = self.state.messages.last_mut() {
                    if let Some(Content::Text(ref mut t)) = a.content.last_mut() {
                        t.text.push_str(&text);
                    } else {
                        a.content
                            .push(Content::Text(crate::message::TextContent { text }));
                    }
                    let msg = AgentMessage::Assistant(a.clone());
                    self.state.streaming_message = Some(msg.clone());
                    events.push(AgentEvent::MessageUpdate {
                        message: msg.clone(),
                        delta: ContentDelta::TextDelta {
                            text: msg.assistant_text(),
                        },
                    });
                }
            }
            LlmChunk::ToolCallDelta {
                tool_call_id,
                delta,
            } => {
                if let Some(AgentMessage::Assistant(ref mut a)) = self.state.messages.last_mut() {
                    events.push(AgentEvent::MessageUpdate {
                        message: AgentMessage::Assistant(a.clone()),
                        delta: ContentDelta::ToolCallDelta {
                            tool_call_id,
                            delta,
                        },
                    });
                }
            }
            LlmChunk::ThinkingDelta { text } => {
                if let Some(AgentMessage::Assistant(ref mut a)) = self.state.messages.last_mut() {
                    events.push(AgentEvent::MessageUpdate {
                        message: AgentMessage::Assistant(a.clone()),
                        delta: ContentDelta::ThinkingDelta { text },
                    });
                }
            }
            LlmChunk::Done | LlmChunk::Error { .. } => {
                // Handled in on_llm_done
            }
        }

        events
    }

    /// Called by the host when the LLM stream ends.
    pub fn on_llm_done(&mut self, result: LlmResult) -> (Vec<AgentEvent>, Vec<AgentAction>) {
        if self.phase != Phase::Streaming {
            warn!(phase = ?self.phase, "on_llm_done requested outside streaming phase");
            return (vec![], vec![]);
        }

        let mut events = Vec::new();
        let mut actions = Vec::new();

        let assistant_msg = result.finalize_message();
        let msg = AgentMessage::Assistant(assistant_msg.clone());

        // Update the last message (which may have been a streaming partial)
        if let Some(AgentMessage::Assistant(_)) = self.state.messages.last() {
            *self.state.messages.last_mut().unwrap() = msg.clone();
        } else {
            self.state.messages.push(msg.clone());
        }

        self.state.streaming_message = None;
        events.push(AgentEvent::MessageEnd {
            message: msg.clone(),
        });

        // Check for error / abort
        if matches!(
            assistant_msg.stop_reason,
            StopReason::Error | StopReason::Aborted
        ) {
            warn!(
                stop_reason = ?assistant_msg.stop_reason,
                error = ?assistant_msg.error_message,
                "llm stream ended with failure"
            );
            self.state.error_message = assistant_msg.error_message.clone();
            events.push(AgentEvent::TurnEnd {
                message: msg,
                tool_results: vec![],
            });
            events.push(AgentEvent::AgentEnd {
                messages: self.state.messages.clone(),
            });
            self.phase = Phase::Idle;
            self.state.is_streaming = false;
            actions.push(AgentAction::Finished {
                messages: self.state.messages.clone(),
            });
            return (events, actions);
        }

        // Check for tool calls
        let tool_calls: Vec<ToolCall> = assistant_msg
            .content
            .iter()
            .filter_map(|c| match c {
                Content::ToolCall(tc) => Some(tc.clone()),
                _ => None,
            })
            .collect();

        if tool_calls.is_empty() {
            debug!("assistant turn finished without tool calls");
            // No tools: turn ends
            events.push(AgentEvent::TurnEnd {
                message: msg,
                tool_results: vec![],
            });

            // Check steering / follow-up queues
            let steering = self.drain_steering();
            if !steering.is_empty() {
                return self.inject_messages_and_stream(steering);
            }

            let follow = self.drain_follow_up();
            if !follow.is_empty() {
                return self.inject_messages_and_stream(follow);
            }

            // Run complete
            events.push(AgentEvent::AgentEnd {
                messages: self.state.messages.clone(),
            });
            self.phase = Phase::Idle;
            self.state.is_streaming = false;
            actions.push(AgentAction::Finished {
                messages: self.state.messages.clone(),
            });
            return (events, actions);
        }

        // Execute tools
        self.phase = Phase::ExecutingTools;
        debug!(
            tool_call_count = tool_calls.len(),
            "assistant requested tool execution"
        );
        for tc in &tool_calls {
            self.pending_tool_calls.insert(tc.id.clone(), tc.clone());
            self.state.pending_tool_calls.push(tc.id.0.clone());
            events.push(AgentEvent::ToolExecutionStart {
                tool_call_id: tc.id.clone(),
                tool_name: tc.name.clone(),
                args: Some(tc.arguments.clone()),
            });
        }
        actions.push(AgentAction::ExecuteTools { calls: tool_calls });

        (events, actions)
    }

    /// Called by the host when a tool finishes executing.
    pub fn on_tool_done(
        &mut self,
        tool_call_id: ToolCallId,
        result: Result<ToolResult, ToolError>,
    ) -> (Vec<AgentEvent>, Vec<AgentAction>) {
        if self.phase != Phase::ExecutingTools {
            warn!(phase = ?self.phase, "on_tool_done requested outside executing tools phase");
            return (vec![], vec![]);
        }

        let mut events = Vec::new();
        let tool_call = match self.pending_tool_calls.remove(&tool_call_id) {
            Some(tc) => tc,
            None => {
                warn!(
                    tool_call_id = tool_call_id.as_str(),
                    "unknown tool completion ignored"
                );
                return (vec![], vec![]);
            }
        };
        self.state
            .pending_tool_calls
            .retain(|id| id != tool_call_id.as_str());

        let (tool_result, is_error) = match result {
            Ok(r) => (r, false),
            Err(e) => (
                ToolResult {
                    content: vec![Content::Text(crate::message::TextContent {
                        text: e.message.clone(),
                    })],
                    details: None,
                    terminate: None,
                },
                true,
            ),
        };

        let result_msg = ToolResultMessage {
            role: "tool_result".to_string(),
            tool_call_id: tool_call_id.clone(),
            tool_name: tool_call.name.clone(),
            content: tool_result.content.clone(),
            details: tool_result.details.clone(),
            is_error,
            timestamp: current_timestamp(),
        };

        events.push(AgentEvent::ToolExecutionEnd {
            tool_call_id: tool_call_id.clone(),
            result: tool_result.clone(),
            is_error,
        });

        let agent_msg = AgentMessage::ToolResult(result_msg);
        if let AgentMessage::ToolResult(msg) = &agent_msg {
            self.completed_tool_terminations
                .push(tool_result.terminate == Some(true));
            self.completed_tool_results.push(msg.clone());
        }
        self.state.messages.push(agent_msg.clone());
        events.push(AgentEvent::MessageStart {
            message: agent_msg.clone(),
        });
        events.push(AgentEvent::MessageEnd {
            message: agent_msg.clone(),
        });

        // Check if all pending tools are done
        if !self.pending_tool_calls.is_empty() {
            trace!(
                pending_tool_calls = self.pending_tool_calls.len(),
                "waiting for remaining tools"
            );
            return (events, vec![]);
        }

        // All tools done: end turn
        let assistant_msg = self
            .state
            .messages
            .iter()
            .rev()
            .find(|msg| matches!(msg, AgentMessage::Assistant(_)))
            .cloned()
            .unwrap_or_else(|| agent_msg.clone());
        let tool_results = std::mem::take(&mut self.completed_tool_results);
        let should_terminate = !self.completed_tool_terminations.is_empty()
            && self
                .completed_tool_terminations
                .iter()
                .all(|terminate| *terminate);
        self.completed_tool_terminations.clear();

        events.push(AgentEvent::TurnEnd {
            message: assistant_msg,
            tool_results,
        });

        // Check for steering / follow-up
        let steering = self.drain_steering();
        if !steering.is_empty() {
            return self.inject_messages_and_stream(steering);
        }

        let follow = self.drain_follow_up();
        if !follow.is_empty() {
            return self.inject_messages_and_stream(follow);
        }

        // Check early termination hint
        if should_terminate {
            debug!("tool batch requested termination");
            events.push(AgentEvent::AgentEnd {
                messages: self.state.messages.clone(),
            });
            self.phase = Phase::Idle;
            self.state.is_streaming = false;
            return (
                events,
                vec![AgentAction::Finished {
                    messages: self.state.messages.clone(),
                }],
            );
        }

        // Continue with another LLM call
        self.phase = Phase::Streaming;
        debug!("tool batch finished; requesting next llm turn");
        events.push(AgentEvent::TurnStart);
        let actions = vec![AgentAction::StreamLlm {
            context: self.build_llm_context(),
            session_id: self.session_id.clone(),
        }];

        (events, actions)
    }

    /// Called by the host when a tool starts executing.
    /// Emits a ToolExecutionUpdate event for trace/observability.
    /// Does not change the core state machine phase.
    pub fn on_tool_started(&mut self, tool_call_id: ToolCallId) -> Vec<AgentEvent> {
        if self.phase != Phase::ExecutingTools {
            trace!(phase = ?self.phase, "on_tool_started outside executing tools phase");
            return vec![];
        }
        if !self.pending_tool_calls.contains_key(&tool_call_id) {
            trace!(tool_call_id = tool_call_id.as_str(), "on_tool_started for unknown tool");
            return vec![];
        }
        trace!(tool_call_id = tool_call_id.as_str(), "tool execution started");
        vec![AgentEvent::ToolExecutionUpdate {
            tool_call_id,
            stream: crate::events::ToolOutputStream::Status,
            chunk: "[started]".to_string(),
            sequence: 0,
            timestamp: current_timestamp(),
        }]
    }

    /// Called by the host with a streaming chunk from a running tool.
    /// Emits a ToolExecutionUpdate event for trace/observability only.
    /// Does NOT add to the canonical model transcript.
    pub fn on_tool_update(&mut self, update: ToolExecutionUpdate) -> Vec<AgentEvent> {
        if self.phase != Phase::ExecutingTools {
            return vec![];
        }
        if !self.pending_tool_calls.contains_key(&update.tool_call_id) {
            return vec![];
        }
        trace!(
            tool_call_id = update.tool_call_id.as_str(),
            stream = ?update.stream,
            seq = update.sequence,
            bytes = update.chunk.len(),
            "tool execution update"
        );
        vec![AgentEvent::ToolExecutionUpdate {
            tool_call_id: update.tool_call_id,
            stream: update.stream,
            chunk: update.chunk,
            sequence: update.sequence,
            timestamp: update.timestamp,
        }]
    }

    /// Called by the host when a tool is cancelled.
    /// Treats cancellation like a tool error result so the state machine can advance.
    pub fn on_tool_cancelled(
        &mut self,
        tool_call_id: ToolCallId,
        reason: CancelReason,
    ) -> (Vec<AgentEvent>, Vec<AgentAction>) {
        if self.phase != Phase::ExecutingTools {
            return (vec![], vec![]);
        }

        let tool_call = match self.pending_tool_calls.remove(&tool_call_id) {
            Some(tc) => tc,
            None => {
                warn!(tool_call_id = tool_call_id.as_str(), "on_tool_cancelled for unknown tool");
                return (vec![], vec![]);
            }
        };
        self.state
            .pending_tool_calls
            .retain(|id| id != tool_call_id.as_str());

        let reason_str = match &reason {
            CancelReason::UserRequested => "cancelled by user".to_string(),
            CancelReason::Timeout => "cancelled due to timeout".to_string(),
            CancelReason::AgentAborted => "cancelled due to agent abort".to_string(),
            CancelReason::DependencyFailed { cause_tool_call_id } => {
                format!("cancelled because dependency {} failed", cause_tool_call_id.as_str())
            }
        };

        let result_msg = ToolResultMessage {
            role: "tool_result".to_string(),
            tool_call_id: tool_call_id.clone(),
            tool_name: tool_call.name.clone(),
            content: vec![Content::Text(crate::message::TextContent {
                text: format!("Tool execution was cancelled: {}", reason_str),
            })],
            details: None,
            is_error: true,
            timestamp: current_timestamp(),
        };

        let mut events = vec![
            AgentEvent::ToolExecutionCancelled {
                tool_call_id: tool_call_id.clone(),
                reason,
            },
            AgentEvent::ToolExecutionEnd {
                tool_call_id: tool_call_id.clone(),
                result: ToolResult {
                    content: result_msg.content.clone(),
                    details: None,
                    terminate: None,
                },
                is_error: true,
            },
        ];

        let agent_msg = AgentMessage::ToolResult(result_msg);
        self.completed_tool_results.push(
            match &agent_msg {
                AgentMessage::ToolResult(m) => m.clone(),
                _ => unreachable!(),
            },
        );
        self.completed_tool_terminations.push(false);
        self.state.messages.push(agent_msg.clone());
        events.push(AgentEvent::MessageStart {
            message: agent_msg.clone(),
        });
        events.push(AgentEvent::MessageEnd {
            message: agent_msg.clone(),
        });

        // If all tools are done, advance the state machine
        if !self.pending_tool_calls.is_empty() {
            return (events, vec![]);
        }

        // All tools done
        let assistant_msg = self
            .state
            .messages
            .iter()
            .rev()
            .find(|msg| matches!(msg, AgentMessage::Assistant(_)))
            .cloned()
            .unwrap_or_else(|| agent_msg.clone());
        let tool_results = std::mem::take(&mut self.completed_tool_results);
        self.completed_tool_terminations.clear();

        events.push(AgentEvent::TurnEnd {
            message: assistant_msg,
            tool_results,
        });

        let steering = self.drain_steering();
        if !steering.is_empty() {
            return self.inject_messages_and_stream(steering);
        }

        let follow = self.drain_follow_up();
        if !follow.is_empty() {
            return self.inject_messages_and_stream(follow);
        }

        self.phase = Phase::Streaming;
        events.push(AgentEvent::TurnStart);
        let actions = vec![AgentAction::StreamLlm {
            context: self.build_llm_context(),
            session_id: self.session_id.clone(),
        }];

        (events, actions)
    }

    /// Inject a steering message mid-run.
    pub fn steer(&mut self, message: AgentMessage) -> Vec<AgentEvent> {
        self.steering_queue.push(message);
        debug!(
            queued = self.steering_queue.len(),
            "steering message queued"
        );
        vec![AgentEvent::QueueUpdate {
            steer: self.steering_queue.clone(),
            follow_up: self.follow_up_queue.clone(),
        }]
    }

    /// Queue a follow-up message for after the run would otherwise stop.
    pub fn follow_up(&mut self, message: AgentMessage) {
        self.follow_up_queue.push(message);
        debug!(
            queued = self.follow_up_queue.len(),
            "follow-up message queued"
        );
    }

    /// Abort the current run.
    pub fn abort(&mut self) -> Vec<AgentEvent> {
        warn!(phase = ?self.phase, "agent aborted");
        self.steering_queue.clear();
        self.follow_up_queue.clear();
        self.pending_tool_calls.clear();
        self.completed_tool_results.clear();
        self.completed_tool_terminations.clear();
        self.state.pending_tool_calls.clear();
        self.state.is_streaming = false;
        self.state.streaming_message = None;
        self.phase = Phase::Idle;

        vec![
            AgentEvent::QueueUpdate {
                steer: vec![],
                follow_up: vec![],
            },
            AgentEvent::AgentEnd {
                messages: self.state.messages.clone(),
            },
        ]
    }

    /// Read-only access to current state.
    pub fn state(&self) -> &AgentState {
        &self.state
    }

    /// Reset state (clear messages, queues, runtime state).
    pub fn reset(&mut self) {
        debug!("agent state reset");
        self.state.messages.clear();
        self.state.is_streaming = false;
        self.state.streaming_message = None;
        self.state.pending_tool_calls.clear();
        self.state.error_message = None;
        self.steering_queue.clear();
        self.follow_up_queue.clear();
        self.pending_tool_calls.clear();
        self.completed_tool_results.clear();
        self.completed_tool_terminations.clear();
        self.phase = Phase::Idle;
    }

    // --- private helpers ---

    fn build_llm_context(&self) -> LlmContext {
        LlmContext {
            system_prompt: self.state.system_prompt.clone(),
            messages: self.state.messages.clone(),
            tools: self.state.tools.clone(),
        }
    }

    fn drain_steering(&mut self) -> Vec<AgentMessage> {
        if self.steering_mode == QueueMode::All {
            std::mem::take(&mut self.steering_queue)
        } else {
            if self.steering_queue.is_empty() {
                vec![]
            } else {
                vec![self.steering_queue.remove(0)]
            }
        }
    }

    fn drain_follow_up(&mut self) -> Vec<AgentMessage> {
        if self.follow_up_mode == QueueMode::All {
            std::mem::take(&mut self.follow_up_queue)
        } else {
            if self.follow_up_queue.is_empty() {
                vec![]
            } else {
                vec![self.follow_up_queue.remove(0)]
            }
        }
    }

    fn inject_messages_and_stream(
        &mut self,
        messages: Vec<AgentMessage>,
    ) -> (Vec<AgentEvent>, Vec<AgentAction>) {
        let mut events = Vec::new();

        for msg in messages {
            events.push(AgentEvent::MessageStart {
                message: msg.clone(),
            });
            self.state.messages.push(msg.clone());
            events.push(AgentEvent::MessageEnd {
                message: msg.clone(),
            });
        }

        self.phase = Phase::Streaming;
        self.state.is_streaming = true;
        events.push(AgentEvent::TurnStart);

        let actions = vec![AgentAction::StreamLlm {
            context: self.build_llm_context(),
            session_id: self.session_id.clone(),
        }];

        (events, actions)
    }
}

fn current_timestamp() -> u64 {
    crate::timestamp::current_timestamp()
}

/// Helper trait for extracting assistant text.
pub trait AssistantTextExt {
    fn assistant_text(&self) -> String;
}

impl AssistantTextExt for AgentMessage {
    fn assistant_text(&self) -> String {
        match self {
            AgentMessage::Assistant(a) => a
                .content
                .iter()
                .filter_map(|c| match c {
                    Content::Text(t) => Some(t.text.clone()),
                    _ => None,
                })
                .collect(),
            _ => String::new(),
        }
    }
}