agent-base 0.4.0

A lightweight Agent Runtime Kernel for building AI agents in Rust
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
use std::sync::{Arc, Mutex};

use tokio::sync::broadcast;

use crate::engine::runtime::llm_engine::LlmTurnResult;
use crate::engine::runtime::plan_runner::RuntimeCore;
use crate::types::{
    AgentResult, FinishReason, MessageRole, RunOutcome, RuntimeEvent, SessionId,
};

use super::turn_loop::TurnFlow;
use super::turn_end::TurnEndCtx;
use super::turn_guard::{TurnCtx, TurnMetrics};
use super::turn_loop::PostLlmMwResult;

impl RuntimeCore {
    // ── Dispatch ────────────────────────────────────────────────────────

    /// Dispatch one LLM turn result: push messages, run tool calls, fire the
    /// turn-end callback, and decide whether the loop continues or the turn ends.
    #[allow(clippy::too_many_arguments)]
    pub(super) async fn handle_llm_turn<F>(
        &self,
        session_id: &SessionId,
        user_input_owned: &str,
        tool_definitions: &[serde_json::Value],
        turn_count: u32,
        turn_start: std::time::Instant,
        model: &str,
        result: AgentResult<LlmTurnResult>,
        event_rx: &mut broadcast::Receiver<RuntimeEvent>,
        on_event: Arc<Mutex<F>>,
        all_user_inputs: &[String],
        max_turns: u32,
    ) -> AgentResult<TurnFlow>
    where
        F: FnMut(RuntimeEvent) -> AgentResult<()> + Send + 'static,
    {
        let LlmTurnResult {
            full_text,
            reasoning_text,
            is_tool_call,
            tool_calls,
            usage,
            finish_reason,
            ttft_ms,
            llm_duration_ms,
            reasoning_only,
            thinking_signature: _,
        } = match result {
            Ok(r) => r,
            Err(e) => return self.handle_llm_error(session_id, turn_count, turn_start, model, user_input_owned, e).await,
        };

        let finish_reason = FinishReason::from_raw(finish_reason.as_deref());
        tracing::info!(
            session_id = session_id.id,
            turn = turn_count,
            text_len = full_text.len(),
            is_tool_call = is_tool_call,
            tool_call_count = tool_calls.len(),
            "LLM turn result"
        );

        let text_len = full_text.len() as u64;
        let has_thinking = !reasoning_text.is_empty();
        let tool_calls_parsed: Vec<(String, String, String)> = tool_calls
            .iter()
            .map(|tc| {
                let id = tc.get("id").and_then(|v| v.as_str()).unwrap_or("").to_string();
                let name = tc.get("function").and_then(|f| f.get("name")).and_then(|n| n.as_str()).unwrap_or("").to_string();
                let args = tc.get("function").and_then(|f| f.get("arguments")).and_then(|a| a.as_str()).unwrap_or("").to_string();
                (id, name, args)
            })
            .collect();
        let available_tools: Vec<String> = tool_definitions
            .iter()
            .filter_map(|d| d.get("function")?.get("name")?.as_str().map(|s| s.to_string()))
            .collect();

        let turn_ctx = TurnCtx {
            session_id,
            turn_count,
            user_input: user_input_owned,
            finish_reason: &finish_reason.clone(),
            available_tools: &available_tools,
            turn_start,
            model,
            all_user_inputs,
            max_turns,
        };
        let metrics = TurnMetrics { ttft_ms, llm_duration_ms, usage: &usage, text_len, has_thinking };

        if reasoning_only {
            return self.handle_reasoning_only(&turn_ctx, &metrics).await;
        }

        self.handle_post_llm_result(
            &turn_ctx,
            &metrics,
            full_text,
            reasoning_text,
            is_tool_call,
            tool_calls_parsed,
            &available_tools,
            turn_count,
            finish_reason,
            event_rx,
            on_event,
        )
        .await
    }

    // ── Branch handlers ─────────────────────────────────────────────────

    /// Reasoning-only: the model emitted thinking content but no answer and no
    /// tool call. Nudge it to commit; fail after consecutive strikes.
    async fn handle_reasoning_only(
        &self,
        turn_ctx: &TurnCtx<'_>,
        metrics: &TurnMetrics<'_>,
    ) -> AgentResult<TurnFlow> {
        let strikes = self
            .with_session_mut(turn_ctx.session_id, |session| {
                session.run_state.record_reasoning_only()
            })
            .await?;
        let thinking_disabled = self
            .with_session_mut(turn_ctx.session_id, |session| {
                session.run_state.thinking_disabled_for_rest_of_run
            })
            .await?;
        tracing::warn!(
            session_id = turn_ctx.session_id.id,
            turn = turn_ctx.turn_count,
            strikes,
            thinking_disabled,
            "reasoning-only response with tools available — nudging the model to commit"
        );

        let guard_ctx = self
            .build_guard_ctx(turn_ctx, "", true, false, false, thinking_disabled)
            .await;
        let decision = self.guard.on_turn(&guard_ctx).await;
        self.execute_guard_decision(decision, turn_ctx, metrics).await
    }

    /// Normal LLM response: apply post-LLM middleware, push messages, then
    /// dispatch to the appropriate outcome branch.
    #[allow(clippy::too_many_arguments)]
    async fn handle_post_llm_result<F>(
        &self,
        turn_ctx: &TurnCtx<'_>,
        metrics: &TurnMetrics<'_>,
        full_text: String,
        reasoning_text: String,
        is_tool_call: bool,
        tool_calls_parsed: Vec<(String, String, String)>,
        available_tools: &[String],
        turn_count: u32,
        finish_reason: FinishReason,
        event_rx: &mut broadcast::Receiver<RuntimeEvent>,
        on_event: Arc<Mutex<F>>,
    ) -> AgentResult<TurnFlow>
    where
        F: FnMut(RuntimeEvent) -> AgentResult<()> + Send + 'static,
    {
        let result = self
            .apply_post_llm_mw(
                turn_ctx.session_id,
                full_text,
                is_tool_call,
                tool_calls_parsed,
                available_tools,
                turn_count,
                finish_reason.clone(),
            )
            .await?;

        // Push text-only assistant message (when there are NO tool calls).
        if !result.skip_push && !result.full_text.is_empty() && !result.is_tool_call {
            let reasoning = reasoning_text.clone();
            self.with_session_mut(turn_ctx.session_id, |session| {
                if !reasoning.is_empty() {
                    session.push_assistant_with_reasoning(&result.full_text, &reasoning);
                } else {
                    session.push_message(MessageRole::Assistant, &result.full_text);
                }
            })
            .await?;
        }

        if let Some(follow_up) = result.follow_up_message {
            self.with_session_mut(turn_ctx.session_id, |session| {
                session.push_message(MessageRole::User, &follow_up);
            })
            .await?;
            return Ok(TurnFlow::Continue);
        }

        if result.full_text.is_empty() && !result.is_tool_call {
            return self.handle_empty_response(turn_ctx, metrics).await;
        }

        if result.is_tool_call && !result.tool_calls.is_empty() {
            return self
                .handle_tool_call_branch(
                    turn_ctx,
                    metrics,
                    result,
                    reasoning_text,
                    event_rx,
                    on_event,
                )
                .await;
        }

        if result.is_tool_call && result.tool_calls.is_empty() {
            return self.handle_incomplete_tool_call(turn_ctx, metrics).await;
        }

        self.handle_finish_anomaly(turn_ctx, metrics, &finish_reason, &result.full_text).await
    }

    /// Empty response: no text, no reasoning, no tool call. Nudge the model;
    /// fail after consecutive strikes.
    async fn handle_empty_response(
        &self,
        turn_ctx: &TurnCtx<'_>,
        metrics: &TurnMetrics<'_>,
    ) -> AgentResult<TurnFlow> {
        let strikes = self
            .with_session_mut(turn_ctx.session_id, |session| {
                session.run_state.record_empty_response()
            })
            .await?;
        tracing::warn!(
            session_id = turn_ctx.session_id.id,
            turn = turn_ctx.turn_count,
            strikes,
            "empty LLM response (no text, no reasoning, no tool call)"
        );

        let guard_ctx = self
            .build_guard_ctx(turn_ctx, "", false, true, false, false)
            .await;
        let decision = self.guard.on_turn(&guard_ctx).await;
        self.execute_guard_decision(decision, turn_ctx, metrics).await
    }

    /// Tool call branch: notify guard, handle RestoreThinking, then execute.
    async fn handle_tool_call_branch<F>(
        &self,
        turn_ctx: &TurnCtx<'_>,
        metrics: &TurnMetrics<'_>,
        result: PostLlmMwResult,
        reasoning_text: String,
        event_rx: &mut broadcast::Receiver<RuntimeEvent>,
        on_event: Arc<Mutex<F>>,
    ) -> AgentResult<TurnFlow>
    where
        F: FnMut(RuntimeEvent) -> AgentResult<()> + Send + 'static,
    {
        // 1. Notify guard about tool call
        let thinking_disabled = self
            .session_manager
            .session_or_err(turn_ctx.session_id)
            .await
            .map(|s| s.run_state.thinking_disabled_for_rest_of_run)
            .unwrap_or(false);
        let guard_ctx = self
            .build_guard_ctx(turn_ctx, "", false, false, false, thinking_disabled)
            .await;
        let decision = self.guard.on_tool_call(&guard_ctx).await;

        // 2. Handle RestoreThinking (update RunState)
        if matches!(
            decision,
            crate::engine::react_loop_guard::GuardDecision::RestoreThinking
        ) {
            self.execute_guard_decision(decision, turn_ctx, metrics)
                .await?;
        }

        // 3. Execute tools regardless of guard decision
        self.run_tool_turn(
            turn_ctx.session_id,
            turn_ctx.user_input,
            turn_ctx.turn_count,
            turn_ctx.turn_start,
            turn_ctx.model,
            result.tool_calls,
            turn_ctx.finish_reason,
            reasoning_text,
            result.full_text,
            metrics,
            event_rx,
            on_event,
        )
        .await
    }

    /// Incomplete tool call: model signalled tool_use but no complete tool calls
    /// were parsed (stream cut off mid-delta, JSON incomplete, etc.).
    async fn handle_incomplete_tool_call(
        &self,
        turn_ctx: &TurnCtx<'_>,
        metrics: &TurnMetrics<'_>,
    ) -> AgentResult<TurnFlow> {
        let strikes = self
            .with_session_mut(turn_ctx.session_id, |session| {
                session.run_state.record_empty_response()
            })
            .await?;
        tracing::warn!(
            session_id = turn_ctx.session_id.id,
            turn = turn_ctx.turn_count,
            strikes,
            "model signalled tool call but no complete tool calls were parsed"
        );
        let guard_ctx = self
            .build_guard_ctx(turn_ctx, "", false, true, false, false)
            .await;
        let decision = self.guard.on_turn(&guard_ctx).await;
        self.execute_guard_decision(decision, turn_ctx, metrics).await
    }

    /// Finish-reason anomaly: tool_use with no parsed tool calls, or truncated.
    async fn handle_finish_anomaly(
        &self,
        turn_ctx: &TurnCtx<'_>,
        metrics: &TurnMetrics<'_>,
        finish_reason: &FinishReason,
        full_text: &str,
    ) -> AgentResult<TurnFlow> {
        match finish_reason {
            FinishReason::ToolUse => {
                let error = "finish_reason=tool_use but no tool calls were parsed";
                tracing::warn!(
                    session_id = turn_ctx.session_id.id,
                    turn = turn_ctx.turn_count,
                    error,
                    "model signalled tool_use but no tool calls were parsed"
                );
                self.fire_turn_end(TurnEndCtx {
                    ttft_ms: metrics.ttft_ms,
                    llm_duration_ms: metrics.llm_duration_ms,
                    usage: metrics.usage,
                    text_length: metrics.text_len,
                    has_thinking: metrics.has_thinking,
                    llm_calls: 1,
                    error_message: Some(error),
                    ..TurnEndCtx::new(
                        turn_ctx.session_id,
                        turn_ctx.turn_count,
                        turn_ctx.turn_start,
                        turn_ctx.model,
                        turn_ctx.user_input,
                        RunOutcome::Failed { error: error.to_string() },
                    )
                })
                .await;
                Ok(TurnFlow::Done(RunOutcome::Failed { error: error.to_string() }))
            }
            FinishReason::Truncated { reason } => {
                let error = format!("response truncated ({:?})", reason);
                tracing::warn!(
                    session_id = turn_ctx.session_id.id,
                    turn = turn_ctx.turn_count,
                    ?reason,
                    "text-only response truncated by token limit"
                );
                self.fire_turn_end(TurnEndCtx {
                    ttft_ms: metrics.ttft_ms,
                    llm_duration_ms: metrics.llm_duration_ms,
                    usage: metrics.usage,
                    text_length: metrics.text_len,
                    has_thinking: metrics.has_thinking,
                    llm_calls: 1,
                    error_message: Some(&error),
                    ..TurnEndCtx::new(
                        turn_ctx.session_id,
                        turn_ctx.turn_count,
                        turn_ctx.turn_start,
                        turn_ctx.model,
                        turn_ctx.user_input,
                        RunOutcome::Failed { error: error.clone() },
                    )
                })
                .await;
                Ok(TurnFlow::Done(RunOutcome::Failed { error }))
            }
            _ => {
                // Text-only branch — use the guard to determine completion.
                let guard_ctx = self
                    .build_guard_ctx(turn_ctx, full_text, false, false, true, false)
                    .await;
                let decision = self.guard.on_turn(&guard_ctx).await;
                self.execute_guard_decision(decision, turn_ctx, metrics).await
            }
        }
    }

    /// LLM stream error: fire turn-end and persist session on cancellation.
    async fn handle_llm_error(
        &self,
        session_id: &SessionId,
        turn_count: u32,
        turn_start: std::time::Instant,
        model: &str,
        user_input_owned: &str,
        e: crate::types::AgentError,
    ) -> AgentResult<TurnFlow> {
        let stream_outcome = if e.is_cancelled() {
            RunOutcome::Cancelled
        } else {
            RunOutcome::Failed { error: e.to_string() }
        };
        self.fire_turn_end(TurnEndCtx {
            error_message: Some(&e.to_string()),
            ..TurnEndCtx::new(session_id, turn_count, turn_start, model, user_input_owned, stream_outcome)
        })
        .await;
        // Persist session on cancellation (LLM-stream path bypasses handle_tool_error)
        if e.is_cancelled()
            && let Ok(session) = self.session_manager.session_or_err(session_id).await
        {
            let _ = self.session_manager.session_store().save(&session).await;
        }
        Err(e)
    }

    // ── Guard decision execution ────────────────────────────────────────

    /// Execute a guard decision — fire events, inject nudge, or terminate.
    pub(super) async fn execute_guard_decision(
        &self,
        decision: crate::engine::react_loop_guard::GuardDecision,
        turn_ctx: &TurnCtx<'_>,
        metrics: &TurnMetrics<'_>,
    ) -> AgentResult<TurnFlow> {
        use crate::engine::react_loop_guard::GuardDecision;
        match decision {
            GuardDecision::Continue { nudge } => {
                tracing::info!(
                    session_id = turn_ctx.session_id.id,
                    turn = turn_ctx.turn_count,
                    "guard decided to continue"
                );
                self.fire_turn_end(TurnEndCtx {
                    ttft_ms: metrics.ttft_ms,
                    llm_duration_ms: metrics.llm_duration_ms,
                    usage: metrics.usage,
                    text_length: metrics.text_len,
                    has_thinking: metrics.has_thinking,
                    llm_calls: 1,
                    ..TurnEndCtx::new(
                        turn_ctx.session_id,
                        turn_ctx.turn_count,
                        turn_ctx.turn_start,
                        turn_ctx.model,
                        turn_ctx.user_input,
                        RunOutcome::Continuing,
                    )
                })
                .await;
                if let Some(msg) = nudge {
                    self.with_session_mut(turn_ctx.session_id, |session| {
                        session.push_message(MessageRole::User, &msg);
                    })
                    .await?;
                }
                Ok(TurnFlow::Continue)
            }
            GuardDecision::Complete => {
                tracing::info!(
                    session_id = turn_ctx.session_id.id,
                    turn = turn_ctx.turn_count,
                    "guard decided task is complete"
                );
                self.fire_turn_end(TurnEndCtx {
                    ttft_ms: metrics.ttft_ms,
                    llm_duration_ms: metrics.llm_duration_ms,
                    usage: metrics.usage,
                    text_length: metrics.text_len,
                    has_thinking: metrics.has_thinking,
                    llm_calls: 1,
                    ..TurnEndCtx::new(
                        turn_ctx.session_id,
                        turn_ctx.turn_count,
                        turn_ctx.turn_start,
                        turn_ctx.model,
                        turn_ctx.user_input,
                        RunOutcome::Completed,
                    )
                })
                .await;
                Ok(TurnFlow::Done(RunOutcome::Completed))
            }
            GuardDecision::Fail { error } => {
                tracing::warn!(
                    session_id = turn_ctx.session_id.id,
                    turn = turn_ctx.turn_count,
                    error = %error,
                    "guard decided to fail"
                );
                self.fire_guard_fail(turn_ctx, metrics, &error).await;
                Ok(TurnFlow::Done(RunOutcome::Failed { error }))
            }
            GuardDecision::DisableThinking { nudge } => {
                self.with_session_mut(turn_ctx.session_id, |session| {
                    session.run_state.thinking_disabled_for_rest_of_run = true;
                    session.push_message(MessageRole::User, &nudge);
                })
                .await?;

                self.fire_turn_end(TurnEndCtx {
                    ttft_ms: metrics.ttft_ms,
                    llm_duration_ms: metrics.llm_duration_ms,
                    usage: metrics.usage,
                    text_length: metrics.text_len,
                    has_thinking: metrics.has_thinking,
                    llm_calls: 1,
                    ..TurnEndCtx::new(
                        turn_ctx.session_id,
                        turn_ctx.turn_count,
                        turn_ctx.turn_start,
                        turn_ctx.model,
                        turn_ctx.user_input,
                        RunOutcome::Continuing,
                    )
                })
                .await;

                tracing::info!(
                    session_id = turn_ctx.session_id.id,
                    turn = turn_ctx.turn_count,
                    "thinking disabled by guard"
                );
                Ok(TurnFlow::Continue)
            }
            GuardDecision::RestoreThinking => {
                let original = self
                    .session_manager
                    .session_or_err(turn_ctx.session_id)
                    .await
                    .map(|s| s.run_state.original_thinking_enabled)
                    .unwrap_or(false);

                self.with_session_mut(turn_ctx.session_id, |session| {
                    session.run_state.thinking_disabled_for_rest_of_run = !original;
                })
                .await?;

                tracing::info!(
                    session_id = turn_ctx.session_id.id,
                    turn = turn_ctx.turn_count,
                    thinking_enabled = original,
                    "thinking restored by guard"
                );
                Ok(TurnFlow::Continue)
            }
        }
    }
}