Skip to main content

vtcode_core/core/agent/runtime/
steering.rs

1use super::*;
2use crate::core::agent::steering::{SteerOutcome, SteerRejection};
3
4/// Manages steering messages (stop, pause, resume, follow-up inputs) for a running agent turn.
5pub struct RuntimeSteering {
6    steering_receiver: Option<UnboundedReceiver<SteeringMessage>>,
7    pub(super) queued_follow_up_inputs: VecDeque<QueuedFollowUpIntent>,
8    /// Overflow park for follow-ups that arrive while the primary FIFO is
9    /// full. Drained FIFO into the primary queue as space frees so a rapid
10    /// influx is never silently dropped.
11    overflow_follow_up_inputs: VecDeque<QueuedFollowUpIntent>,
12    recovered_follow_up: Option<QueuedFollowUpIntent>,
13    pub(super) in_flight_follow_up_intents: VecDeque<QueuedFollowUpIntent>,
14    applied_follow_up_intent_ids: VecDeque<String>,
15    /// Once closed, no further live steer may be admitted. Closed atomically
16    /// with the final steering drain so a late arrival is rejected instead of
17    /// being stranded in the channel after the turn ends.
18    admission_closed: bool,
19    /// Set by the runloop when cancellation outranks a pending steer.
20    cancellation_precedence: bool,
21}
22
23impl Default for RuntimeSteering {
24    fn default() -> Self {
25        Self::new(None)
26    }
27}
28
29impl RuntimeSteering {
30    pub(super) fn new(steering_receiver: Option<UnboundedReceiver<SteeringMessage>>) -> Self {
31        Self {
32            steering_receiver,
33            queued_follow_up_inputs: VecDeque::new(),
34            overflow_follow_up_inputs: VecDeque::new(),
35            recovered_follow_up: None,
36            in_flight_follow_up_intents: VecDeque::new(),
37            applied_follow_up_intent_ids: VecDeque::new(),
38            admission_closed: false,
39            cancellation_precedence: false,
40        }
41    }
42
43    /// Replace the steering message receiver channel.
44    pub fn set_receiver(&mut self, receiver: Option<UnboundedReceiver<SteeringMessage>>) {
45        self.steering_receiver = receiver;
46    }
47
48    /// Take ownership of the steering receiver, leaving `None` in its place.
49    pub fn take_receiver(&mut self) -> Option<UnboundedReceiver<SteeringMessage>> {
50        self.steering_receiver.take()
51    }
52
53    /// Reopen admission for a new turn. Called once at turn setup.
54    pub fn open_admission(&mut self) {
55        self.admission_closed = false;
56        self.cancellation_precedence = false;
57    }
58
59    /// Close admission atomically with the final steering drain. Later arrivals
60    /// are rejected rather than left stranded in the channel.
61    pub fn close_admission(&mut self) {
62        self.admission_closed = true;
63    }
64
65    #[must_use]
66    pub const fn admission_closed(&self) -> bool {
67        self.admission_closed
68    }
69
70    /// Declare that cancellation outranks any pending steer until the next
71    /// [`Self::open_admission`].
72    pub fn set_cancellation_precedence(&mut self, value: bool) {
73        self.cancellation_precedence = value;
74    }
75
76    /// Reject steers that arrived after admission closed but before the next
77    /// turn reopens it. Without this drain a late arrival would be admitted
78    /// into the following turn instead of being rejected as intended.
79    pub fn drain_rejected_steers(&mut self) {
80        let Some(mut receiver) = self.steering_receiver.take() else {
81            return;
82        };
83        while let Ok(message) = receiver.try_recv() {
84            if let SteeringMessage::FollowUpInput(steer) = message {
85                steer.reject(SteerRejection::TurnClosing);
86            }
87        }
88        self.steering_receiver = Some(receiver);
89    }
90
91    /// The single authoritative admission point for a live steer.
92    ///
93    /// Checks the admission gate and capacity, queues the intent with a fresh
94    /// identity, and resolves the receipt with exactly one terminal outcome.
95    /// Returns the admitted intent so callers can apply it to model-facing
96    /// history; `None` means the steer was rejected and the sender must fall
97    /// back to its own queue.
98    pub fn admit_follow_up_steer(&mut self, steer: FollowUpSteer) -> Option<QueuedFollowUpIntent> {
99        let FollowUpSteer { text, mut receipt } = steer;
100        let reject = |reason: SteerRejection, receipt: &mut Option<tokio::sync::oneshot::Sender<SteerOutcome>>| {
101            if let Some(receipt) = receipt.take() {
102                let _ = receipt.send(SteerOutcome::Rejected { reason });
103            }
104            None
105        };
106        if self.admission_closed {
107            return reject(SteerRejection::TurnClosing, &mut receipt);
108        }
109        if self.cancellation_precedence {
110            return reject(SteerRejection::CancellationPrecedence, &mut receipt);
111        }
112        let intent = QueuedFollowUpIntent::new(text);
113        if let Err(error) = self.try_queue_follow_up_intent(intent.clone()) {
114            tracing::warn!(%error, "Rejected live steer: follow-up queue full");
115            return reject(SteerRejection::QueueFull, &mut receipt);
116        }
117        if let Some(receipt) = receipt {
118            let _ = receipt.send(SteerOutcome::Accepted { intent_id: intent.id().to_string() });
119        }
120        Some(intent)
121    }
122
123    #[must_use]
124    pub fn has_pending_follow_up_inputs(&self) -> bool {
125        !self.queued_follow_up_inputs.is_empty()
126            || !self.overflow_follow_up_inputs.is_empty()
127            || self.recovered_follow_up.is_some()
128    }
129
130    /// Dequeue the next follow-up user input, if any are pending.
131    pub fn pop_follow_up_input(&mut self) -> Option<String> {
132        self.pop_follow_up_intent().map(|intent| intent.into_parts().1)
133    }
134
135    /// Dequeue the next identified follow-up intent.
136    ///
137    /// Refills the primary FIFO from overflow first so an empty primary with
138    /// parked overflow still yields (`has_pending_follow_up_inputs` staying
139    /// true must not race a `None` pop).
140    pub fn pop_follow_up_intent(&mut self) -> Option<QueuedFollowUpIntent> {
141        self.drain_overflow_into_primary();
142        self.queued_follow_up_inputs
143            .pop_front()
144            .or_else(|| self.recovered_follow_up.take())
145    }
146
147    /// Move overflow-parked intents into free primary-FIFO slots.
148    fn drain_overflow_into_primary(&mut self) {
149        while self.queued_follow_up_inputs.len() < MAX_QUEUED_FOLLOW_UP_INTENTS
150            && let Some(intent) = self.overflow_follow_up_inputs.pop_front()
151        {
152            self.queued_follow_up_inputs.push_back(intent);
153        }
154        if self.overflow_follow_up_inputs.is_empty()
155            && self.queued_follow_up_inputs.len() < MAX_QUEUED_FOLLOW_UP_INTENTS
156            && let Some(intent) = self.recovered_follow_up.take()
157        {
158            self.queued_follow_up_inputs.push_back(intent);
159        }
160    }
161
162    /// Queue a follow-up user input. The boolean is `false` when the FIFO is
163    /// full; callers that need the error detail should use the `try_` variant.
164    pub fn queue_follow_up_input(&mut self, input: String) -> bool {
165        match self.try_queue_follow_up_input(input) {
166            Ok(()) => true,
167            Err(error) => {
168                tracing::warn!(%error, "Rejected follow-up steering intent");
169                false
170            }
171        }
172    }
173
174    /// Queue a follow-up user input and return an explicit overflow error.
175    pub fn try_queue_follow_up_input(&mut self, input: String) -> Result<(), FollowUpQueueFull> {
176        self.try_queue_follow_up_intent(QueuedFollowUpIntent::new(input))
177    }
178
179    /// Queue a harness-generated continuation or recovery instruction.
180    pub fn try_queue_synthetic_follow_up_input(&mut self, input: String) -> Result<(), FollowUpQueueFull> {
181        self.try_queue_follow_up_intent(QueuedFollowUpIntent::new_with_provenance(input, FollowUpProvenance::Synthetic))
182    }
183
184    /// Queue a recovered intent without changing its stable identity.
185    ///
186    /// Primary FIFO first; when it is full the intent parks in a bounded
187    /// overflow buffer so rapid influx is preserved rather than dropped.
188    /// Only when both buffers are full does the call fail.
189    pub fn try_queue_follow_up_intent(&mut self, intent: QueuedFollowUpIntent) -> Result<(), FollowUpQueueFull> {
190        while self.queued_follow_up_inputs.len() + self.in_flight_follow_up_intents.len() < MAX_QUEUED_FOLLOW_UP_INTENTS
191            && let Some(older) = self.overflow_follow_up_inputs.pop_front()
192        {
193            self.queued_follow_up_inputs.push_back(older);
194        }
195        if self.overflow_follow_up_inputs.is_empty()
196            && self.queued_follow_up_inputs.len() + self.in_flight_follow_up_intents.len()
197                < MAX_QUEUED_FOLLOW_UP_INTENTS
198            && let Some(recovered) = self.recovered_follow_up.take()
199        {
200            self.queued_follow_up_inputs.push_back(recovered);
201        } else if self.overflow_follow_up_inputs.len() < MAX_OVERFLOW_FOLLOW_UP_INTENTS
202            && let Some(recovered) = self.recovered_follow_up.take()
203        {
204            self.overflow_follow_up_inputs.push_back(recovered);
205        }
206        if self.recovered_follow_up.is_some() {
207            return Err(FollowUpQueueFull {
208                capacity: MAX_QUEUED_FOLLOW_UP_INTENTS + MAX_OVERFLOW_FOLLOW_UP_INTENTS,
209            });
210        }
211        if self.queued_follow_up_inputs.len() + self.in_flight_follow_up_intents.len() < MAX_QUEUED_FOLLOW_UP_INTENTS {
212            self.queued_follow_up_inputs.push_back(intent);
213            return Ok(());
214        }
215        if self.overflow_follow_up_inputs.len() < MAX_OVERFLOW_FOLLOW_UP_INTENTS {
216            self.overflow_follow_up_inputs.push_back(intent);
217            return Ok(());
218        }
219        Err(FollowUpQueueFull {
220            capacity: MAX_QUEUED_FOLLOW_UP_INTENTS + MAX_OVERFLOW_FOLLOW_UP_INTENTS,
221        })
222    }
223
224    /// Reserve one additional slot for an interrupted, already accepted input.
225    pub fn try_queue_recovered_follow_up(&mut self, intent: QueuedFollowUpIntent) -> Result<(), FollowUpQueueFull> {
226        if self.recovered_follow_up.is_some() {
227            return Err(FollowUpQueueFull { capacity: MAX_PENDING_FOLLOW_UP_INTENTS });
228        }
229        match self.try_queue_follow_up_intent(intent.clone()) {
230            Ok(()) => Ok(()),
231            Err(_) => {
232                self.recovered_follow_up = Some(intent);
233                Ok(())
234            }
235        }
236    }
237
238    /// Mark an intent as applied after its tagged user message is stored.
239    pub fn acknowledge_follow_up_intent(&mut self, intent_id: impl Into<String>) {
240        if self.applied_follow_up_intent_ids.len() >= MAX_APPLIED_FOLLOW_UP_INTENT_IDS {
241            self.applied_follow_up_intent_ids.pop_front();
242        }
243        self.applied_follow_up_intent_ids.push_back(intent_id.into());
244    }
245
246    #[must_use]
247    pub fn applied_follow_up_intent_ids(&self) -> &VecDeque<String> {
248        &self.applied_follow_up_intent_ids
249    }
250
251    /// Primary-FIFO view of pending follow-ups (excludes overflow park and
252    /// in-flight). Prefer [`Self::pending_follow_up_intents_snapshot`] when
253    /// the complete unwritten set matters.
254    #[must_use]
255    pub fn pending_follow_up_intents(&self) -> &VecDeque<QueuedFollowUpIntent> {
256        &self.queued_follow_up_inputs
257    }
258
259    /// Return all accepted intents that are not yet represented by durable
260    /// session history, including the intent currently being processed and
261    /// any parked in the overflow buffer.
262    #[must_use]
263    pub fn pending_follow_up_intents_snapshot(&self) -> Vec<QueuedFollowUpIntent> {
264        self.in_flight_follow_up_intents
265            .iter()
266            .chain(self.queued_follow_up_inputs.iter())
267            .chain(self.overflow_follow_up_inputs.iter())
268            .chain(self.recovered_follow_up.iter())
269            .cloned()
270            .collect()
271    }
272
273    /// Pop every queued follow-up intent and move it to the in-flight queue,
274    /// returning the intents for immediate application to live history
275    /// (mid-turn steering). Until the post-turn history checkpoint succeeds,
276    /// the moved intents stay in the pending snapshot exactly like
277    /// turn-boundary delivery.
278    pub fn drain_follow_up_intents_to_in_flight(&mut self) -> Vec<QueuedFollowUpIntent> {
279        self.drain_overflow_into_primary();
280        let drained: Vec<_> = self.queued_follow_up_inputs.drain(..).collect();
281        self.in_flight_follow_up_intents.extend(drained.iter().cloned());
282        drained
283    }
284
285    /// Mark intents whose tagged user messages have been durably checkpointed
286    /// as applied. Until this is called, the intents remain in the pending
287    /// snapshot so a crash cannot lose them between history and envelope IO.
288    pub fn acknowledge_durable_follow_up_intents(&mut self) {
289        while let Some(intent) = self.in_flight_follow_up_intents.pop_front() {
290            self.acknowledge_follow_up_intent(intent.id());
291        }
292    }
293
294    /// Release intents after their tagged messages have been applied when no
295    /// history archive exists. This frees FIFO capacity for the in-process
296    /// session without adding applied IDs that could falsely imply crash
297    /// durability.
298    pub fn release_in_flight_follow_up_intents_without_persistence(&mut self) {
299        self.in_flight_follow_up_intents.clear();
300    }
301
302    pub fn clear_pending_follow_up_inputs(&mut self) {
303        self.queued_follow_up_inputs.clear();
304        self.overflow_follow_up_inputs.clear();
305        self.recovered_follow_up = None;
306        self.in_flight_follow_up_intents.clear();
307    }
308
309    /// Poll the steering channel for control signals during the current turn.
310    pub async fn poll_turn_control(&mut self) -> RuntimeControl {
311        self.poll_control().await
312    }
313
314    /// Poll the steering channel for control signals during tool execution.
315    pub async fn poll_tool_control(&mut self) -> RuntimeControl {
316        self.poll_control().await
317    }
318
319    async fn poll_control(&mut self) -> RuntimeControl {
320        let mut paused = false;
321
322        loop {
323            let Some(receiver) = self.steering_receiver.as_mut() else {
324                return if paused {
325                    RuntimeControl::Resumed
326                } else {
327                    RuntimeControl::Continue
328                };
329            };
330
331            match receiver.try_recv() {
332                Ok(SteeringMessage::SteerStop) => return RuntimeControl::StopRequested,
333                Ok(SteeringMessage::Pause) => {
334                    paused = true;
335                    if matches!(self.wait_for_resume().await, RuntimeControl::StopRequested) {
336                        return RuntimeControl::StopRequested;
337                    }
338                }
339                Ok(SteeringMessage::Resume) => {
340                    paused = true;
341                }
342                Ok(SteeringMessage::FollowUpInput(steer)) => {
343                    let _ = self.admit_follow_up_steer(steer);
344                }
345                Err(TryRecvError::Empty | TryRecvError::Disconnected) => {
346                    return if paused {
347                        RuntimeControl::Resumed
348                    } else {
349                        RuntimeControl::Continue
350                    };
351                }
352            }
353        }
354    }
355
356    async fn wait_for_resume(&mut self) -> RuntimeControl {
357        loop {
358            let Some(receiver) = self.steering_receiver.as_mut() else {
359                return RuntimeControl::Continue;
360            };
361
362            match receiver.recv().await {
363                Some(SteeringMessage::Resume) => return RuntimeControl::Continue,
364                Some(SteeringMessage::SteerStop) => return RuntimeControl::StopRequested,
365                Some(SteeringMessage::FollowUpInput(steer)) => {
366                    let _ = self.admit_follow_up_steer(steer);
367                }
368                Some(SteeringMessage::Pause) => {}
369                None => return RuntimeControl::Continue,
370            }
371        }
372    }
373}