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