1use std::pin::Pin;
2use std::sync::{Arc, RwLock};
3use std::time::Duration;
4
5use futures_core::Stream;
6use futures_util::StreamExt;
7use serde_json::Value;
8use tracing::Span;
9
10use crate::engine::runtime::event_bus::EventBus;
11use crate::llm::{ReasoningConfig, StreamChunk, UsageInfo};
12use crate::types::{AgentResult, ChatMessage, RuntimeEvent, SessionId};
13
14const TTFB_TIMEOUT: Duration = Duration::from_secs(60);
19
20const MAX_WIRE_IMAGES: usize = 2;
26
27fn bound_wire_images(messages: &mut [ChatMessage]) {
33 let mut budget = MAX_WIRE_IMAGES;
34 for message in messages.iter_mut().rev() {
35 let (images, content) = match message {
36 ChatMessage::Tool {
37 images, content, ..
38 } => (images, content),
39 ChatMessage::User {
40 images, content, ..
41 } => (images, content),
42 _ => continue,
43 };
44 if images.is_empty() {
45 continue;
46 }
47 if images.len() <= budget {
48 budget -= images.len();
49 continue;
50 }
51 let dropped = images.len();
52 images.clear();
53 budget = 0;
54 content.push_str(&format!(
55 "\n[note: {dropped} image(s) from this older result are not attached to this \
56 request — only the newest {MAX_WIRE_IMAGES} picture(s) travel; call the tool \
57 again if you need to look]"
58 ));
59 }
60}
61
62fn build_chat_request(
64 messages: &[ChatMessage],
65 tool_definitions: &[Value],
66 reasoning: Option<&ReasoningConfig>,
67 response_format: Option<&crate::types::ResponseFormat>,
68 thinking_disabled: bool,
69 model_override: Option<&str>,
70) -> llm_trait::ChatRequest {
71 let mut messages = messages.to_vec();
72 bound_wire_images(&mut messages);
73 let mut request = llm_trait::ChatRequest::new(messages);
74 if !tool_definitions.is_empty() {
75 request = request.with_tools(tool_definitions.to_vec());
76 }
77 if let Some(r) = reasoning {
80 if !thinking_disabled {
81 request = request.with_reasoning(r.clone());
82 } else {
83 tracing::info!(
84 "thinking disabled for rest of run due to too many reasoning-only responses"
85 );
86 }
87 }
88 request.response_format = response_format.cloned();
89
90 if let Some(model) = model_override {
92 request = request.with_model(model);
93 }
94
95 request
96}
97
98fn chat_stream_to_old(
100 chat_stream: llm_trait::ChatStream,
101) -> Pin<Box<dyn Stream<Item = AgentResult<StreamChunk>> + Send>> {
102 let inner = chat_stream.into_inner();
103 Box::pin(inner.map(|item| item.map_err(Into::into)))
104}
105
106pub struct LlmEngine {
107 provider: RwLock<Arc<dyn llm_trait::LlmProvider>>,
108 event_bus: EventBus,
109 model_override: RwLock<Option<String>>,
114}
115
116impl LlmEngine {
117 pub(crate) fn new(provider: Arc<dyn llm_trait::LlmProvider>, event_bus: EventBus) -> Self {
118 Self {
119 provider: RwLock::new(provider),
120 event_bus,
121 model_override: RwLock::new(None),
122 }
123 }
124
125 pub fn get_provider(&self) -> Arc<dyn llm_trait::LlmProvider> {
127 self.provider.read().unwrap().clone()
128 }
129
130 pub fn set_provider(&self, provider: Arc<dyn llm_trait::LlmProvider>) {
132 *self.provider.write().unwrap() = provider;
133 }
134
135 pub fn get_model_override(&self) -> Option<String> {
137 self.model_override.read().unwrap().clone()
138 }
139
140 pub fn set_model_override(&self, model: Option<String>) {
145 *self.model_override.write().unwrap() = model;
146 }
147
148 pub fn set_client(&self, client: Arc<dyn llm_trait::LlmProvider>) {
152 self.set_provider(client);
153 }
154
155 async fn stream_cancellable(
166 &self,
167 cancel_token: &tokio_util::sync::CancellationToken,
168 request: llm_trait::ChatRequest,
169 ) -> AgentResult<Pin<Box<dyn Stream<Item = AgentResult<StreamChunk>> + Send>>> {
170 let provider = self.get_provider();
174 tokio::select! {
175 _ = cancel_token.cancelled() => {
176 tracing::info!("LLM request cancelled while awaiting response");
177 Err(crate::types::AgentError::Cancelled)
178 }
179 result = tokio::time::timeout(TTFB_TIMEOUT, provider.stream(request)) => {
180 match result {
181 Ok(inner) => inner.map(chat_stream_to_old).map_err(Into::into),
182 Err(_) => {
183 tracing::error!(
184 timeout_secs = TTFB_TIMEOUT.as_secs(),
185 "LLM request timed out waiting for response (network stalled?)"
186 );
187 Err(crate::types::AgentError::Llm(format!(
188 "no response within {}s (network stalled or provider unreachable)",
189 TTFB_TIMEOUT.as_secs()
190 )))
191 }
192 }
193 }
194 }
195 }
196
197 pub async fn chat_stream(
198 &self,
199 messages: &[ChatMessage],
200 tool_definitions: &[Value],
201 reasoning: Option<&ReasoningConfig>,
202 response_format: Option<&crate::types::ResponseFormat>,
203 thinking_disabled: bool,
204 cancel_token: &tokio_util::sync::CancellationToken,
205 ) -> AgentResult<Pin<Box<dyn Stream<Item = AgentResult<StreamChunk>> + Send>>> {
206 tracing::info!(
207 msg_count = messages.len(),
208 tool_count = tool_definitions.len(),
209 thinking_disabled,
210 "LLM chat_stream: sending request to API"
211 );
212 let model_override = self.get_model_override();
213 let request = build_chat_request(
214 messages,
215 tool_definitions,
216 reasoning,
217 response_format,
218 thinking_disabled,
219 model_override.as_deref(),
220 );
221 let result = self.stream_cancellable(cancel_token, request).await;
222 match &result {
223 Ok(_) => tracing::info!("LLM chat_stream: API response received"),
224 Err(e) => tracing::error!(error = %e, "LLM chat_stream: API request failed"),
225 }
226 result
227 }
228
229 #[allow(clippy::too_many_arguments)]
230 pub async fn run_llm_turn_with_retry(
231 &self,
232 session_id: &SessionId,
233 messages: &[ChatMessage],
234 tool_definitions: &[Value],
235 reasoning: Option<&ReasoningConfig>,
236 response_format: Option<&crate::types::ResponseFormat>,
237 retry: crate::types::RetryConfig,
238 thinking_disabled: bool,
239 cancel_token: &tokio_util::sync::CancellationToken,
240 ) -> AgentResult<Pin<Box<dyn Stream<Item = AgentResult<StreamChunk>> + Send>>> {
241 let model_override = self.get_model_override();
242 let request = build_chat_request(
243 messages,
244 tool_definitions,
245 reasoning,
246 response_format,
247 thinking_disabled,
248 model_override.as_deref(),
249 );
250 let mut attempt = 1;
251 let mut delay_ms = retry.initial_backoff_ms;
252 loop {
253 match self.stream_cancellable(cancel_token, request.clone()).await {
254 Ok(chat_stream) => return Ok(chat_stream),
255 Err(e) => {
256 let agent_err: crate::types::AgentError = e;
257 if agent_err.is_cancelled() {
260 return Err(agent_err);
261 }
262 if attempt > retry.max_retries {
263 tracing::error!(session_id = session_id.id, attempts = attempt, error = %agent_err, "LLM stream retry exhausted");
264 return Err(agent_err);
265 }
266 tracing::warn!(session_id = session_id.id, attempt, error = %agent_err, "LLM stream failed, retrying...");
267 tokio::time::sleep(Duration::from_millis(delay_ms)).await;
268 delay_ms = (delay_ms as f64 * retry.backoff_multiplier) as u64;
269 if delay_ms > retry.max_backoff_ms {
270 delay_ms = retry.max_backoff_ms;
271 }
272 attempt += 1;
273 }
274 }
275 }
276 }
277
278 pub(crate) async fn process_stream<F>(
279 &self,
280 session_id: &SessionId,
281 mut stream: Pin<Box<dyn Stream<Item = AgentResult<StreamChunk>> + Send>>,
282 span: Span,
283 event_rx: &mut tokio::sync::broadcast::Receiver<RuntimeEvent>,
284 on_event: Arc<std::sync::Mutex<F>>,
285 cancel_token: &tokio_util::sync::CancellationToken,
286 ) -> AgentResult<LlmTurnResult>
287 where
288 F: FnMut(RuntimeEvent) -> AgentResult<()> + Send,
289 {
290 let _enter = span.enter();
291 let start = std::time::Instant::now();
292 let mut first_token = true;
293 let mut aggregator = StreamAggregator::new();
294 tracing::info!(session_id = session_id.id, "LLM process_stream start");
295
296 loop {
303 match event_rx.try_recv() {
304 Ok(event) if crate::engine::runtime::is_self_echo_user_event(&event) => continue,
305 Ok(event) => {
306 if let Ok(mut cb) = on_event.lock() {
309 cb(event)?;
310 }
311 continue;
312 }
313 Err(tokio::sync::broadcast::error::TryRecvError::Lagged(_)) => continue,
314 Err(_) => break,
315 }
316 }
317
318 loop {
319 tokio::select! {
320 recv_result = event_rx.recv() => {
321 match recv_result {
322 Ok(event) => {
323 if crate::engine::runtime::is_self_echo_user_event(&event) {
327 continue;
328 }
329 if let Ok(mut cb) = on_event.lock() {
330 cb(event)?;
331 }
332 }
333 Err(tokio::sync::broadcast::error::RecvError::Lagged(_)) => continue,
334 Err(tokio::sync::broadcast::error::RecvError::Closed) => break,
335 }
336 }
337 _ = cancel_token.cancelled() => {
338 tracing::info!(session_id = session_id.id, "LLM stream cancelled");
339 return Err(crate::types::AgentError::Cancelled);
340 }
341 maybe_chunk = stream.next() => {
342 let Some(chunk) = maybe_chunk else {
343 break;
344 };
345
346 match chunk {
347 Ok(StreamChunk::Text(text)) => {
348 if first_token {
349 let ttft = start.elapsed();
350 aggregator.ttft_ms = ttft.as_millis() as u64;
351 tracing::info!(session_id = session_id.id, ?ttft, "LLM first token received");
352 first_token = false;
353 }
354 if !text.is_empty() {
360 self.event_bus.emit(RuntimeEvent::TextDelta {
361 session_id: session_id.clone(),
362 text: text.clone(),
363 agent_id: None,
364 trace_id: None,
365 });
366 }
367 aggregator.full_text.push_str(&text);
368 }
369 Ok(StreamChunk::Thought(text)) => {
370 tracing::debug!(session_id = session_id.id, len = text.len(), "llm thought chunk");
371 aggregator.reasoning_text.push_str(&text);
372 if !text.is_empty() {
375 self.event_bus.emit(RuntimeEvent::ThoughtDelta {
376 session_id: session_id.clone(),
377 text,
378 agent_id: None,
379 trace_id: None,
380 });
381 }
382 }
383 Ok(StreamChunk::ToolCall(choice)) => {
384 if !aggregator.is_tool_call {
385 tracing::info!(session_id = session_id.id, "LLM stream: first tool_call chunk received");
386 }
387 aggregator.is_tool_call = true;
388 let Some(tool_calls) = choice
389 .get("delta")
390 .and_then(|d| d.get("tool_calls"))
391 .and_then(Value::as_array)
392 else {
393 tracing::debug!("tool_calls missing or not an array in LLM response");
394 continue;
395 };
396
397 for tool_call in tool_calls {
398 let idx = tool_call
399 .get("index")
400 .and_then(Value::as_u64)
401 .unwrap_or(0) as usize;
402 const DRAFT_ARGS_BUCKET: usize = 512;
413 let fresh_slot = !aggregator.partials.contains_key(&idx);
414 let before_args_len =
415 aggregator.partials.get(&idx).map(|e| e.2.len()).unwrap_or(0);
416 let entry = aggregator.partials.entry(idx).or_insert_with(|| (String::new(), String::new(), String::new()));
417 let mut named_now = false;
418 if let Some(id) = tool_call.get("id").and_then(Value::as_str)
419 && !id.is_empty() {
420 entry.0 = id.to_string();
421 }
422 if let Some(func) = tool_call.get("function") {
423 if let Some(name) = func.get("name").and_then(Value::as_str)
424 && !name.is_empty() {
425 named_now = entry.1.is_empty();
426 entry.1 = name.to_string();
427 }
428 if let Some(args) = func.get("arguments").and_then(Value::as_str) {
429 entry.2.push_str(args);
430 }
431 }
432 let args_len = entry.2.len();
433 let grew_bucket =
434 args_len / DRAFT_ARGS_BUCKET > before_args_len / DRAFT_ARGS_BUCKET;
435 if fresh_slot || named_now || grew_bucket {
436 self.event_bus.emit(RuntimeEvent::ActionDraft {
437 session_id: session_id.clone(),
438 index: idx,
439 name: entry.1.clone(),
440 args_len,
441 count: aggregator.partials.len(),
442 agent_id: None,
443 trace_id: None,
444 });
445 }
446 }
447 }
448 Ok(StreamChunk::Usage(usage)) => {
449 tracing::debug!(
456 session_id = session_id.id,
457 input = ?usage.prompt_tokens,
458 output = ?usage.completion_tokens,
459 reasoning = ?usage.reasoning_tokens,
460 "LLM usage chunk received"
461 );
462 match &mut aggregator.usage {
463 Some(existing) => existing.merge(&usage),
464 None => aggregator.usage = Some(usage),
465 }
466 }
467 Ok(StreamChunk::Stop { finish_reason }) => {
468 if finish_reason.is_some() {
473 aggregator.finish_reason = finish_reason;
474 }
475 }
476 Err(e) => {
477 tracing::error!(session_id = session_id.id, error = %e, "LLM stream error");
478 return Err(e);
479 }
480 Ok(StreamChunk::ThinkingSignature(sig)) => {
481 aggregator.thinking_signature = Some(sig);
482 }
483 Ok(StreamChunk::Error(e)) => {
484 tracing::error!(session_id = session_id.id, error = %e, "LLM stream protocol error");
485 return Err(crate::types::AgentError::Llm(e));
486 }
487 }
488
489 {
490 let mut cb = on_event.lock().unwrap();
491 EventBus::drain_async_events(event_rx, &mut *cb)?;
492 }
493 }
494 }
495 }
496
497 let total_elapsed = start.elapsed();
498 let _ttft_ms = aggregator.ttft_ms;
499
500 let full_text = aggregator.full_text;
507 let reasoning_len = aggregator.reasoning_text.len();
508 let reasoning_only = full_text.is_empty() && reasoning_len > 0 && !aggregator.is_tool_call;
509 if reasoning_only {
510 tracing::warn!(
511 session_id = session_id.id,
512 reasoning_len,
513 "content empty but reasoning_content present — model produced reasoning only; \
514 not promoting it to the answer, the react loop will nudge/fail"
515 );
516 }
517
518 tracing::info!(
519 session_id = session_id.id,
520 text_len = full_text.len(),
521 reasoning_len,
522 tool_calls = aggregator.partials.len(),
523 elapsed_ms = total_elapsed.as_millis(),
524 "LLM stream done"
525 );
526
527 let tool_calls = aggregator
528 .partials
529 .into_iter()
530 .filter(|(_idx, (_id, name, _args))| !name.is_empty())
538 .map(|(idx, (id, name, args))| {
539 let mut tc = serde_json::Map::new();
540 tc.insert("index".to_string(), idx.into());
541 tc.insert("id".to_string(), id.into());
542 tc.insert("type".to_string(), "function".into());
543 let mut func = serde_json::Map::new();
544 func.insert("name".to_string(), name.into());
545 func.insert("arguments".to_string(), args.into());
546 tc.insert("function".to_string(), func.into());
547 serde_json::Value::Object(tc)
548 })
549 .collect::<Vec<_>>();
550
551 Ok(LlmTurnResult {
552 full_text,
553 reasoning_text: aggregator.reasoning_text,
554 is_tool_call: aggregator.is_tool_call,
555 tool_calls,
556 usage: aggregator.usage,
557 finish_reason: aggregator.finish_reason,
558 ttft_ms: aggregator.ttft_ms,
559 llm_duration_ms: total_elapsed.as_millis() as u64,
560 reasoning_only,
561 thinking_signature: aggregator.thinking_signature,
562 })
563 }
564
565 pub fn emit_text_delta(&self, session_id: &SessionId, text: String) {
566 self.event_bus.emit(RuntimeEvent::TextDelta {
567 session_id: session_id.clone(),
568 text,
569 agent_id: None,
570 trace_id: None,
571 });
572 }
573}
574
575pub struct LlmTurnResult {
576 pub full_text: String,
577 pub reasoning_text: String,
580 pub is_tool_call: bool,
581 pub tool_calls: Vec<Value>,
582 pub usage: Option<UsageInfo>,
583 pub finish_reason: Option<String>,
586 pub ttft_ms: u64,
588 pub llm_duration_ms: u64,
590 pub reasoning_only: bool,
595 #[allow(dead_code)]
597 pub thinking_signature: Option<String>,
598}
599
600struct StreamAggregator {
601 pub full_text: String,
602 pub reasoning_text: String,
605 pub is_tool_call: bool,
606 pub partials: std::collections::HashMap<usize, (String, String, String)>,
607 pub usage: Option<UsageInfo>,
608 pub finish_reason: Option<String>,
610 pub ttft_ms: u64,
612 pub thinking_signature: Option<String>,
614}
615
616impl StreamAggregator {
617 fn new() -> Self {
618 Self {
619 full_text: String::new(),
620 reasoning_text: String::new(),
621 is_tool_call: false,
622 partials: std::collections::HashMap::new(),
623 usage: None,
624 finish_reason: None,
625 ttft_ms: 0,
626 thinking_signature: None,
627 }
628 }
629}
630
631#[cfg(test)]
632mod tests {
633 use super::*;
634 use crate::types::{AgentError, RetryConfig};
635 use async_trait::async_trait;
636 use llm_trait::{Capabilities, ChatRequest, ChatStream, LlmError, LlmProvider, ProviderInfo};
637 use std::pin::Pin;
638
639 struct StubProvider(&'static str);
640
641 #[async_trait]
642 impl LlmProvider for StubProvider {
643 async fn stream(&self, _request: ChatRequest) -> Result<ChatStream, LlmError> {
644 Ok(ChatStream::new(Box::pin(futures_util::stream::empty())))
645 }
646
647 async fn chat(&self, _request: ChatRequest) -> Result<llm_trait::ChatResponse, LlmError> {
648 Err(LlmError::Llm("not implemented".into()))
649 }
650
651 fn capabilities(&self) -> Capabilities {
652 Capabilities::default()
653 }
654
655 fn info(&self) -> ProviderInfo {
656 ProviderInfo {
657 name: "stub".to_string(),
658 model: self.0.to_string(),
659 version: None,
660 }
661 }
662 }
663
664 fn engine(model: &'static str) -> LlmEngine {
665 LlmEngine::new(Arc::new(StubProvider(model)), EventBus::new(16))
666 }
667
668 #[test]
669 fn get_provider_and_set_provider_swap() {
670 let engine = engine("model-a");
671 assert_eq!(engine.get_provider().info().model, "model-a");
672 engine.set_provider(Arc::new(StubProvider("model-b")));
673 assert_eq!(engine.get_provider().info().model, "model-b");
674 }
675
676 #[test]
677 fn get_provider_returns_provider() {
678 let engine = engine("model-a");
679 let provider = engine.get_provider();
680 assert_eq!(provider.info().model, "model-a");
681 }
682
683 #[tokio::test]
684 async fn process_stream_aggregates_text_usage_and_stop() {
685 let bus = EventBus::new(16);
686 let engine = LlmEngine::new(Arc::new(StubProvider("x")), bus.clone());
687 let chunks = vec![
688 Ok(StreamChunk::Text("Hello".into())),
689 Ok(StreamChunk::Text(" world".into())),
690 Ok(StreamChunk::Usage(UsageInfo {
691 prompt_tokens: Some(5),
692 completion_tokens: Some(2),
693 total_tokens: Some(7),
694 reasoning_tokens: None,
695 })),
696 Ok(StreamChunk::Stop {
697 finish_reason: Some("stop".into()),
698 }),
699 ];
700 let stream = Box::pin(futures_util::stream::iter(chunks));
701 let mut rx = bus.subscribe();
702 let events = std::sync::Arc::new(std::sync::Mutex::new(Vec::new()));
703 let events_clone = events.clone();
704 let cancel = tokio_util::sync::CancellationToken::new();
705 let result = engine
706 .process_stream(
707 &SessionId::new(1),
708 stream,
709 tracing::Span::none(),
710 &mut rx,
711 std::sync::Arc::new(std::sync::Mutex::new(move |e| {
712 events_clone.lock().unwrap().push(e);
713 Ok(())
714 })),
715 &cancel,
716 )
717 .await
718 .unwrap();
719
720 assert_eq!(result.full_text, "Hello world");
721 assert!(!result.is_tool_call);
722 assert_eq!(result.finish_reason.as_deref(), Some("stop"));
723 let usage = result.usage.unwrap();
724 assert_eq!(usage.prompt_tokens, Some(5));
725 assert_eq!(usage.completion_tokens, Some(2));
726 assert_eq!(usage.total_tokens, Some(7));
727 assert!(result.llm_duration_ms >= result.ttft_ms);
728
729 let events = events.lock().unwrap();
730 let texts: Vec<String> = events
731 .iter()
732 .filter_map(|e| match e {
733 RuntimeEvent::TextDelta { text, .. } => Some(text.clone()),
734 _ => None,
735 })
736 .collect();
737 assert_eq!(texts, vec!["Hello".to_string(), " world".to_string()]);
738 }
739
740 #[tokio::test]
741 async fn process_stream_merges_partial_usage_events() {
742 let bus = EventBus::new(16);
747 let engine = LlmEngine::new(Arc::new(StubProvider("x")), bus.clone());
748 let chunks = vec![
749 Ok(StreamChunk::Usage(UsageInfo {
750 prompt_tokens: Some(2),
751 completion_tokens: Some(0),
752 total_tokens: None,
753 reasoning_tokens: None,
754 })),
755 Ok(StreamChunk::Usage(UsageInfo {
756 prompt_tokens: Some(63),
757 completion_tokens: Some(26),
758 total_tokens: None,
759 reasoning_tokens: None,
760 })),
761 Ok(StreamChunk::Stop {
762 finish_reason: Some("end_turn".into()),
763 }),
764 ];
765 let stream = Box::pin(futures_util::stream::iter(chunks));
766 let mut rx = bus.subscribe();
767 let noop = std::sync::Arc::new(std::sync::Mutex::new(|_e: RuntimeEvent| Ok(())));
768 let cancel = tokio_util::sync::CancellationToken::new();
769 let result = engine
770 .process_stream(
771 &SessionId::new(1),
772 stream,
773 tracing::Span::none(),
774 &mut rx,
775 noop,
776 &cancel,
777 )
778 .await
779 .unwrap();
780
781 let usage = result.usage.unwrap();
782 assert_eq!(usage.prompt_tokens, Some(63), "later Some wins");
783 assert_eq!(usage.completion_tokens, Some(26));
784 }
785
786 #[tokio::test]
787 async fn process_stream_keeps_usage_when_delta_omits_prompt() {
788 let bus = EventBus::new(16);
791 let engine = LlmEngine::new(Arc::new(StubProvider("x")), bus.clone());
792 let chunks = vec![
793 Ok(StreamChunk::Usage(UsageInfo {
794 prompt_tokens: Some(5),
795 completion_tokens: Some(1),
796 total_tokens: None,
797 reasoning_tokens: None,
798 })),
799 Ok(StreamChunk::Usage(UsageInfo {
800 prompt_tokens: None,
801 completion_tokens: Some(26),
802 total_tokens: None,
803 reasoning_tokens: None,
804 })),
805 Ok(StreamChunk::Stop {
806 finish_reason: Some("end_turn".into()),
807 }),
808 ];
809 let stream = Box::pin(futures_util::stream::iter(chunks));
810 let mut rx = bus.subscribe();
811 let noop = std::sync::Arc::new(std::sync::Mutex::new(|_e: RuntimeEvent| Ok(())));
812 let cancel = tokio_util::sync::CancellationToken::new();
813 let result = engine
814 .process_stream(
815 &SessionId::new(1),
816 stream,
817 tracing::Span::none(),
818 &mut rx,
819 noop,
820 &cancel,
821 )
822 .await
823 .unwrap();
824
825 let usage = result.usage.unwrap();
826 assert_eq!(
827 usage.prompt_tokens,
828 Some(5),
829 "prompt survives a partial delta"
830 );
831 assert_eq!(usage.completion_tokens, Some(26));
832 }
833
834 #[tokio::test]
835 async fn process_stream_aggregates_tool_calls() {
836 let bus = EventBus::new(16);
837 let engine = LlmEngine::new(Arc::new(StubProvider("x")), bus.clone());
838 let chunks = vec![
839 Ok(StreamChunk::ToolCall(serde_json::json!({
840 "delta": { "tool_calls": [
841 { "index": 0, "id": "call_1", "function": { "name": "shell", "arguments": "{\"cmd\":" } }
842 ] }
843 }))),
844 Ok(StreamChunk::ToolCall(serde_json::json!({
845 "delta": { "tool_calls": [
846 { "index": 0, "function": { "arguments": "\"ls\"" } }
847 ] }
848 }))),
849 ];
850 let stream = Box::pin(futures_util::stream::iter(chunks));
851 let mut rx = bus.subscribe();
852 let cancel = tokio_util::sync::CancellationToken::new();
853 let result = engine
854 .process_stream(
855 &SessionId::new(1),
856 stream,
857 tracing::Span::none(),
858 &mut rx,
859 std::sync::Arc::new(std::sync::Mutex::new(|_e| Ok(()))),
860 &cancel,
861 )
862 .await
863 .unwrap();
864
865 assert!(result.is_tool_call);
866 assert!(result.full_text.is_empty());
867 assert_eq!(result.tool_calls.len(), 1);
868 let tc = &result.tool_calls[0];
869 assert_eq!(tc["id"].as_str(), Some("call_1"));
870 assert_eq!(tc["type"].as_str(), Some("function"));
871 assert_eq!(tc["function"]["name"].as_str(), Some("shell"));
872 assert_eq!(
873 tc["function"]["arguments"].as_str(),
874 Some("{\"cmd\":\"ls\"")
875 );
876 }
877
878 #[tokio::test]
879 async fn process_stream_emits_throttled_tool_call_drafts() {
880 let bus = EventBus::new(16);
887 let engine = LlmEngine::new(Arc::new(StubProvider("x")), bus.clone());
888 let args_400 = "x".repeat(400);
889 let args_200 = "y".repeat(200);
890 let args_50 = "z".repeat(50);
891 let chunks = vec![
892 Ok(StreamChunk::ToolCall(serde_json::json!({
894 "delta": { "tool_calls": [
895 { "index": 0, "id": "call_1", "function": { "name": "spawn_agent", "arguments": args_400 } }
896 ] }
897 }))),
898 Ok(StreamChunk::ToolCall(serde_json::json!({
900 "delta": { "tool_calls": [
901 { "index": 0, "function": { "arguments": args_200 } }
902 ] }
903 }))),
904 Ok(StreamChunk::ToolCall(serde_json::json!({
906 "delta": { "tool_calls": [
907 { "index": 0, "function": { "arguments": args_50 } }
908 ] }
909 }))),
910 Ok(StreamChunk::ToolCall(serde_json::json!({
912 "delta": { "tool_calls": [
913 { "index": 1, "id": "call_2", "function": { "name": "shell", "arguments": "{}" } }
914 ] }
915 }))),
916 ];
917 let stream = Box::pin(futures_util::stream::iter(chunks));
918 let mut rx = bus.subscribe();
919 let events = std::sync::Arc::new(std::sync::Mutex::new(Vec::new()));
920 let events_clone = events.clone();
921 let cancel = tokio_util::sync::CancellationToken::new();
922 let result = engine
923 .process_stream(
924 &SessionId::new(1),
925 stream,
926 tracing::Span::none(),
927 &mut rx,
928 std::sync::Arc::new(std::sync::Mutex::new(move |e| {
929 events_clone.lock().unwrap().push(e);
930 Ok(())
931 })),
932 &cancel,
933 )
934 .await
935 .unwrap();
936 assert_eq!(result.tool_calls.len(), 2);
937
938 let events = events.lock().unwrap();
939 let drafts: Vec<(usize, String, usize, usize)> = events
940 .iter()
941 .filter_map(|e| match e {
942 RuntimeEvent::ActionDraft {
943 index,
944 name,
945 args_len,
946 count,
947 ..
948 } => Some((*index, name.clone(), *args_len, *count)),
949 _ => None,
950 })
951 .collect();
952 assert_eq!(
953 drafts,
954 vec![
955 (0, "spawn_agent".to_string(), 400, 1),
956 (0, "spawn_agent".to_string(), 600, 1),
957 (1, "shell".to_string(), 2, 2),
958 ]
959 );
960 }
961
962 #[tokio::test]
963 async fn process_stream_emits_text_after_tool_call_chunks() {
964 let bus = EventBus::new(16);
970 let engine = LlmEngine::new(Arc::new(StubProvider("x")), bus.clone());
971 let chunks = vec![
972 Ok(StreamChunk::Text("before".into())),
973 Ok(StreamChunk::ToolCall(serde_json::json!({
974 "delta": { "tool_calls": [
975 { "index": 0, "id": "call_1", "function": { "name": "shell", "arguments": "{}" } }
976 ] }
977 }))),
978 Ok(StreamChunk::Text("interleaved".into())),
979 Ok(StreamChunk::Thought("late thought".into())),
980 ];
981 let stream = Box::pin(futures_util::stream::iter(chunks));
982 let mut rx = bus.subscribe();
983 let events = std::sync::Arc::new(std::sync::Mutex::new(Vec::new()));
984 let events_clone = events.clone();
985 let cancel = tokio_util::sync::CancellationToken::new();
986 let result = engine
987 .process_stream(
988 &SessionId::new(1),
989 stream,
990 tracing::Span::none(),
991 &mut rx,
992 std::sync::Arc::new(std::sync::Mutex::new(move |e| {
993 events_clone.lock().unwrap().push(e);
994 Ok(())
995 })),
996 &cancel,
997 )
998 .await
999 .unwrap();
1000
1001 assert!(result.is_tool_call);
1002 assert_eq!(result.full_text, "beforeinterleaved");
1003
1004 let events = events.lock().unwrap();
1005 let texts: Vec<&str> = events
1006 .iter()
1007 .filter_map(|e| match e {
1008 RuntimeEvent::TextDelta { text, .. } => Some(text.as_str()),
1009 _ => None,
1010 })
1011 .collect();
1012 assert_eq!(texts, vec!["before", "interleaved"]);
1013 let thoughts: Vec<&str> = events
1014 .iter()
1015 .filter_map(|e| match e {
1016 RuntimeEvent::ThoughtDelta { text, .. } => Some(text.as_str()),
1017 _ => None,
1018 })
1019 .collect();
1020 assert_eq!(thoughts, vec!["late thought"]);
1021 }
1022
1023 #[tokio::test]
1024 async fn process_stream_flags_reasoning_only_without_promoting() {
1025 let bus = EventBus::new(16);
1026 let engine = LlmEngine::new(Arc::new(StubProvider("x")), bus.clone());
1027 let chunks = vec![Ok(StreamChunk::Thought("deep thought".into()))];
1028 let stream = Box::pin(futures_util::stream::iter(chunks));
1029 let mut rx = bus.subscribe();
1030 let cancel = tokio_util::sync::CancellationToken::new();
1031 let result = engine
1032 .process_stream(
1033 &SessionId::new(1),
1034 stream,
1035 tracing::Span::none(),
1036 &mut rx,
1037 std::sync::Arc::new(std::sync::Mutex::new(|_e| Ok(()))),
1038 &cancel,
1039 )
1040 .await
1041 .unwrap();
1042
1043 assert_eq!(result.full_text, "");
1045 assert_eq!(result.reasoning_text, "deep thought");
1046 assert!(!result.is_tool_call);
1047 assert!(result.reasoning_only, "reasoning-only should be flagged");
1048 }
1049
1050 #[tokio::test]
1051 async fn process_stream_keeps_reasoning_on_tool_call_turns() {
1052 let bus = EventBus::new(16);
1059 let engine = LlmEngine::new(Arc::new(StubProvider("x")), bus.clone());
1060 let chunks = vec![
1061 Ok(StreamChunk::Thought("why this tool, now".into())),
1062 Ok(StreamChunk::ToolCall(serde_json::json!({
1063 "delta": { "tool_calls": [
1064 { "index": 0, "id": "call_1", "function": { "name": "shell", "arguments": "{}" } }
1065 ] }
1066 }))),
1067 Ok(StreamChunk::Thought("...and what it should do".into())),
1068 Ok(StreamChunk::Stop {
1069 finish_reason: Some("tool_calls".to_string()),
1070 }),
1071 ];
1072 let stream = Box::pin(futures_util::stream::iter(chunks));
1073 let mut rx = bus.subscribe();
1074 let cancel = tokio_util::sync::CancellationToken::new();
1075 let result = engine
1076 .process_stream(
1077 &SessionId::new(1),
1078 stream,
1079 tracing::Span::none(),
1080 &mut rx,
1081 std::sync::Arc::new(std::sync::Mutex::new(|_e| Ok(()))),
1082 &cancel,
1083 )
1084 .await
1085 .unwrap();
1086
1087 assert!(result.is_tool_call);
1088 assert!(!result.reasoning_only);
1089 assert_eq!(
1090 result.reasoning_text,
1091 "why this tool, now...and what it should do"
1092 );
1093 assert_eq!(
1095 result.reasoning_text.len(),
1096 "why this tool, now".len() + "...and what it should do".len()
1097 );
1098 }
1099
1100 #[tokio::test]
1101 async fn process_stream_propagates_error() {
1102 let bus = EventBus::new(16);
1103 let engine = LlmEngine::new(Arc::new(StubProvider("x")), bus.clone());
1104 let chunks = vec![
1105 Ok(StreamChunk::Text("partial".into())),
1106 Err(AgentError::internal("boom")),
1107 ];
1108 let stream = Box::pin(futures_util::stream::iter(chunks));
1109 let mut rx = bus.subscribe();
1110 let cancel = tokio_util::sync::CancellationToken::new();
1111 let err = engine
1112 .process_stream(
1113 &SessionId::new(1),
1114 stream,
1115 tracing::Span::none(),
1116 &mut rx,
1117 std::sync::Arc::new(std::sync::Mutex::new(|_e| Ok(()))),
1118 &cancel,
1119 )
1120 .await
1121 .err()
1122 .expect("stream should error");
1123 assert!(err.to_string().contains("boom"));
1124 }
1125
1126 #[tokio::test]
1127 async fn process_stream_cancelled() {
1128 let bus = EventBus::new(16);
1129 let engine = LlmEngine::new(Arc::new(StubProvider("x")), bus.clone());
1130 let stream: Pin<Box<dyn Stream<Item = AgentResult<StreamChunk>> + Send>> =
1131 Box::pin(futures_util::stream::pending());
1132 let mut rx = bus.subscribe();
1133 let cancel = tokio_util::sync::CancellationToken::new();
1134 cancel.cancel();
1135 let err = engine
1136 .process_stream(
1137 &SessionId::new(1),
1138 stream,
1139 tracing::Span::none(),
1140 &mut rx,
1141 std::sync::Arc::new(std::sync::Mutex::new(|_e| Ok(()))),
1142 &cancel,
1143 )
1144 .await
1145 .err()
1146 .expect("stream should error");
1147 assert!(matches!(err, AgentError::Cancelled));
1148 }
1149
1150 struct AlwaysFail;
1154
1155 #[async_trait]
1156 impl LlmProvider for AlwaysFail {
1157 async fn stream(&self, _request: ChatRequest) -> Result<ChatStream, LlmError> {
1158 Err(LlmError::Llm("api down".into()))
1159 }
1160
1161 async fn chat(&self, _request: ChatRequest) -> Result<llm_trait::ChatResponse, LlmError> {
1162 Err(LlmError::Llm("api down".into()))
1163 }
1164
1165 fn capabilities(&self) -> Capabilities {
1166 Capabilities::default()
1167 }
1168
1169 fn info(&self) -> ProviderInfo {
1170 ProviderInfo {
1171 name: "always-fail".to_string(),
1172 model: "always-fail".to_string(),
1173 version: None,
1174 }
1175 }
1176 }
1177
1178 struct FailThenSucceed {
1180 remaining: std::sync::Mutex<usize>,
1181 }
1182
1183 impl FailThenSucceed {
1184 fn new(failures: usize) -> Self {
1185 Self {
1186 remaining: std::sync::Mutex::new(failures),
1187 }
1188 }
1189 }
1190
1191 #[async_trait]
1192 impl LlmProvider for FailThenSucceed {
1193 async fn stream(&self, _request: ChatRequest) -> Result<ChatStream, LlmError> {
1194 let mut remaining = self.remaining.lock().unwrap();
1195 if *remaining > 0 {
1196 *remaining -= 1;
1197 Err(LlmError::Llm("transient".into()))
1198 } else {
1199 Ok(ChatStream::new(Box::pin(futures_util::stream::empty())))
1200 }
1201 }
1202
1203 async fn chat(&self, _request: ChatRequest) -> Result<llm_trait::ChatResponse, LlmError> {
1204 Err(LlmError::Llm("not implemented".into()))
1205 }
1206
1207 fn capabilities(&self) -> Capabilities {
1208 Capabilities::default()
1209 }
1210
1211 fn info(&self) -> ProviderInfo {
1212 ProviderInfo {
1213 name: "fail-then-succeed".to_string(),
1214 model: "fail-then-succeed".to_string(),
1215 version: None,
1216 }
1217 }
1218 }
1219
1220 #[tokio::test]
1221 async fn chat_stream_returns_stream_on_ok() {
1222 let engine = LlmEngine::new(Arc::new(StubProvider("x")), EventBus::new(16));
1223 let mut stream = engine
1224 .chat_stream(
1225 &[],
1226 &[],
1227 None,
1228 None,
1229 false,
1230 &tokio_util::sync::CancellationToken::new(),
1231 )
1232 .await
1233 .unwrap();
1234 let next = futures_util::StreamExt::next(&mut stream).await;
1235 assert!(next.is_none());
1236 }
1237
1238 #[tokio::test]
1239 async fn chat_stream_with_thinking_disabled() {
1240 let engine = LlmEngine::new(Arc::new(StubProvider("x")), EventBus::new(16));
1241 let mut stream = engine
1243 .chat_stream(
1244 &[],
1245 &[],
1246 None,
1247 None,
1248 true,
1249 &tokio_util::sync::CancellationToken::new(),
1250 )
1251 .await
1252 .unwrap();
1253 let next = futures_util::StreamExt::next(&mut stream).await;
1254 assert!(next.is_none());
1255 }
1256
1257 #[tokio::test]
1258 async fn chat_stream_forwards_error() {
1259 let engine = LlmEngine::new(Arc::new(AlwaysFail), EventBus::new(16));
1260 let err = engine
1261 .chat_stream(
1262 &[],
1263 &[],
1264 None,
1265 None,
1266 false,
1267 &tokio_util::sync::CancellationToken::new(),
1268 )
1269 .await
1270 .err()
1271 .expect("should fail");
1272 assert!(err.to_string().contains("api down"));
1273 }
1274
1275 #[tokio::test]
1276 async fn run_llm_turn_retries_then_succeeds() {
1277 let engine = LlmEngine::new(Arc::new(FailThenSucceed::new(2)), EventBus::new(16));
1278 let cfg = RetryConfig {
1279 max_retries: 3,
1280 initial_backoff_ms: 1,
1281 max_backoff_ms: 1000,
1282 backoff_multiplier: 2.0,
1283 jitter: false,
1284 };
1285 let _stream = engine
1286 .run_llm_turn_with_retry(
1287 &SessionId::new(1),
1288 &[],
1289 &[],
1290 None,
1291 None,
1292 cfg,
1293 false,
1294 &tokio_util::sync::CancellationToken::new(),
1295 )
1296 .await
1297 .expect("should succeed after retries");
1298 }
1299
1300 #[tokio::test]
1301 async fn run_llm_turn_retries_exhausted() {
1302 let engine = LlmEngine::new(Arc::new(FailThenSucceed::new(100)), EventBus::new(16));
1303 let cfg = RetryConfig {
1304 max_retries: 2,
1305 initial_backoff_ms: 1,
1306 max_backoff_ms: 1,
1307 backoff_multiplier: 2.0,
1308 jitter: false,
1309 };
1310 let err = engine
1311 .run_llm_turn_with_retry(
1312 &SessionId::new(1),
1313 &[],
1314 &[],
1315 None,
1316 None,
1317 cfg,
1318 false,
1319 &tokio_util::sync::CancellationToken::new(),
1320 )
1321 .await
1322 .err()
1323 .expect("should be exhausted");
1324 assert!(err.to_string().contains("transient"));
1325 }
1326
1327 #[tokio::test]
1328 async fn chat_stream_cancelled_while_awaiting_response() {
1329 struct NeverResolves;
1333
1334 #[async_trait]
1335 impl LlmProvider for NeverResolves {
1336 async fn stream(&self, _request: ChatRequest) -> Result<ChatStream, LlmError> {
1337 std::future::pending().await
1338 }
1339
1340 async fn chat(
1341 &self,
1342 _request: ChatRequest,
1343 ) -> Result<llm_trait::ChatResponse, LlmError> {
1344 Err(LlmError::Llm("not implemented".into()))
1345 }
1346
1347 fn capabilities(&self) -> Capabilities {
1348 Capabilities::default()
1349 }
1350
1351 fn info(&self) -> ProviderInfo {
1352 ProviderInfo {
1353 name: "never-resolves".to_string(),
1354 model: "never-resolves".to_string(),
1355 version: None,
1356 }
1357 }
1358 }
1359
1360 let engine = LlmEngine::new(Arc::new(NeverResolves), EventBus::new(16));
1361 let token = tokio_util::sync::CancellationToken::new();
1362 let fut = engine.chat_stream(&[], &[], None, None, false, &token);
1363 tokio::pin!(fut);
1364 token.cancel();
1365 let err = tokio::time::timeout(std::time::Duration::from_secs(5), fut)
1366 .await
1367 .expect("chat_stream must resolve after cancel")
1368 .err()
1369 .expect("must be cancelled");
1370 assert!(err.is_cancelled(), "expected Cancelled, got: {err}");
1371 }
1372
1373 #[tokio::test]
1374 async fn process_stream_tool_call_missing_delta_continues() {
1375 let bus = EventBus::new(16);
1376 let engine = LlmEngine::new(Arc::new(StubProvider("x")), bus.clone());
1377 let chunks = vec![
1378 Ok(StreamChunk::ToolCall(
1379 serde_json::json!({ "no_delta": true }),
1380 )),
1381 Ok(StreamChunk::Stop {
1382 finish_reason: Some("stop".into()),
1383 }),
1384 ];
1385 let stream = Box::pin(futures_util::stream::iter(chunks));
1386 let mut rx = bus.subscribe();
1387 let cancel = tokio_util::sync::CancellationToken::new();
1388 let result = engine
1389 .process_stream(
1390 &SessionId::new(1),
1391 stream,
1392 tracing::Span::none(),
1393 &mut rx,
1394 std::sync::Arc::new(std::sync::Mutex::new(|_e| Ok(()))),
1395 &cancel,
1396 )
1397 .await
1398 .unwrap();
1399 assert!(result.is_tool_call);
1400 assert!(result.tool_calls.is_empty());
1401 }
1402
1403 #[tokio::test]
1404 async fn process_stream_tool_call_empty_id_and_name_ignored() {
1405 let bus = EventBus::new(16);
1406 let engine = LlmEngine::new(Arc::new(StubProvider("x")), bus.clone());
1407 let chunks = vec![Ok(StreamChunk::ToolCall(serde_json::json!({
1408 "delta": { "tool_calls": [
1409 { "index": 0, "id": "", "function": { "name": "", "arguments": "{}" } }
1410 ] }
1411 })))];
1412 let stream = Box::pin(futures_util::stream::iter(chunks));
1413 let mut rx = bus.subscribe();
1414 let cancel = tokio_util::sync::CancellationToken::new();
1415 let result = engine
1416 .process_stream(
1417 &SessionId::new(1),
1418 stream,
1419 tracing::Span::none(),
1420 &mut rx,
1421 std::sync::Arc::new(std::sync::Mutex::new(|_e| Ok(()))),
1422 &cancel,
1423 )
1424 .await
1425 .unwrap();
1426 assert_eq!(result.tool_calls.len(), 0);
1433 }
1434
1435 #[tokio::test]
1436 async fn process_stream_stop_none_finish_reason_ignored() {
1437 let bus = EventBus::new(16);
1438 let engine = LlmEngine::new(Arc::new(StubProvider("x")), bus.clone());
1439 let chunks = vec![
1440 Ok(StreamChunk::Stop {
1441 finish_reason: Some("length".into()),
1442 }),
1443 Ok(StreamChunk::Stop {
1444 finish_reason: None,
1445 }),
1446 ];
1447 let stream = Box::pin(futures_util::stream::iter(chunks));
1448 let mut rx = bus.subscribe();
1449 let cancel = tokio_util::sync::CancellationToken::new();
1450 let result = engine
1451 .process_stream(
1452 &SessionId::new(1),
1453 stream,
1454 tracing::Span::none(),
1455 &mut rx,
1456 std::sync::Arc::new(std::sync::Mutex::new(|_e| Ok(()))),
1457 &cancel,
1458 )
1459 .await
1460 .unwrap();
1461 assert_eq!(result.finish_reason.as_deref(), Some("length"));
1462 }
1463
1464 #[test]
1465 fn emit_text_delta_emits_event() {
1466 let bus = EventBus::new(16);
1467 let engine = LlmEngine::new(Arc::new(StubProvider("x")), bus.clone());
1468 let mut rx = bus.subscribe();
1469 engine.emit_text_delta(&SessionId::new(1), "hello".into());
1470 let ev = rx.try_recv().expect("event should be emitted");
1471 assert!(matches!(ev, RuntimeEvent::TextDelta { text, .. } if text == "hello"));
1472 }
1473
1474 fn one_picture() -> llm_trait::ImageAttachment {
1475 llm_trait::ImageAttachment::Base64 {
1476 data: "aGVsbG8=".to_string(),
1477 media_type: Some("image/png".to_string()),
1478 detail: None,
1479 }
1480 }
1481
1482 #[test]
1483 fn only_the_newest_pictures_reach_the_wire() {
1484 let mut messages = vec![
1485 ChatMessage::user("look at the board"),
1486 ChatMessage::tool_with_images("t1", "shot 1", vec![one_picture()]),
1487 ChatMessage::tool_with_images("t2", "shot 2", vec![one_picture()]),
1488 ChatMessage::tool_with_images("t3", "shot 3", vec![one_picture()]),
1489 ];
1490 bound_wire_images(&mut messages);
1491
1492 let ChatMessage::Tool {
1493 images: oldest,
1494 content: oldest_text,
1495 ..
1496 } = &messages[1]
1497 else {
1498 panic!("expected a tool result");
1499 };
1500 assert!(oldest.is_empty(), "the oldest picture is off the wire");
1501 assert!(
1502 oldest_text.contains("not attached to this request"),
1503 "the omission is spoken, never silent: {oldest_text}"
1504 );
1505 assert!(
1506 oldest_text.starts_with("shot 1"),
1507 "the text face survives intact: {oldest_text}"
1508 );
1509 for i in [2, 3] {
1510 let ChatMessage::Tool { images, .. } = &messages[i] else {
1511 panic!("expected a tool result");
1512 };
1513 assert_eq!(images.len(), 1, "the newest two keep their pictures");
1514 }
1515 }
1516
1517 #[test]
1518 fn a_word_only_history_is_untouched() {
1519 let mut messages = vec![
1520 ChatMessage::user("hi"),
1521 ChatMessage::tool("t1", "done"),
1522 ChatMessage::assistant("ok"),
1523 ];
1524 let before = format!("{messages:?}");
1525 bound_wire_images(&mut messages);
1526 assert_eq!(format!("{messages:?}"), before);
1527 }
1528
1529 #[test]
1530 fn a_picture_batch_keeps_all_or_none() {
1531 let mut messages = vec![
1532 ChatMessage::tool_with_images("t1", "older", vec![one_picture()]),
1533 ChatMessage::tool_with_images(
1534 "t2",
1535 "a fresh batch of three",
1536 vec![one_picture(), one_picture(), one_picture()],
1537 ),
1538 ];
1539 bound_wire_images(&mut messages);
1540
1541 let ChatMessage::Tool {
1542 images, content, ..
1543 } = &messages[1]
1544 else {
1545 panic!("expected a tool result");
1546 };
1547 assert!(
1548 images.is_empty(),
1549 "three pictures do not fit a budget of two"
1550 );
1551 assert!(
1552 content.contains("3 image(s)"),
1553 "the count is named: {content}"
1554 );
1555 let ChatMessage::Tool { images, .. } = &messages[0] else {
1556 panic!("expected a tool result");
1557 };
1558 assert!(
1559 images.is_empty(),
1560 "once the newest does not fit, older pictures never jump the queue"
1561 );
1562 }
1563
1564 #[test]
1565 fn the_request_leaves_the_throat_already_bounded() {
1566 let messages = vec![
1567 ChatMessage::tool_with_images("t1", "shot 1", vec![one_picture()]),
1568 ChatMessage::tool_with_images("t2", "shot 2", vec![one_picture()]),
1569 ChatMessage::tool_with_images("t3", "shot 3", vec![one_picture()]),
1570 ];
1571 let request = build_chat_request(&messages, &[], None, None, false, None);
1572 assert_eq!(
1573 request.messages.len(),
1574 messages.len(),
1575 "nothing is discarded, only trimmed"
1576 );
1577 let carried: usize = request
1578 .messages
1579 .iter()
1580 .map(|m| match m {
1581 ChatMessage::Tool { images, .. } | ChatMessage::User { images, .. } => images.len(),
1582 _ => 0,
1583 })
1584 .sum();
1585 assert_eq!(carried, MAX_WIRE_IMAGES, "the throat applies the bound");
1586 }
1587}