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