Skip to main content

vtcode_core/core/agent/runtime/
steering.rs

1use super::*;
2
3/// Manages steering messages (stop, pause, resume, follow-up inputs) for a running agent turn.
4pub struct RuntimeSteering {
5    steering_receiver: Option<UnboundedReceiver<SteeringMessage>>,
6    pub(super) queued_follow_up_inputs: VecDeque<QueuedFollowUpIntent>,
7    /// Overflow park for follow-ups that arrive while the primary FIFO is
8    /// full. Drained FIFO into the primary queue as space frees so a rapid
9    /// influx is never silently dropped.
10    overflow_follow_up_inputs: VecDeque<QueuedFollowUpIntent>,
11    pub(super) in_flight_follow_up_intents: VecDeque<QueuedFollowUpIntent>,
12    applied_follow_up_intent_ids: VecDeque<String>,
13}
14
15impl Default for RuntimeSteering {
16    fn default() -> Self {
17        Self::new(None)
18    }
19}
20
21impl RuntimeSteering {
22    pub(super) fn new(steering_receiver: Option<UnboundedReceiver<SteeringMessage>>) -> Self {
23        Self {
24            steering_receiver,
25            queued_follow_up_inputs: VecDeque::new(),
26            overflow_follow_up_inputs: VecDeque::new(),
27            in_flight_follow_up_intents: VecDeque::new(),
28            applied_follow_up_intent_ids: VecDeque::new(),
29        }
30    }
31
32    /// Replace the steering message receiver channel.
33    pub fn set_receiver(&mut self, receiver: Option<UnboundedReceiver<SteeringMessage>>) {
34        self.steering_receiver = receiver;
35    }
36
37    /// Take ownership of the steering receiver, leaving `None` in its place.
38    pub fn take_receiver(&mut self) -> Option<UnboundedReceiver<SteeringMessage>> {
39        self.steering_receiver.take()
40    }
41
42    #[must_use]
43    pub fn has_pending_follow_up_inputs(&self) -> bool {
44        !self.queued_follow_up_inputs.is_empty() || !self.overflow_follow_up_inputs.is_empty()
45    }
46
47    /// Dequeue the next follow-up user input, if any are pending.
48    pub fn pop_follow_up_input(&mut self) -> Option<String> {
49        self.pop_follow_up_intent().map(|intent| intent.into_parts().1)
50    }
51
52    /// Dequeue the next identified follow-up intent.
53    ///
54    /// Refills the primary FIFO from overflow first so an empty primary with
55    /// parked overflow still yields (`has_pending_follow_up_inputs` staying
56    /// true must not race a `None` pop).
57    pub fn pop_follow_up_intent(&mut self) -> Option<QueuedFollowUpIntent> {
58        self.drain_overflow_into_primary();
59        self.queued_follow_up_inputs.pop_front()
60    }
61
62    /// Move overflow-parked intents into free primary-FIFO slots.
63    fn drain_overflow_into_primary(&mut self) {
64        while self.queued_follow_up_inputs.len() < MAX_QUEUED_FOLLOW_UP_INTENTS
65            && let Some(intent) = self.overflow_follow_up_inputs.pop_front()
66        {
67            self.queued_follow_up_inputs.push_back(intent);
68        }
69    }
70
71    /// Queue a follow-up user input. The boolean is `false` when the FIFO is
72    /// full; callers that need the error detail should use the `try_` variant.
73    pub fn queue_follow_up_input(&mut self, input: String) -> bool {
74        match self.try_queue_follow_up_input(input) {
75            Ok(()) => true,
76            Err(error) => {
77                tracing::warn!(%error, "Rejected follow-up steering intent");
78                false
79            }
80        }
81    }
82
83    /// Queue a follow-up user input and return an explicit overflow error.
84    pub fn try_queue_follow_up_input(&mut self, input: String) -> Result<(), FollowUpQueueFull> {
85        self.try_queue_follow_up_intent(QueuedFollowUpIntent::new(input))
86    }
87
88    /// Queue a harness-generated continuation or recovery instruction.
89    pub fn try_queue_synthetic_follow_up_input(&mut self, input: String) -> Result<(), FollowUpQueueFull> {
90        self.try_queue_follow_up_intent(QueuedFollowUpIntent::new_with_provenance(input, FollowUpProvenance::Synthetic))
91    }
92
93    /// Queue a recovered intent without changing its stable identity.
94    ///
95    /// Primary FIFO first; when it is full the intent parks in a bounded
96    /// overflow buffer so rapid influx is preserved rather than dropped.
97    /// Only when both buffers are full does the call fail.
98    pub fn try_queue_follow_up_intent(&mut self, intent: QueuedFollowUpIntent) -> Result<(), FollowUpQueueFull> {
99        if self.queued_follow_up_inputs.len() + self.in_flight_follow_up_intents.len() < MAX_QUEUED_FOLLOW_UP_INTENTS {
100            self.queued_follow_up_inputs.push_back(intent);
101            return Ok(());
102        }
103        if self.overflow_follow_up_inputs.len() < MAX_OVERFLOW_FOLLOW_UP_INTENTS {
104            self.overflow_follow_up_inputs.push_back(intent);
105            return Ok(());
106        }
107        Err(FollowUpQueueFull {
108            capacity: MAX_QUEUED_FOLLOW_UP_INTENTS + MAX_OVERFLOW_FOLLOW_UP_INTENTS,
109        })
110    }
111
112    /// Mark an intent as applied after its tagged user message is stored.
113    pub fn acknowledge_follow_up_intent(&mut self, intent_id: impl Into<String>) {
114        if self.applied_follow_up_intent_ids.len() >= MAX_APPLIED_FOLLOW_UP_INTENT_IDS {
115            self.applied_follow_up_intent_ids.pop_front();
116        }
117        self.applied_follow_up_intent_ids.push_back(intent_id.into());
118    }
119
120    #[must_use]
121    pub fn applied_follow_up_intent_ids(&self) -> &VecDeque<String> {
122        &self.applied_follow_up_intent_ids
123    }
124
125    /// Primary-FIFO view of pending follow-ups (excludes overflow park and
126    /// in-flight). Prefer [`Self::pending_follow_up_intents_snapshot`] when
127    /// the complete unwritten set matters.
128    #[must_use]
129    pub fn pending_follow_up_intents(&self) -> &VecDeque<QueuedFollowUpIntent> {
130        &self.queued_follow_up_inputs
131    }
132
133    /// Return all accepted intents that are not yet represented by durable
134    /// session history, including the intent currently being processed and
135    /// any parked in the overflow buffer.
136    #[must_use]
137    pub fn pending_follow_up_intents_snapshot(&self) -> Vec<QueuedFollowUpIntent> {
138        self.queued_follow_up_inputs
139            .iter()
140            .chain(self.overflow_follow_up_inputs.iter())
141            .chain(self.in_flight_follow_up_intents.iter())
142            .cloned()
143            .collect()
144    }
145
146    /// Pop every queued follow-up intent and move it to the in-flight queue,
147    /// returning the intents for immediate application to live history
148    /// (mid-turn steering). Until the post-turn history checkpoint succeeds,
149    /// the moved intents stay in the pending snapshot exactly like
150    /// turn-boundary delivery.
151    pub fn drain_follow_up_intents_to_in_flight(&mut self) -> Vec<QueuedFollowUpIntent> {
152        self.drain_overflow_into_primary();
153        let drained: Vec<_> = self.queued_follow_up_inputs.drain(..).collect();
154        self.in_flight_follow_up_intents.extend(drained.iter().cloned());
155        drained
156    }
157
158    /// Mark intents whose tagged user messages have been durably checkpointed
159    /// as applied. Until this is called, the intents remain in the pending
160    /// snapshot so a crash cannot lose them between history and envelope IO.
161    pub fn acknowledge_durable_follow_up_intents(&mut self) {
162        while let Some(intent) = self.in_flight_follow_up_intents.pop_front() {
163            self.acknowledge_follow_up_intent(intent.id());
164        }
165    }
166
167    /// Release intents after their tagged messages have been applied when no
168    /// history archive exists. This frees FIFO capacity for the in-process
169    /// session without adding applied IDs that could falsely imply crash
170    /// durability.
171    pub fn release_in_flight_follow_up_intents_without_persistence(&mut self) {
172        self.in_flight_follow_up_intents.clear();
173    }
174
175    pub fn clear_pending_follow_up_inputs(&mut self) {
176        self.queued_follow_up_inputs.clear();
177        self.overflow_follow_up_inputs.clear();
178        self.in_flight_follow_up_intents.clear();
179    }
180
181    /// Poll the steering channel for control signals during the current turn.
182    pub async fn poll_turn_control(&mut self) -> RuntimeControl {
183        self.poll_control().await
184    }
185
186    /// Poll the steering channel for control signals during tool execution.
187    pub async fn poll_tool_control(&mut self) -> RuntimeControl {
188        self.poll_control().await
189    }
190
191    async fn poll_control(&mut self) -> RuntimeControl {
192        let mut paused = false;
193
194        loop {
195            let Some(receiver) = self.steering_receiver.as_mut() else {
196                return if paused {
197                    RuntimeControl::Resumed
198                } else {
199                    RuntimeControl::Continue
200                };
201            };
202
203            match receiver.try_recv() {
204                Ok(SteeringMessage::SteerStop) => return RuntimeControl::StopRequested,
205                Ok(SteeringMessage::Pause) => {
206                    paused = true;
207                    if matches!(self.wait_for_resume().await, RuntimeControl::StopRequested) {
208                        return RuntimeControl::StopRequested;
209                    }
210                }
211                Ok(SteeringMessage::Resume) => {
212                    paused = true;
213                }
214                Ok(SteeringMessage::FollowUpInput(input)) => {
215                    if let Err(error) = self.try_queue_follow_up_input(input) {
216                        tracing::warn!(%error, "Rejected follow-up steering intent");
217                    }
218                }
219                Err(TryRecvError::Empty | TryRecvError::Disconnected) => {
220                    return if paused {
221                        RuntimeControl::Resumed
222                    } else {
223                        RuntimeControl::Continue
224                    };
225                }
226            }
227        }
228    }
229
230    async fn wait_for_resume(&mut self) -> RuntimeControl {
231        loop {
232            let Some(receiver) = self.steering_receiver.as_mut() else {
233                return RuntimeControl::Continue;
234            };
235
236            match receiver.recv().await {
237                Some(SteeringMessage::Resume) => return RuntimeControl::Continue,
238                Some(SteeringMessage::SteerStop) => return RuntimeControl::StopRequested,
239                Some(SteeringMessage::FollowUpInput(input)) => {
240                    if let Err(error) = self.try_queue_follow_up_input(input) {
241                        tracing::warn!(%error, "Rejected follow-up steering intent");
242                    }
243                }
244                Some(SteeringMessage::Pause) => {}
245                None => return RuntimeControl::Continue,
246            }
247        }
248    }
249}