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