bamboo-engine 2026.10.10

Execution engine and orchestration for the Bamboo agent framework
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
//! Event forwarding from MPSC to broadcast channels.
//!
//! Creates an MPSC channel for agent loop events and spawns a background task
//! that relays events to the session's broadcast sender while tracking runner
//! diagnostic state (budget events, tool execution, round progress).

use std::collections::HashMap;
use std::sync::Arc;

use chrono::Utc;
use tokio::sync::{broadcast, mpsc, watch, RwLock};

use bamboo_agent_core::AgentEvent;

use super::runner_state::AgentRunner;

fn visible_terminal_reason(event: &AgentEvent) -> Option<&'static str> {
    match event {
        AgentEvent::Complete { .. } => Some("complete"),
        AgentEvent::Cancelled { .. } => Some("cancelled"),
        AgentEvent::Error { .. } => Some("error"),
        _ => None,
    }
}

/// Inbox to the account-wide change feed: `(session_id, event)` before the
/// writer assigns a seq. Threaded as `Option` so engine-internal callers that
/// have no feed (tests, standalone embeddings) can pass `None`. Defined here so
/// the engine stays free of any `bamboo-server` dependency.
pub type AccountFeedInbox = mpsc::Sender<(Option<String>, AgentEvent)>;

#[cfg(test)]
#[path = "root_actor_event_forwarder_tests.rs"]
mod root_actor_tests;

/// Completion signal for the durable history barrier emitted at the end of a
/// run. The runner must not become replaceable until the forwarder has actually
/// published `SessionHistoryCommitted`; merely enqueueing the event leaves a
/// race where a successor can retire this generation first.
#[derive(Clone, Debug)]
pub struct HistoryCommitBarrier {
    revision: watch::Receiver<u64>,
}

/// Forwarder-owned half of [`HistoryCommitBarrier`].
#[derive(Clone, Debug)]
pub struct HistoryCommitAcknowledger {
    revision: watch::Sender<u64>,
}

/// Create the acknowledgment pair shared by an event producer and forwarder.
pub fn history_commit_barrier() -> (HistoryCommitAcknowledger, HistoryCommitBarrier) {
    let (revision_tx, revision_rx) = watch::channel(0);
    (
        HistoryCommitAcknowledger {
            revision: revision_tx,
        },
        HistoryCommitBarrier {
            revision: revision_rx,
        },
    )
}

impl HistoryCommitAcknowledger {
    /// Mark one history barrier as synchronously published to every configured
    /// sink. Call this only after the publication fence accepts the event.
    pub fn acknowledge(&self) {
        self.revision
            .send_modify(|revision| *revision = revision.saturating_add(1));
    }
}

impl HistoryCommitBarrier {
    /// Enqueue a history barrier and wait until the matching forwarder has
    /// published it. Returns `false` if the forwarder disappeared first.
    pub async fn send_and_wait(
        &mut self,
        event_tx: &mpsc::Sender<AgentEvent>,
        session_id: String,
    ) -> bool {
        let observed = *self.revision.borrow_and_update();
        if event_tx
            .send(AgentEvent::SessionHistoryCommitted { session_id })
            .await
            .is_err()
        {
            return false;
        }

        loop {
            if *self.revision.borrow() > observed {
                return true;
            }
            if self.revision.changed().await.is_err() {
                return false;
            }
        }
    }
}

/// Forward a durable change event onto the account feed, if an inbox is wired.
///
/// Ephemeral events (tokens, heartbeats, …) are filtered out before any clone,
/// so this is near-free on the hot path. `session_id` is supplied explicitly so
/// terminal events (which carry no id) still route to the right session.
fn mirror_to_account_feed(inbox: &Option<AccountFeedInbox>, session_id: &str, event: &AgentEvent) {
    if let Some(inbox) = inbox {
        if event.is_durable_change() {
            let route_session_id = event.session_id().unwrap_or(session_id);
            let _ = inbox.try_send((Some(route_session_id.to_string()), event.clone()));
        }
    }
}

#[cfg(test)]
#[allow(clippy::items_after_test_module)]
mod tests {
    use super::*;

    use bamboo_agent_core::ToolResult;
    use serde_json::json;

    #[tokio::test]
    async fn generic_forwarder_projects_native_download_without_changing_ordinary_results() {
        let session_id = "generic-download-display";
        let (broadcast_tx, mut broadcast_rx) = broadcast::channel(16);
        let mut runner = AgentRunner::new();
        runner.status = super::super::runner_state::AgentStatus::Running;
        runner.event_sender = broadcast_tx.clone();
        let run_id = runner.run_id.clone();
        let runners = Arc::new(RwLock::new(HashMap::from([(
            session_id.to_string(),
            runner,
        )])));
        let (input, forwarder) =
            create_event_forwarder(session_id.to_string(), run_id, broadcast_tx, runners, None);
        assert!(matches!(
            broadcast_rx.recv().await.unwrap(),
            AgentEvent::ExecutionStarted { .. }
        ));

        let private = "private-file-url-and-bytes";
        input
            .send(AgentEvent::ToolStart {
                tool_call_id: "download".into(),
                tool_name: "browser".into(),
                arguments: json!({"action":"download","selector":private,"expected_epoch":9}),
            })
            .await
            .unwrap();
        input
            .send(AgentEvent::ToolError {
                tool_call_id: "download".into(),
                error: private.into(),
            })
            .await
            .unwrap();
        input
            .send(AgentEvent::ToolComplete {
                tool_call_id: "download".into(),
                result: ToolResult::text(false, private),
            })
            .await
            .unwrap();
        input
            .send(AgentEvent::ToolStart {
                tool_call_id: "read".into(),
                tool_name: "Read".into(),
                arguments: json!({"path":"readme.md"}),
            })
            .await
            .unwrap();
        input
            .send(AgentEvent::ToolComplete {
                tool_call_id: "read".into(),
                result: ToolResult::text(true, "ordinary Read result"),
            })
            .await
            .unwrap();
        input
            .send(AgentEvent::HookLifecycle {
                hook_name: private.into(),
                point: bamboo_domain::AgentHookPoint::AfterToolExecution,
                phase: private.into(),
                duration_ms: 7,
                decision: bamboo_domain::HookResult::WithContext {
                    result: Box::new(bamboo_domain::HookResult::Deny {
                        reason: private.into(),
                    }),
                    text: private.into(),
                },
            })
            .await
            .unwrap();
        drop(input);

        let mut visible = Vec::new();
        for _ in 0..6 {
            visible.push(
                tokio::time::timeout(std::time::Duration::from_secs(5), broadcast_rx.recv())
                    .await
                    .unwrap()
                    .unwrap(),
            );
        }
        for event in &visible[..3] {
            assert!(!serde_json::to_string(event).unwrap().contains(private));
        }
        assert!(
            matches!(&visible[2], AgentEvent::ToolComplete { result, .. }
            if result.result == "Tool result hidden" && result.images.is_empty())
        );
        assert!(
            matches!(&visible[4], AgentEvent::ToolComplete { result, .. }
            if result.result == "ordinary Read result")
        );
        assert!(!serde_json::to_string(&visible[5])
            .unwrap()
            .contains(private));
        assert!(matches!(
            &visible[5],
            AgentEvent::HookLifecycle {
                point: bamboo_domain::AgentHookPoint::AfterToolExecution,
                duration_ms: 7,
                decision: bamboo_domain::HookResult::WithContext { .. },
                ..
            }
        ));
        forwarder.await.unwrap();
    }

    #[tokio::test(flavor = "multi_thread", worker_threads = 4)]
    async fn hundreds_of_child_streams_progress_while_global_registry_is_locked() {
        let runners = Arc::new(RwLock::new(HashMap::new()));
        let mut streams = Vec::new();
        for index in 0..512 {
            let id = format!("child-{index}");
            let mut runner = AgentRunner::new();
            runner.status = super::super::runner_state::AgentStatus::Running;
            let mut receiver = runner.event_sender.subscribe();
            let sender = runner.event_sender.clone();
            let run_id = runner.run_id.clone();
            runners.write().await.insert(id.clone(), runner);
            let (input, task) = create_event_forwarder(id, run_id, sender, runners.clone(), None);
            assert!(matches!(
                receiver.recv().await.unwrap(),
                AgentEvent::ExecutionStarted { .. }
            ));
            streams.push((input, receiver, task));
        }
        let held_registry = runners.write().await;
        let started = std::time::Instant::now();
        tokio::time::timeout(std::time::Duration::from_secs(10), async {
            futures::future::join_all(streams.iter_mut().map(|(input, receiver, _)| async move {
                for _ in 0..64 {
                    input
                        .send(AgentEvent::Token {
                            content: "delta".into(),
                        })
                        .await
                        .unwrap();
                }
                for _ in 0..64 {
                    assert!(matches!(
                        receiver.recv().await.unwrap(),
                        AgentEvent::Token { .. }
                    ));
                }
            }))
            .await;
        })
        .await
        .expect("independent token streams must not wait for registry ownership");
        eprintln!(
            "512 child streams / 32768 tokens with held registry: {:?}",
            started.elapsed()
        );
        assert!(held_registry
            .values()
            .all(|runner| runner.last_activity_at().is_some()));
        drop(held_registry);
        for (input, _, task) in streams {
            drop(input);
            task.await.unwrap();
        }
    }

    #[tokio::test]
    async fn child_approval_change_routes_to_parent_account_envelope() {
        let (tx, mut rx) = mpsc::channel(4);
        let event = AgentEvent::ChildApprovalChanged {
            parent_session_id: "parent-1".into(),
            child_session_id: "child-1".into(),
            child_attempt: 1,
            request_id: "req-1".into(),
            version: 2,
            status: "approved".into(),
            reason: None,
            tool_name: "Bash".into(),
            permission: "execute".into(),
            resource: "/tmp/x".into(),
            created_at: "2026-01-01T00:00:00Z".into(),
            resolved_at: Some("2026-01-01T00:00:01Z".into()),
        };

        mirror_to_account_feed(&Some(tx), "child-1", &event);
        let (session_id, mirrored) = rx.recv().await.unwrap();
        assert_eq!(session_id.as_deref(), Some("parent-1"));
        assert!(matches!(mirrored, AgentEvent::ChildApprovalChanged { .. }));
    }

    #[tokio::test]
    async fn child_browser_approval_is_redacted_before_broadcast_replay_and_account_feed() {
        let session_id = "child-browser-private";
        let private = "private-download-selector";
        let (broadcast_tx, mut broadcast_rx) = broadcast::channel(8);
        let mut runner = AgentRunner::new();
        runner.status = super::super::runner_state::AgentStatus::Running;
        runner.event_sender = broadcast_tx.clone();
        let run_id = runner.run_id.clone();
        let runners = Arc::new(RwLock::new(HashMap::from([(
            session_id.to_string(),
            runner,
        )])));
        let (account_tx, mut account_rx) = mpsc::channel(8);
        let (event_tx, forwarder) = create_event_forwarder(
            session_id.into(),
            run_id,
            broadcast_tx,
            runners.clone(),
            Some(account_tx),
        );
        assert!(matches!(
            broadcast_rx.recv().await.unwrap(),
            AgentEvent::ExecutionStarted { .. }
        ));
        event_tx
            .send(AgentEvent::ChildApprovalChanged {
                parent_session_id: "parent-private".into(),
                child_session_id: session_id.into(),
                child_attempt: 4,
                request_id: "request-private".into(),
                version: 7,
                status: "denied".into(),
                reason: Some(private.into()),
                tool_name: "browser".into(),
                permission: private.into(),
                resource: format!("browser:17:download:css:{private}"),
                created_at: "2026-09-24T00:00:00Z".into(),
                resolved_at: Some("2026-09-24T00:00:01Z".into()),
            })
            .await
            .unwrap();
        let live = broadcast_rx.recv().await.unwrap();
        assert!(!serde_json::to_string(&live).unwrap().contains(private));
        let _started = account_rx.recv().await.unwrap();
        let (route, feed) = account_rx.recv().await.unwrap();
        assert_eq!(route.as_deref(), Some("parent-private"));
        assert!(!serde_json::to_string(&feed).unwrap().contains(private));
        assert!(
            !serde_json::to_string(&runners.read().await[session_id].last_critical_events)
                .unwrap()
                .contains(private)
        );
        drop(event_tx);
        forwarder.await.unwrap();
    }

    #[tokio::test]
    async fn history_commit_barrier_acknowledges_actual_publication() {
        let session_id = "session-history-barrier";
        let (broadcast_tx, mut broadcast_rx) = broadcast::channel(16);
        let mut runner = AgentRunner::new();
        runner.status = super::super::runner_state::AgentStatus::Running;
        runner.event_sender = broadcast_tx.clone();
        let run_id = runner.run_id.clone();
        let runners = Arc::new(RwLock::new(HashMap::from([(
            session_id.to_string(),
            runner,
        )])));
        let (event_tx, forwarder, mut barrier) = create_event_forwarder_with_history_commit_barrier(
            session_id.to_string(),
            run_id,
            broadcast_tx,
            runners,
            None,
        );

        assert!(matches!(
            broadcast_rx.recv().await.unwrap(),
            AgentEvent::ExecutionStarted { .. }
        ));
        assert!(
            barrier
                .send_and_wait(&event_tx, session_id.to_string())
                .await,
            "producer must not continue until the forwarder publishes the barrier"
        );
        assert!(matches!(
            broadcast_rx.recv().await.unwrap(),
            AgentEvent::SessionHistoryCommitted { session_id: id } if id == session_id
        ));

        drop(event_tx);
        forwarder.await.unwrap();
    }

    #[tokio::test]
    async fn delayed_old_forwarder_cannot_publish_after_successor_reservation() {
        let session_id = "session-generation";
        let (broadcast_tx, mut broadcast_rx) = broadcast::channel(16);
        let mut successor = AgentRunner::new();
        successor.run_id = "run-new".to_string();
        successor.status = super::super::runner_state::AgentStatus::Running;
        successor.event_sender = broadcast_tx.clone();
        let runners = Arc::new(RwLock::new(HashMap::from([(
            session_id.to_string(),
            successor,
        )])));

        // The successor is already visible on the shared transport before an
        // old forwarder task finally gets CPU time.
        broadcast_tx
            .send(AgentEvent::ExecutionStarted {
                run_id: "run-new".to_string(),
                session_id: session_id.to_string(),
                started_at: Utc::now().to_rfc3339(),
            })
            .unwrap();
        let (old_tx, old_forwarder) = create_event_forwarder(
            session_id.to_string(),
            "run-old".to_string(),
            broadcast_tx.clone(),
            runners,
            None,
        );
        let _ = old_tx
            .send(AgentEvent::NeedClarification {
                question: "stale".to_string(),
                options: Some(vec!["A".to_string()]),
                tool_call_id: Some("old-tool".to_string()),
                tool_name: Some("ConclusionWithOptions".to_string()),
                allow_custom: false,
                source: Some(bamboo_agent_core::PendingQuestionSource::PauseTool),
            })
            .await;
        drop(old_tx);
        old_forwarder.await.unwrap();

        assert!(matches!(
            broadcast_rx.recv().await.unwrap(),
            AgentEvent::ExecutionStarted { ref run_id, .. } if run_id == "run-new"
        ));
        assert!(
            tokio::time::timeout(std::time::Duration::from_millis(50), broadcast_rx.recv())
                .await
                .is_err(),
            "old Started/Need/Complete must all be suppressed"
        );
    }

    #[tokio::test]
    async fn wrapped_child_lifecycle_reaches_bounded_legacy_replay_consumer() {
        let session_id = "root";
        let (broadcast_tx, mut broadcast_rx) = broadcast::channel(8);
        let mut runner = AgentRunner::new();
        runner.status = super::super::runner_state::AgentStatus::Running;
        runner.event_sender = broadcast_tx.clone();
        let run_id = runner.run_id.clone();
        let runners = Arc::new(RwLock::new(HashMap::from([(session_id.into(), runner)])));
        let (input, forwarder) = create_event_forwarder(
            session_id.into(),
            run_id,
            broadcast_tx,
            runners.clone(),
            None,
        );
        assert!(matches!(
            broadcast_rx.recv().await.unwrap(),
            AgentEvent::ExecutionStarted { .. }
        ));
        let legacy = AgentEvent::SubAgentEvent {
            parent_session_id: "root".into(),
            child_session_id: "parent".into(),
            event: Box::new(AgentEvent::SubAgentStarted {
                parent_session_id: "parent".into(),
                child_session_id: "grandchild".into(),
                title: Some("work".into()),
            }),
        };
        input.send(legacy).await.unwrap();
        assert!(matches!(
            broadcast_rx.recv().await.unwrap(),
            AgentEvent::SubAgentEvent { .. }
        ));
        let guard = runners.read().await;
        let cached = &guard[session_id].last_critical_events;
        assert_eq!(cached.len(), 1);
        assert!(matches!(&cached[0], AgentEvent::SubAgentEvent { .. }));
        drop(guard);
        drop(input);
        forwarder.await.unwrap();
    }
}

/// Create an MPSC channel for agent events and spawn a forwarding task
/// that relays events to the broadcast sender while tracking runner
/// diagnostic fields for live visibility.
///
/// `account_feed_inbox`, when present, also mirrors durable change events onto
/// the account-wide feed for resumable multi-client sync.
///
/// Returns `(mpsc_tx, forwarder_handle)`.
pub fn create_event_forwarder(
    session_id: String,
    run_id: String,
    broadcast_tx: broadcast::Sender<AgentEvent>,
    runners: Arc<RwLock<HashMap<String, AgentRunner>>>,
    account_feed_inbox: Option<AccountFeedInbox>,
) -> (mpsc::Sender<AgentEvent>, tokio::task::JoinHandle<()>) {
    let (event_tx, forwarder, _history_commit_barrier) =
        create_event_forwarder_with_history_commit_barrier(
            session_id,
            run_id,
            broadcast_tx,
            runners,
            account_feed_inbox,
        );
    (event_tx, forwarder)
}

/// Create an event forwarder plus a producer-side durable-history barrier.
/// Runtime paths that finalize and replace runner generations must use this
/// variant so they can await actual barrier publication before finalization.
pub fn create_event_forwarder_with_history_commit_barrier(
    session_id: String,
    run_id: String,
    broadcast_tx: broadcast::Sender<AgentEvent>,
    runners: Arc<RwLock<HashMap<String, AgentRunner>>>,
    account_feed_inbox: Option<AccountFeedInbox>,
) -> (
    mpsc::Sender<AgentEvent>,
    tokio::task::JoinHandle<()>,
    HistoryCommitBarrier,
) {
    create_event_forwarder_with_root_actor(
        session_id,
        run_id,
        broadcast_tx,
        runners,
        account_feed_inbox,
        None,
    )
}

async fn publish_forwarded_event(
    root_actor: Option<&crate::events::RootActorEventPublication>,
    session_id: &str,
    event: &AgentEvent,
    publish: Box<dyn FnOnce() -> bool + Send>,
) -> std::io::Result<()> {
    if let Some(owner) = root_actor {
        owner
            .publish(event.session_id().unwrap_or(session_id), event, publish)
            .await
    } else if publish() {
        Ok(())
    } else {
        Err(std::io::Error::other("event publication was retired"))
    }
}

/// The Root adapter passes its immutable capability before any Started frame.
/// Legacy Child/Supervisor/standalone callers keep the existing queue behavior.
pub fn create_event_forwarder_with_root_actor(
    session_id: String,
    run_id: String,
    broadcast_tx: broadcast::Sender<AgentEvent>,
    runners: Arc<RwLock<HashMap<String, AgentRunner>>>,
    account_feed_inbox: Option<AccountFeedInbox>,
    root_actor: Option<crate::events::RootActorEventPublication>,
) -> (
    mpsc::Sender<AgentEvent>,
    tokio::task::JoinHandle<()>,
    HistoryCommitBarrier,
) {
    let (mpsc_tx, mut mpsc_rx) = mpsc::channel::<AgentEvent>(100);
    let (history_commit_acknowledger, history_commit_barrier) = history_commit_barrier();
    let forward = async move {
        if root_actor
            .as_ref()
            .is_some_and(|owner| !owner.matches_execution(&session_id, &run_id))
        {
            tracing::warn!(%session_id, %run_id, "Root forwarder handoff does not match its execution");
            return;
        }
        // A bound Root never enters the legacy account queue.
        let legacy_feed = if root_actor.is_some() {
            None
        } else {
            account_feed_inbox
        };
        let started_event = AgentEvent::ExecutionStarted {
            run_id: run_id.clone(),
            session_id: session_id.clone(),
            started_at: Utc::now().to_rfc3339(),
        };
        let (publication, visible_messages) = {
            let guard = runners.clone().read_owned().await;
            let Some(runner) = guard
                .get(&session_id)
                .filter(|runner| runner.run_id == run_id)
            else {
                return;
            };
            let publication = runner.event_publication.clone();
            let visible_messages = runner.visible_messages.clone();
            let feed = legacy_feed.clone();
            let sid = session_id.clone();
            let tx = broadcast_tx.clone();
            let frame = started_event.clone();
            if let Err(error) = publish_forwarded_event(
                root_actor.as_ref(),
                &session_id,
                &frame,
                Box::new(move || {
                    let _guard = guard;
                    mirror_to_account_feed(&feed, &sid, &started_event);
                    let _ = tx.send(started_event);
                    true
                }),
            )
            .await
            {
                tracing::warn!(%session_id, %run_id, %error, "Root Started publication rejected");
                return;
            }
            (publication, visible_messages)
        };
        let mut tool_event_display = bamboo_agent_core::NativeToolEventDisplay::default();
        while let Some(event) = mpsc_rx.recv().await {
            match &event {
                AgentEvent::VisibleMessageStart {
                    message_id,
                    created_at,
                } => {
                    if !publication.publish(|| {
                        visible_messages.start(message_id.clone(), created_at.to_owned())
                    }) {
                        return;
                    }
                    continue;
                }
                AgentEvent::VisibleMessageDiscard { message_id } => {
                    if !publication.publish(|| visible_messages.discard(message_id)) {
                        return;
                    }
                    continue;
                }
                _ => {}
            }
            let event = tool_event_display.project(event);
            let event = crate::external_agents::live::approval_event_for_display(event);
            let needs_runner_update = event.is_replayable_session_state()
                || matches!(
                    &event,
                    AgentEvent::TokenBudgetUpdated { .. }
                        | AgentEvent::ToolStart { .. }
                        | AgentEvent::ToolLifecycle { .. }
                        | AgentEvent::RunnerProgress { .. }
                );
            let is_history_commit = matches!(&event, AgentEvent::SessionHistoryCommitted { .. });
            let frame = event.clone();
            let feed = legacy_feed.clone();
            let sid = session_id.clone();
            let tx = broadcast_tx.clone();
            let result = if !needs_runner_update {
                let visible_token = match &event {
                    AgentEvent::Token { content } => Some(content.clone()),
                    _ => None,
                };
                let terminal_reason = visible_terminal_reason(&event);
                // Ephemeral token traffic retains its independent hot path.
                let owner = root_actor
                    .as_ref()
                    .filter(|_| event.is_durable_change() || terminal_reason.is_some());
                let publication = publication.clone();
                let visible = visible_messages.clone();
                publish_forwarded_event(
                    owner,
                    &session_id,
                    &frame,
                    Box::new(move || {
                        publication.publish(|| {
                            if let Some(content) = visible_token {
                                visible.append(content);
                            }
                            mirror_to_account_feed(&feed, &sid, &event);
                            let _ = tx.send(event);
                            if let Some(reason) = terminal_reason {
                                visible.mark_terminal(reason);
                            }
                            if is_history_commit {
                                visible.history_committed();
                            }
                        })
                    }),
                )
                .await
            } else {
                let mut guard = runners.clone().write_owned().await;
                if !guard
                    .get(&session_id)
                    .is_some_and(|runner| runner.run_id == run_id)
                {
                    return;
                }
                let publication = publication.clone();
                publish_forwarded_event(
                    root_actor.as_ref(),
                    &session_id,
                    &frame,
                    Box::new(move || {
                        let runner = guard.get_mut(&sid).expect("retained exact runner guard");
                        runner.last_event_at = Some(Utc::now());
                        publication.touch();
                        if event.is_replayable_session_state() {
                            runner.push_critical_event(event.clone());
                        }
                        match &event {
                            AgentEvent::TokenBudgetUpdated { .. } => {
                                runner.last_budget_event = Some(event.clone())
                            }
                            AgentEvent::ToolStart { tool_name, .. } => {
                                runner.last_tool_name = Some(tool_name.clone());
                                runner.last_tool_phase = Some("begin".into());
                            }
                            AgentEvent::ToolLifecycle {
                                tool_name, phase, ..
                            } => {
                                runner.last_tool_name = Some(tool_name.clone());
                                runner.last_tool_phase = Some(phase.clone());
                            }
                            AgentEvent::RunnerProgress { round_count, .. } => {
                                runner.round_count = *round_count;
                                runner.visible_messages.begin_round(*round_count);
                            }
                            _ => {}
                        }
                        mirror_to_account_feed(&feed, &sid, &event);
                        let _ = tx.send(event);
                        true
                    }),
                )
                .await
            };
            if let Err(error) = result {
                tracing::warn!(%session_id, %run_id, %error, "Root runtime publication rejected");
                return;
            }
            if is_history_commit {
                history_commit_acknowledger.acknowledge();
            }
        }
    };
    (mpsc_tx, tokio::spawn(forward), history_commit_barrier)
}