vtcode_core/core/agent/steering.rs
1use serde::{Deserialize, Serialize};
2use std::fmt;
3use uuid::Uuid;
4
5/// Maximum number of follow-up intents held by a runtime before new intents
6/// park in the overflow buffer. The overflow buffer keeps rapid influx from
7/// silently dropping user messages; once both buffers are full the caller
8/// receives `FollowUpQueueFull` so back-pressure stays visible.
9pub const MAX_QUEUED_FOLLOW_UP_INTENTS: usize = 64;
10/// Overflow park capacity after the primary FIFO is full. Combined with the
11/// primary cap this bounds total retained follow-ups while still absorbing
12/// a burst instead of discarding it.
13pub const MAX_OVERFLOW_FOLLOW_UP_INTENTS: usize = 64;
14/// Total follow-up slots: primary plus overflow plus the one reserved
15/// recovery slot. The memory envelope retains the same count oldest-first
16/// per snapshot.
17pub const MAX_PENDING_FOLLOW_UP_INTENTS: usize = MAX_QUEUED_FOLLOW_UP_INTENTS + MAX_OVERFLOW_FOLLOW_UP_INTENTS + 1;
18/// Maximum number of applied follow-up IDs retained for restart recovery.
19pub const MAX_APPLIED_FOLLOW_UP_INTENT_IDS: usize = 64;
20
21/// Origin of a queued follow-up, preserved when it is applied to conversation history.
22#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
23#[serde(rename_all = "snake_case")]
24pub enum FollowUpProvenance {
25 /// Input supplied by a user through the steering interface.
26 #[default]
27 UserInput,
28 /// A harness-generated continuation or recovery instruction.
29 Synthetic,
30}
31
32/// A follow-up instruction with a stable identity for recovery and
33/// de-duplication.
34#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
35pub struct QueuedFollowUpIntent {
36 id: String,
37 text: String,
38 /// Defaults to user input for envelopes written before provenance existed.
39 #[serde(default)]
40 provenance: FollowUpProvenance,
41}
42
43impl QueuedFollowUpIntent {
44 /// Create a new intent with a UUIDv4 identity.
45 #[must_use]
46 pub fn new(text: String) -> Self {
47 Self::new_with_provenance(text, FollowUpProvenance::UserInput)
48 }
49
50 /// Create a new intent with an explicit source and UUIDv4 identity.
51 #[must_use]
52 pub fn new_with_provenance(text: String, provenance: FollowUpProvenance) -> Self {
53 Self { id: Uuid::new_v4().to_string(), text, provenance }
54 }
55
56 /// Reconstruct an intent recovered from durable state.
57 pub fn from_parts(id: impl Into<String>, text: impl Into<String>) -> Self {
58 Self::from_parts_with_provenance(id, text, FollowUpProvenance::UserInput)
59 }
60
61 /// Reconstruct an intent recovered from durable state with its source.
62 pub fn from_parts_with_provenance(
63 id: impl Into<String>,
64 text: impl Into<String>,
65 provenance: FollowUpProvenance,
66 ) -> Self {
67 Self { id: id.into(), text: text.into(), provenance }
68 }
69
70 #[must_use]
71 pub fn id(&self) -> &str {
72 &self.id
73 }
74
75 #[must_use]
76 pub fn text(&self) -> &str {
77 &self.text
78 }
79
80 #[must_use]
81 pub const fn provenance(&self) -> FollowUpProvenance {
82 self.provenance
83 }
84
85 /// Consume the intent and return its user-visible text.
86 #[must_use]
87 pub fn into_parts(self) -> (String, String) {
88 (self.id, self.text)
89 }
90
91 /// Consume the intent and return its identity, text, and source.
92 #[must_use]
93 pub fn into_parts_with_provenance(self) -> (String, String, FollowUpProvenance) {
94 (self.id, self.text, self.provenance)
95 }
96}
97
98/// Error returned when a runtime cannot accept another follow-up intent.
99#[derive(Debug, Clone, PartialEq, Eq)]
100pub struct FollowUpQueueFull {
101 pub capacity: usize,
102}
103
104impl fmt::Display for FollowUpQueueFull {
105 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
106 write!(f, "follow-up intent queue is full (capacity {})", self.capacity)
107 }
108}
109
110impl std::error::Error for FollowUpQueueFull {}
111
112/// Why a runtime refused a live steer. The sender uses this to decide how to
113/// fall back without ever losing the message.
114#[derive(Debug, Clone, Copy, PartialEq, Eq)]
115pub enum SteerRejection {
116 /// The turn's admission window is already closed.
117 TurnClosing,
118 /// Cancellation was requested and takes precedence over the steer.
119 CancellationPrecedence,
120 /// Both the primary follow-up queue and its overflow park are full.
121 QueueFull,
122 /// There is no live turn to steer (no receiver or no active turn).
123 NoLiveTurn,
124 /// The addressed session, turn, or queue entry was superseded.
125 Superseded,
126}
127
128impl fmt::Display for SteerRejection {
129 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
130 let label = match self {
131 Self::TurnClosing => "turn is closing",
132 Self::CancellationPrecedence => "cancellation takes precedence",
133 Self::QueueFull => "follow-up queue is full",
134 Self::NoLiveTurn => "no live turn",
135 Self::Superseded => "session or turn was superseded",
136 };
137 f.write_str(label)
138 }
139}
140
141/// The single terminal outcome of a live steering handoff. Exactly one of
142/// these is sent on the receipt carried by [`FollowUpSteer`].
143#[derive(Debug, Clone, PartialEq, Eq)]
144pub enum SteerOutcome {
145 /// The runtime admitted the intent into the follow-up queue. `intent_id`
146 /// is the stable identity preserved through history and checkpointing.
147 Accepted { intent_id: String },
148 /// The runtime refused the steer; the sender must fall back to its own
149 /// queue so the message is delivered exactly once.
150 Rejected { reason: SteerRejection },
151}
152
153impl SteerOutcome {
154 /// Whether the steer was admitted.
155 #[must_use]
156 pub const fn accepted(&self) -> bool {
157 matches!(self, Self::Accepted { .. })
158 }
159}
160
161/// One-shot channel used to report a steer's terminal outcome back to its sender.
162pub type SteerReceiptSender = tokio::sync::oneshot::Sender<SteerOutcome>;
163/// Receiver half of [`SteerReceiptSender`].
164pub type SteerReceipt = tokio::sync::oneshot::Receiver<SteerOutcome>;
165
166/// A follow-up steering input together with its optional delivery receipt.
167///
168/// The runtime resolves the receipt at the exact moment it admits or refuses
169/// the intent, so the sender never has to guess from a channel send whether
170/// the message reached model-facing history.
171#[derive(Debug)]
172pub struct FollowUpSteer {
173 pub text: String,
174 pub receipt: Option<SteerReceiptSender>,
175}
176
177impl FollowUpSteer {
178 /// A steer without a receipt (control-path and embedded callers).
179 #[must_use]
180 pub fn new(text: String) -> Self {
181 Self { text, receipt: None }
182 }
183
184 /// A steer whose sender expects a terminal outcome.
185 #[must_use]
186 pub fn with_receipt(text: String, receipt: SteerReceiptSender) -> Self {
187 Self { text, receipt: Some(receipt) }
188 }
189
190 /// Create a steer and the receiver for its terminal outcome.
191 #[must_use]
192 pub fn channel(text: String) -> (Self, SteerReceipt) {
193 let (sender, receiver) = tokio::sync::oneshot::channel();
194 (Self::with_receipt(text, sender), receiver)
195 }
196
197 /// Resolve the receipt with exactly one terminal outcome. Consuming `self`
198 /// makes a second outcome impossible.
199 pub fn resolve(self, outcome: SteerOutcome) {
200 if let Some(receipt) = self.receipt {
201 // A dropped receiver means the sender no longer cares; there is
202 // nobody to deliver a second outcome to.
203 let _ = receipt.send(outcome);
204 }
205 }
206
207 /// Reject this steer with a reason.
208 pub fn reject(self, reason: SteerRejection) {
209 self.resolve(SteerOutcome::Rejected { reason });
210 }
211}
212
213/// Messages used to steer the agent's execution loop from an external source.
214///
215/// This is a control-plane value only: it is never serialized or compared for
216/// equality, so it can carry a one-shot receipt directly.
217#[derive(Debug)]
218pub enum SteeringMessage {
219 /// Stop the agent's execution loop immediately (Steering).
220 SteerStop,
221 /// Pause the agent's execution loop.
222 Pause,
223 /// Resume the agent's execution loop.
224 Resume,
225 /// Inject input as a follow-up user message and resolve its delivery
226 /// receipt when the runtime admits or refuses it.
227 FollowUpInput(FollowUpSteer),
228}