Skip to main content

pi_core/
agent.rs

1use ts_rs::TS;
2use serde::{Deserialize, Serialize};
3use std::collections::HashMap;
4
5use crate::context::LlmContext;
6use crate::events::{AgentAction, AgentEvent, CancelReason, ContentDelta, QueueMode, ThinkingLevel, ToolExecutionUpdate, WaitMode};
7use crate::llm::{LlmChunk, LlmResult, Model};
8use crate::message::{AgentMessage, Content, StopReason, ToolCall, ToolResultMessage};
9use crate::tool::{ToolDefinition, ToolError, ToolExecutionMode, ToolResult};
10use crate::types::{SessionId, ToolCallId};
11use tracing::{debug, trace, warn};
12
13/// Public agent state.
14#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, TS)]
15#[ts(export)]
16pub struct AgentState {
17    pub system_prompt: String,
18    pub model: Model,
19    pub thinking_level: ThinkingLevel,
20    pub tools: Vec<ToolDefinition>,
21    pub messages: Vec<AgentMessage>,
22    pub is_streaming: bool,
23    #[serde(skip_serializing_if = "Option::is_none")]
24    pub streaming_message: Option<AgentMessage>,
25    pub pending_tool_calls: Vec<String>,
26    #[serde(skip_serializing_if = "Option::is_none")]
27    pub error_message: Option<String>,
28}
29
30/// Options for constructing an Agent.
31#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, TS)]
32pub struct AgentOptions {
33    pub system_prompt: String,
34    pub model: Model,
35    #[serde(default)]
36    pub thinking_level: ThinkingLevel,
37    #[serde(default)]
38    pub tools: Vec<ToolDefinition>,
39    #[serde(default)]
40    pub steering_mode: QueueMode,
41    #[serde(default)]
42    pub follow_up_mode: QueueMode,
43    #[serde(default)]
44    pub tool_execution_mode: ToolExecutionMode,
45    #[serde(skip_serializing_if = "Option::is_none")]
46    pub session_id: Option<SessionId>,
47    #[serde(default)]
48    pub messages: Vec<AgentMessage>,
49}
50
51/// Internal phase of the agent state machine.
52#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize, TS)]
53#[serde(rename_all = "snake_case")]
54pub enum Phase {
55    Idle,
56    Streaming,
57    ExecutingTools,
58    WaitForInput,
59}
60
61/// The agent state machine. Purely synchronous; the host drives progress.
62pub struct Agent {
63    state: AgentState,
64    steering_queue: Vec<AgentMessage>,
65    follow_up_queue: Vec<AgentMessage>,
66    pub phase: Phase,
67    pending_tool_calls: HashMap<ToolCallId, ToolCall>,
68    completed_tool_results: Vec<ToolResultMessage>,
69    completed_tool_terminations: Vec<bool>,
70    steering_mode: QueueMode,
71    follow_up_mode: QueueMode,
72    #[allow(dead_code)]
73    tool_execution_mode: ToolExecutionMode,
74    session_id: Option<SessionId>,
75}
76
77impl Agent {
78    pub fn new(options: AgentOptions) -> Self {
79        Self {
80            state: AgentState {
81                system_prompt: options.system_prompt,
82                model: options.model,
83                thinking_level: options.thinking_level,
84                tools: options.tools,
85                messages: options.messages,
86                is_streaming: false,
87                streaming_message: None,
88                pending_tool_calls: Vec::new(),
89                error_message: None,
90            },
91            steering_queue: Vec::new(),
92            follow_up_queue: Vec::new(),
93            phase: Phase::Idle,
94            pending_tool_calls: HashMap::new(),
95            completed_tool_results: Vec::new(),
96            completed_tool_terminations: Vec::new(),
97            steering_mode: options.steering_mode,
98            follow_up_mode: options.follow_up_mode,
99            tool_execution_mode: options.tool_execution_mode,
100            session_id: options.session_id,
101        }
102    }
103
104    /// Start processing a new prompt.
105    pub fn start_turn(&mut self, prompt: AgentMessage) -> (Vec<AgentEvent>, Vec<AgentAction>) {
106        if self.phase != Phase::Idle {
107            warn!(phase = ?self.phase, "start_turn requested while agent is not idle");
108            return (
109                vec![AgentEvent::AgentStart],
110                vec![AgentAction::WaitForInput {
111                    mode: WaitMode::Any,
112                }],
113            );
114        }
115
116        self.state.messages.push(prompt.clone());
117        debug!(
118            message_count = self.state.messages.len(),
119            "agent turn started"
120        );
121        let events = vec![
122            AgentEvent::AgentStart,
123            AgentEvent::TurnStart,
124            AgentEvent::MessageStart { message: prompt },
125            AgentEvent::MessageEnd {
126                message: self.state.messages.last().unwrap().clone(),
127            },
128        ];
129
130        self.phase = Phase::Streaming;
131        self.state.is_streaming = true;
132
133        let actions = vec![AgentAction::StreamLlm {
134            context: self.build_llm_context(),
135            session_id: self.session_id.clone(),
136        }];
137
138        (events, actions)
139    }
140
141    /// Continue from the current transcript without adding a new message.
142    pub fn continue_turn(&mut self) -> (Vec<AgentEvent>, Vec<AgentAction>) {
143        if self.phase != Phase::Idle {
144            warn!(phase = ?self.phase, "continue_turn requested while agent is not idle");
145            return (vec![], vec![]);
146        }
147
148        let last = self.state.messages.last();
149        if let Some(AgentMessage::Assistant(_)) = last {
150            // Check steering queue first
151            let drained = self.drain_steering();
152            if !drained.is_empty() {
153                return self.inject_messages_and_stream(drained);
154            }
155
156            let follow = self.drain_follow_up();
157            if !follow.is_empty() {
158                return self.inject_messages_and_stream(follow);
159            }
160
161            return (
162                vec![],
163                vec![AgentAction::WaitForInput {
164                    mode: WaitMode::Any,
165                }],
166            );
167        }
168
169        self.phase = Phase::Streaming;
170        self.state.is_streaming = true;
171
172        let events = vec![AgentEvent::AgentStart, AgentEvent::TurnStart];
173        let actions = vec![AgentAction::StreamLlm {
174            context: self.build_llm_context(),
175            session_id: self.session_id.clone(),
176        }];
177
178        (events, actions)
179    }
180
181    /// Feed a streaming chunk from the LLM.
182    pub fn feed_llm_chunk(&mut self, chunk: LlmChunk) -> Vec<AgentEvent> {
183        if self.phase != Phase::Streaming {
184            trace!(phase = ?self.phase, "ignored llm chunk outside streaming phase");
185            return vec![];
186        }
187
188        let mut events = Vec::new();
189
190        match chunk {
191            LlmChunk::Start { mut partial } => {
192                trace!("llm stream started");
193                partial.timestamp = current_timestamp();
194                let msg = AgentMessage::Assistant(partial.clone());
195                self.state.messages.push(msg.clone());
196                self.state.streaming_message = Some(msg.clone());
197                events.push(AgentEvent::MessageStart { message: msg });
198            }
199            LlmChunk::TextDelta { text } => {
200                trace!(bytes = text.len(), "llm text delta");
201                if let Some(AgentMessage::Assistant(ref mut a)) = self.state.messages.last_mut() {
202                    if let Some(Content::Text(ref mut t)) = a.content.last_mut() {
203                        t.text.push_str(&text);
204                    } else {
205                        a.content
206                            .push(Content::Text(crate::message::TextContent { text }));
207                    }
208                    let msg = AgentMessage::Assistant(a.clone());
209                    self.state.streaming_message = Some(msg.clone());
210                    events.push(AgentEvent::MessageUpdate {
211                        message: msg.clone(),
212                        delta: ContentDelta::TextDelta {
213                            text: msg.assistant_text(),
214                        },
215                    });
216                }
217            }
218            LlmChunk::ToolCallDelta {
219                tool_call_id,
220                delta,
221            } => {
222                if let Some(AgentMessage::Assistant(ref mut a)) = self.state.messages.last_mut() {
223                    events.push(AgentEvent::MessageUpdate {
224                        message: AgentMessage::Assistant(a.clone()),
225                        delta: ContentDelta::ToolCallDelta {
226                            tool_call_id,
227                            delta,
228                        },
229                    });
230                }
231            }
232            LlmChunk::ThinkingDelta { text } => {
233                if let Some(AgentMessage::Assistant(ref mut a)) = self.state.messages.last_mut() {
234                    events.push(AgentEvent::MessageUpdate {
235                        message: AgentMessage::Assistant(a.clone()),
236                        delta: ContentDelta::ThinkingDelta { text },
237                    });
238                }
239            }
240            LlmChunk::Done | LlmChunk::Error { .. } => {
241                // Handled in on_llm_done
242            }
243        }
244
245        events
246    }
247
248    /// Called by the host when the LLM stream ends.
249    pub fn on_llm_done(&mut self, result: LlmResult) -> (Vec<AgentEvent>, Vec<AgentAction>) {
250        if self.phase != Phase::Streaming {
251            warn!(phase = ?self.phase, "on_llm_done requested outside streaming phase");
252            return (vec![], vec![]);
253        }
254
255        let mut events = Vec::new();
256        let mut actions = Vec::new();
257
258        let assistant_msg = result.finalize_message();
259        let msg = AgentMessage::Assistant(assistant_msg.clone());
260
261        // Update the last message (which may have been a streaming partial)
262        if let Some(AgentMessage::Assistant(_)) = self.state.messages.last() {
263            *self.state.messages.last_mut().unwrap() = msg.clone();
264        } else {
265            self.state.messages.push(msg.clone());
266        }
267
268        self.state.streaming_message = None;
269        events.push(AgentEvent::MessageEnd {
270            message: msg.clone(),
271        });
272
273        // Check for error / abort
274        if matches!(
275            assistant_msg.stop_reason,
276            StopReason::Error | StopReason::Aborted
277        ) {
278            warn!(
279                stop_reason = ?assistant_msg.stop_reason,
280                error = ?assistant_msg.error_message,
281                "llm stream ended with failure"
282            );
283            self.state.error_message = assistant_msg.error_message.clone();
284            events.push(AgentEvent::TurnEnd {
285                message: msg,
286                tool_results: vec![],
287            });
288            events.push(AgentEvent::AgentEnd {
289                messages: self.state.messages.clone(),
290            });
291            self.phase = Phase::Idle;
292            self.state.is_streaming = false;
293            actions.push(AgentAction::Finished {
294                messages: self.state.messages.clone(),
295            });
296            return (events, actions);
297        }
298
299        // Check for tool calls
300        let tool_calls: Vec<ToolCall> = assistant_msg
301            .content
302            .iter()
303            .filter_map(|c| match c {
304                Content::ToolCall(tc) => Some(tc.clone()),
305                _ => None,
306            })
307            .collect();
308
309        if tool_calls.is_empty() {
310            debug!("assistant turn finished without tool calls");
311            // No tools: turn ends
312            events.push(AgentEvent::TurnEnd {
313                message: msg,
314                tool_results: vec![],
315            });
316
317            // Check steering / follow-up queues
318            let steering = self.drain_steering();
319            if !steering.is_empty() {
320                return self.inject_messages_and_stream(steering);
321            }
322
323            let follow = self.drain_follow_up();
324            if !follow.is_empty() {
325                return self.inject_messages_and_stream(follow);
326            }
327
328            // Run complete
329            events.push(AgentEvent::AgentEnd {
330                messages: self.state.messages.clone(),
331            });
332            self.phase = Phase::Idle;
333            self.state.is_streaming = false;
334            actions.push(AgentAction::Finished {
335                messages: self.state.messages.clone(),
336            });
337            return (events, actions);
338        }
339
340        // Execute tools
341        self.phase = Phase::ExecutingTools;
342        debug!(
343            tool_call_count = tool_calls.len(),
344            "assistant requested tool execution"
345        );
346        for tc in &tool_calls {
347            self.pending_tool_calls.insert(tc.id.clone(), tc.clone());
348            self.state.pending_tool_calls.push(tc.id.0.clone());
349            events.push(AgentEvent::ToolExecutionStart {
350                tool_call_id: tc.id.clone(),
351                tool_name: tc.name.clone(),
352                args: Some(tc.arguments.clone()),
353            });
354        }
355        actions.push(AgentAction::ExecuteTools { calls: tool_calls });
356
357        (events, actions)
358    }
359
360    /// Called by the host when a tool finishes executing.
361    pub fn on_tool_done(
362        &mut self,
363        tool_call_id: ToolCallId,
364        result: Result<ToolResult, ToolError>,
365    ) -> (Vec<AgentEvent>, Vec<AgentAction>) {
366        if self.phase != Phase::ExecutingTools {
367            warn!(phase = ?self.phase, "on_tool_done requested outside executing tools phase");
368            return (vec![], vec![]);
369        }
370
371        let mut events = Vec::new();
372        let tool_call = match self.pending_tool_calls.remove(&tool_call_id) {
373            Some(tc) => tc,
374            None => {
375                warn!(
376                    tool_call_id = tool_call_id.as_str(),
377                    "unknown tool completion ignored"
378                );
379                return (vec![], vec![]);
380            }
381        };
382        self.state
383            .pending_tool_calls
384            .retain(|id| id != tool_call_id.as_str());
385
386        let (tool_result, is_error) = match result {
387            Ok(r) => (r, false),
388            Err(e) => (
389                ToolResult {
390                    content: vec![Content::Text(crate::message::TextContent {
391                        text: e.message.clone(),
392                    })],
393                    details: None,
394                    terminate: None,
395                },
396                true,
397            ),
398        };
399
400        let result_msg = ToolResultMessage {
401            role: "tool_result".to_string(),
402            tool_call_id: tool_call_id.clone(),
403            tool_name: tool_call.name.clone(),
404            content: tool_result.content.clone(),
405            details: tool_result.details.clone(),
406            is_error,
407            timestamp: current_timestamp(),
408        };
409
410        events.push(AgentEvent::ToolExecutionEnd {
411            tool_call_id: tool_call_id.clone(),
412            result: tool_result.clone(),
413            is_error,
414        });
415
416        let agent_msg = AgentMessage::ToolResult(result_msg);
417        if let AgentMessage::ToolResult(msg) = &agent_msg {
418            self.completed_tool_terminations
419                .push(tool_result.terminate == Some(true));
420            self.completed_tool_results.push(msg.clone());
421        }
422        self.state.messages.push(agent_msg.clone());
423        events.push(AgentEvent::MessageStart {
424            message: agent_msg.clone(),
425        });
426        events.push(AgentEvent::MessageEnd {
427            message: agent_msg.clone(),
428        });
429
430        // Check if all pending tools are done
431        if !self.pending_tool_calls.is_empty() {
432            trace!(
433                pending_tool_calls = self.pending_tool_calls.len(),
434                "waiting for remaining tools"
435            );
436            return (events, vec![]);
437        }
438
439        // All tools done: end turn
440        let assistant_msg = self
441            .state
442            .messages
443            .iter()
444            .rev()
445            .find(|msg| matches!(msg, AgentMessage::Assistant(_)))
446            .cloned()
447            .unwrap_or_else(|| agent_msg.clone());
448        let tool_results = std::mem::take(&mut self.completed_tool_results);
449        let should_terminate = !self.completed_tool_terminations.is_empty()
450            && self
451                .completed_tool_terminations
452                .iter()
453                .all(|terminate| *terminate);
454        self.completed_tool_terminations.clear();
455
456        events.push(AgentEvent::TurnEnd {
457            message: assistant_msg,
458            tool_results,
459        });
460
461        // Check for steering / follow-up
462        let steering = self.drain_steering();
463        if !steering.is_empty() {
464            return self.inject_messages_and_stream(steering);
465        }
466
467        let follow = self.drain_follow_up();
468        if !follow.is_empty() {
469            return self.inject_messages_and_stream(follow);
470        }
471
472        // Check early termination hint
473        if should_terminate {
474            debug!("tool batch requested termination");
475            events.push(AgentEvent::AgentEnd {
476                messages: self.state.messages.clone(),
477            });
478            self.phase = Phase::Idle;
479            self.state.is_streaming = false;
480            return (
481                events,
482                vec![AgentAction::Finished {
483                    messages: self.state.messages.clone(),
484                }],
485            );
486        }
487
488        // Continue with another LLM call
489        self.phase = Phase::Streaming;
490        debug!("tool batch finished; requesting next llm turn");
491        events.push(AgentEvent::TurnStart);
492        let actions = vec![AgentAction::StreamLlm {
493            context: self.build_llm_context(),
494            session_id: self.session_id.clone(),
495        }];
496
497        (events, actions)
498    }
499
500    /// Called by the host when a tool starts executing.
501    /// Emits a ToolExecutionUpdate event for trace/observability.
502    /// Does not change the core state machine phase.
503    pub fn on_tool_started(&mut self, tool_call_id: ToolCallId) -> Vec<AgentEvent> {
504        if self.phase != Phase::ExecutingTools {
505            trace!(phase = ?self.phase, "on_tool_started outside executing tools phase");
506            return vec![];
507        }
508        if !self.pending_tool_calls.contains_key(&tool_call_id) {
509            trace!(tool_call_id = tool_call_id.as_str(), "on_tool_started for unknown tool");
510            return vec![];
511        }
512        trace!(tool_call_id = tool_call_id.as_str(), "tool execution started");
513        vec![AgentEvent::ToolExecutionUpdate {
514            tool_call_id,
515            stream: crate::events::ToolOutputStream::Status,
516            chunk: "[started]".to_string(),
517            sequence: 0,
518            timestamp: current_timestamp(),
519        }]
520    }
521
522    /// Called by the host with a streaming chunk from a running tool.
523    /// Emits a ToolExecutionUpdate event for trace/observability only.
524    /// Does NOT add to the canonical model transcript.
525    pub fn on_tool_update(&mut self, update: ToolExecutionUpdate) -> Vec<AgentEvent> {
526        if self.phase != Phase::ExecutingTools {
527            return vec![];
528        }
529        if !self.pending_tool_calls.contains_key(&update.tool_call_id) {
530            return vec![];
531        }
532        trace!(
533            tool_call_id = update.tool_call_id.as_str(),
534            stream = ?update.stream,
535            seq = update.sequence,
536            bytes = update.chunk.len(),
537            "tool execution update"
538        );
539        vec![AgentEvent::ToolExecutionUpdate {
540            tool_call_id: update.tool_call_id,
541            stream: update.stream,
542            chunk: update.chunk,
543            sequence: update.sequence,
544            timestamp: update.timestamp,
545        }]
546    }
547
548    /// Called by the host when a tool is cancelled.
549    /// Treats cancellation like a tool error result so the state machine can advance.
550    pub fn on_tool_cancelled(
551        &mut self,
552        tool_call_id: ToolCallId,
553        reason: CancelReason,
554    ) -> (Vec<AgentEvent>, Vec<AgentAction>) {
555        if self.phase != Phase::ExecutingTools {
556            return (vec![], vec![]);
557        }
558
559        let tool_call = match self.pending_tool_calls.remove(&tool_call_id) {
560            Some(tc) => tc,
561            None => {
562                warn!(tool_call_id = tool_call_id.as_str(), "on_tool_cancelled for unknown tool");
563                return (vec![], vec![]);
564            }
565        };
566        self.state
567            .pending_tool_calls
568            .retain(|id| id != tool_call_id.as_str());
569
570        let reason_str = match &reason {
571            CancelReason::UserRequested => "cancelled by user".to_string(),
572            CancelReason::Timeout => "cancelled due to timeout".to_string(),
573            CancelReason::AgentAborted => "cancelled due to agent abort".to_string(),
574            CancelReason::DependencyFailed { cause_tool_call_id } => {
575                format!("cancelled because dependency {} failed", cause_tool_call_id.as_str())
576            }
577        };
578
579        let result_msg = ToolResultMessage {
580            role: "tool_result".to_string(),
581            tool_call_id: tool_call_id.clone(),
582            tool_name: tool_call.name.clone(),
583            content: vec![Content::Text(crate::message::TextContent {
584                text: format!("Tool execution was cancelled: {}", reason_str),
585            })],
586            details: None,
587            is_error: true,
588            timestamp: current_timestamp(),
589        };
590
591        let mut events = vec![
592            AgentEvent::ToolExecutionCancelled {
593                tool_call_id: tool_call_id.clone(),
594                reason,
595            },
596            AgentEvent::ToolExecutionEnd {
597                tool_call_id: tool_call_id.clone(),
598                result: ToolResult {
599                    content: result_msg.content.clone(),
600                    details: None,
601                    terminate: None,
602                },
603                is_error: true,
604            },
605        ];
606
607        let agent_msg = AgentMessage::ToolResult(result_msg);
608        self.completed_tool_results.push(
609            match &agent_msg {
610                AgentMessage::ToolResult(m) => m.clone(),
611                _ => unreachable!(),
612            },
613        );
614        self.completed_tool_terminations.push(false);
615        self.state.messages.push(agent_msg.clone());
616        events.push(AgentEvent::MessageStart {
617            message: agent_msg.clone(),
618        });
619        events.push(AgentEvent::MessageEnd {
620            message: agent_msg.clone(),
621        });
622
623        // If all tools are done, advance the state machine
624        if !self.pending_tool_calls.is_empty() {
625            return (events, vec![]);
626        }
627
628        // All tools done
629        let assistant_msg = self
630            .state
631            .messages
632            .iter()
633            .rev()
634            .find(|msg| matches!(msg, AgentMessage::Assistant(_)))
635            .cloned()
636            .unwrap_or_else(|| agent_msg.clone());
637        let tool_results = std::mem::take(&mut self.completed_tool_results);
638        self.completed_tool_terminations.clear();
639
640        events.push(AgentEvent::TurnEnd {
641            message: assistant_msg,
642            tool_results,
643        });
644
645        let steering = self.drain_steering();
646        if !steering.is_empty() {
647            return self.inject_messages_and_stream(steering);
648        }
649
650        let follow = self.drain_follow_up();
651        if !follow.is_empty() {
652            return self.inject_messages_and_stream(follow);
653        }
654
655        self.phase = Phase::Streaming;
656        events.push(AgentEvent::TurnStart);
657        let actions = vec![AgentAction::StreamLlm {
658            context: self.build_llm_context(),
659            session_id: self.session_id.clone(),
660        }];
661
662        (events, actions)
663    }
664
665    /// Inject a steering message mid-run.
666    pub fn steer(&mut self, message: AgentMessage) -> Vec<AgentEvent> {
667        self.steering_queue.push(message);
668        debug!(
669            queued = self.steering_queue.len(),
670            "steering message queued"
671        );
672        vec![AgentEvent::QueueUpdate {
673            steer: self.steering_queue.clone(),
674            follow_up: self.follow_up_queue.clone(),
675        }]
676    }
677
678    /// Queue a follow-up message for after the run would otherwise stop.
679    pub fn follow_up(&mut self, message: AgentMessage) {
680        self.follow_up_queue.push(message);
681        debug!(
682            queued = self.follow_up_queue.len(),
683            "follow-up message queued"
684        );
685    }
686
687    /// Abort the current run.
688    pub fn abort(&mut self) -> Vec<AgentEvent> {
689        warn!(phase = ?self.phase, "agent aborted");
690        self.steering_queue.clear();
691        self.follow_up_queue.clear();
692        self.pending_tool_calls.clear();
693        self.completed_tool_results.clear();
694        self.completed_tool_terminations.clear();
695        self.state.pending_tool_calls.clear();
696        self.state.is_streaming = false;
697        self.state.streaming_message = None;
698        self.phase = Phase::Idle;
699
700        vec![
701            AgentEvent::QueueUpdate {
702                steer: vec![],
703                follow_up: vec![],
704            },
705            AgentEvent::AgentEnd {
706                messages: self.state.messages.clone(),
707            },
708        ]
709    }
710
711    /// Read-only access to current state.
712    pub fn state(&self) -> &AgentState {
713        &self.state
714    }
715
716    /// Reset state (clear messages, queues, runtime state).
717    pub fn reset(&mut self) {
718        debug!("agent state reset");
719        self.state.messages.clear();
720        self.state.is_streaming = false;
721        self.state.streaming_message = None;
722        self.state.pending_tool_calls.clear();
723        self.state.error_message = None;
724        self.steering_queue.clear();
725        self.follow_up_queue.clear();
726        self.pending_tool_calls.clear();
727        self.completed_tool_results.clear();
728        self.completed_tool_terminations.clear();
729        self.phase = Phase::Idle;
730    }
731
732    // --- private helpers ---
733
734    fn build_llm_context(&self) -> LlmContext {
735        LlmContext {
736            system_prompt: self.state.system_prompt.clone(),
737            messages: self.state.messages.clone(),
738            tools: self.state.tools.clone(),
739        }
740    }
741
742    fn drain_steering(&mut self) -> Vec<AgentMessage> {
743        if self.steering_mode == QueueMode::All {
744            std::mem::take(&mut self.steering_queue)
745        } else {
746            if self.steering_queue.is_empty() {
747                vec![]
748            } else {
749                vec![self.steering_queue.remove(0)]
750            }
751        }
752    }
753
754    fn drain_follow_up(&mut self) -> Vec<AgentMessage> {
755        if self.follow_up_mode == QueueMode::All {
756            std::mem::take(&mut self.follow_up_queue)
757        } else {
758            if self.follow_up_queue.is_empty() {
759                vec![]
760            } else {
761                vec![self.follow_up_queue.remove(0)]
762            }
763        }
764    }
765
766    fn inject_messages_and_stream(
767        &mut self,
768        messages: Vec<AgentMessage>,
769    ) -> (Vec<AgentEvent>, Vec<AgentAction>) {
770        let mut events = Vec::new();
771
772        for msg in messages {
773            events.push(AgentEvent::MessageStart {
774                message: msg.clone(),
775            });
776            self.state.messages.push(msg.clone());
777            events.push(AgentEvent::MessageEnd {
778                message: msg.clone(),
779            });
780        }
781
782        self.phase = Phase::Streaming;
783        self.state.is_streaming = true;
784        events.push(AgentEvent::TurnStart);
785
786        let actions = vec![AgentAction::StreamLlm {
787            context: self.build_llm_context(),
788            session_id: self.session_id.clone(),
789        }];
790
791        (events, actions)
792    }
793}
794
795fn current_timestamp() -> u64 {
796    crate::timestamp::current_timestamp()
797}
798
799/// Helper trait for extracting assistant text.
800pub trait AssistantTextExt {
801    fn assistant_text(&self) -> String;
802}
803
804impl AssistantTextExt for AgentMessage {
805    fn assistant_text(&self) -> String {
806        match self {
807            AgentMessage::Assistant(a) => a
808                .content
809                .iter()
810                .filter_map(|c| match c {
811                    Content::Text(t) => Some(t.text.clone()),
812                    _ => None,
813                })
814                .collect(),
815            _ => String::new(),
816        }
817    }
818}