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
44mod steering;
45pub use steering::RuntimeSteering;
46
47#[derive(Debug, Clone, Copy, PartialEq, Eq)]
49pub enum RuntimeControl {
50 Continue,
52 Resumed,
54 StopRequested,
56}
57
58#[doc(hidden)]
60#[derive(Debug, Clone, PartialEq, Eq)]
61pub enum RuntimeModelProgress {
62 OutputDelta(String),
64 ReasoningDelta(String),
66 ReasoningStage(String),
68 ProviderActivity,
70 ToolCallStarted {
72 call_id: String,
74 name: Option<String>,
76 },
77 ToolCallDelta {
79 call_id: String,
81 delta: String,
83 },
84}
85
86#[derive(Debug, Clone)]
87struct RuntimeModelOutput {
88 response: LLMResponse,
89}
90
91#[async_trait]
92trait RuntimeModelAdapter {
93 async fn execute(
94 &mut self,
95 request: LLMRequest,
96 timeout: Option<std::time::Duration>,
97 on_progress: &mut (dyn FnMut(RuntimeModelProgress) + Send),
98 ) -> Result<RuntimeModelOutput>;
99}
100
101struct ProviderRuntimeModelAdapter<'a> {
102 provider: &'a mut Box<dyn LLMProvider>,
103 steering: &'a mut RuntimeSteering,
104}
105
106impl<'a> ProviderRuntimeModelAdapter<'a> {
107 fn new(provider: &'a mut Box<dyn LLMProvider>, steering: &'a mut RuntimeSteering) -> Self {
108 Self { provider, steering }
109 }
110}
111
112#[async_trait]
113impl RuntimeModelAdapter for ProviderRuntimeModelAdapter<'_> {
114 async fn execute(
115 &mut self,
116 request: LLMRequest,
117 timeout: Option<std::time::Duration>,
118 on_progress: &mut (dyn FnMut(RuntimeModelProgress) + Send),
119 ) -> Result<RuntimeModelOutput> {
120 let started_at = Instant::now();
121 let request_model = request.model.clone();
122 let mut stream = if let Some(duration) = timeout {
123 match tokio::time::timeout(duration, self.provider.stream_normalized(request)).await {
124 Ok(result) => result?,
125 Err(_) => {
126 tracing::warn!(model = %request_model, elapsed_ms = started_at.elapsed().as_millis() as u64, "model stream timed out");
127 return Err(anyhow::anyhow!("Stream request timed out after {duration:?}"));
128 }
129 }
130 } else {
131 self.provider.stream_normalized(request).await?
132 };
133
134 let mut final_usage = ProviderUsage::default();
135 let mut completed_response: Option<LLMResponse> = None;
136 let mut provider_activity_reported = false;
137 while let Some(event_result) = stream.next().await {
138 if matches!(self.steering.poll_turn_control().await, RuntimeControl::StopRequested) {
139 tracing::info!(model = %request_model, elapsed_ms = started_at.elapsed().as_millis() as u64, "model stream cancelled");
140 let mut response = LLMResponse {
141 model: request_model.clone(),
142 finish_reason: FinishReason::Error("Cancelled".to_string()),
143 usage: Some(final_usage.clone()),
144 ..Default::default()
145 };
146 if response.usage.as_ref().is_some_and(|usage| {
147 usage.prompt_tokens == 0 && usage.completion_tokens == 0 && usage.total_tokens == 0
148 }) {
149 response.usage = None;
150 }
151 return Ok(RuntimeModelOutput { response });
152 }
153
154 match event_result? {
155 NormalizedStreamEvent::TextDelta { delta } => {
156 on_progress(RuntimeModelProgress::OutputDelta(delta));
157 }
158 NormalizedStreamEvent::ReasoningDelta { delta, source } if source.is_public_summary() => {
159 on_progress(RuntimeModelProgress::ReasoningDelta(delta));
160 }
161 NormalizedStreamEvent::ReasoningDelta { .. } => {
162 if !provider_activity_reported {
163 provider_activity_reported = true;
164 on_progress(RuntimeModelProgress::ProviderActivity);
165 }
166 }
167 NormalizedStreamEvent::ReasoningStage { stage } => {
168 on_progress(RuntimeModelProgress::ReasoningStage(stage));
169 }
170 NormalizedStreamEvent::ToolCallStart { call_id, name } => {
171 on_progress(RuntimeModelProgress::ToolCallStarted { call_id, name });
172 }
173 NormalizedStreamEvent::ToolCallDelta { call_id, delta } => {
174 on_progress(RuntimeModelProgress::ToolCallDelta { call_id, delta });
175 }
176 NormalizedStreamEvent::Usage { usage } => {
177 final_usage = usage;
178 }
179 NormalizedStreamEvent::Done { response } => {
180 let mut response = *response;
181 if response.usage.is_none()
182 && (final_usage.prompt_tokens > 0
183 || final_usage.completion_tokens > 0
184 || final_usage.total_tokens > 0)
185 {
186 response.usage = Some(final_usage.clone());
187 }
188 completed_response = Some(response);
189 break;
190 }
191 }
192 }
193
194 let mut response = completed_response.unwrap_or_default();
195 if response.model.is_empty() {
196 response.model = request_model;
197 }
198 if response.usage.is_none()
199 && (final_usage.prompt_tokens > 0 || final_usage.completion_tokens > 0 || final_usage.total_tokens > 0)
200 {
201 response.usage = Some(final_usage);
202 }
203
204 tracing::debug!(
205 model = %response.model,
206 elapsed_ms = started_at.elapsed().as_millis() as u64,
207 input_tokens = response.usage.as_ref().map_or(0, |usage| usage.prompt_tokens),
208 output_tokens = response.usage.as_ref().map_or(0, |usage| usage.completion_tokens),
209 finish_reason = ?response.finish_reason,
210 "model stream completed"
211 );
212 Ok(RuntimeModelOutput { response })
213 }
214}
215
216pub struct TurnExecution {
218 pub response: LLMResponse,
220 pub content: String,
222 pub reasoning: Option<String>,
224}
225
226const MIN_REASONING_UPDATE_BYTES: usize = 256;
227const MAX_REASONING_UPDATE_EVENTS: usize = 2;
228const MIN_OUTPUT_UPDATE_BYTES: usize = 1024;
229const MAX_OUTPUT_UPDATE_EVENTS: usize = 64;
230
231#[derive(Debug, Clone, Default)]
246struct UpdateThrottle {
247 events: usize,
248 last_emit_len: usize,
249}
250
251impl UpdateThrottle {
252 const fn new() -> Self {
253 Self { events: 0, last_emit_len: 0 }
254 }
255
256 fn should_emit(&self, current_len: usize, eager: bool, min_bytes: usize, max_events: usize) -> bool {
258 if self.events >= max_events {
259 return false;
260 }
261 eager || current_len.saturating_sub(self.last_emit_len) >= min_bytes
262 }
263
264 fn record(&mut self, current_len: usize) {
266 self.events += 1;
267 self.last_emit_len = current_len;
268 }
269
270 fn advance_to(&mut self, current_len: usize) {
274 self.last_emit_len = current_len;
275 }
276
277 fn is_first(&self) -> bool {
279 self.events == 0
280 }
281
282 fn reset(&mut self) {
284 self.events = 0;
285 self.last_emit_len = 0;
286 }
287}
288
289#[doc(hidden)]
291pub struct StreamingLifecycleBridge {
292 event_sink: Option<EventSink>,
293 assistant_item_id: String,
294 reasoning_item_id: String,
295 lifecycle: SharedLifecycleEmitter,
296 tool_call_item_ids: hashbrown::HashMap<String, (String, String)>,
300 reasoning_stage: Option<String>,
301 output: UpdateThrottle,
302 reasoning: UpdateThrottle,
303}
304
305impl StreamingLifecycleBridge {
306 pub fn assistant_item_id(&self) -> &str {
308 &self.assistant_item_id
309 }
310
311 #[must_use]
313 pub fn new(event_sink: Option<EventSink>, turn_id: &str, step: usize, attempt: usize) -> Self {
314 Self {
315 event_sink,
316 assistant_item_id: format!("{turn_id}-step-{step}-assistant-stream-{attempt}"),
317 reasoning_item_id: format!("{turn_id}-step-{step}-reasoning-stream-{attempt}"),
318 lifecycle: SharedLifecycleEmitter::default(),
319 tool_call_item_ids: hashbrown::HashMap::new(),
320 reasoning_stage: None,
321 output: UpdateThrottle::new(),
322 reasoning: UpdateThrottle::new(),
323 }
324 }
325
326 pub fn on_progress(&mut self, event: RuntimeModelProgress) {
328 match event {
329 RuntimeModelProgress::OutputDelta(delta) => self.push_assistant_delta(&delta),
330 RuntimeModelProgress::ReasoningDelta(delta) => self.push_reasoning_delta(&delta),
331 RuntimeModelProgress::ReasoningStage(stage) => self.update_reasoning_stage(stage),
332 RuntimeModelProgress::ProviderActivity => {}
333 RuntimeModelProgress::ToolCallStarted { call_id, name } => {
334 self.start_tool_call(call_id, name);
335 }
336 RuntimeModelProgress::ToolCallDelta { call_id, delta } => {
337 self.push_tool_call_delta(call_id, &delta);
338 }
339 }
340 }
341
342 pub fn abort(&mut self) {
344 self.lifecycle.complete_open_text_items();
345 self.lifecycle.complete_open_tool_calls_with_status(ToolCallStatus::Failed);
346 self.emit_pending_events();
347 }
348
349 pub fn complete_open_items(&mut self) {
351 self.lifecycle.flush_open_tool_call_arguments();
355 self.lifecycle.complete_open_text_items();
356 self.emit_pending_events();
357 }
358
359 #[must_use]
362 pub fn take_streamed_tool_call_items(&mut self) -> hashbrown::HashMap<String, (String, String)> {
363 std::mem::take(&mut self.tool_call_item_ids)
364 }
365
366 fn push_assistant_delta(&mut self, delta: &str) {
367 if !self.lifecycle.append_assistant_delta(delta) {
368 return;
369 }
370
371 let len = self.lifecycle.assistant_len();
372 if self
373 .output
374 .should_emit(len, self.output.is_first(), MIN_OUTPUT_UPDATE_BYTES, MAX_OUTPUT_UPDATE_EVENTS)
375 && self.lifecycle.emit_assistant_snapshot(Some(self.assistant_item_id.clone()))
376 {
377 self.output.record(len);
378 self.emit_pending_events();
379 }
380 }
381
382 fn push_reasoning_delta(&mut self, delta: &str) {
383 if !self.lifecycle.append_reasoning_delta(delta) {
384 return;
385 }
386
387 if !self.lifecycle.reasoning_started() {
388 if self.lifecycle.emit_reasoning_snapshot(Some(self.reasoning_item_id.clone())) {
389 self.reasoning.advance_to(self.lifecycle.reasoning_len());
390 self.emit_pending_events();
391 }
392 return;
393 }
394
395 let len = self.lifecycle.reasoning_len();
396 if self
397 .reasoning
398 .should_emit(len, false, MIN_REASONING_UPDATE_BYTES, MAX_REASONING_UPDATE_EVENTS)
399 && self.lifecycle.emit_reasoning_snapshot(Some(self.reasoning_item_id.clone()))
400 {
401 self.reasoning.record(len);
402 self.emit_pending_events();
403 }
404 }
405
406 fn update_reasoning_stage(&mut self, stage: String) {
407 let stage_changed = self.reasoning_stage.as_deref() != Some(stage.as_str());
408 if !stage_changed || !self.lifecycle.set_reasoning_stage(Some(stage.clone())) {
409 self.reasoning_stage = Some(stage);
410 return;
411 }
412 self.reasoning_stage = Some(stage);
413
414 if !self.lifecycle.reasoning_started() {
415 return;
416 }
417
418 let len = self.lifecycle.reasoning_len();
419 if self
420 .reasoning
421 .should_emit(len, true, MIN_REASONING_UPDATE_BYTES, MAX_REASONING_UPDATE_EVENTS)
422 && self.lifecycle.emit_reasoning_stage_update()
423 {
424 self.reasoning.record(len);
425 self.emit_pending_events();
426 }
427 }
428
429 fn start_tool_call(&mut self, call_id: String, name: Option<String>) {
430 let item_id = format!("{}-tool-call-{call_id}", self.assistant_item_id);
431 let tool_name = name.clone().unwrap_or_default();
432 self.tool_call_item_ids.insert(call_id.clone(), (item_id.clone(), tool_name));
433 let _ = self.lifecycle.start_tool_call(&call_id, name, Some(item_id));
434 self.emit_pending_events();
435 }
436
437 fn push_tool_call_delta(&mut self, call_id: String, delta: &str) {
438 if !self.lifecycle.append_tool_call_delta(
439 &call_id,
440 delta,
441 None,
442 Some(format!("{}-tool-call-{call_id}", self.assistant_item_id)),
443 ) {
444 return;
445 }
446 self.emit_pending_events();
447 }
448
449 fn emit_pending_events(&mut self) {
450 let Some(sink) = &self.event_sink else {
451 let _ = self.lifecycle.drain_events();
452 return;
453 };
454
455 for event in self.lifecycle.drain_events() {
456 let mut callback = sink.lock();
457 callback(&event);
458 }
459 }
460}
461
462pub struct AgentRuntime {
464 pub state: AgentSessionState,
466 steering: RuntimeSteering,
467 event_sink: Option<EventSink>,
468 lifecycle: SharedLifecycleEmitter,
469 emitted_events: Vec<ThreadEvent>,
470 output: UpdateThrottle,
471 reasoning: UpdateThrottle,
472}
473
474impl AgentRuntime {
475 pub fn new(
477 state: AgentSessionState,
478 event_sink: Option<EventSink>,
479 steering_receiver: Option<UnboundedReceiver<SteeringMessage>>,
480 ) -> Self {
481 Self {
482 state,
483 steering: RuntimeSteering::new(steering_receiver),
484 event_sink,
485 lifecycle: SharedLifecycleEmitter::default(),
486 emitted_events: Vec::new(),
487 output: UpdateThrottle::new(),
488 reasoning: UpdateThrottle::new(),
489 }
490 }
491
492 pub fn set_event_handler(&mut self, sink: Option<EventSink>) {
494 self.event_sink = sink;
495 }
496
497 pub fn set_steering_receiver(&mut self, receiver: Option<UnboundedReceiver<SteeringMessage>>) {
499 self.steering.set_receiver(receiver);
500 }
501
502 pub fn take_steering_receiver(&mut self) -> Option<UnboundedReceiver<SteeringMessage>> {
504 self.steering.take_receiver()
505 }
506
507 pub fn split_mut(&mut self) -> (&mut AgentSessionState, &mut RuntimeSteering) {
509 (&mut self.state, &mut self.steering)
510 }
511
512 #[must_use]
514 pub fn has_pending_follow_up_inputs(&self) -> bool {
515 self.steering.has_pending_follow_up_inputs()
516 }
517
518 pub fn run_until_idle(&mut self) -> Option<String> {
521 let intent = self.steering.pop_follow_up_intent()?;
522 let (intent_id, input, provenance) = intent.into_parts_with_provenance();
523 match provenance {
524 FollowUpProvenance::UserInput => {
525 self.state.add_user_message_with_intent(input.clone(), Some(intent_id.clone()));
526 }
527 FollowUpProvenance::Synthetic => {
528 self.state
529 .add_synthetic_user_message_with_intent(input.clone(), Some(intent_id.clone()));
530 }
531 }
532 self.steering
533 .in_flight_follow_up_intents
534 .push_back(QueuedFollowUpIntent::from_parts_with_provenance(intent_id, input.clone(), provenance));
535 Some(input)
536 }
537
538 pub fn queue_follow_up_input(&mut self, input: String) {
542 let _ = self.steering.queue_follow_up_input(input);
543 }
544
545 pub fn try_queue_follow_up_input(&mut self, input: String) -> Result<(), FollowUpQueueFull> {
547 self.steering.try_queue_follow_up_input(input)
548 }
549
550 pub fn try_queue_synthetic_follow_up_input(&mut self, input: String) -> Result<(), FollowUpQueueFull> {
552 self.steering.try_queue_synthetic_follow_up_input(input)
553 }
554
555 pub fn restore_follow_up_state(
560 &mut self,
561 pending_intents: impl IntoIterator<Item = QueuedFollowUpIntent>,
562 applied_intent_ids: impl IntoIterator<Item = String>,
563 ) -> Result<(), FollowUpQueueFull> {
564 let mut applied = HashSet::new();
565 for intent_id in applied_intent_ids {
566 if applied.insert(intent_id.clone()) {
567 self.steering.acknowledge_follow_up_intent(intent_id);
568 }
569 }
570 let represented: HashSet<String> = self
571 .state
572 .messages
573 .iter()
574 .filter_map(|message| message.metadata.as_ref().and_then(|metadata| metadata.intent_id()))
575 .map(ToOwned::to_owned)
576 .collect();
577
578 for intent in pending_intents {
579 if applied.contains(intent.id()) || represented.contains(intent.id()) {
580 continue;
581 }
582 self.steering.try_queue_follow_up_intent(intent)?;
583 }
584 Ok(())
585 }
586
587 #[must_use]
589 pub fn applied_follow_up_intent_ids(&self) -> &VecDeque<String> {
590 self.steering.applied_follow_up_intent_ids()
591 }
592
593 pub fn clear_pending_follow_up_inputs(&mut self) {
595 self.steering.clear_pending_follow_up_inputs();
596 }
597
598 pub async fn poll_turn_control(&mut self) -> RuntimeControl {
600 self.steering.poll_turn_control().await
601 }
602
603 pub async fn poll_tool_control(&mut self) -> RuntimeControl {
605 self.steering.poll_tool_control().await
606 }
607
608 pub fn take_emitted_events(&mut self) -> Vec<ThreadEvent> {
610 std::mem::take(&mut self.emitted_events)
611 }
612
613 #[must_use]
615 pub fn tool_call_item_id(&self, call_id: &str) -> Option<String> {
616 self.lifecycle.tool_call_item_id(call_id).map(str::to_string)
617 }
618
619 pub fn complete_tool_call(&mut self, call_id: &str, status: ToolCallStatus, outcome: Option<ToolOutcome>) {
621 let _ = self.lifecycle.complete_tool_call(call_id, status, outcome);
622 self.emit_pending_lifecycle_events();
623 }
624
625 pub fn complete_open_tool_calls(&mut self, status: ToolCallStatus) {
627 self.lifecycle.complete_open_tool_calls_with_status(status);
628 self.emit_pending_lifecycle_events();
629 }
630
631 fn emit_event(&mut self, event: ThreadEvent) {
632 self.emitted_events.push(event.clone());
633 if let Some(sink) = &self.event_sink {
634 let mut callback = sink.lock();
635 callback(&event);
636 }
637 }
638
639 fn emit_pending_lifecycle_events(&mut self) {
640 for event in self.lifecycle.drain_events() {
641 self.emit_event(event);
642 }
643 }
644
645 fn finalize_assistant_lifecycle(&mut self, text: &str) {
646 if text.trim().is_empty() {
647 return;
648 }
649
650 let should_emit_snapshot = !self.lifecycle.assistant_started() || self.lifecycle.replace_assistant_text(text);
651 if should_emit_snapshot {
652 let _ = self.lifecycle.emit_assistant_snapshot(None);
653 }
654 let _ = self.lifecycle.complete_assistant_stream();
655 }
656
657 fn finalize_reasoning_lifecycle(&mut self, text: &str) {
658 if text.trim().is_empty() {
659 return;
660 }
661
662 let should_emit_snapshot = !self.lifecycle.reasoning_started() || self.lifecycle.replace_reasoning_text(text);
663 if should_emit_snapshot {
664 let _ = self.lifecycle.emit_reasoning_snapshot(None);
665 }
666 let _ = self.lifecycle.complete_reasoning_stream();
667 }
668
669 fn finalize_tool_call_lifecycle(&mut self, tool_calls: Option<&[ToolCall]>, _finish_reason: &str) {
670 if let Some(tool_calls) = tool_calls {
671 for call in tool_calls {
672 let tool_name = call.function.as_ref().map(|function| function.name.clone());
673 let _ = self.lifecycle.start_tool_call(&call.id, tool_name.clone(), None);
674 if let Some(function) = call.function.as_ref() {
675 let _ = self
676 .lifecycle
677 .sync_tool_call_arguments(&call.id, &function.arguments, tool_name, None);
678 }
679 }
680 return;
681 }
682
683 self.lifecycle.complete_open_tool_calls_with_status(ToolCallStatus::Failed);
684 }
685
686 fn record_model_progress(
687 &mut self,
688 event: RuntimeModelProgress,
689 full_text: &mut String,
690 full_reasoning: &mut String,
691 ) {
692 match event {
693 RuntimeModelProgress::OutputDelta(delta) => {
694 full_text.push_str(&delta);
695 if self.lifecycle.append_assistant_delta(&delta) {
696 let len = self.lifecycle.assistant_len();
697 if self.output.should_emit(
698 len,
699 self.output.is_first(),
700 MIN_OUTPUT_UPDATE_BYTES,
701 MAX_OUTPUT_UPDATE_EVENTS,
702 ) && self.lifecycle.emit_assistant_snapshot(None)
703 {
704 self.output.record(len);
705 self.emit_pending_lifecycle_events();
706 }
707 }
708 }
709 RuntimeModelProgress::ReasoningDelta(delta) => {
710 full_reasoning.push_str(&delta);
711 if self.lifecycle.append_reasoning_delta(&delta) {
712 let len = self.lifecycle.reasoning_len();
713 if self.reasoning.should_emit(
714 len,
715 self.reasoning.is_first(),
716 MIN_REASONING_UPDATE_BYTES,
717 MAX_REASONING_UPDATE_EVENTS,
718 ) && self.lifecycle.emit_reasoning_snapshot(None)
719 {
720 self.reasoning.record(len);
721 self.emit_pending_lifecycle_events();
722 }
723 }
724 }
725 RuntimeModelProgress::ReasoningStage(stage) => {
726 if self.lifecycle.set_reasoning_stage(Some(stage)) {
727 let _ = self.lifecycle.emit_reasoning_stage_update();
728 self.emit_pending_lifecycle_events();
729 }
730 }
731 RuntimeModelProgress::ProviderActivity => {}
732 RuntimeModelProgress::ToolCallStarted { call_id, name } => {
733 let _ = self.lifecycle.start_tool_call(&call_id, name, None);
734 self.emit_pending_lifecycle_events();
735 }
736 RuntimeModelProgress::ToolCallDelta { call_id, delta } => {
737 if self.lifecycle.append_tool_call_delta(&call_id, &delta, None, None) {
738 self.emit_pending_lifecycle_events();
739 }
740 }
741 }
742 }
743
744 async fn run_turn_once_with_adapter<A: RuntimeModelAdapter + ?Sized>(
745 &mut self,
746 adapter: &mut A,
747 request: LLMRequest,
748 timeout: Option<std::time::Duration>,
749 ) -> Result<TurnExecution> {
750 let request_model = request.model.clone();
751 let start_time = Instant::now();
752 self.output.reset();
753 self.reasoning.reset();
754 let mut full_text = String::new();
755 let mut full_reasoning = String::new();
756 let mut on_progress = |event| self.record_model_progress(event, &mut full_text, &mut full_reasoning);
757 let RuntimeModelOutput { mut response } = match adapter.execute(request, timeout, &mut on_progress).await {
758 Ok(output) => output,
759 Err(error) => {
760 self.complete_open_tool_calls(ToolCallStatus::Failed);
761 tracing::warn!(elapsed_ms = start_time.elapsed().as_millis() as u64, error = %error, "agent turn failed during model execution");
762 return Err(error);
763 }
764 };
765
766 merge_stream_and_completed_text(&mut full_text, response.content.as_deref());
767 let provider_reasoning = response.reasoning.clone();
768
769 let finish_reason = match response.finish_reason.clone() {
770 FinishReason::Stop => "stop".to_string(),
771 FinishReason::ToolCalls => "tool_calls".to_string(),
772 FinishReason::Length => "length".to_string(),
773 FinishReason::Error(message) => message,
774 _ => "unknown".to_string(),
775 };
776 let final_usage = response.usage.take().unwrap_or_default();
777 let mut aggregated_tool_calls = response.tool_calls.take();
778
779 self.finalize_assistant_lifecycle(&full_text);
780 self.finalize_reasoning_lifecycle(&full_reasoning);
781 self.finalize_tool_call_lifecycle(aggregated_tool_calls.as_deref(), &finish_reason);
782 self.emit_pending_lifecycle_events();
783
784 let mut turn_recorded = false;
785 self.state.record_turn(&start_time, &mut turn_recorded);
786
787 if final_usage.prompt_tokens > 0 || final_usage.completion_tokens > 0 {
788 if let Some(alert) = self.state.stats.merge_usage(&final_usage) {
792 let message = alert.message();
793 tracing::warn!("{message}");
794 self.state.push_warning(message);
795 }
796 }
797
798 aggregated_tool_calls = aggregated_tool_calls.filter(|calls| !calls.is_empty());
799
800 let mut assistant_message = crate::llm::provider::Message::assistant(full_text.clone());
801 if let Some(reasoning) = provider_reasoning
802 .clone()
803 .or_else(|| (!full_reasoning.is_empty()).then(|| full_reasoning.clone()))
804 {
805 assistant_message = assistant_message.with_reasoning(Some(reasoning));
806 }
807 if let Some(details) = response.reasoning_details.clone() {
808 let values: Vec<serde_json::Value> = details.into_iter().map(serde_json::Value::String).collect();
809 assistant_message = assistant_message.with_reasoning_details(Some(values));
810 }
811
812 match aggregated_tool_calls.as_ref() {
813 Some(calls) => {
814 assistant_message = assistant_message
815 .with_tool_calls(calls.clone())
816 .with_phase(Some(AssistantPhase::Commentary));
817 }
818 None => {
819 assistant_message = assistant_message.with_phase(Some(AssistantPhase::FinalAnswer));
820 }
821 }
822
823 self.state.adjust_token_count(assistant_message.estimate_tokens() as isize);
824 self.state.messages_mut().push(assistant_message);
825
826 self.state.conversation.push(Content {
827 role: "model".to_string(),
828 parts: vec![Part::Text { text: full_text.clone(), thought_signature: None }],
829 });
830 self.state.last_processed_message_idx = self.state.conversation.len();
831
832 if response.model.is_empty() {
833 response.model = request_model;
834 }
835 response.content = Some(full_text.clone());
836 if response.reasoning.is_none() && !full_reasoning.is_empty() {
837 response.reasoning = Some(full_reasoning.clone());
838 }
839 response.tool_calls = aggregated_tool_calls;
840 response.usage = Some(final_usage);
841 response.finish_reason = if finish_reason == "tool_calls" {
842 FinishReason::ToolCalls
843 } else if finish_reason == "Cancelled" || finish_reason == "cancelled" {
844 FinishReason::Error("Cancelled".to_string())
845 } else {
846 response.finish_reason
847 };
848
849 tracing::debug!(
850 elapsed_ms = start_time.elapsed().as_millis() as u64,
851 output_bytes = full_text.len(),
852 reasoning_bytes = full_reasoning.len(),
853 tool_calls = response.tool_calls.as_ref().map_or(0, Vec::len),
854 input_tokens = response.usage.as_ref().map_or(0, |usage| usage.prompt_tokens),
855 output_tokens = response.usage.as_ref().map_or(0, |usage| usage.completion_tokens),
856 finish_reason = %finish_reason,
857 "agent turn completed"
858 );
859
860 Ok(TurnExecution {
861 response,
862 content: full_text,
863 reasoning: if full_reasoning.is_empty() {
864 None
865 } else {
866 Some(full_reasoning)
867 },
868 })
869 }
870
871 pub async fn run_turn_once(
873 &mut self,
874 provider: &mut Box<dyn LLMProvider>,
875 request: LLMRequest,
876 timeout: Option<std::time::Duration>,
877 ) -> Result<TurnExecution> {
878 let mut steering = std::mem::take(&mut self.steering);
879 let mut adapter = ProviderRuntimeModelAdapter::new(provider, &mut steering);
880 let result = self.run_turn_once_with_adapter(&mut adapter, request, timeout).await;
881 self.steering = steering;
882 result
883 }
884}
885
886#[cfg(test)]
887mod tests;