use super::*;
use crate::core::agent::steering::{SteerOutcome, SteerRejection};
pub struct RuntimeSteering {
steering_receiver: Option<UnboundedReceiver<SteeringMessage>>,
pub(super) queued_follow_up_inputs: VecDeque<QueuedFollowUpIntent>,
overflow_follow_up_inputs: VecDeque<QueuedFollowUpIntent>,
recovered_follow_up: Option<QueuedFollowUpIntent>,
pub(super) in_flight_follow_up_intents: VecDeque<QueuedFollowUpIntent>,
applied_follow_up_intent_ids: VecDeque<String>,
admission_closed: bool,
cancellation_precedence: bool,
}
impl Default for RuntimeSteering {
fn default() -> Self {
Self::new(None)
}
}
impl RuntimeSteering {
pub(super) fn new(steering_receiver: Option<UnboundedReceiver<SteeringMessage>>) -> Self {
Self {
steering_receiver,
queued_follow_up_inputs: VecDeque::new(),
overflow_follow_up_inputs: VecDeque::new(),
recovered_follow_up: None,
in_flight_follow_up_intents: VecDeque::new(),
applied_follow_up_intent_ids: VecDeque::new(),
admission_closed: false,
cancellation_precedence: false,
}
}
pub fn set_receiver(&mut self, receiver: Option<UnboundedReceiver<SteeringMessage>>) {
self.steering_receiver = receiver;
}
pub fn take_receiver(&mut self) -> Option<UnboundedReceiver<SteeringMessage>> {
self.steering_receiver.take()
}
pub fn open_admission(&mut self) {
self.admission_closed = false;
self.cancellation_precedence = false;
}
pub fn close_admission(&mut self) {
self.admission_closed = true;
}
#[must_use]
pub const fn admission_closed(&self) -> bool {
self.admission_closed
}
pub fn set_cancellation_precedence(&mut self, value: bool) {
self.cancellation_precedence = value;
}
pub fn drain_rejected_steers(&mut self) {
let Some(mut receiver) = self.steering_receiver.take() else {
return;
};
while let Ok(message) = receiver.try_recv() {
if let SteeringMessage::FollowUpInput(steer) = message {
steer.reject(SteerRejection::TurnClosing);
}
}
self.steering_receiver = Some(receiver);
}
pub fn admit_follow_up_steer(&mut self, steer: FollowUpSteer) -> Option<QueuedFollowUpIntent> {
let FollowUpSteer { text, mut receipt } = steer;
let reject = |reason: SteerRejection, receipt: &mut Option<tokio::sync::oneshot::Sender<SteerOutcome>>| {
if let Some(receipt) = receipt.take() {
let _ = receipt.send(SteerOutcome::Rejected { reason });
}
None
};
if self.admission_closed {
return reject(SteerRejection::TurnClosing, &mut receipt);
}
if self.cancellation_precedence {
return reject(SteerRejection::CancellationPrecedence, &mut receipt);
}
let intent = QueuedFollowUpIntent::new(text);
if let Err(error) = self.try_queue_follow_up_intent(intent.clone()) {
tracing::warn!(%error, "Rejected live steer: follow-up queue full");
return reject(SteerRejection::QueueFull, &mut receipt);
}
if let Some(receipt) = receipt {
let _ = receipt.send(SteerOutcome::Accepted { intent_id: intent.id().to_string() });
}
Some(intent)
}
#[must_use]
pub fn has_pending_follow_up_inputs(&self) -> bool {
!self.queued_follow_up_inputs.is_empty()
|| !self.overflow_follow_up_inputs.is_empty()
|| self.recovered_follow_up.is_some()
}
pub fn pop_follow_up_input(&mut self) -> Option<String> {
self.pop_follow_up_intent().map(|intent| intent.into_parts().1)
}
pub fn pop_follow_up_intent(&mut self) -> Option<QueuedFollowUpIntent> {
self.drain_overflow_into_primary();
self.queued_follow_up_inputs
.pop_front()
.or_else(|| self.recovered_follow_up.take())
}
fn drain_overflow_into_primary(&mut self) {
while self.queued_follow_up_inputs.len() < MAX_QUEUED_FOLLOW_UP_INTENTS
&& let Some(intent) = self.overflow_follow_up_inputs.pop_front()
{
self.queued_follow_up_inputs.push_back(intent);
}
if self.overflow_follow_up_inputs.is_empty()
&& self.queued_follow_up_inputs.len() < MAX_QUEUED_FOLLOW_UP_INTENTS
&& let Some(intent) = self.recovered_follow_up.take()
{
self.queued_follow_up_inputs.push_back(intent);
}
}
pub fn queue_follow_up_input(&mut self, input: String) -> bool {
match self.try_queue_follow_up_input(input) {
Ok(()) => true,
Err(error) => {
tracing::warn!(%error, "Rejected follow-up steering intent");
false
}
}
}
pub fn try_queue_follow_up_input(&mut self, input: String) -> Result<(), FollowUpQueueFull> {
self.try_queue_follow_up_intent(QueuedFollowUpIntent::new(input))
}
pub fn try_queue_synthetic_follow_up_input(&mut self, input: String) -> Result<(), FollowUpQueueFull> {
self.try_queue_follow_up_intent(QueuedFollowUpIntent::new_with_provenance(input, FollowUpProvenance::Synthetic))
}
pub fn try_queue_follow_up_intent(&mut self, intent: QueuedFollowUpIntent) -> Result<(), FollowUpQueueFull> {
while self.queued_follow_up_inputs.len() + self.in_flight_follow_up_intents.len() < MAX_QUEUED_FOLLOW_UP_INTENTS
&& let Some(older) = self.overflow_follow_up_inputs.pop_front()
{
self.queued_follow_up_inputs.push_back(older);
}
if self.overflow_follow_up_inputs.is_empty()
&& self.queued_follow_up_inputs.len() + self.in_flight_follow_up_intents.len()
< MAX_QUEUED_FOLLOW_UP_INTENTS
&& let Some(recovered) = self.recovered_follow_up.take()
{
self.queued_follow_up_inputs.push_back(recovered);
} else if self.overflow_follow_up_inputs.len() < MAX_OVERFLOW_FOLLOW_UP_INTENTS
&& let Some(recovered) = self.recovered_follow_up.take()
{
self.overflow_follow_up_inputs.push_back(recovered);
}
if self.recovered_follow_up.is_some() {
return Err(FollowUpQueueFull {
capacity: MAX_QUEUED_FOLLOW_UP_INTENTS + MAX_OVERFLOW_FOLLOW_UP_INTENTS,
});
}
if self.queued_follow_up_inputs.len() + self.in_flight_follow_up_intents.len() < MAX_QUEUED_FOLLOW_UP_INTENTS {
self.queued_follow_up_inputs.push_back(intent);
return Ok(());
}
if self.overflow_follow_up_inputs.len() < MAX_OVERFLOW_FOLLOW_UP_INTENTS {
self.overflow_follow_up_inputs.push_back(intent);
return Ok(());
}
Err(FollowUpQueueFull {
capacity: MAX_QUEUED_FOLLOW_UP_INTENTS + MAX_OVERFLOW_FOLLOW_UP_INTENTS,
})
}
pub fn try_queue_recovered_follow_up(&mut self, intent: QueuedFollowUpIntent) -> Result<(), FollowUpQueueFull> {
if self.recovered_follow_up.is_some() {
return Err(FollowUpQueueFull { capacity: MAX_PENDING_FOLLOW_UP_INTENTS });
}
match self.try_queue_follow_up_intent(intent.clone()) {
Ok(()) => Ok(()),
Err(_) => {
self.recovered_follow_up = Some(intent);
Ok(())
}
}
}
pub fn acknowledge_follow_up_intent(&mut self, intent_id: impl Into<String>) {
if self.applied_follow_up_intent_ids.len() >= MAX_APPLIED_FOLLOW_UP_INTENT_IDS {
self.applied_follow_up_intent_ids.pop_front();
}
self.applied_follow_up_intent_ids.push_back(intent_id.into());
}
#[must_use]
pub fn applied_follow_up_intent_ids(&self) -> &VecDeque<String> {
&self.applied_follow_up_intent_ids
}
#[must_use]
pub fn pending_follow_up_intents(&self) -> &VecDeque<QueuedFollowUpIntent> {
&self.queued_follow_up_inputs
}
#[must_use]
pub fn pending_follow_up_intents_snapshot(&self) -> Vec<QueuedFollowUpIntent> {
self.in_flight_follow_up_intents
.iter()
.chain(self.queued_follow_up_inputs.iter())
.chain(self.overflow_follow_up_inputs.iter())
.chain(self.recovered_follow_up.iter())
.cloned()
.collect()
}
pub fn drain_follow_up_intents_to_in_flight(&mut self) -> Vec<QueuedFollowUpIntent> {
self.drain_overflow_into_primary();
let drained: Vec<_> = self.queued_follow_up_inputs.drain(..).collect();
self.in_flight_follow_up_intents.extend(drained.iter().cloned());
drained
}
pub fn acknowledge_durable_follow_up_intents(&mut self) {
while let Some(intent) = self.in_flight_follow_up_intents.pop_front() {
self.acknowledge_follow_up_intent(intent.id());
}
}
pub fn release_in_flight_follow_up_intents_without_persistence(&mut self) {
self.in_flight_follow_up_intents.clear();
}
pub fn clear_pending_follow_up_inputs(&mut self) {
self.queued_follow_up_inputs.clear();
self.overflow_follow_up_inputs.clear();
self.recovered_follow_up = None;
self.in_flight_follow_up_intents.clear();
}
pub async fn poll_turn_control(&mut self) -> RuntimeControl {
self.poll_control().await
}
pub async fn poll_tool_control(&mut self) -> RuntimeControl {
self.poll_control().await
}
async fn poll_control(&mut self) -> RuntimeControl {
let mut paused = false;
loop {
let Some(receiver) = self.steering_receiver.as_mut() else {
return if paused {
RuntimeControl::Resumed
} else {
RuntimeControl::Continue
};
};
match receiver.try_recv() {
Ok(SteeringMessage::SteerStop) => return RuntimeControl::StopRequested,
Ok(SteeringMessage::Pause) => {
paused = true;
if matches!(self.wait_for_resume().await, RuntimeControl::StopRequested) {
return RuntimeControl::StopRequested;
}
}
Ok(SteeringMessage::Resume) => {
paused = true;
}
Ok(SteeringMessage::FollowUpInput(steer)) => {
let _ = self.admit_follow_up_steer(steer);
}
Err(TryRecvError::Empty | TryRecvError::Disconnected) => {
return if paused {
RuntimeControl::Resumed
} else {
RuntimeControl::Continue
};
}
}
}
}
async fn wait_for_resume(&mut self) -> RuntimeControl {
loop {
let Some(receiver) = self.steering_receiver.as_mut() else {
return RuntimeControl::Continue;
};
match receiver.recv().await {
Some(SteeringMessage::Resume) => return RuntimeControl::Continue,
Some(SteeringMessage::SteerStop) => return RuntimeControl::StopRequested,
Some(SteeringMessage::FollowUpInput(steer)) => {
let _ = self.admit_follow_up_steer(steer);
}
Some(SteeringMessage::Pause) => {}
None => return RuntimeControl::Continue,
}
}
}
}