Skip to main content

vtcode_core/core/agent/runtime/
mod.rs

1use crate::core::agent::events::{EventSink, SharedLifecycleEmitter};
2use crate::core::agent::session::AgentSessionState;
3use crate::core::agent::steering::{
4    FollowUpProvenance, FollowUpQueueFull, FollowUpSteer, MAX_APPLIED_FOLLOW_UP_INTENT_IDS,
5    MAX_OVERFLOW_FOLLOW_UP_INTENTS, MAX_PENDING_FOLLOW_UP_INTENTS, MAX_QUEUED_FOLLOW_UP_INTENTS, QueuedFollowUpIntent,
6    SteeringMessage,
7};
8use crate::exec::events::{ThreadEvent, ToolCallStatus, ToolOutcome};
9use crate::llm::provider::{
10    AssistantPhase, FinishReason, LLMProvider, LLMRequest, LLMResponse, NormalizedStreamEvent, ToolCall,
11    Usage as ProviderUsage,
12};
13use crate::llm::providers::gemini::wire::{Content, Part};
14use anyhow::Result;
15use async_trait::async_trait;
16use futures::StreamExt;
17use std::collections::HashSet;
18use std::collections::VecDeque;
19use std::time::Instant;
20use tokio::sync::mpsc::UnboundedReceiver;
21use tokio::sync::mpsc::error::TryRecvError;
22
23fn merge_stream_and_completed_text(accumulated: &mut String, completed: Option<&str>) {
24    let Some(completed_text) = completed else {
25        return;
26    };
27    if completed_text.is_empty() {
28        return;
29    }
30    if accumulated.is_empty() {
31        accumulated.push_str(completed_text);
32        return;
33    }
34    if completed_text == accumulated.as_str() {
35        return;
36    }
37    if let Some(suffix) = completed_text.strip_prefix(accumulated.as_str()) {
38        accumulated.push_str(suffix);
39        return;
40    }
41    accumulated.clear();
42    accumulated.push_str(completed_text);
43}
44
45mod steering;
46pub use steering::RuntimeSteering;
47
48/// Control signal returned when polling the steering channel between turns or tool calls.
49#[derive(Debug, Clone, Copy, PartialEq, Eq)]
50pub enum RuntimeControl {
51    /// No steering message pending; execution may proceed normally.
52    Continue,
53    /// Execution was paused and has now been resumed.
54    Resumed,
55    /// A stop request was received; the current turn should be cancelled.
56    StopRequested,
57}
58
59/// Progress event emitted by the model adapter during a streaming LLM response.
60#[doc(hidden)]
61#[derive(Debug, Clone, PartialEq, Eq)]
62pub enum RuntimeModelProgress {
63    /// A chunk of assistant output text.
64    OutputDelta(String),
65    /// A chunk of reasoning/thinking text.
66    ReasoningDelta(String),
67    /// The active reasoning stage label changed.
68    ReasoningStage(String),
69    /// The provider produced progress that is intentionally not user-visible.
70    ProviderActivity,
71    /// A new tool call began streaming.
72    ToolCallStarted {
73        /// Identifier of the tool call.
74        call_id: String,
75        /// Optional name of the tool being invoked.
76        name: Option<String>,
77    },
78    /// A chunk of arguments for an in-progress tool call.
79    ToolCallDelta {
80        /// Identifier of the tool call receiving the delta.
81        call_id: String,
82        /// Serialized argument fragment.
83        delta: String,
84    },
85}
86
87#[derive(Debug, Clone)]
88struct RuntimeModelOutput {
89    response: LLMResponse,
90}
91
92#[async_trait]
93trait RuntimeModelAdapter {
94    async fn execute(
95        &mut self,
96        request: LLMRequest,
97        timeout: Option<std::time::Duration>,
98        on_progress: &mut (dyn FnMut(RuntimeModelProgress) + Send),
99    ) -> Result<RuntimeModelOutput>;
100}
101
102struct ProviderRuntimeModelAdapter<'a> {
103    provider: &'a mut Box<dyn LLMProvider>,
104    steering: &'a mut RuntimeSteering,
105}
106
107impl<'a> ProviderRuntimeModelAdapter<'a> {
108    fn new(provider: &'a mut Box<dyn LLMProvider>, steering: &'a mut RuntimeSteering) -> Self {
109        Self { provider, steering }
110    }
111}
112
113#[async_trait]
114impl RuntimeModelAdapter for ProviderRuntimeModelAdapter<'_> {
115    async fn execute(
116        &mut self,
117        request: LLMRequest,
118        timeout: Option<std::time::Duration>,
119        on_progress: &mut (dyn FnMut(RuntimeModelProgress) + Send),
120    ) -> Result<RuntimeModelOutput> {
121        let started_at = Instant::now();
122        let request_model = request.model.clone();
123        let mut stream = if let Some(duration) = timeout {
124            match tokio::time::timeout(duration, self.provider.stream_normalized(request)).await {
125                Ok(result) => result?,
126                Err(_) => {
127                    tracing::warn!(model = %request_model, elapsed_ms = started_at.elapsed().as_millis() as u64, "model stream timed out");
128                    return Err(anyhow::anyhow!("Stream request timed out after {duration:?}"));
129                }
130            }
131        } else {
132            self.provider.stream_normalized(request).await?
133        };
134
135        let mut final_usage = ProviderUsage::default();
136        let mut completed_response: Option<LLMResponse> = None;
137        let mut provider_activity_reported = false;
138        while let Some(event_result) = stream.next().await {
139            if matches!(self.steering.poll_turn_control().await, RuntimeControl::StopRequested) {
140                tracing::info!(model = %request_model, elapsed_ms = started_at.elapsed().as_millis() as u64, "model stream cancelled");
141                let mut response = LLMResponse {
142                    model: request_model.clone(),
143                    finish_reason: FinishReason::Error("Cancelled".to_string()),
144                    usage: Some(final_usage.clone()),
145                    ..Default::default()
146                };
147                if response.usage.as_ref().is_some_and(|usage| {
148                    usage.prompt_tokens == 0 && usage.completion_tokens == 0 && usage.total_tokens == 0
149                }) {
150                    response.usage = None;
151                }
152                return Ok(RuntimeModelOutput { response });
153            }
154
155            match event_result? {
156                NormalizedStreamEvent::TextDelta { delta } => {
157                    on_progress(RuntimeModelProgress::OutputDelta(delta));
158                }
159                NormalizedStreamEvent::ReasoningDelta { delta, source } if source.is_public_summary() => {
160                    on_progress(RuntimeModelProgress::ReasoningDelta(delta));
161                }
162                NormalizedStreamEvent::ReasoningDelta { .. } => {
163                    if !provider_activity_reported {
164                        provider_activity_reported = true;
165                        on_progress(RuntimeModelProgress::ProviderActivity);
166                    }
167                }
168                NormalizedStreamEvent::ReasoningStage { stage } => {
169                    on_progress(RuntimeModelProgress::ReasoningStage(stage));
170                }
171                NormalizedStreamEvent::ToolCallStart { call_id, name } => {
172                    on_progress(RuntimeModelProgress::ToolCallStarted { call_id, name });
173                }
174                NormalizedStreamEvent::ToolCallDelta { call_id, delta } => {
175                    on_progress(RuntimeModelProgress::ToolCallDelta { call_id, delta });
176                }
177                NormalizedStreamEvent::Usage { usage } => {
178                    final_usage = usage;
179                }
180                NormalizedStreamEvent::Done { response } => {
181                    let mut response = *response;
182                    if response.usage.is_none()
183                        && (final_usage.prompt_tokens > 0
184                            || final_usage.completion_tokens > 0
185                            || final_usage.total_tokens > 0)
186                    {
187                        response.usage = Some(final_usage.clone());
188                    }
189                    completed_response = Some(response);
190                    break;
191                }
192            }
193        }
194
195        let mut response = completed_response.unwrap_or_default();
196        if response.model.is_empty() {
197            response.model = request_model;
198        }
199        if response.usage.is_none()
200            && (final_usage.prompt_tokens > 0 || final_usage.completion_tokens > 0 || final_usage.total_tokens > 0)
201        {
202            response.usage = Some(final_usage);
203        }
204
205        tracing::debug!(
206            model = %response.model,
207            elapsed_ms = started_at.elapsed().as_millis() as u64,
208            input_tokens = response.usage.as_ref().map_or(0, |usage| usage.prompt_tokens),
209            output_tokens = response.usage.as_ref().map_or(0, |usage| usage.completion_tokens),
210            finish_reason = ?response.finish_reason,
211            "model stream completed"
212        );
213        Ok(RuntimeModelOutput { response })
214    }
215}
216
217/// Result of executing a single LLM turn, containing the full response and extracted fields.
218pub struct TurnExecution {
219    /// The complete LLM response including usage and finish reason.
220    pub response: LLMResponse,
221    /// The accumulated assistant output text.
222    pub content: String,
223    /// The accumulated reasoning/thinking text, if present.
224    pub reasoning: Option<String>,
225}
226
227const MIN_REASONING_UPDATE_BYTES: usize = 256;
228const MAX_REASONING_UPDATE_EVENTS: usize = 2;
229const MIN_OUTPUT_UPDATE_BYTES: usize = 1024;
230const MAX_OUTPUT_UPDATE_EVENTS: usize = 64;
231
232mod throttle;
233use throttle::UpdateThrottle;
234
235/// Bridges streaming model progress events to the lifecycle event sink for real-time UI updates.
236#[doc(hidden)]
237pub struct StreamingLifecycleBridge {
238    event_sink: Option<EventSink>,
239    assistant_item_id: String,
240    reasoning_item_id: String,
241    lifecycle: SharedLifecycleEmitter,
242    /// Streamed tool calls keyed by provider call id, valued as
243    /// `(harness item id, tool name)` so turn teardown can close items whose
244    /// dispatch never happened with their real tool label.
245    tool_call_item_ids: hashbrown::HashMap<String, (String, String)>,
246    reasoning_stage: Option<String>,
247    output: UpdateThrottle,
248    reasoning: UpdateThrottle,
249}
250
251impl StreamingLifecycleBridge {
252    /// Stable identity used for the assistant item emitted by this bridge.
253    pub fn assistant_item_id(&self) -> &str {
254        &self.assistant_item_id
255    }
256
257    /// Create a new bridge that emits lifecycle events to the provided sink.
258    #[must_use]
259    pub fn new(event_sink: Option<EventSink>, turn_id: &str, step: usize, attempt: usize) -> Self {
260        Self {
261            event_sink,
262            assistant_item_id: format!("{turn_id}-step-{step}-assistant-stream-{attempt}"),
263            reasoning_item_id: format!("{turn_id}-step-{step}-reasoning-stream-{attempt}"),
264            lifecycle: SharedLifecycleEmitter::default(),
265            tool_call_item_ids: hashbrown::HashMap::new(),
266            reasoning_stage: None,
267            output: UpdateThrottle::new(),
268            reasoning: UpdateThrottle::new(),
269        }
270    }
271
272    /// Forward a streaming progress event to the lifecycle emitter and sink.
273    pub fn on_progress(&mut self, event: RuntimeModelProgress) {
274        match event {
275            RuntimeModelProgress::OutputDelta(delta) => self.push_assistant_delta(&delta),
276            RuntimeModelProgress::ReasoningDelta(delta) => self.push_reasoning_delta(&delta),
277            RuntimeModelProgress::ReasoningStage(stage) => self.update_reasoning_stage(stage),
278            RuntimeModelProgress::ProviderActivity => {}
279            RuntimeModelProgress::ToolCallStarted { call_id, name } => {
280                self.start_tool_call(call_id, name);
281            }
282            RuntimeModelProgress::ToolCallDelta { call_id, delta } => {
283                self.push_tool_call_delta(call_id, &delta);
284            }
285        }
286    }
287
288    /// Abort the streaming turn, marking all open items as failed and flushing events.
289    pub fn abort(&mut self) {
290        self.lifecycle.complete_open_text_items();
291        self.lifecycle.complete_open_tool_calls_with_status(ToolCallStatus::Failed);
292        self.emit_pending_events();
293    }
294
295    /// Complete all open text items gracefully and flush pending events.
296    pub fn complete_open_items(&mut self) {
297        // Flush the authoritative accumulated tool-call arguments before
298        // closing text items so the UI sees the full streamed arguments even
299        // when intermediate deltas were throttled (small tool calls).
300        self.lifecycle.flush_open_tool_call_arguments();
301        self.lifecycle.complete_open_text_items();
302        self.emit_pending_events();
303    }
304
305    /// Take the mapping of tool call IDs to their `(lifecycle item id, tool
306    /// name)`, leaving the map empty.
307    #[must_use]
308    pub fn take_streamed_tool_call_items(&mut self) -> hashbrown::HashMap<String, (String, String)> {
309        std::mem::take(&mut self.tool_call_item_ids)
310    }
311
312    fn push_assistant_delta(&mut self, delta: &str) {
313        if !self.lifecycle.append_assistant_delta(delta) {
314            return;
315        }
316
317        let len = self.lifecycle.assistant_len();
318        if self
319            .output
320            .should_emit(len, self.output.is_first(), MIN_OUTPUT_UPDATE_BYTES, MAX_OUTPUT_UPDATE_EVENTS)
321            && self.lifecycle.emit_assistant_snapshot(Some(self.assistant_item_id.clone()))
322        {
323            self.output.record(len);
324            self.emit_pending_events();
325        }
326    }
327
328    fn push_reasoning_delta(&mut self, delta: &str) {
329        if !self.lifecycle.append_reasoning_delta(delta) {
330            return;
331        }
332
333        if !self.lifecycle.reasoning_started() {
334            if self.lifecycle.emit_reasoning_snapshot(Some(self.reasoning_item_id.clone())) {
335                self.reasoning.advance_to(self.lifecycle.reasoning_len());
336                self.emit_pending_events();
337            }
338            return;
339        }
340
341        let len = self.lifecycle.reasoning_len();
342        if self
343            .reasoning
344            .should_emit(len, false, MIN_REASONING_UPDATE_BYTES, MAX_REASONING_UPDATE_EVENTS)
345            && self.lifecycle.emit_reasoning_snapshot(Some(self.reasoning_item_id.clone()))
346        {
347            self.reasoning.record(len);
348            self.emit_pending_events();
349        }
350    }
351
352    fn update_reasoning_stage(&mut self, stage: String) {
353        let stage_changed = self.reasoning_stage.as_deref() != Some(stage.as_str());
354        if !stage_changed || !self.lifecycle.set_reasoning_stage(Some(stage.clone())) {
355            self.reasoning_stage = Some(stage);
356            return;
357        }
358        self.reasoning_stage = Some(stage);
359
360        if !self.lifecycle.reasoning_started() {
361            return;
362        }
363
364        let len = self.lifecycle.reasoning_len();
365        if self
366            .reasoning
367            .should_emit(len, true, MIN_REASONING_UPDATE_BYTES, MAX_REASONING_UPDATE_EVENTS)
368            && self.lifecycle.emit_reasoning_stage_update()
369        {
370            self.reasoning.record(len);
371            self.emit_pending_events();
372        }
373    }
374
375    fn start_tool_call(&mut self, call_id: String, name: Option<String>) {
376        let item_id = format!("{}-tool-call-{call_id}", self.assistant_item_id);
377        let tool_name = name.clone().unwrap_or_default();
378        self.tool_call_item_ids.insert(call_id.clone(), (item_id.clone(), tool_name));
379        let _ = self.lifecycle.start_tool_call(&call_id, name, Some(item_id));
380        self.emit_pending_events();
381    }
382
383    fn push_tool_call_delta(&mut self, call_id: String, delta: &str) {
384        if !self.lifecycle.append_tool_call_delta(
385            &call_id,
386            delta,
387            None,
388            Some(format!("{}-tool-call-{call_id}", self.assistant_item_id)),
389        ) {
390            return;
391        }
392        self.emit_pending_events();
393    }
394
395    fn emit_pending_events(&mut self) {
396        let Some(sink) = &self.event_sink else {
397            let _ = self.lifecycle.drain_events();
398            return;
399        };
400
401        for event in self.lifecycle.drain_events() {
402            let mut callback = sink.lock();
403            callback(&event);
404        }
405    }
406}
407
408/// Orchestrates a single agent turn: manages steering, lifecycle events, and the LLM call.
409pub struct AgentRuntime {
410    /// Mutable session state including conversation history and statistics.
411    pub state: AgentSessionState,
412    steering: RuntimeSteering,
413    event_sink: Option<EventSink>,
414    lifecycle: SharedLifecycleEmitter,
415    emitted_events: Vec<ThreadEvent>,
416    output: UpdateThrottle,
417    reasoning: UpdateThrottle,
418}
419
420impl AgentRuntime {
421    /// Create a new runtime with the given session state, optional event sink, and steering receiver.
422    pub fn new(
423        state: AgentSessionState,
424        event_sink: Option<EventSink>,
425        steering_receiver: Option<UnboundedReceiver<SteeringMessage>>,
426    ) -> Self {
427        Self {
428            state,
429            steering: RuntimeSteering::new(steering_receiver),
430            event_sink,
431            lifecycle: SharedLifecycleEmitter::default(),
432            emitted_events: Vec::new(),
433            output: UpdateThrottle::new(),
434            reasoning: UpdateThrottle::new(),
435        }
436    }
437
438    /// Replace the structured event sink used for lifecycle event emission.
439    pub fn set_event_handler(&mut self, sink: Option<EventSink>) {
440        self.event_sink = sink;
441    }
442
443    /// Replace the steering message receiver channel for this runtime.
444    pub fn set_steering_receiver(&mut self, receiver: Option<UnboundedReceiver<SteeringMessage>>) {
445        self.steering.set_receiver(receiver);
446    }
447
448    /// Take ownership of the steering receiver, leaving `None` in its place.
449    pub fn take_steering_receiver(&mut self) -> Option<UnboundedReceiver<SteeringMessage>> {
450        self.steering.take_receiver()
451    }
452
453    /// Borrow the session state and steering controller mutably at the same time.
454    pub fn split_mut(&mut self) -> (&mut AgentSessionState, &mut RuntimeSteering) {
455        (&mut self.state, &mut self.steering)
456    }
457
458    /// Returns `true` if there are queued follow-up user inputs waiting to be consumed.
459    #[must_use]
460    pub fn has_pending_follow_up_inputs(&self) -> bool {
461        self.steering.has_pending_follow_up_inputs()
462    }
463
464    /// Pop the next queued follow-up input, add a tagged user message, and
465    /// retain the intent until the enclosing history checkpoint succeeds.
466    pub fn run_until_idle(&mut self) -> Option<String> {
467        let intent = self.steering.pop_follow_up_intent()?;
468        let (intent_id, input, provenance) = intent.into_parts_with_provenance();
469        match provenance {
470            FollowUpProvenance::UserInput => {
471                self.state.add_user_message_with_intent(input.clone(), Some(intent_id.clone()));
472            }
473            FollowUpProvenance::Synthetic => {
474                self.state
475                    .add_synthetic_user_message_with_intent(input.clone(), Some(intent_id.clone()));
476            }
477        }
478        self.steering
479            .in_flight_follow_up_intents
480            .push_back(QueuedFollowUpIntent::from_parts_with_provenance(intent_id, input.clone(), provenance));
481        Some(input)
482    }
483
484    /// Queue a follow-up input to be consumed by `run_until_idle` on the next
485    /// iteration, causing the session loop to start a new turn with this input
486    /// without waiting for the user to type anything.
487    pub fn queue_follow_up_input(&mut self, input: String) {
488        let _ = self.steering.queue_follow_up_input(input);
489    }
490
491    /// Queue a follow-up input while exposing FIFO overflow to the caller.
492    pub fn try_queue_follow_up_input(&mut self, input: String) -> Result<(), FollowUpQueueFull> {
493        self.steering.try_queue_follow_up_input(input)
494    }
495
496    /// Queue a harness-generated continuation or recovery instruction.
497    pub fn try_queue_synthetic_follow_up_input(&mut self, input: String) -> Result<(), FollowUpQueueFull> {
498        self.steering.try_queue_synthetic_follow_up_input(input)
499    }
500
501    /// Authoritatively admit a live steer, resolving its receipt with exactly
502    /// one terminal outcome. See [`RuntimeSteering::admit_follow_up_steer`].
503    pub fn admit_follow_up_steer(&mut self, steer: FollowUpSteer) -> Option<QueuedFollowUpIntent> {
504        self.steering.admit_follow_up_steer(steer)
505    }
506
507    /// Reject steers left in the channel after admission closed. Called before
508    /// [`Self::open_admission`] so a late arrival cannot leak into the next turn.
509    pub fn drain_rejected_steers(&mut self) {
510        self.steering.drain_rejected_steers();
511    }
512
513    /// Reopen live-steer admission for a new turn.
514    pub fn open_admission(&mut self) {
515        self.steering.open_admission();
516    }
517
518    /// Close live-steer admission atomically with the final steering drain.
519    pub fn close_admission(&mut self) {
520        self.steering.close_admission();
521    }
522
523    #[must_use]
524    pub const fn admission_closed(&self) -> bool {
525        self.steering.admission_closed()
526    }
527
528    /// Declare that cancellation outranks pending steers for this turn.
529    pub fn set_cancellation_precedence(&mut self, value: bool) {
530        self.steering.set_cancellation_precedence(value);
531    }
532
533    /// Restore the durable steering snapshot after loading session history.
534    /// Pending intents already represented by a tagged user message, or
535    /// already in the applied-ID window, are skipped; identical text with a
536    /// different ID is intentionally retained.
537    pub fn restore_follow_up_state(
538        &mut self,
539        pending_intents: impl IntoIterator<Item = QueuedFollowUpIntent>,
540        applied_intent_ids: impl IntoIterator<Item = String>,
541    ) -> Result<(), FollowUpQueueFull> {
542        let mut applied: HashSet<String> = self.steering.applied_follow_up_intent_ids().iter().cloned().collect();
543        for intent_id in applied_intent_ids {
544            if applied.insert(intent_id.clone()) {
545                self.steering.acknowledge_follow_up_intent(intent_id);
546            }
547        }
548        let mut represented: HashSet<String> = self
549            .state
550            .messages
551            .iter()
552            .filter_map(|message| message.metadata.as_ref().and_then(|metadata| metadata.intent_id()))
553            .map(ToOwned::to_owned)
554            .collect();
555        represented.extend(
556            self.steering
557                .pending_follow_up_intents_snapshot()
558                .into_iter()
559                .map(|intent| intent.id().to_owned()),
560        );
561
562        for intent in pending_intents {
563            if applied.contains(intent.id()) || !represented.insert(intent.id().to_owned()) {
564                continue;
565            }
566            self.steering.try_queue_recovered_follow_up(intent)?;
567        }
568        Ok(())
569    }
570
571    /// Access the intent IDs acknowledged by this runtime for checkpointing.
572    #[must_use]
573    pub fn applied_follow_up_intent_ids(&self) -> &VecDeque<String> {
574        self.steering.applied_follow_up_intent_ids()
575    }
576
577    /// Drop follow-up inputs belonging to the discarded execution context.
578    pub fn clear_pending_follow_up_inputs(&mut self) {
579        self.steering.clear_pending_follow_up_inputs();
580    }
581
582    /// Poll the steering channel for control signals during the current turn.
583    pub async fn poll_turn_control(&mut self) -> RuntimeControl {
584        self.steering.poll_turn_control().await
585    }
586
587    /// Poll the steering channel for control signals during tool execution.
588    pub async fn poll_tool_control(&mut self) -> RuntimeControl {
589        self.steering.poll_tool_control().await
590    }
591
592    /// Take all emitted lifecycle events, leaving the internal buffer empty.
593    pub fn take_emitted_events(&mut self) -> Vec<ThreadEvent> {
594        std::mem::take(&mut self.emitted_events)
595    }
596
597    /// Look up the lifecycle item ID for a given tool call identifier.
598    #[must_use]
599    pub fn tool_call_item_id(&self, call_id: &str) -> Option<String> {
600        self.lifecycle.tool_call_item_id(call_id).map(str::to_string)
601    }
602
603    /// Mark a specific tool call as completed with the given status and emit lifecycle events.
604    pub fn complete_tool_call(&mut self, call_id: &str, status: ToolCallStatus, outcome: Option<ToolOutcome>) {
605        let _ = self.lifecycle.complete_tool_call(call_id, status, outcome);
606        self.emit_pending_lifecycle_events();
607    }
608
609    /// Mark all still-open tool calls as completed with the given status and emit lifecycle events.
610    pub fn complete_open_tool_calls(&mut self, status: ToolCallStatus) {
611        self.lifecycle.complete_open_tool_calls_with_status(status);
612        self.emit_pending_lifecycle_events();
613    }
614
615    fn emit_event(&mut self, event: ThreadEvent) {
616        self.emitted_events.push(event.clone());
617        if let Some(sink) = &self.event_sink {
618            let mut callback = sink.lock();
619            callback(&event);
620        }
621    }
622
623    fn emit_pending_lifecycle_events(&mut self) {
624        for event in self.lifecycle.drain_events() {
625            self.emit_event(event);
626        }
627    }
628
629    fn finalize_assistant_lifecycle(&mut self, text: &str) {
630        if text.trim().is_empty() {
631            return;
632        }
633
634        let should_emit_snapshot = !self.lifecycle.assistant_started() || self.lifecycle.replace_assistant_text(text);
635        if should_emit_snapshot {
636            let _ = self.lifecycle.emit_assistant_snapshot(None);
637        }
638        let _ = self.lifecycle.complete_assistant_stream();
639    }
640
641    fn finalize_reasoning_lifecycle(&mut self, text: &str) {
642        if text.trim().is_empty() {
643            return;
644        }
645
646        let should_emit_snapshot = !self.lifecycle.reasoning_started() || self.lifecycle.replace_reasoning_text(text);
647        if should_emit_snapshot {
648            let _ = self.lifecycle.emit_reasoning_snapshot(None);
649        }
650        let _ = self.lifecycle.complete_reasoning_stream();
651    }
652
653    fn finalize_tool_call_lifecycle(&mut self, tool_calls: Option<&[ToolCall]>, _finish_reason: &str) {
654        if let Some(tool_calls) = tool_calls {
655            for call in tool_calls {
656                let tool_name = call.function.as_ref().map(|function| function.name.clone());
657                let _ = self.lifecycle.start_tool_call(&call.id, tool_name.clone(), None);
658                if let Some(function) = call.function.as_ref() {
659                    let _ = self
660                        .lifecycle
661                        .sync_tool_call_arguments(&call.id, &function.arguments, tool_name, None);
662                }
663            }
664            return;
665        }
666
667        self.lifecycle.complete_open_tool_calls_with_status(ToolCallStatus::Failed);
668    }
669
670    fn record_model_progress(
671        &mut self,
672        event: RuntimeModelProgress,
673        full_text: &mut String,
674        full_reasoning: &mut String,
675    ) {
676        match event {
677            RuntimeModelProgress::OutputDelta(delta) => {
678                full_text.push_str(&delta);
679                if self.lifecycle.append_assistant_delta(&delta) {
680                    let len = self.lifecycle.assistant_len();
681                    if self.output.should_emit(
682                        len,
683                        self.output.is_first(),
684                        MIN_OUTPUT_UPDATE_BYTES,
685                        MAX_OUTPUT_UPDATE_EVENTS,
686                    ) && self.lifecycle.emit_assistant_snapshot(None)
687                    {
688                        self.output.record(len);
689                        self.emit_pending_lifecycle_events();
690                    }
691                }
692            }
693            RuntimeModelProgress::ReasoningDelta(delta) => {
694                full_reasoning.push_str(&delta);
695                if self.lifecycle.append_reasoning_delta(&delta) {
696                    let len = self.lifecycle.reasoning_len();
697                    if self.reasoning.should_emit(
698                        len,
699                        self.reasoning.is_first(),
700                        MIN_REASONING_UPDATE_BYTES,
701                        MAX_REASONING_UPDATE_EVENTS,
702                    ) && self.lifecycle.emit_reasoning_snapshot(None)
703                    {
704                        self.reasoning.record(len);
705                        self.emit_pending_lifecycle_events();
706                    }
707                }
708            }
709            RuntimeModelProgress::ReasoningStage(stage) => {
710                if self.lifecycle.set_reasoning_stage(Some(stage)) {
711                    let _ = self.lifecycle.emit_reasoning_stage_update();
712                    self.emit_pending_lifecycle_events();
713                }
714            }
715            RuntimeModelProgress::ProviderActivity => {}
716            RuntimeModelProgress::ToolCallStarted { call_id, name } => {
717                let _ = self.lifecycle.start_tool_call(&call_id, name, None);
718                self.emit_pending_lifecycle_events();
719            }
720            RuntimeModelProgress::ToolCallDelta { call_id, delta } => {
721                if self.lifecycle.append_tool_call_delta(&call_id, &delta, None, None) {
722                    self.emit_pending_lifecycle_events();
723                }
724            }
725        }
726    }
727
728    async fn run_turn_once_with_adapter<A: RuntimeModelAdapter + ?Sized>(
729        &mut self,
730        adapter: &mut A,
731        request: LLMRequest,
732        timeout: Option<std::time::Duration>,
733    ) -> Result<TurnExecution> {
734        let request_model = request.model.clone();
735        let start_time = Instant::now();
736        self.output.reset();
737        self.reasoning.reset();
738        let mut full_text = String::new();
739        let mut full_reasoning = String::new();
740        let mut on_progress = |event| self.record_model_progress(event, &mut full_text, &mut full_reasoning);
741        let RuntimeModelOutput { mut response } = match adapter.execute(request, timeout, &mut on_progress).await {
742            Ok(output) => output,
743            Err(error) => {
744                self.complete_open_tool_calls(ToolCallStatus::Failed);
745                tracing::warn!(elapsed_ms = start_time.elapsed().as_millis() as u64, error = %error, "agent turn failed during model execution");
746                return Err(error);
747            }
748        };
749
750        merge_stream_and_completed_text(&mut full_text, response.content.as_deref());
751        let provider_reasoning = response.reasoning.clone();
752
753        let finish_reason = match response.finish_reason.clone() {
754            FinishReason::Stop => "stop".to_string(),
755            FinishReason::ToolCalls => "tool_calls".to_string(),
756            FinishReason::Length => "length".to_string(),
757            FinishReason::Error(message) => message,
758            _ => "unknown".to_string(),
759        };
760        let final_usage = response.usage.take().unwrap_or_default();
761        let mut aggregated_tool_calls = response.tool_calls.take();
762
763        self.finalize_assistant_lifecycle(&full_text);
764        self.finalize_reasoning_lifecycle(&full_reasoning);
765        self.finalize_tool_call_lifecycle(aggregated_tool_calls.as_deref(), &finish_reason);
766        self.emit_pending_lifecycle_events();
767
768        let mut turn_recorded = false;
769        self.state.record_turn(&start_time, &mut turn_recorded);
770
771        if final_usage.prompt_tokens > 0 || final_usage.completion_tokens > 0 {
772            // `merge_usage` also feeds the session prompt-cache health
773            // monitor; a sustained hit-rate collapse warns once per session
774            // (SEV-style) instead of silently re-paying full input cost.
775            if let Some(alert) = self.state.stats.merge_usage(&final_usage) {
776                let message = alert.message();
777                tracing::warn!("{message}");
778                self.state.push_warning(message);
779            }
780        }
781
782        aggregated_tool_calls = aggregated_tool_calls.filter(|calls| !calls.is_empty());
783
784        let mut assistant_message = crate::llm::provider::Message::assistant(full_text.clone());
785        if let Some(reasoning) = provider_reasoning
786            .clone()
787            .or_else(|| (!full_reasoning.is_empty()).then(|| full_reasoning.clone()))
788        {
789            assistant_message = assistant_message.with_reasoning(Some(reasoning));
790        }
791        if let Some(details) = response.reasoning_details.clone() {
792            let values: Vec<serde_json::Value> = details.into_iter().map(serde_json::Value::String).collect();
793            assistant_message = assistant_message.with_reasoning_details(Some(values));
794        }
795
796        match aggregated_tool_calls.as_ref() {
797            Some(calls) => {
798                assistant_message = assistant_message
799                    .with_tool_calls(calls.clone())
800                    .with_phase(Some(AssistantPhase::Commentary));
801            }
802            None => {
803                assistant_message = assistant_message.with_phase(Some(AssistantPhase::FinalAnswer));
804            }
805        }
806
807        self.state.adjust_token_count(assistant_message.estimate_tokens() as isize);
808        self.state.messages_mut().push(assistant_message);
809
810        self.state.conversation.push(Content {
811            role: "model".to_string(),
812            parts: vec![Part::Text { text: full_text.clone(), thought_signature: None }],
813        });
814        self.state.last_processed_message_idx = self.state.conversation.len();
815
816        if response.model.is_empty() {
817            response.model = request_model;
818        }
819        response.content = Some(full_text.clone());
820        if response.reasoning.is_none() && !full_reasoning.is_empty() {
821            response.reasoning = Some(full_reasoning.clone());
822        }
823        response.tool_calls = aggregated_tool_calls;
824        response.usage = Some(final_usage);
825        response.finish_reason = if finish_reason == "tool_calls" {
826            FinishReason::ToolCalls
827        } else if finish_reason == "Cancelled" || finish_reason == "cancelled" {
828            FinishReason::Error("Cancelled".to_string())
829        } else {
830            response.finish_reason
831        };
832
833        tracing::debug!(
834            elapsed_ms = start_time.elapsed().as_millis() as u64,
835            output_bytes = full_text.len(),
836            reasoning_bytes = full_reasoning.len(),
837            tool_calls = response.tool_calls.as_ref().map_or(0, Vec::len),
838            input_tokens = response.usage.as_ref().map_or(0, |usage| usage.prompt_tokens),
839            output_tokens = response.usage.as_ref().map_or(0, |usage| usage.completion_tokens),
840            finish_reason = %finish_reason,
841            "agent turn completed"
842        );
843
844        Ok(TurnExecution {
845            response,
846            content: full_text,
847            reasoning: if full_reasoning.is_empty() {
848                None
849            } else {
850                Some(full_reasoning)
851            },
852        })
853    }
854
855    /// Execute a single LLM turn: stream the response, update session state, and return the result.
856    pub async fn run_turn_once(
857        &mut self,
858        provider: &mut Box<dyn LLMProvider>,
859        request: LLMRequest,
860        timeout: Option<std::time::Duration>,
861    ) -> Result<TurnExecution> {
862        let mut steering = std::mem::take(&mut self.steering);
863        let mut adapter = ProviderRuntimeModelAdapter::new(provider, &mut steering);
864        let result = self.run_turn_once_with_adapter(&mut adapter, request, timeout).await;
865        self.steering = steering;
866        result
867    }
868}
869
870#[cfg(test)]
871mod tests;