bamboo-engine 2026.10.17

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
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
//! Stable public API for the agent runtime.
//!
//! [`Agent`] wraps an [`AgentRuntime`] with method-based access and serves as
//! the primary entry point for SDK consumers.

use std::sync::Arc;

use bamboo_agent_core::Session;

use crate::runtime::{AgentRuntime, AgentRuntimeBuilder, ExecuteRequest};
use bamboo_domain::RuntimeSessionPersistence;

// ---------------------------------------------------------------------------
// Agent — stable public object
// ---------------------------------------------------------------------------

/// Stable public entry point for agent execution.
///
/// Wraps an [`AgentRuntime`] and provides:
/// - [`Agent::execute()`] — run the agent loop on a session
/// - [`Agent::storage()`] — access the shared storage backend
///
/// Clone is cheap (inner is `Arc`).
#[derive(Clone)]
pub struct Agent {
    runtime: Arc<AgentRuntime>,
}

/// Opaque ownership lease for one direct logical-session execution.
///
/// SDK facades acquire this before any pre-execution side effect, then transfer
/// it into [`Agent::execute_direct_registered`]. Dropping it early invokes the
/// same abandoned-owner recovery as cancellation during provider execution.
pub struct DirectExecutionLease {
    target_session_id: String,
    router: Option<Arc<crate::session_activation::SessionActivationRouter>>,
    registration: Option<crate::session_activation::SessionRunRegistration>,
}

impl DirectExecutionLease {
    /// Release ownership before returning a handled pre-execution stop to an
    /// SDK caller, so its next resume does not race the asynchronous Drop path.
    pub async fn abandon(mut self) {
        if let Some(registration) = self.registration.take() {
            registration.abandon().await;
        }
    }
}

/// Opaque, single-use SDK submission receipt. The owned User is the genuine
/// portable-hook result; subsequent F preparation may change only its prompt.
pub struct SdkInputSubmission {
    session_id: String,
    execution_id: String,
    user: bamboo_agent_core::Message,
    hook_runner: Arc<crate::runtime::hooks::HookRunner>,
}

impl SdkInputSubmission {
    pub fn execution_id(&self) -> &str {
        &self.execution_id
    }
    pub fn user(&self) -> &bamboo_agent_core::Message {
        &self.user
    }
}

impl Agent {
    /// Wrap an existing [`AgentRuntime`] in an `Agent`.
    pub fn from_runtime(runtime: Arc<AgentRuntime>) -> Self {
        Agent { runtime }
    }

    /// One execution's immutable persistence capability. Shared tool/provider
    /// resources remain on the existing runtime; default callers stay unbound.
    #[doc(hidden)]
    pub fn with_execution_persistence(
        &self,
        persistence: Arc<dyn RuntimeSessionPersistence>,
    ) -> Self {
        let mut runtime = (*self.runtime).clone();
        runtime.persistence = persistence;
        runtime.inherited_child_wait_captured = true;
        Self::from_runtime(Arc::new(runtime))
    }

    /// Install the registered SDK adapter on this execution's runtime only.
    #[doc(hidden)]
    pub fn with_sdk_skill_execution_host(
        &self,
        host: Arc<dyn crate::runtime::config::SdkSkillExecutionHost>,
    ) -> Self {
        self.with_skill_execution_host(host)
    }

    /// Attach an execution-local registered host; this creates no caller authority.
    #[doc(hidden)]
    pub fn with_skill_execution_host(
        &self,
        host: Arc<dyn crate::runtime::config::SkillExecutionHost>,
    ) -> Self {
        let mut runtime = (*self.runtime).clone();
        runtime.sdk_skill_execution_host = Some(host);
        Self::from_runtime(Arc::new(runtime))
    }

    /// Bind Workspace adoption to this execution without opting into Skill mode.
    #[doc(hidden)]
    pub fn with_workspace_execution_host(
        &self,
        host: Arc<dyn crate::runtime::config::WorkspaceExecutionHost>,
    ) -> Self {
        let mut runtime = (*self.runtime).clone();
        runtime.workspace_execution_host = Some(host);
        Self::from_runtime(Arc::new(runtime))
    }

    /// Run the genuine portable submission hook before F and append. No old
    /// metadata receipt may skip this new submission's hook.
    #[doc(hidden)]
    pub async fn precheck_sdk_user_input(
        &self,
        session: &mut Session,
        user: &bamboo_agent_core::Message,
        app_data_dir: Option<std::path::PathBuf>,
    ) -> crate::runtime::runner::Result<SdkInputSubmission> {
        session
            .check_execution_compatibility()
            .map_err(|error| bamboo_agent_core::AgentError::Tool(error.to_string()))?;
        if user.role != bamboo_agent_core::Role::User
            || crate::runtime::config::UntrustedInputObservation::new(&user.id, None).is_none()
            || session.messages.iter().any(|message| message.id == user.id)
        {
            return Err(bamboo_agent_core::AgentError::Tool(
                "invalid new SDK User".into(),
            ));
        }
        let hook_runner = {
            let config = self.runtime.config.read().await;
            Arc::new(
                self.runtime
                    .hook_runner
                    .with_lifecycle_config(&config.lifecycle_hooks, app_data_dir),
            )
        };
        session.metadata.remove("runtime.plugin_prompt_prechecked");
        let prompt = hook_runner
            .apply_portable_user_prompt(session, &user.content)
            .await?;
        let mut transformed = user.clone();
        transformed.content = prompt.clone();
        if let Some(parts) = transformed.content_parts.as_mut() {
            if let Some(bamboo_domain::MessagePart::Text { text }) =
                parts.iter_mut().find(|part| matches!(part, bamboo_domain::MessagePart::Text { text } if text == &user.content))
            {
                *text = prompt;
            }
        }
        Ok(SdkInputSubmission {
            session_id: session.id.clone(),
            execution_id: crate::runtime::runner::round_prelude::new_execution_id(),
            user: transformed,
            hook_runner,
        })
    }

    /// Actual SDK producer append. The private pending receipt becomes checked
    /// only after startup hooks and a durable same-repository checkpoint.
    #[doc(hidden)]
    pub fn append_sdk_user_input(
        &self,
        session: &mut Session,
        user: bamboo_agent_core::Message,
        receipt: Option<SdkInputSubmission>,
        request: Option<bamboo_domain::SessionSkillRequest>,
    ) -> crate::runtime::runner::Result<crate::runtime::config::UntrustedExecutionInputs> {
        session
            .check_execution_compatibility()
            .map_err(|error| bamboo_agent_core::AgentError::Tool(error.to_string()))?;
        use crate::runtime::config::{
            sdk_message_digest, sdk_message_header_digest, SdkPendingInput,
            UntrustedExecutionInputs, UntrustedInputObservation,
        };
        let invalid = || bamboo_agent_core::AgentError::Tool("invalid SDK append receipt".into());
        let header_digest = sdk_message_header_digest(&user);
        let input_id = user.id.clone();
        if let Some(receipt) = receipt.as_ref() {
            if receipt.session_id != session.id
                || receipt.user.role != bamboo_agent_core::Role::User
                || user.role != bamboo_agent_core::Role::User
                || sdk_message_header_digest(&receipt.user) != header_digest
                || session
                    .messages
                    .iter()
                    .any(|message| message.id == input_id)
            {
                return Err(invalid());
            }
        }
        // Preserve the legacy String append even when optional observation data
        // is malformed. Typed callers fail before append on an invalid receipt.
        let final_digest = receipt.as_ref().map(|_| sdk_message_digest(&user));
        if receipt.is_some() {
            crate::runtime::hooks::HookRunner::mark_user_prompt_prechecked(session, &user.content);
        }
        session.add_message(user);
        let observation =
            UntrustedInputObservation::new(&input_id, request.as_ref()).ok_or_else(invalid)?;
        let carrier = UntrustedExecutionInputs::new(vec![observation]).ok_or_else(invalid)?;
        let (execution_id, hook_runner) = receipt
            .map(|receipt| (receipt.execution_id, Some(receipt.hook_runner)))
            .unwrap_or_else(|| {
                (
                    crate::runtime::runner::round_prelude::new_execution_id(),
                    None,
                )
            });
        Ok(carrier.bind_sdk_append(
            execution_id,
            SdkPendingInput {
                session_id: session.id.clone(),
                input_id,
                header_digest,
                final_digest,
            },
            hook_runner,
        ))
    }

    /// Return a new builder.
    pub fn builder() -> AgentBuilder {
        AgentBuilder::new()
    }

    /// Execute the agent loop with the given request.
    pub async fn execute(
        &self,
        session: &mut Session,
        req: ExecuteRequest,
    ) -> crate::runtime::runner::Result<()> {
        self.runtime.execute(session, req).await
    }

    /// Explicit bounded caller-data handoff; no currentness or Skill authority.
    /// Ordinary execute/direct/spawn entrypoints continue to supply None.
    pub async fn execute_with_inputs(
        &self,
        session: &mut Session,
        req: ExecuteRequest,
        inputs: Option<crate::runtime::config::UntrustedExecutionInputs>,
    ) -> crate::runtime::runner::Result<()> {
        self.runtime.execute_with_inputs(session, req, inputs).await
    }

    /// Execute a caller-owned session under a complete logical-session
    /// activation lifecycle.
    ///
    /// Server/child entry points already own an external runner reservation and
    /// therefore use [`execute`](Self::execute) plus their existing terminal
    /// handshake. Direct SDK callers have no runner registry, so this wrapper
    /// registers the current run before entering the provider loop, marks it
    /// finalizing immediately after return, migrates any terminal-window legacy
    /// ingress, and lets the router reserve at most one successor for work the
    /// completed reasoning turn did not admit.
    pub async fn execute_direct(
        &self,
        session: &mut Session,
        req: ExecuteRequest,
    ) -> crate::runtime::runner::Result<()> {
        session
            .check_execution_compatibility()
            .map_err(|error| bamboo_agent_core::AgentError::Tool(error.to_string()))?;
        let lease = self.begin_direct_execution(&session.id).await?;
        self.check_direct_execution_admission(session, &lease)
            .await?;
        self.prepare_external_session_for_execution(session).await?;
        self.execute_direct_registered(session, req, lease).await
    }

    /// Check counted-state admission under an already acquired opaque lease.
    /// SDK facades call this before Project preparation or approved-tool replay.
    /// This can refuse/fence an interrupted generation; it never replays it.
    pub fn check_direct_execution_admission<'a>(
        &'a self,
        session: &'a mut Session,
        lease: &'a DirectExecutionLease,
    ) -> impl std::future::Future<Output = crate::runtime::runner::Result<()>> + Send + 'a {
        let matches_target = lease.target_session_id == session.id;
        // Keep the lease borrowed for this future's lifetime without carrying
        // its non-Sync FnOnce cleanup across await. Only real private proof
        // enters the Send future; it is revalidated against the current owner.
        let ownership = lease.registration.as_ref().map(|run| run.ownership());
        async move {
            if !matches_target {
                return Err(bamboo_agent_core::AgentError::LLM(
                    "direct execution lease target does not match session".into(),
                ));
            }
            session
                .check_execution_compatibility()
                .map_err(|error| bamboo_agent_core::AgentError::Tool(error.to_string()))?;
            super::counted_loop::admit_registered(
                session,
                ownership.as_ref(),
                self.activation_router(),
                self.persistence().as_ref(),
            )
            .await
        }
    }

    /// Validate and publish Project/Workspace context for a caller-owned
    /// session before any external pre-execution side effect.
    ///
    /// SDK facades that acquire a direct lease themselves call this before
    /// approved-tool replay. [`execute_direct`](Self::execute_direct) also calls
    /// it, so the lower-level escape hatch cannot bypass legacy migration,
    /// Project validation, or runtime workspace publication.
    pub async fn prepare_external_session_for_execution(
        &self,
        session: &mut Session,
    ) -> crate::runtime::runner::Result<()> {
        crate::session_app::execution_prep::prepare_external_session_for_execution(
            session,
            self.runtime.project_context_resolver.as_deref(),
        )
        .await
    }

    /// Resolve a proposed SDK Project assignment without publishing a runtime
    /// workspace. The caller must persist the validated candidate before the
    /// ordinary execution handoff publishes it or replays an approved tool.
    pub async fn prepare_external_project_assignment_read_only(
        &self,
        session: &mut Session,
    ) -> crate::runtime::runner::Result<()> {
        let resolver = self
            .runtime
            .project_context_resolver
            .as_deref()
            .ok_or_else(|| {
                bamboo_agent_core::AgentError::ProjectContext(
                    "Project assignment requires a ProjectContextResolver".to_string(),
                )
            })?;
        resolver
            .refresh_session_prompt_read_only(session)
            .await
            .map(|_| ())
            .map_err(|error| bamboo_agent_core::AgentError::ProjectContext(error.to_string()))
    }

    /// Acquire direct logical-session ownership before an SDK facade performs
    /// pre-execution work such as replaying an approved mutating tool.
    pub async fn begin_direct_execution(
        &self,
        target_session_id: &str,
    ) -> crate::runtime::runner::Result<DirectExecutionLease> {
        let Some(router) = self.activation_router().cloned() else {
            return Ok(DirectExecutionLease {
                target_session_id: target_session_id.to_string(),
                router: None,
                registration: None,
            });
        };
        let run_id = format!("sdk-direct-{}", uuid::Uuid::new_v4());
        let registration = router
            .register_run(target_session_id, &run_id)
            .await
            .map_err(|error| bamboo_agent_core::AgentError::LLM(error.to_string()))?;
        Ok(DirectExecutionLease {
            target_session_id: target_session_id.to_string(),
            router: Some(router),
            registration: Some(registration),
        })
    }

    /// Execute and finalize a direct run whose ownership was acquired by
    /// [`begin_direct_execution`](Self::begin_direct_execution).
    pub async fn execute_direct_registered(
        &self,
        session: &mut Session,
        req: ExecuteRequest,
        lease: DirectExecutionLease,
    ) -> crate::runtime::runner::Result<()> {
        self.execute_direct_registered_with_inputs(session, req, lease, None)
            .await
    }

    /// Existing direct lifecycle with a separately owned, untrusted input handoff.
    pub async fn execute_direct_registered_with_inputs(
        &self,
        session: &mut Session,
        req: ExecuteRequest,
        lease: DirectExecutionLease,
        inputs: Option<crate::runtime::config::UntrustedExecutionInputs>,
    ) -> crate::runtime::runner::Result<()> {
        self.check_direct_execution_admission(session, &lease)
            .await?;
        let inherited = self.persistence().inherited_child_wait().or_else(|| {
            (!self.runtime.inherited_child_wait_captured)
                .then(|| bamboo_domain::InheritedChildWait::capture(session))
                .flatten()
        });
        let agent = if let Some(inherited) = inherited {
            inherited
                .validate_session(session)
                .map_err(|error| bamboo_agent_core::AgentError::LLM(error.to_string()))?;
            if self.persistence().inherited_child_wait().is_some() {
                self.clone()
            } else {
                self.with_execution_persistence(
                    self.persistence()
                        .bind_inherited_child_wait(inherited)
                        .map_err(|error| bamboo_agent_core::AgentError::LLM(error.to_string()))?,
                )
            }
        } else {
            self.with_execution_persistence(self.persistence().clone())
        };
        agent
            .execute_direct_registered_bound(session, req, lease, inputs)
            .await
    }

    async fn execute_direct_registered_bound(
        &self,
        session: &mut Session,
        mut req: ExecuteRequest,
        mut lease: DirectExecutionLease,
        inputs: Option<crate::runtime::config::UntrustedExecutionInputs>,
    ) -> crate::runtime::runner::Result<()> {
        if lease.target_session_id != session.id {
            return Err(bamboo_agent_core::AgentError::LLM(format!(
                "direct execution lease target {} does not match session {}",
                lease.target_session_id, session.id
            )));
        }
        let Some(router) = lease.router.take() else {
            return self.execute_with_inputs(session, req, inputs).await;
        };
        let mut registration = lease.registration.take().ok_or_else(|| {
            bamboo_agent_core::AgentError::LLM(
                "direct execution lease is missing its router registration".to_string(),
            )
        })?;
        if !router
            .bind_run_lifetime(&registration.ownership(), session)
            .await
        {
            return Err(bamboo_agent_core::AgentError::Tool(
                "registered run Session lifetime differs".into(),
            ));
        }
        if let Some(counted) = req.counted_loop.as_mut() {
            counted.bind_owner(registration.ownership(), session);
        }
        if let Some(control) = req.loop_control.as_mut() {
            control.bind_owner(registration.ownership(), session);
            control.bind_transport_cleanup(
                &mut registration,
                self.storage().clone(),
                self.session_inbox().cloned(),
                self.persistence().root_actor_writer(),
            );
        }
        let result = if req.loop_control.is_some() {
            bamboo_agent_core::tools::observe_tool_suspension(false, async {
                let token = bamboo_agent_core::tools::capture_suspension_restriction().ok_or_else(
                    || {
                        bamboo_agent_core::AgentError::Tool(
                            "direct loop_control execution is missing its host observation scope"
                                .into(),
                        )
                    },
                )?;
                // Bind before the runtime is first polled, so cancellation of
                // this observer still leaves Drop the same sticky host proof.
                registration.bind_tool_suspension_observation(token);
                self.execute_with_inputs(session, req, inputs).await
            })
            .await
            .0
        } else {
            self.execute_with_inputs(session, req, inputs).await
        };
        if registration.observed_forbidden_running() {
            // No stop receipt exists for this detached outcome, including when
            // direct Root execution has no LocalTaskResources domain.
            // Retain the exact owner before migration or ordinary finish can
            // release it or dispatch a successor. Preserve the runtime error.
            registration.quarantine().await;
            return match result {
                Err(error) => Err(error),
                Ok(()) => Err(bamboo_agent_core::AgentError::Tool(
                    "suspension_disabled: detached Running outcome; stop unconfirmed".into(),
                )),
            };
        }

        // Freeze what this provider execution actually consumed. Compatibility
        // migration and concurrent deliveries below must remain newer work.
        let executed_admitted_generation = session
            .session_inbox_admission()
            .map_or(0, |state| state.last_admitted_sequence);
        registration.begin_finalization().await;

        let legacy_migration = crate::runtime::runner::state_bridge::migrate_legacy_pending_only(
            session,
            Some(self.storage()),
            Some(self.persistence()),
            self.session_inbox(),
        )
        .await;
        if let Some(generation) = legacy_migration.highest_generation {
            session.session_inbox_admission_mut().observe(generation);
        }
        let pending_generation = session
            .session_inbox_admission()
            .and_then(|state| state.pending_activation_generation());
        if let Some(generation) = pending_generation {
            let activation_ready = if let Some(inbox) = self.session_inbox() {
                match inbox
                    .mark_activation_eligible(
                        &session.id,
                        generation,
                        bamboo_domain::SessionActivationPolicy::InterruptSpecificWait,
                    )
                    .await
                {
                    Ok(()) => true,
                    Err(error) => {
                        tracing::error!(
                            session_id = %session.id,
                            %error,
                            "failed to persist direct SDK SessionInbox activation watermark"
                        );
                        false
                    }
                }
            } else {
                false
            };
            if activation_ready {
                if let Err(error) = bamboo_domain::SessionActivationPort::request_activation(
                    router.as_ref(),
                    &session.id,
                    generation,
                )
                .await
                {
                    tracing::error!(
                        session_id = %session.id,
                        %error,
                        "failed to hand direct SDK SessionInbox generation to activation router"
                    );
                }
            }
        }

        // Keep the owner receiver alive until finalizing is visible. Persist
        // the observed-generation marker before a successor can start.
        if let Err(error) = self.persistence().checkpoint_runtime_session(session).await {
            tracing::warn!(
                session_id = %session.id,
                %error,
                "failed to checkpoint direct SDK terminal SessionInbox state"
            );
        }
        if let Err(error) = registration.finish(executed_admitted_generation).await {
            tracing::error!(
                session_id = %session.id,
                %error,
                "direct SDK SessionInbox finalization failed"
            );
        }

        result
    }

    /// Access the shared storage backend.
    pub fn storage(&self) -> &Arc<dyn bamboo_agent_core::storage::Storage> {
        &self.runtime.storage
    }

    /// Access the runtime persistence adapter for non-authoritative saves.
    pub fn persistence(&self) -> &Arc<dyn RuntimeSessionPersistence> {
        &self.runtime.persistence
    }

    pub fn session_inbox(&self) -> Option<&Arc<dyn bamboo_domain::SessionInboxPort>> {
        self.runtime.session_inbox.as_ref()
    }

    /// Execute the same durable SessionInbox boundary used by the agent loop
    /// before its first provider call. This compatibility method reports only
    /// the merge count; it cannot confirm successful ACK. Execution entry points
    /// must use [`Self::admit_session_inbox_at_safe_boundary_checked`] instead.
    pub async fn admit_session_inbox_at_safe_boundary(
        &self,
        session: &mut bamboo_agent_core::Session,
    ) -> usize {
        crate::runtime::runner::state_bridge::refresh_turn_boundary_with_inbox(
            session,
            Some(self.storage()),
            Some(self.persistence()),
            self.session_inbox(),
        )
        .await
        .merged
    }

    /// Confirm the durable admission boundary before entering provider execution.
    /// An ACK error is unresolved even after receipt publication. Preserve the
    /// checkpoint and existing claim recovery, but reject this activation.
    pub async fn admit_session_inbox_at_safe_boundary_checked(
        &self,
        session: &mut bamboo_agent_core::Session,
    ) -> Result<usize, bamboo_agent_core::AgentError> {
        let refresh = crate::runtime::runner::state_bridge::refresh_turn_boundary_with_inbox(
            session,
            Some(self.storage()),
            Some(self.persistence()),
            self.session_inbox(),
        )
        .await;
        if let Some(error) = refresh.admission_error {
            return Err(bamboo_agent_core::AgentError::Tool(error));
        }
        Ok(refresh.merged)
    }

    pub fn activation_router(
        &self,
    ) -> Option<&Arc<crate::session_activation::SessionActivationRouter>> {
        self.runtime.activation_router.as_ref()
    }

    pub fn session_messenger(&self) -> Option<&Arc<crate::SessionMessenger>> {
        self.runtime.session_messenger.as_ref()
    }

    /// Access the runtime's default tool executor (the root/full tool surface
    /// assembled at build time).
    ///
    /// Exposed so callers can compose additional one-off dispatches against the
    /// SAME executor the loop itself uses — e.g. re-executing a single
    /// previously-gated tool call after a permission approval — without forking
    /// or reaching into `AgentLoopConfig` (which stays unconstructible outside
    /// the engine). This is a read-only accessor alongside `storage()` /
    /// `persistence()`; it does not touch the sealed loop config.
    pub fn default_tools(&self) -> &Arc<dyn bamboo_agent_core::tools::ToolExecutor> {
        &self.runtime.default_tools
    }
}

// ---------------------------------------------------------------------------
// AgentBuilder
// ---------------------------------------------------------------------------

/// Builder for [`Agent`].
///
/// Delegates to [`AgentRuntimeBuilder`] internally.
pub struct AgentBuilder {
    inner: AgentRuntimeBuilder,
}

impl AgentBuilder {
    pub fn new() -> Self {
        Self {
            inner: AgentRuntimeBuilder::new(),
        }
    }

    pub fn storage(mut self, v: Arc<dyn bamboo_agent_core::storage::Storage>) -> Self {
        self.inner = self.inner.storage(v);
        self
    }

    pub fn persistence(mut self, v: Arc<dyn RuntimeSessionPersistence>) -> Self {
        self.inner = self.inner.persistence(v);
        self
    }

    pub fn session_inbox(mut self, v: Arc<dyn bamboo_domain::SessionInboxPort>) -> Self {
        self.inner = self.inner.session_inbox(v);
        self
    }

    pub fn activation_router(
        mut self,
        v: Arc<crate::session_activation::SessionActivationRouter>,
    ) -> Self {
        self.inner = self.inner.activation_router(v);
        self
    }

    pub fn session_messenger(mut self, v: Arc<crate::SessionMessenger>) -> Self {
        self.inner = self.inner.session_messenger(v);
        self
    }

    pub fn attachment_reader(
        mut self,
        v: Arc<dyn bamboo_agent_core::storage::AttachmentReader>,
    ) -> Self {
        self.inner = self.inner.attachment_reader(v);
        self
    }

    pub fn skill_manager(mut self, v: Arc<bamboo_skills::SkillManager>) -> Self {
        self.inner = self.inner.skill_manager(v);
        self
    }

    pub fn project_context_resolver(
        mut self,
        v: Arc<crate::project_context::ProjectContextResolver>,
    ) -> Self {
        self.inner = self.inner.project_context_resolver(v);
        self
    }

    pub fn metrics_collector(mut self, v: bamboo_metrics::MetricsCollector) -> Self {
        self.inner = self.inner.metrics_collector(v);
        self
    }

    pub fn config(mut self, v: Arc<tokio::sync::RwLock<bamboo_llm::Config>>) -> Self {
        self.inner = self.inner.config(v);
        self
    }

    /// Resolve model limits from a host-owned last-known-good section on each
    /// round instead of reopening the instance's configuration file.
    pub fn model_limits_section(
        mut self,
        section: Arc<bamboo_config::LiveSection<bamboo_config::ModelLimitsSection>>,
    ) -> Self {
        self.inner = self.inner.model_limits_section(section);
        self
    }

    pub fn permission_config(mut self, v: Arc<bamboo_tools::permission::PermissionConfig>) -> Self {
        self.inner = self.inner.permission_config(v);
        self
    }

    pub fn permission_mode(mut self, v: bamboo_domain::PermissionMode) -> Self {
        self.inner = self.inner.permission_mode(v);
        self
    }

    pub fn provider(mut self, v: Arc<dyn bamboo_llm::LLMProvider>) -> Self {
        self.inner = self.inner.provider(v);
        self
    }

    pub fn memory_store(mut self, v: bamboo_memory::memory_store::MemoryStore) -> Self {
        self.inner = self.inner.memory_store(v);
        self
    }

    pub fn default_tools(mut self, v: Arc<dyn bamboo_agent_core::tools::ToolExecutor>) -> Self {
        self.inner = self.inner.default_tools(v);
        self
    }

    /// Install an immutable lifecycle-hook registry for this agent runtime.
    pub fn hook_runner(mut self, v: Arc<crate::runtime::HookRunner>) -> Self {
        self.inner = self.inner.hook_runner(v);
        self
    }

    pub fn build(self) -> Result<Agent, &'static str> {
        let runtime = self.inner.build()?;
        Ok(Agent {
            runtime: Arc::new(runtime),
        })
    }
}

impl Default for AgentBuilder {
    fn default() -> Self {
        Self::new()
    }
}