1use crate::core::agent::events::{EventSink, SharedLifecycleEmitter};
2use crate::core::agent::session::AgentSessionState;
3use crate::core::agent::steering::{
4 FollowUpProvenance, FollowUpQueueFull, MAX_APPLIED_FOLLOW_UP_INTENT_IDS, MAX_OVERFLOW_FOLLOW_UP_INTENTS,
5 MAX_QUEUED_FOLLOW_UP_INTENTS, QueuedFollowUpIntent, SteeringMessage,
6};
7use crate::exec::events::{ThreadEvent, ToolCallStatus, ToolOutcome};
8use crate::llm::provider::{
9 AssistantPhase, FinishReason, LLMProvider, LLMRequest, LLMResponse, NormalizedStreamEvent, ToolCall,
10 Usage as ProviderUsage,
11};
12use crate::llm::providers::gemini::wire::{Content, Part};
13use anyhow::Result;
14use async_trait::async_trait;
15use futures::StreamExt;
16use std::collections::HashSet;
17use std::collections::VecDeque;
18use std::time::Instant;
19use tokio::sync::mpsc::UnboundedReceiver;
20use tokio::sync::mpsc::error::TryRecvError;
21
22fn merge_stream_and_completed_text(accumulated: &mut String, completed: Option<&str>) {
23 let Some(completed_text) = completed else {
24 return;
25 };
26 if completed_text.is_empty() {
27 return;
28 }
29 if accumulated.is_empty() {
30 accumulated.push_str(completed_text);
31 return;
32 }
33 if completed_text == accumulated.as_str() {
34 return;
35 }
36 if let Some(suffix) = completed_text.strip_prefix(accumulated.as_str()) {
37 accumulated.push_str(suffix);
38 return;
39 }
40 accumulated.clear();
41 accumulated.push_str(completed_text);
42}
43
44#[derive(Debug, Clone, Copy, PartialEq, Eq)]
46pub enum RuntimeControl {
47 Continue,
49 Resumed,
51 StopRequested,
53}
54
55#[doc(hidden)]
57#[derive(Debug, Clone, PartialEq, Eq)]
58pub enum RuntimeModelProgress {
59 OutputDelta(String),
61 ReasoningDelta(String),
63 ReasoningStage(String),
65 ProviderActivity,
67 ToolCallStarted {
69 call_id: String,
71 name: Option<String>,
73 },
74 ToolCallDelta {
76 call_id: String,
78 delta: String,
80 },
81}
82
83#[derive(Debug, Clone)]
84struct RuntimeModelOutput {
85 response: LLMResponse,
86}
87
88#[async_trait]
89trait RuntimeModelAdapter {
90 async fn execute(
91 &mut self,
92 request: LLMRequest,
93 timeout: Option<std::time::Duration>,
94 on_progress: &mut (dyn FnMut(RuntimeModelProgress) + Send),
95 ) -> Result<RuntimeModelOutput>;
96}
97
98struct ProviderRuntimeModelAdapter<'a> {
99 provider: &'a mut Box<dyn LLMProvider>,
100 steering: &'a mut RuntimeSteering,
101}
102
103impl<'a> ProviderRuntimeModelAdapter<'a> {
104 fn new(provider: &'a mut Box<dyn LLMProvider>, steering: &'a mut RuntimeSteering) -> Self {
105 Self { provider, steering }
106 }
107}
108
109#[async_trait]
110impl RuntimeModelAdapter for ProviderRuntimeModelAdapter<'_> {
111 async fn execute(
112 &mut self,
113 request: LLMRequest,
114 timeout: Option<std::time::Duration>,
115 on_progress: &mut (dyn FnMut(RuntimeModelProgress) + Send),
116 ) -> Result<RuntimeModelOutput> {
117 let started_at = Instant::now();
118 let request_model = request.model.clone();
119 let mut stream = if let Some(duration) = timeout {
120 match tokio::time::timeout(duration, self.provider.stream_normalized(request)).await {
121 Ok(result) => result?,
122 Err(_) => {
123 tracing::warn!(model = %request_model, elapsed_ms = started_at.elapsed().as_millis() as u64, "model stream timed out");
124 return Err(anyhow::anyhow!("Stream request timed out after {duration:?}"));
125 }
126 }
127 } else {
128 self.provider.stream_normalized(request).await?
129 };
130
131 let mut final_usage = ProviderUsage::default();
132 let mut completed_response: Option<LLMResponse> = None;
133 let mut provider_activity_reported = false;
134 while let Some(event_result) = stream.next().await {
135 if matches!(self.steering.poll_turn_control().await, RuntimeControl::StopRequested) {
136 tracing::info!(model = %request_model, elapsed_ms = started_at.elapsed().as_millis() as u64, "model stream cancelled");
137 let mut response = LLMResponse {
138 model: request_model.clone(),
139 finish_reason: FinishReason::Error("Cancelled".to_string()),
140 usage: Some(final_usage.clone()),
141 ..Default::default()
142 };
143 if response.usage.as_ref().is_some_and(|usage| {
144 usage.prompt_tokens == 0 && usage.completion_tokens == 0 && usage.total_tokens == 0
145 }) {
146 response.usage = None;
147 }
148 return Ok(RuntimeModelOutput { response });
149 }
150
151 match event_result? {
152 NormalizedStreamEvent::TextDelta { delta } => {
153 on_progress(RuntimeModelProgress::OutputDelta(delta));
154 }
155 NormalizedStreamEvent::ReasoningDelta { delta, source } if source.is_public_summary() => {
156 on_progress(RuntimeModelProgress::ReasoningDelta(delta));
157 }
158 NormalizedStreamEvent::ReasoningDelta { .. } => {
159 if !provider_activity_reported {
160 provider_activity_reported = true;
161 on_progress(RuntimeModelProgress::ProviderActivity);
162 }
163 }
164 NormalizedStreamEvent::ReasoningStage { stage } => {
165 on_progress(RuntimeModelProgress::ReasoningStage(stage));
166 }
167 NormalizedStreamEvent::ToolCallStart { call_id, name } => {
168 on_progress(RuntimeModelProgress::ToolCallStarted { call_id, name });
169 }
170 NormalizedStreamEvent::ToolCallDelta { call_id, delta } => {
171 on_progress(RuntimeModelProgress::ToolCallDelta { call_id, delta });
172 }
173 NormalizedStreamEvent::Usage { usage } => {
174 final_usage = usage;
175 }
176 NormalizedStreamEvent::Done { response } => {
177 let mut response = *response;
178 if response.usage.is_none()
179 && (final_usage.prompt_tokens > 0
180 || final_usage.completion_tokens > 0
181 || final_usage.total_tokens > 0)
182 {
183 response.usage = Some(final_usage.clone());
184 }
185 completed_response = Some(response);
186 break;
187 }
188 }
189 }
190
191 let mut response = completed_response.unwrap_or_default();
192 if response.model.is_empty() {
193 response.model = request_model;
194 }
195 if response.usage.is_none()
196 && (final_usage.prompt_tokens > 0 || final_usage.completion_tokens > 0 || final_usage.total_tokens > 0)
197 {
198 response.usage = Some(final_usage);
199 }
200
201 tracing::debug!(
202 model = %response.model,
203 elapsed_ms = started_at.elapsed().as_millis() as u64,
204 input_tokens = response.usage.as_ref().map_or(0, |usage| usage.prompt_tokens),
205 output_tokens = response.usage.as_ref().map_or(0, |usage| usage.completion_tokens),
206 finish_reason = ?response.finish_reason,
207 "model stream completed"
208 );
209 Ok(RuntimeModelOutput { response })
210 }
211}
212
213pub struct RuntimeSteering {
215 steering_receiver: Option<UnboundedReceiver<SteeringMessage>>,
216 queued_follow_up_inputs: VecDeque<QueuedFollowUpIntent>,
217 overflow_follow_up_inputs: VecDeque<QueuedFollowUpIntent>,
221 in_flight_follow_up_intents: VecDeque<QueuedFollowUpIntent>,
222 applied_follow_up_intent_ids: VecDeque<String>,
223}
224
225impl Default for RuntimeSteering {
226 fn default() -> Self {
227 Self::new(None)
228 }
229}
230
231impl RuntimeSteering {
232 fn new(steering_receiver: Option<UnboundedReceiver<SteeringMessage>>) -> Self {
233 Self {
234 steering_receiver,
235 queued_follow_up_inputs: VecDeque::new(),
236 overflow_follow_up_inputs: VecDeque::new(),
237 in_flight_follow_up_intents: VecDeque::new(),
238 applied_follow_up_intent_ids: VecDeque::new(),
239 }
240 }
241
242 pub fn set_receiver(&mut self, receiver: Option<UnboundedReceiver<SteeringMessage>>) {
244 self.steering_receiver = receiver;
245 }
246
247 pub fn take_receiver(&mut self) -> Option<UnboundedReceiver<SteeringMessage>> {
249 self.steering_receiver.take()
250 }
251
252 #[must_use]
253 pub fn has_pending_follow_up_inputs(&self) -> bool {
254 !self.queued_follow_up_inputs.is_empty() || !self.overflow_follow_up_inputs.is_empty()
255 }
256
257 pub fn pop_follow_up_input(&mut self) -> Option<String> {
259 self.pop_follow_up_intent().map(|intent| intent.into_parts().1)
260 }
261
262 pub fn pop_follow_up_intent(&mut self) -> Option<QueuedFollowUpIntent> {
268 self.drain_overflow_into_primary();
269 self.queued_follow_up_inputs.pop_front()
270 }
271
272 fn drain_overflow_into_primary(&mut self) {
274 while self.queued_follow_up_inputs.len() < MAX_QUEUED_FOLLOW_UP_INTENTS
275 && let Some(intent) = self.overflow_follow_up_inputs.pop_front()
276 {
277 self.queued_follow_up_inputs.push_back(intent);
278 }
279 }
280
281 pub fn queue_follow_up_input(&mut self, input: String) -> bool {
284 match self.try_queue_follow_up_input(input) {
285 Ok(()) => true,
286 Err(error) => {
287 tracing::warn!(%error, "Rejected follow-up steering intent");
288 false
289 }
290 }
291 }
292
293 pub fn try_queue_follow_up_input(&mut self, input: String) -> Result<(), FollowUpQueueFull> {
295 self.try_queue_follow_up_intent(QueuedFollowUpIntent::new(input))
296 }
297
298 pub fn try_queue_synthetic_follow_up_input(&mut self, input: String) -> Result<(), FollowUpQueueFull> {
300 self.try_queue_follow_up_intent(QueuedFollowUpIntent::new_with_provenance(input, FollowUpProvenance::Synthetic))
301 }
302
303 pub fn try_queue_follow_up_intent(&mut self, intent: QueuedFollowUpIntent) -> Result<(), FollowUpQueueFull> {
309 if self.queued_follow_up_inputs.len() + self.in_flight_follow_up_intents.len() < MAX_QUEUED_FOLLOW_UP_INTENTS {
310 self.queued_follow_up_inputs.push_back(intent);
311 return Ok(());
312 }
313 if self.overflow_follow_up_inputs.len() < MAX_OVERFLOW_FOLLOW_UP_INTENTS {
314 self.overflow_follow_up_inputs.push_back(intent);
315 return Ok(());
316 }
317 Err(FollowUpQueueFull {
318 capacity: MAX_QUEUED_FOLLOW_UP_INTENTS + MAX_OVERFLOW_FOLLOW_UP_INTENTS,
319 })
320 }
321
322 pub fn acknowledge_follow_up_intent(&mut self, intent_id: impl Into<String>) {
324 if self.applied_follow_up_intent_ids.len() >= MAX_APPLIED_FOLLOW_UP_INTENT_IDS {
325 self.applied_follow_up_intent_ids.pop_front();
326 }
327 self.applied_follow_up_intent_ids.push_back(intent_id.into());
328 }
329
330 #[must_use]
331 pub fn applied_follow_up_intent_ids(&self) -> &VecDeque<String> {
332 &self.applied_follow_up_intent_ids
333 }
334
335 #[must_use]
339 pub fn pending_follow_up_intents(&self) -> &VecDeque<QueuedFollowUpIntent> {
340 &self.queued_follow_up_inputs
341 }
342
343 #[must_use]
347 pub fn pending_follow_up_intents_snapshot(&self) -> Vec<QueuedFollowUpIntent> {
348 self.queued_follow_up_inputs
349 .iter()
350 .chain(self.overflow_follow_up_inputs.iter())
351 .chain(self.in_flight_follow_up_intents.iter())
352 .cloned()
353 .collect()
354 }
355
356 pub fn drain_follow_up_intents_to_in_flight(&mut self) -> Vec<QueuedFollowUpIntent> {
362 self.drain_overflow_into_primary();
363 let drained: Vec<_> = self.queued_follow_up_inputs.drain(..).collect();
364 self.in_flight_follow_up_intents.extend(drained.iter().cloned());
365 drained
366 }
367
368 pub fn acknowledge_durable_follow_up_intents(&mut self) {
372 while let Some(intent) = self.in_flight_follow_up_intents.pop_front() {
373 self.acknowledge_follow_up_intent(intent.id());
374 }
375 }
376
377 pub fn release_in_flight_follow_up_intents_without_persistence(&mut self) {
382 self.in_flight_follow_up_intents.clear();
383 }
384
385 pub fn clear_pending_follow_up_inputs(&mut self) {
386 self.queued_follow_up_inputs.clear();
387 self.overflow_follow_up_inputs.clear();
388 self.in_flight_follow_up_intents.clear();
389 }
390
391 pub async fn poll_turn_control(&mut self) -> RuntimeControl {
393 self.poll_control().await
394 }
395
396 pub async fn poll_tool_control(&mut self) -> RuntimeControl {
398 self.poll_control().await
399 }
400
401 async fn poll_control(&mut self) -> RuntimeControl {
402 let mut paused = false;
403
404 loop {
405 let Some(receiver) = self.steering_receiver.as_mut() else {
406 return if paused {
407 RuntimeControl::Resumed
408 } else {
409 RuntimeControl::Continue
410 };
411 };
412
413 match receiver.try_recv() {
414 Ok(SteeringMessage::SteerStop) => return RuntimeControl::StopRequested,
415 Ok(SteeringMessage::Pause) => {
416 paused = true;
417 if matches!(self.wait_for_resume().await, RuntimeControl::StopRequested) {
418 return RuntimeControl::StopRequested;
419 }
420 }
421 Ok(SteeringMessage::Resume) => {
422 paused = true;
423 }
424 Ok(SteeringMessage::FollowUpInput(input)) => {
425 if let Err(error) = self.try_queue_follow_up_input(input) {
426 tracing::warn!(%error, "Rejected follow-up steering intent");
427 }
428 }
429 Err(TryRecvError::Empty | TryRecvError::Disconnected) => {
430 return if paused {
431 RuntimeControl::Resumed
432 } else {
433 RuntimeControl::Continue
434 };
435 }
436 }
437 }
438 }
439
440 async fn wait_for_resume(&mut self) -> RuntimeControl {
441 loop {
442 let Some(receiver) = self.steering_receiver.as_mut() else {
443 return RuntimeControl::Continue;
444 };
445
446 match receiver.recv().await {
447 Some(SteeringMessage::Resume) => return RuntimeControl::Continue,
448 Some(SteeringMessage::SteerStop) => return RuntimeControl::StopRequested,
449 Some(SteeringMessage::FollowUpInput(input)) => {
450 if let Err(error) = self.try_queue_follow_up_input(input) {
451 tracing::warn!(%error, "Rejected follow-up steering intent");
452 }
453 }
454 Some(SteeringMessage::Pause) => {}
455 None => return RuntimeControl::Continue,
456 }
457 }
458 }
459}
460
461pub struct TurnExecution {
463 pub response: LLMResponse,
465 pub content: String,
467 pub reasoning: Option<String>,
469}
470
471const MIN_REASONING_UPDATE_BYTES: usize = 256;
472const MAX_REASONING_UPDATE_EVENTS: usize = 2;
473const MIN_OUTPUT_UPDATE_BYTES: usize = 1024;
474const MAX_OUTPUT_UPDATE_EVENTS: usize = 64;
475
476#[derive(Debug, Clone, Default)]
491struct UpdateThrottle {
492 events: usize,
493 last_emit_len: usize,
494}
495
496impl UpdateThrottle {
497 const fn new() -> Self {
498 Self { events: 0, last_emit_len: 0 }
499 }
500
501 fn should_emit(&self, current_len: usize, eager: bool, min_bytes: usize, max_events: usize) -> bool {
503 if self.events >= max_events {
504 return false;
505 }
506 eager || current_len.saturating_sub(self.last_emit_len) >= min_bytes
507 }
508
509 fn record(&mut self, current_len: usize) {
511 self.events += 1;
512 self.last_emit_len = current_len;
513 }
514
515 fn advance_to(&mut self, current_len: usize) {
519 self.last_emit_len = current_len;
520 }
521
522 fn is_first(&self) -> bool {
524 self.events == 0
525 }
526
527 fn reset(&mut self) {
529 self.events = 0;
530 self.last_emit_len = 0;
531 }
532}
533
534#[doc(hidden)]
536pub struct StreamingLifecycleBridge {
537 event_sink: Option<EventSink>,
538 assistant_item_id: String,
539 reasoning_item_id: String,
540 lifecycle: SharedLifecycleEmitter,
541 tool_call_item_ids: hashbrown::HashMap<String, (String, String)>,
545 reasoning_stage: Option<String>,
546 output: UpdateThrottle,
547 reasoning: UpdateThrottle,
548}
549
550impl StreamingLifecycleBridge {
551 #[must_use]
553 pub fn new(event_sink: Option<EventSink>, turn_id: &str, step: usize, attempt: usize) -> Self {
554 Self {
555 event_sink,
556 assistant_item_id: format!("{turn_id}-step-{step}-assistant-stream-{attempt}"),
557 reasoning_item_id: format!("{turn_id}-step-{step}-reasoning-stream-{attempt}"),
558 lifecycle: SharedLifecycleEmitter::default(),
559 tool_call_item_ids: hashbrown::HashMap::new(),
560 reasoning_stage: None,
561 output: UpdateThrottle::new(),
562 reasoning: UpdateThrottle::new(),
563 }
564 }
565
566 pub fn on_progress(&mut self, event: RuntimeModelProgress) {
568 match event {
569 RuntimeModelProgress::OutputDelta(delta) => self.push_assistant_delta(&delta),
570 RuntimeModelProgress::ReasoningDelta(delta) => self.push_reasoning_delta(&delta),
571 RuntimeModelProgress::ReasoningStage(stage) => self.update_reasoning_stage(stage),
572 RuntimeModelProgress::ProviderActivity => {}
573 RuntimeModelProgress::ToolCallStarted { call_id, name } => {
574 self.start_tool_call(call_id, name);
575 }
576 RuntimeModelProgress::ToolCallDelta { call_id, delta } => {
577 self.push_tool_call_delta(call_id, &delta);
578 }
579 }
580 }
581
582 pub fn abort(&mut self) {
584 self.lifecycle.complete_open_text_items();
585 self.lifecycle.complete_open_tool_calls_with_status(ToolCallStatus::Failed);
586 self.emit_pending_events();
587 }
588
589 pub fn complete_open_items(&mut self) {
591 self.lifecycle.flush_open_tool_call_arguments();
595 self.lifecycle.complete_open_text_items();
596 self.emit_pending_events();
597 }
598
599 #[must_use]
602 pub fn take_streamed_tool_call_items(&mut self) -> hashbrown::HashMap<String, (String, String)> {
603 std::mem::take(&mut self.tool_call_item_ids)
604 }
605
606 fn push_assistant_delta(&mut self, delta: &str) {
607 if !self.lifecycle.append_assistant_delta(delta) {
608 return;
609 }
610
611 let len = self.lifecycle.assistant_len();
612 if self
613 .output
614 .should_emit(len, self.output.is_first(), MIN_OUTPUT_UPDATE_BYTES, MAX_OUTPUT_UPDATE_EVENTS)
615 && self.lifecycle.emit_assistant_snapshot(Some(self.assistant_item_id.clone()))
616 {
617 self.output.record(len);
618 self.emit_pending_events();
619 }
620 }
621
622 fn push_reasoning_delta(&mut self, delta: &str) {
623 if !self.lifecycle.append_reasoning_delta(delta) {
624 return;
625 }
626
627 if !self.lifecycle.reasoning_started() {
628 if self.lifecycle.emit_reasoning_snapshot(Some(self.reasoning_item_id.clone())) {
629 self.reasoning.advance_to(self.lifecycle.reasoning_len());
630 self.emit_pending_events();
631 }
632 return;
633 }
634
635 let len = self.lifecycle.reasoning_len();
636 if self
637 .reasoning
638 .should_emit(len, false, MIN_REASONING_UPDATE_BYTES, MAX_REASONING_UPDATE_EVENTS)
639 && self.lifecycle.emit_reasoning_snapshot(Some(self.reasoning_item_id.clone()))
640 {
641 self.reasoning.record(len);
642 self.emit_pending_events();
643 }
644 }
645
646 fn update_reasoning_stage(&mut self, stage: String) {
647 let stage_changed = self.reasoning_stage.as_deref() != Some(stage.as_str());
648 if !stage_changed || !self.lifecycle.set_reasoning_stage(Some(stage.clone())) {
649 self.reasoning_stage = Some(stage);
650 return;
651 }
652 self.reasoning_stage = Some(stage);
653
654 if !self.lifecycle.reasoning_started() {
655 return;
656 }
657
658 let len = self.lifecycle.reasoning_len();
659 if self
660 .reasoning
661 .should_emit(len, true, MIN_REASONING_UPDATE_BYTES, MAX_REASONING_UPDATE_EVENTS)
662 && self.lifecycle.emit_reasoning_stage_update()
663 {
664 self.reasoning.record(len);
665 self.emit_pending_events();
666 }
667 }
668
669 fn start_tool_call(&mut self, call_id: String, name: Option<String>) {
670 let item_id = format!("{}-tool-call-{call_id}", self.assistant_item_id);
671 let tool_name = name.clone().unwrap_or_default();
672 self.tool_call_item_ids.insert(call_id.clone(), (item_id.clone(), tool_name));
673 let _ = self.lifecycle.start_tool_call(&call_id, name, Some(item_id));
674 self.emit_pending_events();
675 }
676
677 fn push_tool_call_delta(&mut self, call_id: String, delta: &str) {
678 if !self.lifecycle.append_tool_call_delta(
679 &call_id,
680 delta,
681 None,
682 Some(format!("{}-tool-call-{call_id}", self.assistant_item_id)),
683 ) {
684 return;
685 }
686 self.emit_pending_events();
687 }
688
689 fn emit_pending_events(&mut self) {
690 let Some(sink) = &self.event_sink else {
691 let _ = self.lifecycle.drain_events();
692 return;
693 };
694
695 for event in self.lifecycle.drain_events() {
696 let mut callback = sink.lock();
697 callback(&event);
698 }
699 }
700}
701
702pub struct AgentRuntime {
704 pub state: AgentSessionState,
706 steering: RuntimeSteering,
707 event_sink: Option<EventSink>,
708 lifecycle: SharedLifecycleEmitter,
709 emitted_events: Vec<ThreadEvent>,
710 output: UpdateThrottle,
711 reasoning: UpdateThrottle,
712}
713
714impl AgentRuntime {
715 pub fn new(
717 state: AgentSessionState,
718 event_sink: Option<EventSink>,
719 steering_receiver: Option<UnboundedReceiver<SteeringMessage>>,
720 ) -> Self {
721 Self {
722 state,
723 steering: RuntimeSteering::new(steering_receiver),
724 event_sink,
725 lifecycle: SharedLifecycleEmitter::default(),
726 emitted_events: Vec::new(),
727 output: UpdateThrottle::new(),
728 reasoning: UpdateThrottle::new(),
729 }
730 }
731
732 pub fn set_event_handler(&mut self, sink: Option<EventSink>) {
734 self.event_sink = sink;
735 }
736
737 pub fn set_steering_receiver(&mut self, receiver: Option<UnboundedReceiver<SteeringMessage>>) {
739 self.steering.set_receiver(receiver);
740 }
741
742 pub fn take_steering_receiver(&mut self) -> Option<UnboundedReceiver<SteeringMessage>> {
744 self.steering.take_receiver()
745 }
746
747 pub fn split_mut(&mut self) -> (&mut AgentSessionState, &mut RuntimeSteering) {
749 (&mut self.state, &mut self.steering)
750 }
751
752 #[must_use]
754 pub fn has_pending_follow_up_inputs(&self) -> bool {
755 self.steering.has_pending_follow_up_inputs()
756 }
757
758 pub fn run_until_idle(&mut self) -> Option<String> {
761 let intent = self.steering.pop_follow_up_intent()?;
762 let (intent_id, input, provenance) = intent.into_parts_with_provenance();
763 match provenance {
764 FollowUpProvenance::UserInput => {
765 self.state.add_user_message_with_intent(input.clone(), Some(intent_id.clone()));
766 }
767 FollowUpProvenance::Synthetic => {
768 self.state
769 .add_synthetic_user_message_with_intent(input.clone(), Some(intent_id.clone()));
770 }
771 }
772 self.steering
773 .in_flight_follow_up_intents
774 .push_back(QueuedFollowUpIntent::from_parts_with_provenance(intent_id, input.clone(), provenance));
775 Some(input)
776 }
777
778 pub fn queue_follow_up_input(&mut self, input: String) {
782 let _ = self.steering.queue_follow_up_input(input);
783 }
784
785 pub fn try_queue_follow_up_input(&mut self, input: String) -> Result<(), FollowUpQueueFull> {
787 self.steering.try_queue_follow_up_input(input)
788 }
789
790 pub fn try_queue_synthetic_follow_up_input(&mut self, input: String) -> Result<(), FollowUpQueueFull> {
792 self.steering.try_queue_synthetic_follow_up_input(input)
793 }
794
795 pub fn restore_follow_up_state(
800 &mut self,
801 pending_intents: impl IntoIterator<Item = QueuedFollowUpIntent>,
802 applied_intent_ids: impl IntoIterator<Item = String>,
803 ) -> Result<(), FollowUpQueueFull> {
804 let mut applied = HashSet::new();
805 for intent_id in applied_intent_ids {
806 if applied.insert(intent_id.clone()) {
807 self.steering.acknowledge_follow_up_intent(intent_id);
808 }
809 }
810 let represented: HashSet<String> = self
811 .state
812 .messages
813 .iter()
814 .filter_map(|message| message.metadata.as_ref().and_then(|metadata| metadata.intent_id()))
815 .map(ToOwned::to_owned)
816 .collect();
817
818 for intent in pending_intents {
819 if applied.contains(intent.id()) || represented.contains(intent.id()) {
820 continue;
821 }
822 self.steering.try_queue_follow_up_intent(intent)?;
823 }
824 Ok(())
825 }
826
827 #[must_use]
829 pub fn applied_follow_up_intent_ids(&self) -> &VecDeque<String> {
830 self.steering.applied_follow_up_intent_ids()
831 }
832
833 pub fn clear_pending_follow_up_inputs(&mut self) {
835 self.steering.clear_pending_follow_up_inputs();
836 }
837
838 pub async fn poll_turn_control(&mut self) -> RuntimeControl {
840 self.steering.poll_turn_control().await
841 }
842
843 pub async fn poll_tool_control(&mut self) -> RuntimeControl {
845 self.steering.poll_tool_control().await
846 }
847
848 pub fn take_emitted_events(&mut self) -> Vec<ThreadEvent> {
850 std::mem::take(&mut self.emitted_events)
851 }
852
853 #[must_use]
855 pub fn tool_call_item_id(&self, call_id: &str) -> Option<String> {
856 self.lifecycle.tool_call_item_id(call_id).map(str::to_string)
857 }
858
859 pub fn complete_tool_call(&mut self, call_id: &str, status: ToolCallStatus, outcome: Option<ToolOutcome>) {
861 let _ = self.lifecycle.complete_tool_call(call_id, status, outcome);
862 self.emit_pending_lifecycle_events();
863 }
864
865 pub fn complete_open_tool_calls(&mut self, status: ToolCallStatus) {
867 self.lifecycle.complete_open_tool_calls_with_status(status);
868 self.emit_pending_lifecycle_events();
869 }
870
871 fn emit_event(&mut self, event: ThreadEvent) {
872 self.emitted_events.push(event.clone());
873 if let Some(sink) = &self.event_sink {
874 let mut callback = sink.lock();
875 callback(&event);
876 }
877 }
878
879 fn emit_pending_lifecycle_events(&mut self) {
880 for event in self.lifecycle.drain_events() {
881 self.emit_event(event);
882 }
883 }
884
885 fn finalize_assistant_lifecycle(&mut self, text: &str) {
886 if text.trim().is_empty() {
887 return;
888 }
889
890 let should_emit_snapshot = !self.lifecycle.assistant_started() || self.lifecycle.replace_assistant_text(text);
891 if should_emit_snapshot {
892 let _ = self.lifecycle.emit_assistant_snapshot(None);
893 }
894 let _ = self.lifecycle.complete_assistant_stream();
895 }
896
897 fn finalize_reasoning_lifecycle(&mut self, text: &str) {
898 if text.trim().is_empty() {
899 return;
900 }
901
902 let should_emit_snapshot = !self.lifecycle.reasoning_started() || self.lifecycle.replace_reasoning_text(text);
903 if should_emit_snapshot {
904 let _ = self.lifecycle.emit_reasoning_snapshot(None);
905 }
906 let _ = self.lifecycle.complete_reasoning_stream();
907 }
908
909 fn finalize_tool_call_lifecycle(&mut self, tool_calls: Option<&[ToolCall]>, _finish_reason: &str) {
910 if let Some(tool_calls) = tool_calls {
911 for call in tool_calls {
912 let tool_name = call.function.as_ref().map(|function| function.name.clone());
913 let _ = self.lifecycle.start_tool_call(&call.id, tool_name.clone(), None);
914 if let Some(function) = call.function.as_ref() {
915 let _ = self
916 .lifecycle
917 .sync_tool_call_arguments(&call.id, &function.arguments, tool_name, None);
918 }
919 }
920 return;
921 }
922
923 self.lifecycle.complete_open_tool_calls_with_status(ToolCallStatus::Failed);
924 }
925
926 fn record_model_progress(
927 &mut self,
928 event: RuntimeModelProgress,
929 full_text: &mut String,
930 full_reasoning: &mut String,
931 ) {
932 match event {
933 RuntimeModelProgress::OutputDelta(delta) => {
934 full_text.push_str(&delta);
935 if self.lifecycle.append_assistant_delta(&delta) {
936 let len = self.lifecycle.assistant_len();
937 if self.output.should_emit(
938 len,
939 self.output.is_first(),
940 MIN_OUTPUT_UPDATE_BYTES,
941 MAX_OUTPUT_UPDATE_EVENTS,
942 ) && self.lifecycle.emit_assistant_snapshot(None)
943 {
944 self.output.record(len);
945 self.emit_pending_lifecycle_events();
946 }
947 }
948 }
949 RuntimeModelProgress::ReasoningDelta(delta) => {
950 full_reasoning.push_str(&delta);
951 if self.lifecycle.append_reasoning_delta(&delta) {
952 let len = self.lifecycle.reasoning_len();
953 if self.reasoning.should_emit(
954 len,
955 self.reasoning.is_first(),
956 MIN_REASONING_UPDATE_BYTES,
957 MAX_REASONING_UPDATE_EVENTS,
958 ) && self.lifecycle.emit_reasoning_snapshot(None)
959 {
960 self.reasoning.record(len);
961 self.emit_pending_lifecycle_events();
962 }
963 }
964 }
965 RuntimeModelProgress::ReasoningStage(stage) => {
966 if self.lifecycle.set_reasoning_stage(Some(stage)) {
967 let _ = self.lifecycle.emit_reasoning_stage_update();
968 self.emit_pending_lifecycle_events();
969 }
970 }
971 RuntimeModelProgress::ProviderActivity => {}
972 RuntimeModelProgress::ToolCallStarted { call_id, name } => {
973 let _ = self.lifecycle.start_tool_call(&call_id, name, None);
974 self.emit_pending_lifecycle_events();
975 }
976 RuntimeModelProgress::ToolCallDelta { call_id, delta } => {
977 if self.lifecycle.append_tool_call_delta(&call_id, &delta, None, None) {
978 self.emit_pending_lifecycle_events();
979 }
980 }
981 }
982 }
983
984 async fn run_turn_once_with_adapter<A: RuntimeModelAdapter + ?Sized>(
985 &mut self,
986 adapter: &mut A,
987 request: LLMRequest,
988 timeout: Option<std::time::Duration>,
989 ) -> Result<TurnExecution> {
990 let request_model = request.model.clone();
991 let start_time = Instant::now();
992 self.output.reset();
993 self.reasoning.reset();
994 let mut full_text = String::new();
995 let mut full_reasoning = String::new();
996 let mut on_progress = |event| self.record_model_progress(event, &mut full_text, &mut full_reasoning);
997 let RuntimeModelOutput { mut response } = match adapter.execute(request, timeout, &mut on_progress).await {
998 Ok(output) => output,
999 Err(error) => {
1000 self.complete_open_tool_calls(ToolCallStatus::Failed);
1001 tracing::warn!(elapsed_ms = start_time.elapsed().as_millis() as u64, error = %error, "agent turn failed during model execution");
1002 return Err(error);
1003 }
1004 };
1005
1006 merge_stream_and_completed_text(&mut full_text, response.content.as_deref());
1007 let provider_reasoning = response.reasoning.clone();
1008
1009 let finish_reason = match response.finish_reason.clone() {
1010 FinishReason::Stop => "stop".to_string(),
1011 FinishReason::ToolCalls => "tool_calls".to_string(),
1012 FinishReason::Length => "length".to_string(),
1013 FinishReason::Error(message) => message,
1014 _ => "unknown".to_string(),
1015 };
1016 let final_usage = response.usage.take().unwrap_or_default();
1017 let mut aggregated_tool_calls = response.tool_calls.take();
1018
1019 self.finalize_assistant_lifecycle(&full_text);
1020 self.finalize_reasoning_lifecycle(&full_reasoning);
1021 self.finalize_tool_call_lifecycle(aggregated_tool_calls.as_deref(), &finish_reason);
1022 self.emit_pending_lifecycle_events();
1023
1024 let mut turn_recorded = false;
1025 self.state.record_turn(&start_time, &mut turn_recorded);
1026
1027 if final_usage.prompt_tokens > 0 || final_usage.completion_tokens > 0 {
1028 if let Some(alert) = self.state.stats.merge_usage(&final_usage) {
1032 let message = alert.message();
1033 tracing::warn!("{message}");
1034 self.state.push_warning(message);
1035 }
1036 }
1037
1038 aggregated_tool_calls = aggregated_tool_calls.filter(|calls| !calls.is_empty());
1039
1040 let mut assistant_message = crate::llm::provider::Message::assistant(full_text.clone());
1041 if let Some(reasoning) = provider_reasoning
1042 .clone()
1043 .or_else(|| (!full_reasoning.is_empty()).then(|| full_reasoning.clone()))
1044 {
1045 assistant_message = assistant_message.with_reasoning(Some(reasoning));
1046 }
1047 if let Some(details) = response.reasoning_details.clone() {
1048 let values: Vec<serde_json::Value> = details.into_iter().map(serde_json::Value::String).collect();
1049 assistant_message = assistant_message.with_reasoning_details(Some(values));
1050 }
1051
1052 match aggregated_tool_calls.as_ref() {
1053 Some(calls) => {
1054 assistant_message = assistant_message
1055 .with_tool_calls(calls.clone())
1056 .with_phase(Some(AssistantPhase::Commentary));
1057 }
1058 None => {
1059 assistant_message = assistant_message.with_phase(Some(AssistantPhase::FinalAnswer));
1060 }
1061 }
1062
1063 self.state.adjust_token_count(assistant_message.estimate_tokens() as isize);
1064 self.state.messages_mut().push(assistant_message);
1065
1066 self.state.conversation.push(Content {
1067 role: "model".to_string(),
1068 parts: vec![Part::Text { text: full_text.clone(), thought_signature: None }],
1069 });
1070 self.state.last_processed_message_idx = self.state.conversation.len();
1071
1072 if response.model.is_empty() {
1073 response.model = request_model;
1074 }
1075 response.content = Some(full_text.clone());
1076 if response.reasoning.is_none() && !full_reasoning.is_empty() {
1077 response.reasoning = Some(full_reasoning.clone());
1078 }
1079 response.tool_calls = aggregated_tool_calls;
1080 response.usage = Some(final_usage);
1081 response.finish_reason = if finish_reason == "tool_calls" {
1082 FinishReason::ToolCalls
1083 } else if finish_reason == "Cancelled" || finish_reason == "cancelled" {
1084 FinishReason::Error("Cancelled".to_string())
1085 } else {
1086 response.finish_reason
1087 };
1088
1089 tracing::debug!(
1090 elapsed_ms = start_time.elapsed().as_millis() as u64,
1091 output_bytes = full_text.len(),
1092 reasoning_bytes = full_reasoning.len(),
1093 tool_calls = response.tool_calls.as_ref().map_or(0, Vec::len),
1094 input_tokens = response.usage.as_ref().map_or(0, |usage| usage.prompt_tokens),
1095 output_tokens = response.usage.as_ref().map_or(0, |usage| usage.completion_tokens),
1096 finish_reason = %finish_reason,
1097 "agent turn completed"
1098 );
1099
1100 Ok(TurnExecution {
1101 response,
1102 content: full_text,
1103 reasoning: if full_reasoning.is_empty() {
1104 None
1105 } else {
1106 Some(full_reasoning)
1107 },
1108 })
1109 }
1110
1111 pub async fn run_turn_once(
1113 &mut self,
1114 provider: &mut Box<dyn LLMProvider>,
1115 request: LLMRequest,
1116 timeout: Option<std::time::Duration>,
1117 ) -> Result<TurnExecution> {
1118 let mut steering = std::mem::take(&mut self.steering);
1119 let mut adapter = ProviderRuntimeModelAdapter::new(provider, &mut steering);
1120 let result = self.run_turn_once_with_adapter(&mut adapter, request, timeout).await;
1121 self.steering = steering;
1122 result
1123 }
1124}
1125
1126#[cfg(test)]
1127mod tests {
1128 use super::*;
1129 use async_trait::async_trait;
1130 use futures::stream;
1131
1132 use crate::llm::provider::{
1133 LLMError, LLMNormalizedStream, LLMStream, LLMStreamEvent, NormalizedStreamEvent, ReasoningSource,
1134 };
1135
1136 #[derive(Clone)]
1137 struct CompletedOnlyStreamProvider {
1138 response: LLMResponse,
1139 }
1140
1141 #[derive(Clone)]
1142 struct DeltaStreamProvider {
1143 response: LLMResponse,
1144 text_delta: String,
1145 reasoning_delta: String,
1146 reasoning_source: ReasoningSource,
1147 tool_call_start: bool,
1148 }
1149
1150 #[async_trait]
1151 impl LLMProvider for CompletedOnlyStreamProvider {
1152 fn name(&self) -> &str {
1153 "test-provider"
1154 }
1155
1156 fn supports_streaming(&self) -> bool {
1157 true
1158 }
1159
1160 async fn generate(&self, _request: LLMRequest) -> Result<LLMResponse, LLMError> {
1161 Ok(self.response.clone())
1162 }
1163
1164 async fn stream(&self, _request: LLMRequest) -> Result<LLMStream, LLMError> {
1165 Ok(Box::pin(stream::iter(vec![Ok(LLMStreamEvent::Completed {
1166 response: Box::new(self.response.clone()),
1167 })])))
1168 }
1169
1170 async fn stream_normalized(&self, _request: LLMRequest) -> Result<LLMNormalizedStream, LLMError> {
1171 Ok(Box::pin(stream::iter(vec![Ok(NormalizedStreamEvent::Done {
1172 response: Box::new(self.response.clone()),
1173 })])))
1174 }
1175
1176 fn supported_models(&self) -> Vec<String> {
1177 vec!["test-model".to_string()]
1178 }
1179
1180 fn validate_request(&self, _request: &LLMRequest) -> Result<(), LLMError> {
1181 Ok(())
1182 }
1183 }
1184
1185 #[async_trait]
1186 impl LLMProvider for DeltaStreamProvider {
1187 fn name(&self) -> &str {
1188 "delta-provider"
1189 }
1190
1191 fn supports_streaming(&self) -> bool {
1192 true
1193 }
1194
1195 async fn generate(&self, _request: LLMRequest) -> Result<LLMResponse, LLMError> {
1196 Ok(self.response.clone())
1197 }
1198
1199 async fn stream(&self, _request: LLMRequest) -> Result<LLMStream, LLMError> {
1200 Ok(Box::pin(stream::iter(vec![Ok(LLMStreamEvent::Completed {
1201 response: Box::new(self.response.clone()),
1202 })])))
1203 }
1204
1205 async fn stream_normalized(&self, _request: LLMRequest) -> Result<LLMNormalizedStream, LLMError> {
1206 let mut events = vec![Ok(NormalizedStreamEvent::ReasoningDelta {
1207 delta: self.reasoning_delta.clone(),
1208 source: self.reasoning_source,
1209 })];
1210 if self.tool_call_start {
1211 events.push(Ok(NormalizedStreamEvent::ToolCallStart {
1212 call_id: "call_test".to_string(),
1213 name: Some("read_file".to_string()),
1214 }));
1215 }
1216 events.extend([
1217 Ok(NormalizedStreamEvent::TextDelta { delta: self.text_delta.clone() }),
1218 Ok(NormalizedStreamEvent::Done { response: Box::new(self.response.clone()) }),
1219 ]);
1220 Ok(Box::pin(stream::iter(events)))
1221 }
1222
1223 fn supported_models(&self) -> Vec<String> {
1224 vec!["test-model".to_string()]
1225 }
1226
1227 fn validate_request(&self, _request: &LLMRequest) -> Result<(), LLMError> {
1228 Ok(())
1229 }
1230 }
1231
1232 #[tokio::test]
1233 async fn queued_follow_up_inputs_are_applied_one_at_a_time() {
1234 let state = AgentSessionState::new("session".to_string(), 16, 4, 128_000);
1235 let (sender, receiver) = tokio::sync::mpsc::unbounded_channel();
1236 let mut runtime = AgentRuntime::new(state, None, Some(receiver));
1237
1238 sender
1239 .send(SteeringMessage::FollowUpInput("first".to_string()))
1240 .expect("first follow-up should queue");
1241 sender
1242 .send(SteeringMessage::FollowUpInput("second".to_string()))
1243 .expect("second follow-up should queue");
1244
1245 assert_eq!(runtime.poll_turn_control().await, RuntimeControl::Continue);
1246 assert!(runtime.has_pending_follow_up_inputs());
1247 assert!(runtime.state.messages.is_empty());
1248
1249 assert_eq!(runtime.run_until_idle().as_deref(), Some("first"));
1250 assert_eq!(
1251 runtime
1252 .state
1253 .messages
1254 .last()
1255 .map(|message| message.get_text_content().into_owned()),
1256 Some("first".to_string())
1257 );
1258 assert!(runtime.has_pending_follow_up_inputs());
1259
1260 assert_eq!(runtime.run_until_idle().as_deref(), Some("second"));
1261 assert_eq!(
1262 runtime
1263 .state
1264 .messages
1265 .last()
1266 .map(|message| message.get_text_content().into_owned()),
1267 Some("second".to_string())
1268 );
1269 assert!(!runtime.has_pending_follow_up_inputs());
1270 }
1271
1272 #[test]
1273 fn follow_up_queue_has_bounded_identity_preserving_fifo() {
1274 let mut steering = RuntimeSteering::default();
1275 let total_capacity = MAX_QUEUED_FOLLOW_UP_INTENTS + MAX_OVERFLOW_FOLLOW_UP_INTENTS;
1276 for index in 0..total_capacity {
1277 assert!(
1278 steering.try_queue_follow_up_input(format!("input-{index}")).is_ok(),
1279 "input {index} must be accepted within the combined capacity"
1280 );
1281 }
1282 let error = steering
1283 .try_queue_follow_up_input("overflow".to_string())
1284 .expect_err("overflow must be reported once both buffers are full");
1285 assert_eq!(error.capacity, total_capacity);
1286
1287 let first = steering.pop_follow_up_intent().expect("first intent should exist");
1289 let second = steering.pop_follow_up_intent().expect("second intent should exist");
1290 assert_ne!(first.id(), second.id());
1291 assert_eq!(first.text(), "input-0");
1292 assert_eq!(second.text(), "input-1");
1293 }
1294
1295 #[test]
1296 fn follow_up_overflow_parks_instead_of_dropping_bursts() {
1297 let mut steering = RuntimeSteering::default();
1298 for index in 0..MAX_QUEUED_FOLLOW_UP_INTENTS {
1300 assert!(steering.try_queue_follow_up_input(format!("primary-{index}")).is_ok());
1301 }
1302 for index in 0..5 {
1304 assert!(steering.try_queue_follow_up_input(format!("overflow-{index}")).is_ok());
1305 }
1306 assert!(steering.has_pending_follow_up_inputs());
1307
1308 for index in 0..MAX_QUEUED_FOLLOW_UP_INTENTS {
1310 let intent = steering.pop_follow_up_intent().expect("primary intent");
1311 assert_eq!(intent.text(), format!("primary-{index}"));
1312 }
1313 for index in 0..5 {
1314 let intent = steering.pop_follow_up_intent().expect("overflow intent");
1315 assert_eq!(intent.text(), format!("overflow-{index}"));
1316 }
1317 assert!(!steering.has_pending_follow_up_inputs());
1318 }
1319
1320 #[test]
1321 fn pop_yields_overflow_when_primary_is_empty() {
1322 let mut steering = RuntimeSteering::default();
1326 for index in 0..MAX_QUEUED_FOLLOW_UP_INTENTS {
1327 assert!(steering.try_queue_follow_up_input(format!("inflight-{index}")).is_ok());
1328 }
1329 assert_eq!(steering.drain_follow_up_intents_to_in_flight().len(), MAX_QUEUED_FOLLOW_UP_INTENTS);
1330 assert!(steering.queued_follow_up_inputs.is_empty(), "primary must be empty after a full in-flight drain");
1331 assert!(steering.try_queue_follow_up_input("parked".to_string()).is_ok());
1332 assert!(steering.has_pending_follow_up_inputs());
1333 let intent = steering
1334 .pop_follow_up_intent()
1335 .expect("pop must yield overflow when primary is empty");
1336 assert_eq!(intent.text(), "parked");
1337 }
1338
1339 #[test]
1340 fn run_until_idle_tags_and_acknowledges_follow_up_intent() {
1341 let state = AgentSessionState::new("session".to_string(), 16, 4, 128_000);
1342 let mut runtime = AgentRuntime::new(state, None, None);
1343 runtime
1344 .try_queue_follow_up_input("steer me".to_string())
1345 .expect("intent should be accepted");
1346
1347 assert_eq!(runtime.run_until_idle().as_deref(), Some("steer me"));
1348 let message = runtime.state.messages.last().expect("tagged message should exist");
1349 let intent_id = message
1350 .metadata
1351 .as_ref()
1352 .and_then(|metadata| metadata.intent_id())
1353 .expect("follow-up message should carry intent identity")
1354 .to_string();
1355 assert_eq!(
1356 message.metadata.as_ref().and_then(|metadata| metadata.source()),
1357 Some("user_input"),
1358 "ordinary steering input must remain attributed to the user"
1359 );
1360 assert!(runtime.applied_follow_up_intent_ids().is_empty());
1361 assert_eq!(runtime.steering.pending_follow_up_intents_snapshot().len(), 1);
1362 runtime.steering.acknowledge_durable_follow_up_intents();
1363 assert_eq!(runtime.applied_follow_up_intent_ids().back(), Some(&intent_id));
1364 }
1365
1366 #[test]
1367 fn run_until_idle_preserves_synthetic_follow_up_provenance_at_turn_boundary() {
1368 let state = AgentSessionState::new("session".to_string(), 16, 4, 128_000);
1369 let mut runtime = AgentRuntime::new(state, None, None);
1370 runtime
1371 .try_queue_synthetic_follow_up_input("continue the saved plan".to_string())
1372 .expect("harness intent should be accepted");
1373
1374 assert_eq!(runtime.run_until_idle().as_deref(), Some("continue the saved plan"));
1375
1376 let message = runtime.state.messages.last().expect("turn-boundary message should be present");
1377 let metadata = message.metadata.as_ref().expect("turn-boundary message should have metadata");
1378 assert_eq!(metadata.source(), Some("synthetic"));
1379 assert!(metadata.is_synthetic());
1380 assert!(metadata.intent_id().is_some(), "synthetic message must retain its recovery identity");
1381
1382 let pending = runtime.steering.pending_follow_up_intents_snapshot();
1383 assert_eq!(pending.len(), 1);
1384 assert_eq!(pending[0].provenance(), FollowUpProvenance::Synthetic);
1385 }
1386
1387 #[test]
1388 fn follow_up_provenance_round_trips_and_legacy_intents_default_to_user_input() {
1389 let synthetic =
1390 QueuedFollowUpIntent::new_with_provenance("auto continue".to_string(), FollowUpProvenance::Synthetic);
1391 let encoded = serde_json::to_value(&synthetic).expect("intent should serialize");
1392 assert_eq!(encoded["provenance"], "synthetic");
1393 let restored: QueuedFollowUpIntent = serde_json::from_value(encoded).expect("intent should deserialize");
1394 assert_eq!(restored.provenance(), FollowUpProvenance::Synthetic);
1395
1396 let legacy = serde_json::json!({"id": "legacy", "text": "continue"});
1397 let restored_legacy: QueuedFollowUpIntent =
1398 serde_json::from_value(legacy).expect("legacy intent without provenance should deserialize");
1399 assert_eq!(restored_legacy.provenance(), FollowUpProvenance::UserInput);
1400 }
1401
1402 #[test]
1403 fn recovery_replays_only_unrepresented_intent_ids() {
1404 let pending = QueuedFollowUpIntent::from_parts_with_provenance(
1405 "intent-pending",
1406 "finish the request",
1407 FollowUpProvenance::Synthetic,
1408 );
1409 let same_text_different_id = QueuedFollowUpIntent::from_parts("intent-distinct", pending.text());
1410
1411 let mut interrupted =
1412 AgentRuntime::new(AgentSessionState::new("session".to_string(), 16, 4, 128_000), None, None);
1413 interrupted
1414 .restore_follow_up_state([pending.clone(), same_text_different_id.clone()], Vec::new())
1415 .expect("unwritten intents should be recoverable");
1416 assert_eq!(interrupted.steering.pending_follow_up_intents().len(), 2);
1417 assert_eq!(interrupted.steering.pending_follow_up_intents()[0], pending);
1418 assert_eq!(interrupted.steering.pending_follow_up_intents()[1], same_text_different_id);
1419
1420 let mut restarted_state = AgentSessionState::new("session".to_string(), 16, 4, 128_000);
1421 restarted_state.add_user_message_with_intent(pending.text().to_string(), Some(pending.id().to_string()));
1422 let mut restarted = AgentRuntime::new(restarted_state, None, None);
1423 restarted
1424 .restore_follow_up_state([pending.clone(), same_text_different_id], Vec::new())
1425 .expect("distinct pending intent should fit the recovery queue");
1426
1427 assert_eq!(restarted.steering.pending_follow_up_intents().len(), 1);
1428 assert_eq!(restarted.steering.pending_follow_up_intents()[0].id(), "intent-distinct");
1429 assert_eq!(restarted.steering.pending_follow_up_intents()[0].provenance(), FollowUpProvenance::UserInput);
1430 }
1431
1432 #[test]
1433 fn no_archive_release_reuses_follow_up_capacity_without_applied_ids() {
1434 let state = AgentSessionState::new("session".to_string(), 16, 4, 128_000);
1435 let mut runtime = AgentRuntime::new(state, None, None);
1436 let total_capacity = MAX_QUEUED_FOLLOW_UP_INTENTS + MAX_OVERFLOW_FOLLOW_UP_INTENTS;
1437 for index in 0..total_capacity {
1438 runtime
1439 .try_queue_follow_up_input(format!("input-{index}"))
1440 .expect("intent should be accepted");
1441 }
1442
1443 for _ in 0..total_capacity {
1444 runtime.run_until_idle().expect("queued intent should become a user message");
1445 }
1446 assert!(runtime.try_queue_follow_up_input("parked-0".to_string()).is_ok());
1449 for index in 1..MAX_OVERFLOW_FOLLOW_UP_INTENTS {
1450 assert!(runtime.try_queue_follow_up_input(format!("parked-{index}")).is_ok());
1451 }
1452 assert!(runtime.try_queue_follow_up_input("rejected".to_string()).is_err());
1453
1454 runtime.steering.release_in_flight_follow_up_intents_without_persistence();
1455 assert!(runtime.try_queue_follow_up_input("after-release".to_string()).is_ok());
1456 assert!(runtime.applied_follow_up_intent_ids().is_empty());
1457 }
1458
1459 #[tokio::test]
1460 async fn paused_runtime_resumes_and_preserves_follow_up_inputs() {
1461 let state = AgentSessionState::new("session".to_string(), 16, 4, 128_000);
1462 let (sender, receiver) = tokio::sync::mpsc::unbounded_channel();
1463 let mut runtime = AgentRuntime::new(state, None, Some(receiver));
1464
1465 sender.send(SteeringMessage::Pause).expect("pause should send");
1466 sender
1467 .send(SteeringMessage::FollowUpInput("queued while paused".to_string()))
1468 .expect("follow-up should send");
1469 sender.send(SteeringMessage::Resume).expect("resume should send");
1470
1471 assert_eq!(runtime.poll_turn_control().await, RuntimeControl::Resumed);
1472 assert!(runtime.has_pending_follow_up_inputs());
1473 assert_eq!(runtime.run_until_idle().as_deref(), Some("queued while paused"));
1474 }
1475
1476 #[tokio::test]
1477 async fn paused_runtime_stop_request_wins() {
1478 let state = AgentSessionState::new("session".to_string(), 16, 4, 128_000);
1479 let (sender, receiver) = tokio::sync::mpsc::unbounded_channel();
1480 let mut runtime = AgentRuntime::new(state, None, Some(receiver));
1481
1482 sender.send(SteeringMessage::Pause).expect("pause should send");
1483 sender.send(SteeringMessage::SteerStop).expect("stop should send");
1484
1485 assert_eq!(runtime.poll_turn_control().await, RuntimeControl::StopRequested);
1486 assert!(!runtime.has_pending_follow_up_inputs());
1487 }
1488
1489 #[tokio::test]
1490 async fn run_turn_once_uses_completed_payload_when_no_deltas_exist() {
1491 let response = LLMResponse {
1492 content: Some("### Header\n- item".to_string()),
1493 model: "test-model".to_string(),
1494 finish_reason: FinishReason::Stop,
1495 reasoning: Some("**why** this works".to_string()),
1496 reasoning_details: Some(vec!["continuation detail".to_string()]),
1497 ..Default::default()
1498 };
1499 let provider = CompletedOnlyStreamProvider { response: response.clone() };
1500 let state = AgentSessionState::new("session".to_string(), 16, 4, 128_000);
1501 let mut runtime = AgentRuntime::new(state, None, None);
1502 let mut provider_box: Box<dyn LLMProvider> = Box::new(provider);
1503 let request = LLMRequest {
1504 model: "test-model".to_string(),
1505 ..Default::default()
1506 };
1507
1508 let turn = runtime
1509 .run_turn_once(&mut provider_box, request, None)
1510 .await
1511 .expect("run_turn_once should succeed");
1512
1513 assert_eq!(turn.content, "### Header\n- item");
1514 assert_eq!(turn.reasoning, None);
1515 assert_eq!(turn.response.content.as_deref(), Some("### Header\n- item"));
1516 assert_eq!(turn.response.reasoning.as_deref(), Some("**why** this works"));
1517 assert_eq!(turn.response.reasoning_details.as_deref(), Some(["continuation detail".to_string()].as_slice()));
1518 }
1519
1520 #[tokio::test]
1521 async fn provider_runtime_model_adapter_emits_delta_progress() {
1522 let response = LLMResponse {
1523 content: Some("hello world".to_string()),
1524 model: "test-model".to_string(),
1525 finish_reason: FinishReason::Stop,
1526 reasoning: Some("trace".to_string()),
1527 ..Default::default()
1528 };
1529 let provider = DeltaStreamProvider {
1530 response,
1531 text_delta: "hello world".to_string(),
1532 reasoning_delta: "trace".to_string(),
1533 reasoning_source: ReasoningSource::ProviderSummary,
1534 tool_call_start: false,
1535 };
1536 let mut steering = RuntimeSteering::default();
1537 let mut provider_box: Box<dyn LLMProvider> = Box::new(provider);
1538 let request = LLMRequest {
1539 model: "test-model".to_string(),
1540 ..Default::default()
1541 };
1542
1543 let mut adapter = ProviderRuntimeModelAdapter::new(&mut provider_box, &mut steering);
1544 let mut seen_progress = Vec::new();
1545 let mut callback = |event| seen_progress.push(event);
1546 let output = adapter
1547 .execute(request, None, &mut callback)
1548 .await
1549 .expect("adapter execution should succeed");
1550
1551 assert_eq!(output.response.content.as_deref(), Some("hello world"));
1552 assert_eq!(output.response.reasoning.as_deref(), Some("trace"));
1553 assert_eq!(
1554 seen_progress,
1555 vec![
1556 RuntimeModelProgress::ReasoningDelta("trace".to_string()),
1557 RuntimeModelProgress::OutputDelta("hello world".to_string()),
1558 ]
1559 );
1560 }
1561
1562 #[tokio::test]
1563 async fn adapter_hides_unclassified_reasoning_but_keeps_text_and_metadata() {
1564 let response = LLMResponse {
1565 content: Some("hello".to_string()),
1566 model: "test-model".to_string(),
1567 finish_reason: FinishReason::Stop,
1568 reasoning: Some("private trace".to_string()),
1569 reasoning_details: Some(vec!["continuation detail".to_string()]),
1570 ..Default::default()
1571 };
1572 let provider = DeltaStreamProvider {
1573 response,
1574 text_delta: "hello".to_string(),
1575 reasoning_delta: "private trace".to_string(),
1576 reasoning_source: ReasoningSource::Unknown,
1577 tool_call_start: false,
1578 };
1579 let mut steering = RuntimeSteering::default();
1580 let mut provider_box: Box<dyn LLMProvider> = Box::new(provider);
1581 let mut seen_progress = Vec::new();
1582 let mut callback = |event| seen_progress.push(event);
1583 let output = ProviderRuntimeModelAdapter::new(&mut provider_box, &mut steering)
1584 .execute(LLMRequest::default(), None, &mut callback)
1585 .await
1586 .expect("adapter execution should succeed");
1587
1588 assert_eq!(output.response.reasoning.as_deref(), Some("private trace"));
1589 assert_eq!(output.response.reasoning_details.as_deref(), Some(["continuation detail".to_string()].as_slice()));
1590 assert_eq!(
1591 seen_progress,
1592 vec![
1593 RuntimeModelProgress::ProviderActivity,
1594 RuntimeModelProgress::OutputDelta("hello".to_string())
1595 ]
1596 );
1597 assert!(
1598 !seen_progress
1599 .iter()
1600 .any(|event| matches!(event, RuntimeModelProgress::ToolCallStarted { .. }))
1601 );
1602 }
1603
1604 #[tokio::test]
1605 async fn adapter_emits_structured_tool_call_status_without_textual_trigger() {
1606 let provider = DeltaStreamProvider {
1607 response: LLMResponse {
1608 model: "test-model".to_string(),
1609 finish_reason: FinishReason::ToolCalls,
1610 ..Default::default()
1611 },
1612 text_delta: String::new(),
1613 reasoning_delta: String::new(),
1614 reasoning_source: ReasoningSource::Unknown,
1615 tool_call_start: true,
1616 };
1617 let mut steering = RuntimeSteering::default();
1618 let mut provider_box: Box<dyn LLMProvider> = Box::new(provider);
1619 let mut seen_progress = Vec::new();
1620 let mut callback = |event| seen_progress.push(event);
1621 ProviderRuntimeModelAdapter::new(&mut provider_box, &mut steering)
1622 .execute(LLMRequest::default(), None, &mut callback)
1623 .await
1624 .expect("adapter execution should succeed");
1625
1626 assert!(seen_progress.iter().any(|event| matches!(
1627 event,
1628 RuntimeModelProgress::ToolCallStarted { call_id, name }
1629 if call_id == "call_test" && name.as_deref() == Some("read_file")
1630 )));
1631 }
1632
1633 #[test]
1634 fn streaming_lifecycle_bridge_tracks_tool_call_item_ids() {
1635 let mut bridge = StreamingLifecycleBridge::new(None, "turn_tool_map", 5, 2);
1636 bridge.on_progress(RuntimeModelProgress::ToolCallStarted {
1637 call_id: "call_42".to_string(),
1638 name: Some("shell".to_string()),
1639 });
1640
1641 let item_ids = bridge.take_streamed_tool_call_items();
1642 assert_eq!(
1643 item_ids.get("call_42").map(|(item_id, _)| item_id.as_str()),
1644 Some("turn_tool_map-step-5-assistant-stream-2-tool-call-call_42")
1645 );
1646 assert_eq!(item_ids.get("call_42").map(|(_, name)| name.as_str()), Some("shell"));
1647 }
1648
1649 #[test]
1650 fn update_throttle_first_update_is_eager() {
1651 let mut throttle = UpdateThrottle::new();
1652 assert!(throttle.is_first());
1653 assert!(throttle.should_emit(0, throttle.is_first(), 1024, 64));
1655 throttle.record(0);
1656 assert!(!throttle.is_first());
1657 }
1658
1659 #[test]
1660 fn update_throttle_requires_min_bytes_after_first() {
1661 let mut throttle = UpdateThrottle::new();
1662 throttle.record(0);
1663 assert!(!throttle.should_emit(500, false, 1024, 64));
1665 assert!(throttle.should_emit(1024, false, 1024, 64));
1667 }
1668
1669 #[test]
1670 fn update_throttle_stops_at_max_events() {
1671 let mut throttle = UpdateThrottle::new();
1672 for _ in 0..2 {
1673 assert!(throttle.should_emit(0, true, 256, 2));
1674 throttle.record(0);
1675 }
1676 assert!(!throttle.should_emit(0, true, 256, 2));
1678 }
1679
1680 #[test]
1681 fn update_throttle_advance_to_does_not_count_event() {
1682 let mut throttle = UpdateThrottle::new();
1683 throttle.advance_to(100);
1684 assert!(throttle.is_first());
1685 assert!(!throttle.should_emit(200, false, 256, 2));
1687 assert!(throttle.should_emit(356, false, 256, 2));
1689 }
1690
1691 #[test]
1692 fn update_throttle_reset_restores_initial_state() {
1693 let mut throttle = UpdateThrottle::new();
1694 throttle.record(500);
1695 assert!(!throttle.is_first());
1696 throttle.reset();
1697 assert!(throttle.is_first());
1698 assert!(throttle.should_emit(0, true, 1024, 64));
1699 }
1700}