Skip to main content

agent_base/engine/runtime/
llm_engine.rs

1use std::pin::Pin;
2use std::sync::atomic::{AtomicUsize, Ordering as AtomicOrdering};
3use std::sync::{Arc, RwLock};
4use std::time::Duration;
5
6use futures_core::Stream;
7use futures_util::StreamExt;
8use serde_json::Value;
9use tracing::Span;
10
11use crate::engine::runtime::event_bus::EventBus;
12use crate::llm::{ReasoningConfig, StreamChunk, UsageInfo};
13use crate::types::{AgentResult, ChatMessage, RuntimeEvent, SessionId};
14
15/// Bound on the wait for the LLM to *start* responding (time to response
16/// headers). Generous enough for slow providers cold-starting a long prompt
17/// (typical TTFT is well under 10 s), tight enough to surface a dead
18/// network within a minute instead of hanging forever.
19const TTFB_TIMEOUT: Duration = Duration::from_secs(60);
20
21/// Build a `ChatRequest` from individual parameters.
22///
23/// Every picture is shrunk to the wire size and judged by
24/// [`crate::image_ops::apply_image_budget`] on the way out: over either
25/// budget line the WHOLE request is refused with a size inventory — the one
26/// place a picture may leave the wire, and never silently. The pass runs on
27/// this wire copy only; the session's history keeps the originals (each turn
28/// re-shrinks its own copy).
29fn build_chat_request(
30    messages: &[ChatMessage],
31    tool_definitions: &[Value],
32    reasoning: Option<&ReasoningConfig>,
33    response_format: Option<&crate::types::ResponseFormat>,
34    thinking_disabled: bool,
35    model_override: Option<&str>,
36    supports_vision: bool,
37) -> AgentResult<llm_trait::ChatRequest> {
38    let mut messages = messages.to_vec();
39    if !supports_vision {
40        withhold_images_for_text_only(&mut messages);
41    }
42    crate::image_ops::apply_image_budget(&mut messages)
43        .map_err(|e| crate::types::AgentError::llm(e.to_string()))?;
44    let mut request = llm_trait::ChatRequest::new(messages);
45    if !tool_definitions.is_empty() {
46        request = request.with_tools(tool_definitions.to_vec());
47    }
48    // Only include reasoning if not disabled
49    // This is a workaround for LLM providers that ignore budget_tokens limit
50    if let Some(r) = reasoning {
51        if !thinking_disabled {
52            request = request.with_reasoning(r.clone());
53        } else {
54            tracing::info!(
55                "thinking disabled for rest of run due to too many reasoning-only responses"
56            );
57        }
58    }
59    request.response_format = response_format.cloned();
60
61    // A conversation appends: it never rewrites its own prefix. Say so, so a
62    // provider that caches prefixes can stop re-billing the settled part of
63    // the prompt at the input rate. Marking through the newest message is the
64    // standard shape — the breakpoint trails the conversation and each call
65    // pays only for what is new. Providers without caching ignore the claim.
66    let cache_through = request.messages.len().saturating_sub(1);
67    request = request.with_cache_through(cache_through);
68
69    // Tool-call batching is a permission, and the engine can honour it: the
70    // orchestrator already runs an approved batch concurrently. Claiming it
71    // costs nothing when the model emits one call per turn, and the alternative
72    // is a provider default we did not choose. It is not a promise the model
73    // will batch — phimint session 20261115_2fbff82e issued 1.41 calls per turn
74    // with nothing forbidding it.
75    //
76    // Note what this cannot do: on an Anthropic-shaped request there is nowhere
77    // to put the claim, because that protocol has no such field and the model
78    // batches on its own. This is the OpenAI-side lever only — see
79    // `notes/tool-face-design.md` §2.4 for the probe that established that.
80    request = request.with_parallel_tool_calls(true);
81
82    // Apply model override if specified
83    if let Some(model) = model_override {
84        request = request.with_model(model);
85    }
86
87    Ok(request)
88}
89
90/// Modality normalization: a text-only model gets words about the picture,
91/// never the picture. The pass runs on this wire copy only — the session's
92/// history keeps the originals (a later vision model sees them for free),
93/// the same contract [`crate::image_ops::apply_image_budget`] documents.
94/// Never silent: the residue says a picture existed and how to recover it.
95fn withhold_images_for_text_only(messages: &mut [ChatMessage]) {
96    for msg in messages.iter_mut() {
97        let (content, images) = match msg {
98            ChatMessage::User {
99                content, images, ..
100            }
101            | ChatMessage::Tool {
102                content, images, ..
103            } => (content, images),
104            _ => continue,
105        };
106        if images.is_empty() {
107            continue;
108        }
109        let count = images.len();
110        images.clear();
111        content.push_str(&format!(
112            "\n[image omitted: this model cannot see images — {count} picture(s) withheld; \
113             switch to a vision model with /model and ask again]"
114        ));
115    }
116}
117
118/// Convert a `ChatStream` (new) to the old stream type consumed by `process_stream`.
119fn chat_stream_to_old(
120    chat_stream: llm_trait::ChatStream,
121) -> Pin<Box<dyn Stream<Item = AgentResult<StreamChunk>> + Send>> {
122    let inner = chat_stream.into_inner();
123    Box::pin(inner.map(|item| item.map_err(Into::into)))
124}
125
126/// Run-liveness accounting for [`LlmEngine::begin_run`]: counts one run
127/// against the engine and lands staged provider swaps when the last run
128/// ends. Held for the duration of one `run` / `run_turn`.
129pub(crate) struct RunGuard<'a> {
130    engine: &'a LlmEngine,
131}
132
133impl Drop for RunGuard<'_> {
134    fn drop(&mut self) {
135        self.engine.active_runs.fetch_sub(1, AtomicOrdering::AcqRel);
136        self.engine.flush_pending_if_idle();
137    }
138}
139
140/// A live view of the engine's provider slot ([`LlmEngine::provider_handle`]).
141///
142/// Resolves the current provider at USE time, so a holder survives
143/// [`LlmEngine::set_provider`] / [`LlmEngine::set_provider_when_idle`] swaps
144/// (a `/model` switch). A provider cloned out of the engine at build time is
145/// a boot-time snapshot: the guard's completion judge kept judging on the old
146/// model after a swap and treated that model's own identity as the session's
147/// ground truth (session 20261107_27dc727a).
148#[derive(Clone)]
149pub struct ProviderHandle(Arc<RwLock<Arc<dyn llm_trait::LlmProvider>>>);
150
151impl ProviderHandle {
152    /// A standalone handle over `initial` — for holders that get their handle
153    /// directly instead of from an engine (and for tests).
154    pub fn new(initial: Arc<dyn llm_trait::LlmProvider>) -> Self {
155        Self(Arc::new(RwLock::new(initial)))
156    }
157
158    /// The provider currently in the slot.
159    pub fn current(&self) -> Arc<dyn llm_trait::LlmProvider> {
160        self.0.read().unwrap().clone()
161    }
162}
163
164pub struct LlmEngine {
165    provider: Arc<RwLock<Arc<dyn llm_trait::LlmProvider>>>,
166    event_bus: EventBus,
167    /// Optional model override for all requests.
168    ///
169    /// When set, this overrides the model in ChatRequest.
170    /// Used by sub-agents to specify their model tier (e.g., "lite").
171    model_override: RwLock<Option<String>>,
172    /// Runs currently executing against this engine (see [`RunGuard`]).
173    active_runs: AtomicUsize,
174    /// A staged provider swap waiting for the engine to go idle
175    /// ([`Self::set_provider_when_idle`]).
176    pending_provider: RwLock<Option<Arc<dyn llm_trait::LlmProvider>>>,
177}
178
179impl LlmEngine {
180    pub(crate) fn new(provider: Arc<dyn llm_trait::LlmProvider>, event_bus: EventBus) -> Self {
181        Self {
182            provider: Arc::new(RwLock::new(provider)),
183            event_bus,
184            model_override: RwLock::new(None),
185            active_runs: AtomicUsize::new(0),
186            pending_provider: RwLock::new(None),
187        }
188    }
189
190    /// Get a clone of the current LLM provider.
191    pub fn get_provider(&self) -> Arc<dyn llm_trait::LlmProvider> {
192        self.provider.read().unwrap().clone()
193    }
194
195    /// A handle that always resolves to this engine's CURRENT provider —
196    /// hand it to long-lived holders (e.g. the react-loop guard) instead of a
197    /// provider clone so model swaps reach them too. See [`ProviderHandle`].
198    pub fn provider_handle(&self) -> ProviderHandle {
199        ProviderHandle(Arc::clone(&self.provider))
200    }
201
202    /// Replace the LLM provider at runtime (e.g., model switch).
203    ///
204    /// Immediate: the swap lands even while a run is streaming. Callers that
205    /// must not split one conversation across two models use
206    /// [`Self::set_provider_when_idle`] instead. Every [`ProviderHandle`]
207    /// handed out by [`Self::provider_handle`] follows the swap.
208    pub fn set_provider(&self, provider: Arc<dyn llm_trait::LlmProvider>) {
209        *self.provider.write().unwrap() = provider;
210    }
211
212    /// Stage a provider swap for the end of the run executing now.
213    ///
214    /// Hot-swapping mid-run would split one conversation across two models —
215    /// the tool-continuation steps would run on the new provider with the old
216    /// provider's history and identity. So the swap lands when the last active
217    /// run ends; when the engine is already idle it lands at once. Returns
218    /// `true` when the swap was deferred, `false` when it landed immediately.
219    /// A second staged swap replaces the first (the last pick wins).
220    pub fn set_provider_when_idle(&self, provider: Arc<dyn llm_trait::LlmProvider>) -> bool {
221        *self.pending_provider.write().unwrap() = Some(provider);
222        self.flush_pending_if_idle();
223        self.pending_provider.read().unwrap().is_some()
224    }
225
226    /// Whether a run is executing against this engine right now.
227    pub fn has_active_run(&self) -> bool {
228        self.active_runs.load(AtomicOrdering::Acquire) > 0
229    }
230
231    /// Count one run against the engine. The returned guard decrements on
232    /// drop and lands any staged swap once the count reaches zero.
233    pub(crate) fn begin_run(&self) -> RunGuard<'_> {
234        self.active_runs.fetch_add(1, AtomicOrdering::AcqRel);
235        RunGuard { engine: self }
236    }
237
238    /// Land the staged swap if no run is in flight. Called at every point
239    /// that can change the answer (a stage, a run's end) so no interleaving
240    /// of the two can strand a staged swap.
241    fn flush_pending_if_idle(&self) {
242        if self.has_active_run() {
243            return;
244        }
245        if let Some(provider) = self.pending_provider.write().unwrap().take() {
246            self.set_provider(provider);
247        }
248    }
249
250    /// Get the model override, if set.
251    pub fn get_model_override(&self) -> Option<String> {
252        self.model_override.read().unwrap().clone()
253    }
254
255    /// Set a model override for all requests.
256    ///
257    /// This is used by sub-agents to specify their model tier (e.g., "lite").
258    /// The override is applied to all ChatRequests before sending to the provider.
259    pub fn set_model_override(&self, model: Option<String>) {
260        *self.model_override.write().unwrap() = model;
261    }
262
263    /// Replace the LLM client at runtime (e.g., model switch).
264    ///
265    /// Accepts an `Arc<dyn llm_trait::LlmProvider>`.
266    pub fn set_client(&self, client: Arc<dyn llm_trait::LlmProvider>) {
267        self.set_provider(client);
268    }
269
270    /// Await the provider's `stream()` with cancellation + TTFB timeout.
271    ///
272    /// reqwest's connect_timeout covers only TCP connect and read_timeout
273    /// only response-body reads — the wait for response headers is covered
274    /// by neither, so a silently dropped network hangs the await forever
275    /// (session 20260910_e528c7a3: 1.5 h silent hang, TUI unresponsive to
276    /// Ctrl+C for the same reason). Both gaps are closed here: the cancel
277    /// token aborts the in-flight request, and the TTFB timeout turns a
278    /// stalled connection into a regular error that the caller's retry
279    /// logic can handle.
280    async fn stream_cancellable(
281        &self,
282        cancel_token: &tokio_util::sync::CancellationToken,
283        request: llm_trait::ChatRequest,
284    ) -> AgentResult<Pin<Box<dyn Stream<Item = AgentResult<StreamChunk>> + Send>>> {
285        // Bind the provider handle outside the select!: select! drops
286        // temporaries at the end of the statement, which would free the
287        // Arc clone mid-await.
288        let provider = self.get_provider();
289        tokio::select! {
290            _ = cancel_token.cancelled() => {
291                tracing::info!("LLM request cancelled while awaiting response");
292                Err(crate::types::AgentError::Cancelled)
293            }
294            result = tokio::time::timeout(TTFB_TIMEOUT, provider.stream(request)) => {
295                match result {
296                    Ok(inner) => inner.map(chat_stream_to_old).map_err(Into::into),
297                    Err(_) => {
298                        tracing::error!(
299                            timeout_secs = TTFB_TIMEOUT.as_secs(),
300                            "LLM request timed out waiting for response (network stalled?)"
301                        );
302                        Err(crate::types::AgentError::Llm(format!(
303                            "no response within {}s (network stalled or provider unreachable)",
304                            TTFB_TIMEOUT.as_secs()
305                        )))
306                    }
307                }
308            }
309        }
310    }
311
312    pub async fn chat_stream(
313        &self,
314        messages: &[ChatMessage],
315        tool_definitions: &[Value],
316        reasoning: Option<&ReasoningConfig>,
317        response_format: Option<&crate::types::ResponseFormat>,
318        thinking_disabled: bool,
319        cancel_token: &tokio_util::sync::CancellationToken,
320    ) -> AgentResult<Pin<Box<dyn Stream<Item = AgentResult<StreamChunk>> + Send>>> {
321        tracing::info!(
322            msg_count = messages.len(),
323            tool_count = tool_definitions.len(),
324            thinking_disabled,
325            "LLM chat_stream: sending request to API"
326        );
327        let model_override = self.get_model_override();
328        let request = build_chat_request(
329            messages,
330            tool_definitions,
331            reasoning,
332            response_format,
333            thinking_disabled,
334            model_override.as_deref(),
335            self.get_provider().capabilities().supports_vision,
336        )?;
337        let result = self.stream_cancellable(cancel_token, request).await;
338        match &result {
339            Ok(_) => tracing::info!("LLM chat_stream: API response received"),
340            Err(e) => tracing::error!(error = %e, "LLM chat_stream: API request failed"),
341        }
342        result
343    }
344
345    #[allow(clippy::too_many_arguments)]
346    pub async fn run_llm_turn_with_retry(
347        &self,
348        session_id: &SessionId,
349        messages: &[ChatMessage],
350        tool_definitions: &[Value],
351        reasoning: Option<&ReasoningConfig>,
352        response_format: Option<&crate::types::ResponseFormat>,
353        retry: crate::types::RetryConfig,
354        thinking_disabled: bool,
355        cancel_token: &tokio_util::sync::CancellationToken,
356    ) -> AgentResult<Pin<Box<dyn Stream<Item = AgentResult<StreamChunk>> + Send>>> {
357        let model_override = self.get_model_override();
358        let request = build_chat_request(
359            messages,
360            tool_definitions,
361            reasoning,
362            response_format,
363            thinking_disabled,
364            model_override.as_deref(),
365            self.get_provider().capabilities().supports_vision,
366        )?;
367        let mut attempt = 1;
368        let mut delay_ms = retry.initial_backoff_ms;
369        loop {
370            match self.stream_cancellable(cancel_token, request.clone()).await {
371                Ok(chat_stream) => return Ok(chat_stream),
372                Err(e) => {
373                    let agent_err: crate::types::AgentError = e;
374                    // Cancellation is a user decision, not a transient
375                    // failure — never retry past it.
376                    if agent_err.is_cancelled() {
377                        return Err(agent_err);
378                    }
379                    if attempt > retry.max_retries {
380                        tracing::error!(session_id = session_id.id, attempts = attempt, error = %agent_err, "LLM stream retry exhausted");
381                        return Err(agent_err);
382                    }
383                    tracing::warn!(session_id = session_id.id, attempt, error = %agent_err, "LLM stream failed, retrying...");
384                    tokio::time::sleep(Duration::from_millis(delay_ms)).await;
385                    delay_ms = (delay_ms as f64 * retry.backoff_multiplier) as u64;
386                    if delay_ms > retry.max_backoff_ms {
387                        delay_ms = retry.max_backoff_ms;
388                    }
389                    attempt += 1;
390                }
391            }
392        }
393    }
394
395    pub(crate) async fn process_stream<F>(
396        &self,
397        session_id: &SessionId,
398        mut stream: Pin<Box<dyn Stream<Item = AgentResult<StreamChunk>> + Send>>,
399        span: Span,
400        event_rx: &mut tokio::sync::broadcast::Receiver<RuntimeEvent>,
401        on_event: Arc<std::sync::Mutex<F>>,
402        cancel_token: &tokio_util::sync::CancellationToken,
403    ) -> AgentResult<LlmTurnResult>
404    where
405        F: FnMut(RuntimeEvent) -> AgentResult<()> + Send,
406    {
407        let _enter = span.enter();
408        let start = std::time::Instant::now();
409        let mut first_token = true;
410        let mut aggregator = StreamAggregator::new();
411        tracing::info!(session_id = session_id.id, "LLM process_stream start");
412
413        // Sweep self-echo UserEvent copies (dual-written by ctx.emit() during
414        // middleware — compression Progress/Started/Completed) before the main
415        // loop starts: they were already rendered to on_event and must not
416        // double-render here. Run-local echoes are recognized by
417        // `is_self_echo_user_event`; bridged child events (agent_id: Some) are
418        // bus-only and get delivered like any other event.
419        loop {
420            match event_rx.try_recv() {
421                Ok(event) if crate::engine::runtime::is_self_echo_user_event(&event) => continue,
422                Ok(event) => {
423                    // Non-echo (e.g. Checkpoint) — push back by processing
424                    // and let the main loop handle the next ones normally.
425                    if let Ok(mut cb) = on_event.lock() {
426                        cb(event)?;
427                    }
428                    continue;
429                }
430                Err(tokio::sync::broadcast::error::TryRecvError::Lagged(_)) => continue,
431                Err(_) => break,
432            }
433        }
434
435        loop {
436            tokio::select! {
437                recv_result = event_rx.recv() => {
438                    match recv_result {
439                        Ok(event) => {
440                            // Same dual-write rule as the sweep above: a
441                            // run-local UserEvent copy that slipped in mid-stream
442                            // must not re-render; everything else flows.
443                            if crate::engine::runtime::is_self_echo_user_event(&event) {
444                                continue;
445                            }
446                            if let Ok(mut cb) = on_event.lock() {
447                                cb(event)?;
448                            }
449                        }
450                        Err(tokio::sync::broadcast::error::RecvError::Lagged(_)) => continue,
451                        Err(tokio::sync::broadcast::error::RecvError::Closed) => break,
452                    }
453                }
454                _ = cancel_token.cancelled() => {
455                    tracing::info!(session_id = session_id.id, "LLM stream cancelled");
456                    return Err(crate::types::AgentError::Cancelled);
457                }
458                maybe_chunk = stream.next() => {
459                    let Some(chunk) = maybe_chunk else {
460                        break;
461                    };
462
463                    match chunk {
464                        Ok(StreamChunk::Text(text)) => {
465                            if first_token {
466                                let ttft = start.elapsed();
467                                aggregator.ttft_ms = ttft.as_millis() as u64;
468                                tracing::info!(session_id = session_id.id, ?ttft, "LLM first token received");
469                                first_token = false;
470                            }
471                            // Emit unconditionally: some providers interleave
472                            // text between/after tool_call chunks. Suppressing
473                            // on is_tool_call hides real content from the user
474                            // while aggregator.full_text still feeds the model
475                            // context — user sees ≠ model sees.
476                            if !text.is_empty() {
477                                self.event_bus.emit(RuntimeEvent::TextDelta {
478                                    session_id: session_id.clone(),
479                                    text: text.clone(),
480                                    agent_id: None,
481                                    trace_id: None,
482                                });
483                            }
484                            aggregator.full_text.push_str(&text);
485                        }
486                        Ok(StreamChunk::Thought(text)) => {
487                            tracing::debug!(session_id = session_id.id, len = text.len(), "llm thought chunk");
488                            aggregator.reasoning_text.push_str(&text);
489                            // Same as TextDelta: never suppress on is_tool_call —
490                            // thought chunks after tool_call chunks are real.
491                            if !text.is_empty() {
492                                self.event_bus.emit(RuntimeEvent::ThoughtDelta {
493                                    session_id: session_id.clone(),
494                                    text,
495                                    agent_id: None,
496                                    trace_id: None,
497                                });
498                            }
499                        }
500                        Ok(StreamChunk::ToolCall(choice)) => {
501                            if !aggregator.is_tool_call {
502                                tracing::info!(session_id = session_id.id, "LLM stream: first tool_call chunk received");
503                            }
504                            aggregator.is_tool_call = true;
505                            let Some(tool_calls) = choice
506                                .get("delta")
507                                .and_then(|d| d.get("tool_calls"))
508                                .and_then(Value::as_array)
509                            else {
510                                tracing::debug!("tool_calls missing or not an array in LLM response");
511                                continue;
512                            };
513
514                            for tool_call in tool_calls {
515                                let idx = tool_call
516                                    .get("index")
517                                    .and_then(Value::as_u64)
518                                    .unwrap_or(0) as usize;
519                                // Liveness for the drafting window: tool-call
520                                // args stream in as fragments and nothing else
521                                // is observable until the whole turn's stream
522                                // is drained — multi-KB calls (a spawn_agent
523                                // task brief) leave every consumer blind for
524                                // tens of seconds. Emit a coarse draft on each
525                                // slot's first fragment, on function-name
526                                // arrival, and on every 512-char args bucket —
527                                // never the text itself, and never per
528                                // fragment (the bus is a bounded broadcast).
529                                const DRAFT_ARGS_BUCKET: usize = 512;
530                                let fresh_slot = !aggregator.partials.contains_key(&idx);
531                                let before_args_len =
532                                    aggregator.partials.get(&idx).map(|e| e.2.len()).unwrap_or(0);
533                                let entry = aggregator.partials.entry(idx).or_insert_with(|| (String::new(), String::new(), String::new()));
534                                let mut named_now = false;
535                                if let Some(id) = tool_call.get("id").and_then(Value::as_str)
536                                    && !id.is_empty() {
537                                        entry.0 = id.to_string();
538                                    }
539                                if let Some(func) = tool_call.get("function") {
540                                    if let Some(name) = func.get("name").and_then(Value::as_str)
541                                        && !name.is_empty() {
542                                            named_now = entry.1.is_empty();
543                                            entry.1 = name.to_string();
544                                        }
545                                    if let Some(args) = func.get("arguments").and_then(Value::as_str) {
546                                        entry.2.push_str(args);
547                                    }
548                                }
549                                let args_len = entry.2.len();
550                                let grew_bucket =
551                                    args_len / DRAFT_ARGS_BUCKET > before_args_len / DRAFT_ARGS_BUCKET;
552                                if fresh_slot || named_now || grew_bucket {
553                                    self.event_bus.emit(RuntimeEvent::ActionDraft {
554                                        session_id: session_id.clone(),
555                                        index: idx,
556                                        name: entry.1.clone(),
557                                        args_len,
558                                        count: aggregator.partials.len(),
559                                        agent_id: None,
560                                        trace_id: None,
561                                    });
562                                }
563                            }
564                        }
565                        Ok(StreamChunk::Usage(usage)) => {
566                            // Usage arrives as partial events on some
567                            // protocols (Anthropic splits prompt/output
568                            // across message_start / message_delta), so fold
569                            // field-by-field instead of replacing the whole
570                            // struct — the same overwrite hazard already
571                            // handled for finish_reason below.
572                            tracing::debug!(
573                                session_id = session_id.id,
574                                input = ?usage.prompt_tokens,
575                                output = ?usage.completion_tokens,
576                                reasoning = ?usage.reasoning_tokens,
577                                "LLM usage chunk received"
578                            );
579                            match &mut aggregator.usage {
580                                Some(existing) => existing.merge(&usage),
581                                None => aggregator.usage = Some(usage),
582                            }
583                        }
584                        Ok(StreamChunk::Stop { finish_reason }) => {
585                            // Only capture the first non-None finish_reason.
586                            // OpenAI emits [DONE] after the final chunk, which
587                            // would overwrite a "length" finish_reason with None,
588                            // silently disabling the truncation guard.
589                            if finish_reason.is_some() {
590                                aggregator.finish_reason = finish_reason;
591                            }
592                        }
593                        Err(e) => {
594                            tracing::error!(session_id = session_id.id, error = %e, "LLM stream error");
595                            return Err(e);
596                        }
597                        Ok(StreamChunk::ThinkingSignature(sig)) => {
598                            aggregator.thinking_signature = Some(sig);
599                        }
600                        Ok(StreamChunk::Error(e)) => {
601                            tracing::error!(session_id = session_id.id, error = %e, "LLM stream protocol error");
602                            return Err(crate::types::AgentError::Llm(e));
603                        }
604                    }
605
606                    {
607                        let mut cb = on_event.lock().unwrap();
608                        EventBus::drain_async_events(event_rx, &mut *cb)?;
609                    }
610                }
611            }
612        }
613
614        let total_elapsed = start.elapsed();
615        let _ttft_ms = aggregator.ttft_ms;
616
617        // Reasoning is a separate channel from the final answer. We NEVER promote
618        // reasoning_content into `content`: some models (e.g. qwen3.7-max) answer
619        // entirely in the reasoning channel, but papering over that masks a stuck
620        // agent as a completed run. Instead we classify and let the react loop route
621        // it — `reasoning_only` (reasoning but no text and no tool call) is always a
622        // degenerate state the loop nudges and eventually fails, never a fake answer.
623        let full_text = aggregator.full_text;
624        let reasoning_len = aggregator.reasoning_text.len();
625        let reasoning_only = full_text.is_empty() && reasoning_len > 0 && !aggregator.is_tool_call;
626        if reasoning_only {
627            tracing::warn!(
628                session_id = session_id.id,
629                reasoning_len,
630                "content empty but reasoning_content present — model produced reasoning only; \
631                 not promoting it to the answer, the react loop will nudge/fail"
632            );
633        }
634
635        tracing::info!(
636            session_id = session_id.id,
637            text_len = full_text.len(),
638            reasoning_len,
639            tool_calls = aggregator.partials.len(),
640            elapsed_ms = total_elapsed.as_millis(),
641            "LLM stream done"
642        );
643
644        // Integrity facts (shape-based): orphan args bytes on name-less
645        // buckets (misplaced tail) and named calls whose args are non-empty
646        // but unparseable (wire truncation). Computed over ALL buckets —
647        // the filter below drops orphans from tool_calls but the evidence
648        // must survive into the record.
649        let mut integrity = StreamIntegrity::default();
650        for (_id, name, args) in aggregator.partials.values() {
651            if name.is_empty() {
652                integrity.orphan_args_bytes += args.len();
653            } else if !args.is_empty() && serde_json::from_str::<Value>(args).is_err() {
654                integrity.invalid_args += 1;
655            }
656        }
657
658        let tool_calls = aggregator
659            .partials
660            .into_iter()
661            // Drop phantom buckets: a fragment that carried an index but never
662            // a function name is not a real tool call. Some OpenAI-compatible
663            // providers (e.g. mimo) emit an empty `{index, name:""}` fragment;
664            // kept, it lands in assistant history as a name-less tool_call and
665            // the NEXT request is rejected with HTTP 400 "missing a function
666            // name". The stream is fully drained here, so an empty name means
667            // no name ever arrived — this is permanent, not a late fragment.
668            .filter(|(_idx, (_id, name, _args))| !name.is_empty())
669            .map(|(idx, (id, name, args))| {
670                let mut tc = serde_json::Map::new();
671                tc.insert("index".to_string(), idx.into());
672                tc.insert("id".to_string(), id.into());
673                tc.insert("type".to_string(), "function".into());
674                let mut func = serde_json::Map::new();
675                func.insert("name".to_string(), name.into());
676                func.insert("arguments".to_string(), args.into());
677                tc.insert("function".to_string(), func.into());
678                serde_json::Value::Object(tc)
679            })
680            .collect::<Vec<_>>();
681
682        Ok(LlmTurnResult {
683            full_text,
684            reasoning_text: aggregator.reasoning_text,
685            is_tool_call: aggregator.is_tool_call,
686            tool_calls,
687            integrity,
688            usage: aggregator.usage,
689            finish_reason: aggregator.finish_reason,
690            ttft_ms: aggregator.ttft_ms,
691            llm_duration_ms: total_elapsed.as_millis() as u64,
692            reasoning_only,
693            thinking_signature: aggregator.thinking_signature,
694        })
695    }
696
697    pub fn emit_text_delta(&self, session_id: &SessionId, text: String) {
698        self.event_bus.emit(RuntimeEvent::TextDelta {
699            session_id: session_id.clone(),
700            text,
701            agent_id: None,
702            trace_id: None,
703        });
704    }
705}
706
707/// Structural integrity facts about one assembled tool-call batch —
708/// shared vocabulary with the guard seam (single source of truth:
709/// `agent_types::StreamIntegrity`).
710pub use agent_types::StreamIntegrity;
711
712pub struct LlmTurnResult {
713    pub full_text: String,
714    /// Reasoning/thinking content accumulated from Thought stream chunks.
715    /// Populated when the model uses thinking mode (e.g. qwen3.7-max).
716    pub reasoning_text: String,
717    pub is_tool_call: bool,
718    pub tool_calls: Vec<Value>,
719    /// Structural facts about the assembled tool calls (wire-corruption
720    /// detection). Computed from shape only — provider stop reasons are
721    /// never trusted (they lie; see notes/spawn-agent-truncation-analysis.md).
722    pub integrity: StreamIntegrity,
723    pub usage: Option<UsageInfo>,
724    /// Provider stop reason (e.g. "stop", "length", "tool_calls", "end_turn").
725    /// `"length"` means the response hit the token limit — tool call arguments may be truncated.
726    pub finish_reason: Option<String>,
727    /// Time to first token in milliseconds (user-perceived latency).
728    pub ttft_ms: u64,
729    /// LLM stream duration in milliseconds (from stream start to end).
730    pub llm_duration_ms: u64,
731    /// True when the model emitted reasoning_content but no `content` and no tool
732    /// call. This is always a degenerate state (the model "thought" but neither
733    /// committed to a tool call nor produced an answer); the react loop nudges and
734    /// eventually fails rather than promoting the reasoning into `full_text`.
735    pub reasoning_only: bool,
736    /// Thinking signature from the provider (e.g. Anthropic extended thinking).
737    #[allow(dead_code)]
738    pub thinking_signature: Option<String>,
739}
740
741struct StreamAggregator {
742    pub full_text: String,
743    /// Accumulated reasoning/thinking content (from StreamChunk::Thought).
744    /// Kept separate from `full_text`; never promoted into the final answer.
745    pub reasoning_text: String,
746    pub is_tool_call: bool,
747    pub partials: std::collections::HashMap<usize, (String, String, String)>,
748    pub usage: Option<UsageInfo>,
749    /// Provider stop reason captured from StreamChunk::Stop.
750    pub finish_reason: Option<String>,
751    /// Time to first token in milliseconds.
752    pub ttft_ms: u64,
753    /// Thinking signature from StreamChunk::ThinkingSignature.
754    pub thinking_signature: Option<String>,
755}
756
757impl StreamAggregator {
758    fn new() -> Self {
759        Self {
760            full_text: String::new(),
761            reasoning_text: String::new(),
762            is_tool_call: false,
763            partials: std::collections::HashMap::new(),
764            usage: None,
765            finish_reason: None,
766            ttft_ms: 0,
767            thinking_signature: None,
768        }
769    }
770}
771
772#[cfg(test)]
773mod image_tests;
774#[cfg(test)]
775mod tests;