agent-base 0.13.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
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
use std::sync::{Arc, Mutex};

use tokio::sync::broadcast;

use crate::engine::executor::INTERRUPTED_SUMMARY;
use crate::engine::middleware::UserMessageCtx;
use crate::engine::runtime::is_self_echo_user_event;
use crate::engine::runtime::plan_runner::RuntimeCore;
use crate::types::{
    ActionFormat, ActionOutcome, AgentError, AgentResult, CheckpointData, CheckpointStep,
    ImageAttachment, MessageRole, RunOutcome, RuntimeEvent, SessionId,
};

/// Drain events from a `broadcast::Receiver` and invoke a `Mutex<FnMut>` callback
/// for each one.
///
/// Run-local `UserEvent` self-echoes (see
/// [`is_self_echo_user_event`](crate::engine::runtime::is_self_echo_user_event))
/// are dropped — the publisher already rendered them to `on_event`.
pub(super) fn drain_locked<F>(
    event_rx: &mut broadcast::Receiver<RuntimeEvent>,
    on_event: &Mutex<F>,
) -> AgentResult<()>
where
    F: FnMut(RuntimeEvent) -> AgentResult<()>,
{
    let events: Vec<RuntimeEvent> = {
        let mut buf = Vec::new();
        loop {
            match event_rx.try_recv() {
                Ok(ev) => buf.push(ev),
                Err(broadcast::error::TryRecvError::Empty) => break,
                Err(broadcast::error::TryRecvError::Lagged(n)) => {
                    tracing::warn!(skipped = n, "EventBus consumer lagged, events dropped");
                    continue;
                }
                Err(broadcast::error::TryRecvError::Closed) => break,
            }
        }
        buf
    };
    if !events.is_empty()
        && let Ok(mut cb) = on_event.lock()
    {
        for ev in events {
            if is_self_echo_user_event(&ev) {
                continue;
            }
            cb(ev)?;
        }
    }
    Ok(())
}

/// Publish the terminal `RunCancelled` on the event bus, then loop it back to
/// the run's own `on_event` callback via [`drain_locked`] — the same delivery
/// contract as `RunFinished` (bus first, loopback second). External
/// subscribers (`subscribe_runtime_events`) must see the cancellation; the
/// run's recorder gets its copy from the loopback like every other event.
fn emit_run_cancelled<F>(
    runtime: &RuntimeCore,
    session_id: &SessionId,
    event_rx: &mut broadcast::Receiver<RuntimeEvent>,
    on_event: &Mutex<F>,
) -> AgentResult<()>
where
    F: FnMut(RuntimeEvent) -> AgentResult<()>,
{
    runtime.event_bus.emit(RuntimeEvent::RunCancelled {
        session_id: session_id.clone(),
        agent_id: None,
        trace_id: None,
    });
    drain_locked(event_rx, on_event)
}

/// Provenance of a turn's user input: how it is pushed into the transcript
/// (and what the rotation trail may later carry into a fresh window).
enum UserInputKind {
    /// A real user submit — the task trail.
    Real,
    /// An ephemeral skill body: visible this turn only, stripped at turn end.
    Ephemeral,
    /// Machine-composed input on the user role (notices, wakes): the model
    /// treats it like a user turn, but it is never the user's own words.
    Synthetic,
}

impl RuntimeCore {
    pub async fn run<F>(&self, session_id: SessionId, on_event: F) -> AgentResult<RunOutcome>
    where
        F: FnMut(RuntimeEvent) -> AgentResult<()> + Send + 'static,
    {
        // Reset cancel token for this run
        self.reset_cancel();
        // Notice pump (Batch E): drop leftovers from before this run so they
        // can never be stamped with this run's session id.
        self.discard_pending_notices();

        let span = tracing::info_span!("agent_run", session_id = session_id.id);
        let _enter = span.enter();

        let mut event_rx = self.event_bus.subscribe();
        let on_event = Arc::new(Mutex::new(on_event));

        if let Err(e) = self.validate_session(&session_id).await {
            tracing::warn!(session_id = session_id.id, error = %e, "session validation failed");
            self.event_bus.emit(RuntimeEvent::RunFinished {
                session_id: session_id.clone(),
                agent_id: None,
                trace_id: None,
            });
            drain_locked(&mut event_rx, &on_event)?;
            return Err(e);
        }

        tracing::debug!(session_id = session_id.id, "agent run start");
        let user_input_owned = self
            .with_session_mut(&session_id, |session| {
                session
                    .chat_messages()
                    .last()
                    .and_then(|m| match m {
                        crate::types::ChatMessage::User { content, .. } => Some(content.clone()),
                        _ => None,
                    })
                    .unwrap_or_default()
            })
            .await?;

        // Apply user message middleware (same as run_turn)
        let user_input_owned = self
            .apply_user_message_mw(&session_id, user_input_owned)
            .await?;

        // Reset run state for the new turn
        self.with_session_mut(&session_id, |session| {
            session.run_state.reset_for_new_run();
        })
        .await?;

        let all_user_inputs = self.collect_user_inputs(&session_id).await?;

        let result = self
            .run_react_loop(
                &session_id,
                &user_input_owned,
                0,
                &mut event_rx,
                on_event.clone(),
                &all_user_inputs,
            )
            .await;

        // Notice pump (Batch E): deliver pending notices before any
        // terminal event (RunFinished / RunCancelled), on every exit path.
        self.drain_notices(&session_id, &on_event)?;

        // Emit RunCancelled if cancelled, RunFinished otherwise (same as run_turn)
        match &result {
            Ok((RunOutcome::Cancelled, _)) => {
                emit_run_cancelled(self, &session_id, &mut event_rx, &on_event)?;
            }
            Err(e) if e.is_cancelled() => {
                emit_run_cancelled(self, &session_id, &mut event_rx, &on_event)?;
            }
            _ => {
                // Notice pump (Batch E): deliver guard/mechanism notices
                // before the terminal event. Pure addition — no existing
                // branch is touched.
                self.drain_notices(&session_id, &on_event)?;
                self.event_bus.emit(RuntimeEvent::RunFinished {
                    session_id: session_id.clone(),
                    agent_id: None,
                    trace_id: None,
                });
                drain_locked(&mut event_rx, &on_event)?;
            }
        }

        // Turn end: clean up ephemeral messages (including on error paths, to
        // avoid ephemeral residue leaking into persistence)
        if let Err(e) = self
            .with_session_mut(&session_id, |session| {
                session.remove_ephemeral_messages();
            })
            .await
        {
            tracing::warn!(error = %e, "failed to clean up ephemeral messages");
        }

        let (outcome, _turn_count) = result?;
        Ok(outcome)
    }

    pub async fn run_turn<F>(
        &self,
        session_id: SessionId,
        user_input: &str,
        on_event: F,
    ) -> AgentResult<RunOutcome>
    where
        F: FnMut(RuntimeEvent) -> AgentResult<()> + Send + 'static,
    {
        self.run_turn_impl(
            session_id,
            user_input,
            UserInputKind::Real,
            Vec::new(),
            on_event,
        )
        .await
    }

    /// Like `run_turn`, but the user message carries pictures (the paste
    /// pipeline's face): the images ride the message through the existing
    /// vision channel as [`ImageAttachment`]s. They land in the session's
    /// history with the text — the wire budget shrinks and judges them at
    /// send time.
    pub async fn run_turn_with_images<F>(
        &self,
        session_id: SessionId,
        user_input: &str,
        images: Vec<ImageAttachment>,
        on_event: F,
    ) -> AgentResult<RunOutcome>
    where
        F: FnMut(RuntimeEvent) -> AgentResult<()> + Send + 'static,
    {
        self.run_turn_impl(
            session_id,
            user_input,
            UserInputKind::Real,
            images,
            on_event,
        )
        .await
    }

    /// Like `run_turn`, but the user input is pushed as an **ephemeral**
    /// message: the LLM sees it for this turn only, then the existing
    /// turn-end cleanup removes it from memory and persistence. Used for
    /// skill-body injection. Note: the turn leaves NO trace in conversation
    /// history — neither the body nor any command (hosts that need a trail
    /// keep it in their own turn log).
    pub async fn run_turn_ephemeral_input<F>(
        &self,
        session_id: SessionId,
        user_input: &str,
        on_event: F,
    ) -> AgentResult<RunOutcome>
    where
        F: FnMut(RuntimeEvent) -> AgentResult<()> + Send + 'static,
    {
        self.run_turn_impl(
            session_id,
            user_input,
            UserInputKind::Ephemeral,
            Vec::new(),
            on_event,
        )
        .await
    }

    /// Like `run_turn`, but the input is **synthetic**: machine-composed
    /// input on the user role (a background-task wake, a child-result batch).
    /// The model treats it like a user turn — the transcript keeps it — but
    /// the message carries the synthetic flag, so context rotation never
    /// carries it into a fresh window as the user's task trail.
    pub async fn run_turn_synthetic_input<F>(
        &self,
        session_id: SessionId,
        user_input: &str,
        on_event: F,
    ) -> AgentResult<RunOutcome>
    where
        F: FnMut(RuntimeEvent) -> AgentResult<()> + Send + 'static,
    {
        self.run_turn_impl(
            session_id,
            user_input,
            UserInputKind::Synthetic,
            Vec::new(),
            on_event,
        )
        .await
    }

    async fn run_turn_impl<F>(
        &self,
        session_id: SessionId,
        user_input: &str,
        input_kind: UserInputKind,
        images: Vec<ImageAttachment>,
        on_event: F,
    ) -> AgentResult<RunOutcome>
    where
        F: FnMut(RuntimeEvent) -> AgentResult<()> + Send + 'static,
    {
        // Reset cancel token for this turn
        self.reset_cancel();
        // Notice pump (Batch E): drop leftovers from before this run so they
        // can never be stamped with this run's session id.
        self.discard_pending_notices();

        let span = tracing::Span::current();
        let _guard = span.enter();
        tracing::info!(session_id = session_id.id, user_input = %user_input, "agent turn start");
        drop(_guard);

        let mut event_rx = self.event_bus.subscribe();
        let on_event = Arc::new(Mutex::new(on_event));

        let user_input_owned = match self
            .apply_user_message_mw(&session_id, user_input.to_string())
            .await
        {
            Ok(u) => u,
            Err(e) => {
                let _ = on_event.lock().unwrap()(RuntimeEvent::RunFinished {
                    session_id: session_id.clone(),
                    agent_id: None,
                    trace_id: None,
                });
                return Err(e);
            }
        };

        // Turn-input size gate (the safety valve's visible face): the valve
        // pops an oversized message at push time, which for the turn's own
        // input means the user's words silently vanish and the turn runs on
        // nothing. Refuse the turn BEFORE the push instead, with the size
        // spelled out — the same voice as the image budget's "NOT sent".
        {
            let est = crate::engine::context::ContextWindowManager::user_message_tokens(
                &user_input_owned,
                &images,
            );
            let limit = self.config.read().await.session.max_message_tokens;
            if let Some(max) = limit
                && est > max
            {
                let _ = on_event.lock().unwrap()(RuntimeEvent::RunFinished {
                    session_id: session_id.clone(),
                    agent_id: None,
                    trace_id: None,
                });
                return Err(AgentError::llm(format!(
                    "message NOT sent - too large for one turn (about {est} tokens, limit {max}); \
                     split it into smaller messages or send the pictures across fewer turns"
                )));
            }
        }

        // Reset the run-level counting state for the new turn
        if let Err(e) = self
            .with_session_mut(&session_id, |session| {
                session.run_state.reset_for_new_run();
            })
            .await
        {
            let _ = on_event.lock().unwrap()(RuntimeEvent::RunFinished {
                session_id: session_id.clone(),
                agent_id: None,
                trace_id: None,
            });
            return Err(e);
        }

        // The push closure also snapshots the counting state: the checkpoint
        // line co-writes 账 (step) + 数 (RunState) in one write (D5+OV-11).
        let run_state = match self
            .with_session_mut(&session_id, |session| {
                match input_kind {
                    UserInputKind::Real => {
                        if images.is_empty() {
                            session.push_message(MessageRole::User, &user_input_owned);
                        } else {
                            // The paste pipeline's face: the pictures ride the
                            // user message through the vision channel.
                            session.push_user_message_with_images(&user_input_owned, images);
                        }
                    }
                    UserInputKind::Ephemeral => {
                        session.push_message_ephemeral(MessageRole::User, &user_input_owned);
                    }
                    UserInputKind::Synthetic => {
                        session.push_user_synthetic(&user_input_owned);
                    }
                }
                session.run_state.clone()
            })
            .await
        {
            Ok(run_state) => run_state,
            Err(e) => {
                let _ = on_event.lock().unwrap()(RuntimeEvent::RunFinished {
                    session_id: session_id.clone(),
                    agent_id: None,
                    trace_id: None,
                });
                return Err(e);
            }
        };

        self.event_bus.emit(RuntimeEvent::Checkpoint {
            session_id: session_id.clone(),
            checkpoint: Box::new(CheckpointData::new(
                session_id.clone(),
                user_input_owned.clone(),
                CheckpointStep::AfterUserInput,
                0,
                ActionFormat::ToolCall,
                run_state,
            )),
            agent_id: None,
            trace_id: None,
        });

        tracing::info!(
            session_id = session_id.id,
            "run_turn: entering run_react_loop"
        );
        let all_user_inputs = self.collect_user_inputs(&session_id).await?;
        let result = self
            .run_react_loop(
                &session_id,
                &user_input_owned,
                0,
                &mut event_rx,
                on_event.clone(),
                &all_user_inputs,
            )
            .await;

        // Notice pump (Batch E): deliver pending notices before any
        // terminal event (RunFinished / RunCancelled), on every exit path.
        self.drain_notices(&session_id, &on_event)?;

        // Emit RunCancelled event if cancelled
        match &result {
            Ok((RunOutcome::Cancelled, _)) => {
                emit_run_cancelled(self, &session_id, &mut event_rx, &on_event)?;
            }
            Err(e) if e.is_cancelled() => {
                emit_run_cancelled(self, &session_id, &mut event_rx, &on_event)?;
            }
            _ => {}
        }

        // Clean up ephemeral messages
        if let Err(e) = self
            .with_session_mut(&session_id, |session| {
                session.remove_ephemeral_messages();
            })
            .await
        {
            tracing::warn!(error = %e, "failed to clean up ephemeral messages");
        }

        // Emit RunFinished on any non-cancelled error so event listeners
        // know the turn ended.
        let (outcome, turn_count) = match result {
            Ok((RunOutcome::Cancelled, _)) => return Ok(RunOutcome::Cancelled),
            Ok(tuple) => {
                // The loop no longer emits RunFinished on completion; emit it
                // here once so listeners see a single terminal event.
                // Notice pump (Batch E): deliver guard/mechanism notices
                // before the terminal event. Pure addition.
                self.drain_notices(&session_id, &on_event)?;
                self.event_bus.emit(RuntimeEvent::RunFinished {
                    session_id: session_id.clone(),
                    agent_id: None,
                    trace_id: None,
                });
                drain_locked(&mut event_rx, &on_event)?;
                tuple
            }
            Err(e) if e.is_cancelled() => {
                return Err(e);
            }
            Err(e) => {
                let _ = on_event.lock().unwrap()(RuntimeEvent::RunFinished {
                    session_id: session_id.clone(),
                    agent_id: None,
                    trace_id: None,
                });
                return Err(e);
            }
        };

        tracing::info!(
            session_id = session_id.id,
            turn_count,
            "agent turn completed"
        );
        Ok(outcome)
    }

    pub async fn run_turn_collect(
        &self,
        session_id: SessionId,
        user_input: &str,
    ) -> AgentResult<(Vec<RuntimeEvent>, RunOutcome)> {
        let events = Arc::new(Mutex::new(Vec::new()));
        let events_clone = events.clone();
        let outcome = self
            .run_turn(session_id, user_input, move |event| {
                events_clone.lock().unwrap().push(event);
                Ok(())
            })
            .await?;
        let events = Arc::try_unwrap(events).unwrap().into_inner().unwrap();
        Ok((events, outcome))
    }

    pub async fn resume_from_checkpoint<F>(
        &self,
        checkpoint: CheckpointData,
        on_event: F,
    ) -> AgentResult<RunOutcome>
    where
        F: FnMut(RuntimeEvent) -> AgentResult<()> + Send + 'static,
    {
        // T5 persistence contract: backend affinity is pinned on the
        // checkpoint; cross-backend resumes are refused with the mismatch
        // spelled out. A runtime resumes every action format it is assembled
        // with (T10c) — one session may interleave tool-call turns with a
        // mounted backend's turns — and refuses a pin naming a backend it
        // does not carry.
        checkpoint
            .verify_for_resume_any(&self.resume_formats().await)
            .map_err(AgentError::Checkpoint)?;

        // Reset cancel token for this resume
        self.reset_cancel();
        // Notice pump (Batch E): drop leftovers from before this run so they
        // can never be stamped with this run's session id.
        self.discard_pending_notices();

        let session_id = checkpoint.session_id.clone();
        let user_input = checkpoint.user_input.clone();
        let turn_count = checkpoint.turn_count;

        tracing::info!(session_id = session_id.id, turn_count, step = ?checkpoint.step, "resuming from checkpoint");

        // D5+OV-11: counting restores trust the persisted value — the
        // RunState co-written in this very checkpoint — never a recount from
        // messages (the assistant lens counts call attempts, not executed
        // actions, and lies for replayed/synthesized history). Pre-T7
        // checkpoints carry no state (不猜不回填): those sessions keep whatever
        // counting state they loaded with and fall back to the old-format paths.
        if let Some(run_state) = checkpoint.run_state.clone() {
            self.with_session_mut(&session_id, |session| {
                session.run_state = run_state;
            })
            .await?;
        }

        let mut event_rx = self.event_bus.subscribe();
        let on_event = Arc::new(Mutex::new(on_event));

        // D3 observation replay (T6): a resumed batch is never re-executed —
        // side effects stay one-shot. Completed batches replay their stored
        // observation verbatim; a dangling batch (crash window) gets synthetic
        // fates (已中断/未执行) so the model sees plainly that nothing ran.
        let batch = match &checkpoint.step {
            CheckpointStep::BeforeActions { actions } => Some((actions, None)),
            CheckpointStep::AfterActions {
                actions,
                observation,
            } => Some((actions, observation.as_ref())),
            CheckpointStep::AfterUserInput | CheckpointStep::BeforeLlm { .. } => None,
        };
        if let Some((actions, recorded)) = batch {
            if checkpoint.backend == ActionFormat::ToolCall {
                let executor =
                    super::tool_executor::ToolCallExecutor::new(self, session_id.clone());
                let tool_calls = super::tool_executor::actions_to_triples(actions);
                // T5 mark: pre-M3 `AfterToolCalls { results }` summaries are
                // recorded evidence — replayed as-is, never rewritten.
                let legacy = checkpoint
                    .migrated_from
                    .as_ref()
                    .map(|m| m.legacy_results.as_slice())
                    .unwrap_or(&[]);
                executor
                    .replay_batch(&session_id, &tool_calls, recorded.cloned(), legacy)
                    .await?;
            } else {
                // Mounted-backend replay (T10c): a recorded observation
                // replays verbatim (backend-neutral, D3); a dangling batch
                // gets synthetic fates in the bound backend's own history
                // shape (OV-4) carrying the kernel's fate vocabulary.
                // Pre-M3 legacy summaries cannot exist under a non-tool pin.
                let Some(backend) = &self.action_backend else {
                    return Err(AgentError::Checkpoint(
                        "resume refused: checkpoint is pinned to a mounted backend's protocol, but this runtime has none mounted".to_string(),
                    ));
                };
                if let Some(observation) = recorded {
                    self.with_session_mut(&session_id, |session| {
                        for msg in &observation.history_messages {
                            session.push_chat_message(msg.clone());
                        }
                    })
                    .await?;
                } else {
                    let fates: Vec<ActionOutcome> = actions
                        .iter()
                        .map(|a| ActionOutcome {
                            action_id: a.id.clone(),
                            name: a.name.clone(),
                            ok: false,
                            denied: false,
                            summary: INTERRUPTED_SUMMARY.to_string(),
                            details: None,
                        })
                        .collect();
                    let history_messages = backend.lock().await.render_fates(actions, &fates);
                    self.with_session_mut(&session_id, |session| {
                        for msg in &history_messages {
                            session.push_chat_message(msg.clone());
                        }
                    })
                    .await?;
                }
            }
        }

        let all_user_inputs = self.collect_user_inputs(&session_id).await?;

        let result = self
            .run_react_loop(
                &session_id,
                &user_input,
                turn_count,
                &mut event_rx,
                on_event.clone(),
                &all_user_inputs,
            )
            .await;

        // Notice pump (Batch E): deliver pending notices before any
        // terminal event (RunFinished / RunCancelled), on every exit path.
        self.drain_notices(&session_id, &on_event)?;

        // Emit RunCancelled if cancelled, same as run_turn
        match &result {
            Ok((RunOutcome::Cancelled, _)) => {
                emit_run_cancelled(self, &session_id, &mut event_rx, &on_event)?;
            }
            Err(e) if e.is_cancelled() => {
                emit_run_cancelled(self, &session_id, &mut event_rx, &on_event)?;
            }
            _ => {}
        }

        // Turn end: clean up ephemeral messages (including on error paths)
        if let Err(e) = self
            .with_session_mut(&session_id, |session| {
                session.remove_ephemeral_messages();
            })
            .await
        {
            tracing::warn!(error = %e, "failed to clean up ephemeral messages");
        }

        let (outcome, _final_turn_count) = result?;
        Ok(outcome)
    }

    async fn apply_user_message_mw(
        &self,
        session_id: &SessionId,
        user_input: String,
    ) -> AgentResult<String> {
        let mut ctx = UserMessageCtx {
            session_id: session_id.clone(),
            user_input,
        };
        for mw in &self.middlewares {
            mw.on_user_message(&mut ctx).await?;
        }
        Ok(ctx.user_input)
    }

    /// Managed run with follow-up queue support (P2).
    ///
    /// After the inner turn loop completes naturally (text response, no tool calls),
    /// follow-up messages are drained and a new inner loop is started. This repeats
    /// until no more follow-up messages are queued.
    pub(crate) async fn run_managed<F>(
        &self,
        session_id: SessionId,
        user_input: &str,
        on_event: F,
    ) -> AgentResult<RunOutcome>
    where
        F: FnMut(RuntimeEvent) -> AgentResult<()> + Send + 'static,
    {
        // Reset cancel token for this managed run
        self.reset_cancel();
        // Notice pump (Batch E): drop leftovers from before this run so they
        // can never be stamped with this run's session id.
        self.discard_pending_notices();

        let span = tracing::info_span!("agent_managed_run", session_id = session_id.id);
        let _enter = span.enter();

        let mut event_rx = self.event_bus.subscribe();
        let on_event = Arc::new(Mutex::new(on_event));

        if let Err(e) = self.validate_session(&session_id).await {
            tracing::warn!(session_id = session_id.id, error = %e, "session validation failed");
            self.event_bus.emit(RuntimeEvent::RunFinished {
                session_id: session_id.clone(),
                agent_id: None,
                trace_id: None,
            });
            drain_locked(&mut event_rx, &on_event)?;
            return Err(e);
        }

        tracing::debug!(session_id = session_id.id, "managed run start");

        // Push initial user message
        self.with_session_mut(&session_id, |session| {
            session.push_message(MessageRole::User, user_input);
        })
        .await?;

        // Apply user message middleware
        let user_input_owned = self
            .apply_user_message_mw(&session_id, user_input.to_string())
            .await?;

        // Reset run state for the new turn
        self.with_session_mut(&session_id, |session| {
            session.run_state.reset_for_new_run();
        })
        .await?;

        // Outer follow-up loop
        let mut current_input = user_input_owned;
        let mut final_outcome;
        let mut total_turns = 0u32;

        let config = self.config_snapshot_async().await;
        let max_turns = config
            .execution
            .max_turns
            .unwrap_or(crate::engine::runtime::DEFAULT_MAX_TURNS);

        loop {
            // Guard against unbounded execution: if follow-up messages
            // keep arriving, break out when the cumulative turn budget is
            // exhausted.
            if total_turns >= max_turns {
                tracing::warn!(
                    session_id = session_id.id,
                    total_turns,
                    max_turns,
                    "managed run: global turn cap reached"
                );
                final_outcome = RunOutcome::MaxTurnsExceeded { turns: total_turns };
                break;
            }

            // Run inner turn loop (steering drained at each iteration inside)
            let all_user_inputs = self.collect_user_inputs(&session_id).await?;
            let result = self
                .run_react_loop(
                    &session_id,
                    &current_input,
                    total_turns,
                    &mut event_rx,
                    on_event.clone(),
                    &all_user_inputs,
                )
                .await;

            // Notice pump (Batch E): deliver pending notices before any
            // terminal event (RunFinished / RunCancelled), on every exit path.
            self.drain_notices(&session_id, &on_event)?;

            // Emit RunCancelled if cancelled
            let is_cancelled = matches!(&result, Err(e) if e.is_cancelled());
            if is_cancelled {
                emit_run_cancelled(self, &session_id, &mut event_rx, &on_event)?;
                self.cleanup_ephemeral(&session_id).await;
                // Safe: we just checked it's Err and cancelled
                return Err(result.unwrap_err());
            }

            // Emit RunCancelled for Ok(Cancelled) outcome
            if let Ok((RunOutcome::Cancelled, _)) = &result {
                emit_run_cancelled(self, &session_id, &mut event_rx, &on_event)?;
                self.cleanup_ephemeral(&session_id).await;
                return Ok(RunOutcome::Cancelled);
            }

            let (outcome, turns) = result?;
            total_turns += turns;
            final_outcome = outcome;

            // Check for follow-up messages
            let follow_up_msgs = self.message_queue.drain_follow_up();
            if follow_up_msgs.is_empty() {
                break;
            }

            tracing::info!(
                session_id = session_id.id,
                count = follow_up_msgs.len(),
                "drained follow-up messages, starting new inner loop"
            );

            for msg in follow_up_msgs {
                self.with_session_mut(&session_id, |session| {
                    session.push_message(MessageRole::User, &msg);
                })
                .await?;
            }

            // Use an empty input for follow-up continuation (messages are already in session)
            current_input = String::new();
        }

        // Emit RunFinished
        // Notice pump (Batch E): deliver guard/mechanism notices
        // before the terminal event. Pure addition.
        self.drain_notices(&session_id, &on_event)?;
        self.event_bus.emit(RuntimeEvent::RunFinished {
            session_id: session_id.clone(),
            agent_id: None,
            trace_id: None,
        });
        drain_locked(&mut event_rx, &on_event)?;

        // Clean up ephemeral messages
        self.cleanup_ephemeral(&session_id).await;

        Ok(final_outcome)
    }

    /// Collect all user messages from the session (oldest-first).
    async fn collect_user_inputs(&self, session_id: &SessionId) -> AgentResult<Vec<String>> {
        self.with_session_mut(session_id, |session| {
            session
                .chat_messages()
                .iter()
                .filter_map(|m| match m {
                    crate::types::ChatMessage::User { content, .. } => Some(content.clone()),
                    _ => None,
                })
                .collect()
        })
        .await
    }

    /// Remove ephemeral messages from the session, best-effort (warn on failure).
    async fn cleanup_ephemeral(&self, session_id: &SessionId) {
        if let Err(e) = self
            .with_session_mut(session_id, |session| {
                session.remove_ephemeral_messages();
            })
            .await
        {
            tracing::warn!(error = %e, "failed to clean up ephemeral messages");
        }
    }
}