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