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_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    /// Create a new bridge that emits lifecycle events to the provided sink.
307    #[must_use]
308    pub fn new(event_sink: Option<EventSink>, turn_id: &str, step: usize, attempt: usize) -> Self {
309        Self {
310            event_sink,
311            assistant_item_id: format!("{turn_id}-step-{step}-assistant-stream-{attempt}"),
312            reasoning_item_id: format!("{turn_id}-step-{step}-reasoning-stream-{attempt}"),
313            lifecycle: SharedLifecycleEmitter::default(),
314            tool_call_item_ids: hashbrown::HashMap::new(),
315            reasoning_stage: None,
316            output: UpdateThrottle::new(),
317            reasoning: UpdateThrottle::new(),
318        }
319    }
320
321    /// Forward a streaming progress event to the lifecycle emitter and sink.
322    pub fn on_progress(&mut self, event: RuntimeModelProgress) {
323        match event {
324            RuntimeModelProgress::OutputDelta(delta) => self.push_assistant_delta(&delta),
325            RuntimeModelProgress::ReasoningDelta(delta) => self.push_reasoning_delta(&delta),
326            RuntimeModelProgress::ReasoningStage(stage) => self.update_reasoning_stage(stage),
327            RuntimeModelProgress::ProviderActivity => {}
328            RuntimeModelProgress::ToolCallStarted { call_id, name } => {
329                self.start_tool_call(call_id, name);
330            }
331            RuntimeModelProgress::ToolCallDelta { call_id, delta } => {
332                self.push_tool_call_delta(call_id, &delta);
333            }
334        }
335    }
336
337    /// Abort the streaming turn, marking all open items as failed and flushing events.
338    pub fn abort(&mut self) {
339        self.lifecycle.complete_open_text_items();
340        self.lifecycle.complete_open_tool_calls_with_status(ToolCallStatus::Failed);
341        self.emit_pending_events();
342    }
343
344    /// Complete all open text items gracefully and flush pending events.
345    pub fn complete_open_items(&mut self) {
346        // Flush the authoritative accumulated tool-call arguments before
347        // closing text items so the UI sees the full streamed arguments even
348        // when intermediate deltas were throttled (small tool calls).
349        self.lifecycle.flush_open_tool_call_arguments();
350        self.lifecycle.complete_open_text_items();
351        self.emit_pending_events();
352    }
353
354    /// Take the mapping of tool call IDs to their `(lifecycle item id, tool
355    /// name)`, leaving the map empty.
356    #[must_use]
357    pub fn take_streamed_tool_call_items(&mut self) -> hashbrown::HashMap<String, (String, String)> {
358        std::mem::take(&mut self.tool_call_item_ids)
359    }
360
361    fn push_assistant_delta(&mut self, delta: &str) {
362        if !self.lifecycle.append_assistant_delta(delta) {
363            return;
364        }
365
366        let len = self.lifecycle.assistant_len();
367        if self
368            .output
369            .should_emit(len, self.output.is_first(), MIN_OUTPUT_UPDATE_BYTES, MAX_OUTPUT_UPDATE_EVENTS)
370            && self.lifecycle.emit_assistant_snapshot(Some(self.assistant_item_id.clone()))
371        {
372            self.output.record(len);
373            self.emit_pending_events();
374        }
375    }
376
377    fn push_reasoning_delta(&mut self, delta: &str) {
378        if !self.lifecycle.append_reasoning_delta(delta) {
379            return;
380        }
381
382        if !self.lifecycle.reasoning_started() {
383            if self.lifecycle.emit_reasoning_snapshot(Some(self.reasoning_item_id.clone())) {
384                self.reasoning.advance_to(self.lifecycle.reasoning_len());
385                self.emit_pending_events();
386            }
387            return;
388        }
389
390        let len = self.lifecycle.reasoning_len();
391        if self
392            .reasoning
393            .should_emit(len, false, MIN_REASONING_UPDATE_BYTES, MAX_REASONING_UPDATE_EVENTS)
394            && self.lifecycle.emit_reasoning_snapshot(Some(self.reasoning_item_id.clone()))
395        {
396            self.reasoning.record(len);
397            self.emit_pending_events();
398        }
399    }
400
401    fn update_reasoning_stage(&mut self, stage: String) {
402        let stage_changed = self.reasoning_stage.as_deref() != Some(stage.as_str());
403        if !stage_changed || !self.lifecycle.set_reasoning_stage(Some(stage.clone())) {
404            self.reasoning_stage = Some(stage);
405            return;
406        }
407        self.reasoning_stage = Some(stage);
408
409        if !self.lifecycle.reasoning_started() {
410            return;
411        }
412
413        let len = self.lifecycle.reasoning_len();
414        if self
415            .reasoning
416            .should_emit(len, true, MIN_REASONING_UPDATE_BYTES, MAX_REASONING_UPDATE_EVENTS)
417            && self.lifecycle.emit_reasoning_stage_update()
418        {
419            self.reasoning.record(len);
420            self.emit_pending_events();
421        }
422    }
423
424    fn start_tool_call(&mut self, call_id: String, name: Option<String>) {
425        let item_id = format!("{}-tool-call-{call_id}", self.assistant_item_id);
426        let tool_name = name.clone().unwrap_or_default();
427        self.tool_call_item_ids.insert(call_id.clone(), (item_id.clone(), tool_name));
428        let _ = self.lifecycle.start_tool_call(&call_id, name, Some(item_id));
429        self.emit_pending_events();
430    }
431
432    fn push_tool_call_delta(&mut self, call_id: String, delta: &str) {
433        if !self.lifecycle.append_tool_call_delta(
434            &call_id,
435            delta,
436            None,
437            Some(format!("{}-tool-call-{call_id}", self.assistant_item_id)),
438        ) {
439            return;
440        }
441        self.emit_pending_events();
442    }
443
444    fn emit_pending_events(&mut self) {
445        let Some(sink) = &self.event_sink else {
446            let _ = self.lifecycle.drain_events();
447            return;
448        };
449
450        for event in self.lifecycle.drain_events() {
451            let mut callback = sink.lock();
452            callback(&event);
453        }
454    }
455}
456
457/// Orchestrates a single agent turn: manages steering, lifecycle events, and the LLM call.
458pub struct AgentRuntime {
459    /// Mutable session state including conversation history and statistics.
460    pub state: AgentSessionState,
461    steering: RuntimeSteering,
462    event_sink: Option<EventSink>,
463    lifecycle: SharedLifecycleEmitter,
464    emitted_events: Vec<ThreadEvent>,
465    output: UpdateThrottle,
466    reasoning: UpdateThrottle,
467}
468
469impl AgentRuntime {
470    /// Create a new runtime with the given session state, optional event sink, and steering receiver.
471    pub fn new(
472        state: AgentSessionState,
473        event_sink: Option<EventSink>,
474        steering_receiver: Option<UnboundedReceiver<SteeringMessage>>,
475    ) -> Self {
476        Self {
477            state,
478            steering: RuntimeSteering::new(steering_receiver),
479            event_sink,
480            lifecycle: SharedLifecycleEmitter::default(),
481            emitted_events: Vec::new(),
482            output: UpdateThrottle::new(),
483            reasoning: UpdateThrottle::new(),
484        }
485    }
486
487    /// Replace the structured event sink used for lifecycle event emission.
488    pub fn set_event_handler(&mut self, sink: Option<EventSink>) {
489        self.event_sink = sink;
490    }
491
492    /// Replace the steering message receiver channel for this runtime.
493    pub fn set_steering_receiver(&mut self, receiver: Option<UnboundedReceiver<SteeringMessage>>) {
494        self.steering.set_receiver(receiver);
495    }
496
497    /// Take ownership of the steering receiver, leaving `None` in its place.
498    pub fn take_steering_receiver(&mut self) -> Option<UnboundedReceiver<SteeringMessage>> {
499        self.steering.take_receiver()
500    }
501
502    /// Borrow the session state and steering controller mutably at the same time.
503    pub fn split_mut(&mut self) -> (&mut AgentSessionState, &mut RuntimeSteering) {
504        (&mut self.state, &mut self.steering)
505    }
506
507    /// Returns `true` if there are queued follow-up user inputs waiting to be consumed.
508    #[must_use]
509    pub fn has_pending_follow_up_inputs(&self) -> bool {
510        self.steering.has_pending_follow_up_inputs()
511    }
512
513    /// Pop the next queued follow-up input, add a tagged user message, and
514    /// retain the intent until the enclosing history checkpoint succeeds.
515    pub fn run_until_idle(&mut self) -> Option<String> {
516        let intent = self.steering.pop_follow_up_intent()?;
517        let (intent_id, input, provenance) = intent.into_parts_with_provenance();
518        match provenance {
519            FollowUpProvenance::UserInput => {
520                self.state.add_user_message_with_intent(input.clone(), Some(intent_id.clone()));
521            }
522            FollowUpProvenance::Synthetic => {
523                self.state
524                    .add_synthetic_user_message_with_intent(input.clone(), Some(intent_id.clone()));
525            }
526        }
527        self.steering
528            .in_flight_follow_up_intents
529            .push_back(QueuedFollowUpIntent::from_parts_with_provenance(intent_id, input.clone(), provenance));
530        Some(input)
531    }
532
533    /// Queue a follow-up input to be consumed by `run_until_idle` on the next
534    /// iteration, causing the session loop to start a new turn with this input
535    /// without waiting for the user to type anything.
536    pub fn queue_follow_up_input(&mut self, input: String) {
537        let _ = self.steering.queue_follow_up_input(input);
538    }
539
540    /// Queue a follow-up input while exposing FIFO overflow to the caller.
541    pub fn try_queue_follow_up_input(&mut self, input: String) -> Result<(), FollowUpQueueFull> {
542        self.steering.try_queue_follow_up_input(input)
543    }
544
545    /// Queue a harness-generated continuation or recovery instruction.
546    pub fn try_queue_synthetic_follow_up_input(&mut self, input: String) -> Result<(), FollowUpQueueFull> {
547        self.steering.try_queue_synthetic_follow_up_input(input)
548    }
549
550    /// Restore the durable steering snapshot after loading session history.
551    /// Pending intents already represented by a tagged user message, or
552    /// already in the applied-ID window, are skipped; identical text with a
553    /// different ID is intentionally retained.
554    pub fn restore_follow_up_state(
555        &mut self,
556        pending_intents: impl IntoIterator<Item = QueuedFollowUpIntent>,
557        applied_intent_ids: impl IntoIterator<Item = String>,
558    ) -> Result<(), FollowUpQueueFull> {
559        let mut applied = HashSet::new();
560        for intent_id in applied_intent_ids {
561            if applied.insert(intent_id.clone()) {
562                self.steering.acknowledge_follow_up_intent(intent_id);
563            }
564        }
565        let represented: HashSet<String> = self
566            .state
567            .messages
568            .iter()
569            .filter_map(|message| message.metadata.as_ref().and_then(|metadata| metadata.intent_id()))
570            .map(ToOwned::to_owned)
571            .collect();
572
573        for intent in pending_intents {
574            if applied.contains(intent.id()) || represented.contains(intent.id()) {
575                continue;
576            }
577            self.steering.try_queue_follow_up_intent(intent)?;
578        }
579        Ok(())
580    }
581
582    /// Access the intent IDs acknowledged by this runtime for checkpointing.
583    #[must_use]
584    pub fn applied_follow_up_intent_ids(&self) -> &VecDeque<String> {
585        self.steering.applied_follow_up_intent_ids()
586    }
587
588    /// Drop follow-up inputs belonging to the discarded execution context.
589    pub fn clear_pending_follow_up_inputs(&mut self) {
590        self.steering.clear_pending_follow_up_inputs();
591    }
592
593    /// Poll the steering channel for control signals during the current turn.
594    pub async fn poll_turn_control(&mut self) -> RuntimeControl {
595        self.steering.poll_turn_control().await
596    }
597
598    /// Poll the steering channel for control signals during tool execution.
599    pub async fn poll_tool_control(&mut self) -> RuntimeControl {
600        self.steering.poll_tool_control().await
601    }
602
603    /// Take all emitted lifecycle events, leaving the internal buffer empty.
604    pub fn take_emitted_events(&mut self) -> Vec<ThreadEvent> {
605        std::mem::take(&mut self.emitted_events)
606    }
607
608    /// Look up the lifecycle item ID for a given tool call identifier.
609    #[must_use]
610    pub fn tool_call_item_id(&self, call_id: &str) -> Option<String> {
611        self.lifecycle.tool_call_item_id(call_id).map(str::to_string)
612    }
613
614    /// Mark a specific tool call as completed with the given status and emit lifecycle events.
615    pub fn complete_tool_call(&mut self, call_id: &str, status: ToolCallStatus, outcome: Option<ToolOutcome>) {
616        let _ = self.lifecycle.complete_tool_call(call_id, status, outcome);
617        self.emit_pending_lifecycle_events();
618    }
619
620    /// Mark all still-open tool calls as completed with the given status and emit lifecycle events.
621    pub fn complete_open_tool_calls(&mut self, status: ToolCallStatus) {
622        self.lifecycle.complete_open_tool_calls_with_status(status);
623        self.emit_pending_lifecycle_events();
624    }
625
626    fn emit_event(&mut self, event: ThreadEvent) {
627        self.emitted_events.push(event.clone());
628        if let Some(sink) = &self.event_sink {
629            let mut callback = sink.lock();
630            callback(&event);
631        }
632    }
633
634    fn emit_pending_lifecycle_events(&mut self) {
635        for event in self.lifecycle.drain_events() {
636            self.emit_event(event);
637        }
638    }
639
640    fn finalize_assistant_lifecycle(&mut self, text: &str) {
641        if text.trim().is_empty() {
642            return;
643        }
644
645        let should_emit_snapshot = !self.lifecycle.assistant_started() || self.lifecycle.replace_assistant_text(text);
646        if should_emit_snapshot {
647            let _ = self.lifecycle.emit_assistant_snapshot(None);
648        }
649        let _ = self.lifecycle.complete_assistant_stream();
650    }
651
652    fn finalize_reasoning_lifecycle(&mut self, text: &str) {
653        if text.trim().is_empty() {
654            return;
655        }
656
657        let should_emit_snapshot = !self.lifecycle.reasoning_started() || self.lifecycle.replace_reasoning_text(text);
658        if should_emit_snapshot {
659            let _ = self.lifecycle.emit_reasoning_snapshot(None);
660        }
661        let _ = self.lifecycle.complete_reasoning_stream();
662    }
663
664    fn finalize_tool_call_lifecycle(&mut self, tool_calls: Option<&[ToolCall]>, _finish_reason: &str) {
665        if let Some(tool_calls) = tool_calls {
666            for call in tool_calls {
667                let tool_name = call.function.as_ref().map(|function| function.name.clone());
668                let _ = self.lifecycle.start_tool_call(&call.id, tool_name.clone(), None);
669                if let Some(function) = call.function.as_ref() {
670                    let _ = self
671                        .lifecycle
672                        .sync_tool_call_arguments(&call.id, &function.arguments, tool_name, None);
673                }
674            }
675            return;
676        }
677
678        self.lifecycle.complete_open_tool_calls_with_status(ToolCallStatus::Failed);
679    }
680
681    fn record_model_progress(
682        &mut self,
683        event: RuntimeModelProgress,
684        full_text: &mut String,
685        full_reasoning: &mut String,
686    ) {
687        match event {
688            RuntimeModelProgress::OutputDelta(delta) => {
689                full_text.push_str(&delta);
690                if self.lifecycle.append_assistant_delta(&delta) {
691                    let len = self.lifecycle.assistant_len();
692                    if self.output.should_emit(
693                        len,
694                        self.output.is_first(),
695                        MIN_OUTPUT_UPDATE_BYTES,
696                        MAX_OUTPUT_UPDATE_EVENTS,
697                    ) && self.lifecycle.emit_assistant_snapshot(None)
698                    {
699                        self.output.record(len);
700                        self.emit_pending_lifecycle_events();
701                    }
702                }
703            }
704            RuntimeModelProgress::ReasoningDelta(delta) => {
705                full_reasoning.push_str(&delta);
706                if self.lifecycle.append_reasoning_delta(&delta) {
707                    let len = self.lifecycle.reasoning_len();
708                    if self.reasoning.should_emit(
709                        len,
710                        self.reasoning.is_first(),
711                        MIN_REASONING_UPDATE_BYTES,
712                        MAX_REASONING_UPDATE_EVENTS,
713                    ) && self.lifecycle.emit_reasoning_snapshot(None)
714                    {
715                        self.reasoning.record(len);
716                        self.emit_pending_lifecycle_events();
717                    }
718                }
719            }
720            RuntimeModelProgress::ReasoningStage(stage) => {
721                if self.lifecycle.set_reasoning_stage(Some(stage)) {
722                    let _ = self.lifecycle.emit_reasoning_stage_update();
723                    self.emit_pending_lifecycle_events();
724                }
725            }
726            RuntimeModelProgress::ProviderActivity => {}
727            RuntimeModelProgress::ToolCallStarted { call_id, name } => {
728                let _ = self.lifecycle.start_tool_call(&call_id, name, None);
729                self.emit_pending_lifecycle_events();
730            }
731            RuntimeModelProgress::ToolCallDelta { call_id, delta } => {
732                if self.lifecycle.append_tool_call_delta(&call_id, &delta, None, None) {
733                    self.emit_pending_lifecycle_events();
734                }
735            }
736        }
737    }
738
739    async fn run_turn_once_with_adapter<A: RuntimeModelAdapter + ?Sized>(
740        &mut self,
741        adapter: &mut A,
742        request: LLMRequest,
743        timeout: Option<std::time::Duration>,
744    ) -> Result<TurnExecution> {
745        let request_model = request.model.clone();
746        let start_time = Instant::now();
747        self.output.reset();
748        self.reasoning.reset();
749        let mut full_text = String::new();
750        let mut full_reasoning = String::new();
751        let mut on_progress = |event| self.record_model_progress(event, &mut full_text, &mut full_reasoning);
752        let RuntimeModelOutput { mut response } = match adapter.execute(request, timeout, &mut on_progress).await {
753            Ok(output) => output,
754            Err(error) => {
755                self.complete_open_tool_calls(ToolCallStatus::Failed);
756                tracing::warn!(elapsed_ms = start_time.elapsed().as_millis() as u64, error = %error, "agent turn failed during model execution");
757                return Err(error);
758            }
759        };
760
761        merge_stream_and_completed_text(&mut full_text, response.content.as_deref());
762        let provider_reasoning = response.reasoning.clone();
763
764        let finish_reason = match response.finish_reason.clone() {
765            FinishReason::Stop => "stop".to_string(),
766            FinishReason::ToolCalls => "tool_calls".to_string(),
767            FinishReason::Length => "length".to_string(),
768            FinishReason::Error(message) => message,
769            _ => "unknown".to_string(),
770        };
771        let final_usage = response.usage.take().unwrap_or_default();
772        let mut aggregated_tool_calls = response.tool_calls.take();
773
774        self.finalize_assistant_lifecycle(&full_text);
775        self.finalize_reasoning_lifecycle(&full_reasoning);
776        self.finalize_tool_call_lifecycle(aggregated_tool_calls.as_deref(), &finish_reason);
777        self.emit_pending_lifecycle_events();
778
779        let mut turn_recorded = false;
780        self.state.record_turn(&start_time, &mut turn_recorded);
781
782        if final_usage.prompt_tokens > 0 || final_usage.completion_tokens > 0 {
783            // `merge_usage` also feeds the session prompt-cache health
784            // monitor; a sustained hit-rate collapse warns once per session
785            // (SEV-style) instead of silently re-paying full input cost.
786            if let Some(alert) = self.state.stats.merge_usage(&final_usage) {
787                let message = alert.message();
788                tracing::warn!("{message}");
789                self.state.push_warning(message);
790            }
791        }
792
793        aggregated_tool_calls = aggregated_tool_calls.filter(|calls| !calls.is_empty());
794
795        let mut assistant_message = crate::llm::provider::Message::assistant(full_text.clone());
796        if let Some(reasoning) = provider_reasoning
797            .clone()
798            .or_else(|| (!full_reasoning.is_empty()).then(|| full_reasoning.clone()))
799        {
800            assistant_message = assistant_message.with_reasoning(Some(reasoning));
801        }
802        if let Some(details) = response.reasoning_details.clone() {
803            let values: Vec<serde_json::Value> = details.into_iter().map(serde_json::Value::String).collect();
804            assistant_message = assistant_message.with_reasoning_details(Some(values));
805        }
806
807        match aggregated_tool_calls.as_ref() {
808            Some(calls) => {
809                assistant_message = assistant_message
810                    .with_tool_calls(calls.clone())
811                    .with_phase(Some(AssistantPhase::Commentary));
812            }
813            None => {
814                assistant_message = assistant_message.with_phase(Some(AssistantPhase::FinalAnswer));
815            }
816        }
817
818        self.state.adjust_token_count(assistant_message.estimate_tokens() as isize);
819        self.state.messages_mut().push(assistant_message);
820
821        self.state.conversation.push(Content {
822            role: "model".to_string(),
823            parts: vec![Part::Text { text: full_text.clone(), thought_signature: None }],
824        });
825        self.state.last_processed_message_idx = self.state.conversation.len();
826
827        if response.model.is_empty() {
828            response.model = request_model;
829        }
830        response.content = Some(full_text.clone());
831        if response.reasoning.is_none() && !full_reasoning.is_empty() {
832            response.reasoning = Some(full_reasoning.clone());
833        }
834        response.tool_calls = aggregated_tool_calls;
835        response.usage = Some(final_usage);
836        response.finish_reason = if finish_reason == "tool_calls" {
837            FinishReason::ToolCalls
838        } else if finish_reason == "Cancelled" || finish_reason == "cancelled" {
839            FinishReason::Error("Cancelled".to_string())
840        } else {
841            response.finish_reason
842        };
843
844        tracing::debug!(
845            elapsed_ms = start_time.elapsed().as_millis() as u64,
846            output_bytes = full_text.len(),
847            reasoning_bytes = full_reasoning.len(),
848            tool_calls = response.tool_calls.as_ref().map_or(0, Vec::len),
849            input_tokens = response.usage.as_ref().map_or(0, |usage| usage.prompt_tokens),
850            output_tokens = response.usage.as_ref().map_or(0, |usage| usage.completion_tokens),
851            finish_reason = %finish_reason,
852            "agent turn completed"
853        );
854
855        Ok(TurnExecution {
856            response,
857            content: full_text,
858            reasoning: if full_reasoning.is_empty() {
859                None
860            } else {
861                Some(full_reasoning)
862            },
863        })
864    }
865
866    /// Execute a single LLM turn: stream the response, update session state, and return the result.
867    pub async fn run_turn_once(
868        &mut self,
869        provider: &mut Box<dyn LLMProvider>,
870        request: LLMRequest,
871        timeout: Option<std::time::Duration>,
872    ) -> Result<TurnExecution> {
873        let mut steering = std::mem::take(&mut self.steering);
874        let mut adapter = ProviderRuntimeModelAdapter::new(provider, &mut steering);
875        let result = self.run_turn_once_with_adapter(&mut adapter, request, timeout).await;
876        self.steering = steering;
877        result
878    }
879}
880
881#[cfg(test)]
882mod tests;