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