Skip to main content

bamboo_engine/session_app/child_session/
mod.rs

1//! Child session management use cases.
2//!
3//! Provides the application-layer logic for managing child sessions within
4//! a root session. The server layer implements `ChildSessionPort` to supply
5//! the infrastructure operations (load, save, schedule, cancel).
6
7use async_trait::async_trait;
8use bamboo_domain::session::runtime_state::ChildWaitPolicy;
9use bamboo_domain::Session;
10use std::collections::HashMap;
11
12mod actions;
13mod helpers;
14
15#[cfg(test)]
16mod tests;
17
18pub use actions::{
19    assemble_session_tree, build_session_tree_action, cancel_child_action, create_child_action,
20    delete_child_action, get_child_action, list_children_action, run_child_action,
21    send_message_to_child_action, update_child_action, SessionTreeNode,
22};
23pub use helpers::{
24    compute_status_guidance, format_child_assignment, map_child_entry, metadata_text,
25    normalize_non_empty_optional, normalize_required_text, replace_or_append_last_user_message,
26    truncate_after_index, truncate_after_last_user,
27};
28
29// ---------------------------------------------------------------------------
30// Error type
31// ---------------------------------------------------------------------------
32
33#[derive(Debug, thiserror::Error)]
34pub enum ChildSessionError {
35    #[error("session not found: {0}")]
36    NotFound(String),
37    #[error("session is not a root session: {0}")]
38    NotRootSession(String),
39    #[error("session is not a child session: {0}")]
40    NotChildSession(String),
41    #[error("child session {child_id} does not belong to parent {parent_id}")]
42    NotChildOfParent { child_id: String, parent_id: String },
43    #[error("{0}")]
44    InvalidArguments(String),
45    #[error("{0}")]
46    Execution(String),
47}
48
49// ---------------------------------------------------------------------------
50// Value types
51// ---------------------------------------------------------------------------
52
53/// Summary of a child session for listing.
54#[derive(Debug, Clone)]
55pub struct ChildSessionEntry {
56    pub child_session_id: String,
57    pub title: String,
58    pub pinned: bool,
59    pub message_count: usize,
60    pub updated_at: String,
61    pub last_run_status: Option<String>,
62    pub last_run_error: Option<String>,
63}
64
65/// Result of deleting a child session.
66#[derive(Debug, Clone)]
67pub struct DeleteChildResult {
68    pub deleted: bool,
69    pub cancelled_running_child: bool,
70}
71
72/// Diagnostic snapshot of a running child session runner.
73#[derive(Debug, Clone)]
74pub struct ChildRunnerInfo {
75    pub started_at: Option<chrono::DateTime<chrono::Utc>>,
76    pub completed_at: Option<chrono::DateTime<chrono::Utc>>,
77    pub last_tool_name: Option<String>,
78    pub last_tool_phase: Option<String>,
79    pub last_event_at: Option<chrono::DateTime<chrono::Utc>>,
80    pub round_count: u32,
81}
82
83/// Short delegation note appended to the full root-style base prompt for a
84/// sub-agent. A sub-agent is a first-class agent (same base prompt + context
85/// enhancement as a top-level session); this note only frames the delegation
86/// relationship and the expected concise hand-back to the parent.
87pub const DELEGATION_NOTE: &str = r#"---
88
89You are running as a delegated sub-agent, spawned by a parent agent to handle a focused task. You have the full capabilities of a top-level agent, including the ability to spawn your own sub-agents when that helps. Stay focused on the assigned task, and when you finish, report a concise conclusion first (the parent receives your final message as the task result)."#;
90
91/// Input for creating a child session.
92#[derive(Debug, Clone)]
93pub struct CreateChildInput {
94    pub parent_session: Session,
95    pub child_id: String,
96    pub title: String,
97    pub responsibility: String,
98    pub assignment_prompt: String,
99    pub subagent_type: String,
100    /// Absolute path to the working directory for the child session.
101    pub workspace: String,
102    /// Optional model override resolved from subagent_type routing.
103    /// When `None`, the child inherits the parent session's model.
104    pub model_override: Option<String>,
105    /// Optional provider+model override resolved from subagent routing.
106    /// When present, this preserves cross-provider routing for child execution.
107    pub model_ref_override: Option<bamboo_domain::ProviderModelRef>,
108    /// Runtime metadata resolved from subagent routing (e.g. external agent config).
109    pub runtime_metadata: std::collections::HashMap<String, String>,
110    /// Whether to immediately enqueue the child for execution.
111    /// Defaults to `true`.
112    pub auto_run: bool,
113    /// Optional reasoning effort to apply to the child's own LLM calls.
114    /// `None` (the default) leaves `Session::reasoning_effort` at `None`,
115    /// so the provider falls back to its default. The child does NOT
116    /// inherit the parent's reasoning_effort — fan-out children that
117    /// only need a quick lookup should not pay for `xhigh` reasoning
118    /// just because the orchestrator is running at `xhigh`.
119    pub reasoning_effort: Option<bamboo_domain::ReasoningEffort>,
120    /// Lifecycle of this child: `Some("resident")` marks a reusable resident
121    /// agent (one stable session reused for successive tasks under the same
122    /// root); `None`/`Some("oneshot")` is the default throwaway child.
123    pub lifecycle: Option<String>,
124    /// For a resident agent, the stable reuse key (scoped to the root session).
125    pub resident_name: Option<String>,
126    /// For a resident agent, how successive tasks treat prior context:
127    /// `"reset"` (default — independent tasks) or `"accumulate"` (remember).
128    pub resident_context: Option<String>,
129    /// Tool names to disable for this child (denylist; matched by EXACT
130    /// `ToolSchema.function.name`). `None` (the default) = full toolset. A
131    /// read-only Guardian reviewer sets e.g. {"Edit","Write","SubAgent",...}.
132    /// Carried to the child's `SpawnJob.disabled_tools` via the child session
133    /// metadata (see `create_child_action`) so the worker trims its toolset.
134    pub disabled_tools: Option<std::collections::BTreeSet<String>>,
135    /// Model-controllable context fork (Phase 3): when `Some(n)` with `n > 0`,
136    /// the last `n` non-system parent messages are rendered into a "Forked
137    /// context from parent" block prepended to the child's task brief. `None`
138    /// (the default) keeps the child on a clean, freshly-seeded context.
139    pub context_fork: Option<usize>,
140}
141
142/// Result of creating a child session.
143#[derive(Debug, Clone)]
144pub struct CreateChildResult {
145    pub child_session_id: String,
146    pub model: String,
147}
148
149/// A queued follow-up message stored in session metadata for later injection.
150#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
151pub struct QueuedInjectedMessage {
152    pub content: String,
153    #[serde(default)]
154    pub created_at: Option<chrono::DateTime<chrono::Utc>>,
155}
156
157// ---------------------------------------------------------------------------
158// Port trait
159// ---------------------------------------------------------------------------
160
161#[async_trait]
162pub trait ChildSessionPort: Send + Sync {
163    /// Validate and normalize the child's workspace before any child/session
164    /// state is created. Server adapters override this with the authoritative
165    /// Project registry ownership check; non-server embeddings still apply the
166    /// shared confinement resolver.
167    async fn validate_child_workspace(
168        &self,
169        _project_id: Option<&bamboo_domain::ProjectId>,
170        requested_workspace: &str,
171    ) -> Result<String, ChildSessionError> {
172        normalize_child_workspace(requested_workspace)
173    }
174
175    async fn load_root_session(&self, root_id: &str) -> Result<Session, ChildSessionError>;
176    async fn load_child_for_parent(
177        &self,
178        parent_id: &str,
179        child_id: &str,
180    ) -> Result<Session, ChildSessionError>;
181    async fn save_child_session(&self, child: &mut Session) -> Result<(), ChildSessionError>;
182    /// Save a child session whose `agent_runtime_state` posture flags
183    /// (`bypass_permissions` / `no_human_approver`) the caller just set
184    /// authoritatively (the #74 resident-reuse re-seed) — persists them as-is
185    /// instead of adopting the child's stale on-disk value, unlike
186    /// [`Self::save_child_session`], which protects a concurrent `PATCH` to a
187    /// running child. Use ONLY right after deliberately writing those flags. #540.
188    async fn save_child_session_authoritative_flags(
189        &self,
190        child: &mut Session,
191    ) -> Result<(), ChildSessionError>;
192    /// Commit the live parent's posture plus a validated workspace when
193    /// reusing a resident. Persistence happens before the runtime workspace is
194    /// published, so a failed save cannot move tools onto an uncommitted path.
195    async fn save_resident_reuse_state(
196        &self,
197        child: &mut Session,
198        workspace: &str,
199    ) -> Result<(), ChildSessionError> {
200        child.workspace = Some(workspace.to_string());
201        child.set_workspace_path_meta(workspace);
202        self.save_child_session_authoritative_flags(child).await?;
203        bamboo_agent_core::workspace_state::publish_resolved_workspace(
204            &child.id,
205            std::path::PathBuf::from(workspace),
206        );
207        Ok(())
208    }
209    async fn is_child_running(&self, child_id: &str) -> bool;
210    async fn list_children(&self, parent_id: &str) -> Vec<ChildSessionEntry>;
211    async fn enqueue_child_run(
212        &self,
213        parent: &Session,
214        child: &Session,
215    ) -> Result<(), ChildSessionError>;
216    async fn cancel_child_run_and_wait(&self, child_id: &str) -> Result<(), ChildSessionError>;
217    async fn delete_child_session(
218        &self,
219        parent_id: &str,
220        child_id: &str,
221    ) -> Result<DeleteChildResult, ChildSessionError>;
222    /// Return live diagnostic info for a running child session, if available.
223    async fn get_child_runner_info(&self, child_id: &str) -> Option<ChildRunnerInfo>;
224
225    /// Register a durable parent wait for a single enqueued child. Idempotent
226    /// and coalesced per parent (concurrent sibling spawns merge into one write).
227    async fn register_parent_wait_for_child(
228        &self,
229        parent_session_id: &str,
230        child_session_id: &str,
231        tool_call_id: Option<&str>,
232    ) -> Result<(), ChildSessionError>;
233
234    /// Register a durable parent wait over an explicit set of children with a
235    /// chosen policy (the `SubAgent.wait` action). Returns the number of
236    /// children the wait now covers (0 = nothing to wait on).
237    async fn register_parent_wait_for_children(
238        &self,
239        parent_session_id: &str,
240        child_session_ids: &[String],
241        policy: ChildWaitPolicy,
242    ) -> Result<usize, ChildSessionError>;
243
244    /// The parent's currently-active (non-terminal) child session ids.
245    async fn active_child_ids(&self, parent_session_id: &str) -> Vec<String>;
246
247    /// The subset of `candidates` the session index POSITIVELY reports as
248    /// terminal children of this parent, as `(child_id, status)` pairs
249    /// (issue #546). `SubAgent.wait` uses this to avoid arming a wait over a
250    /// child that fires no further completion — and, policy-permitting, to
251    /// short-circuit a wait the terminal statuses already satisfy. Unknown
252    /// ids are NOT reported (index-less backends can't distinguish "terminal"
253    /// from "not yet indexed"); the child-wait watchdog rescues those at
254    /// runtime. Default: empty (no filtering).
255    async fn terminal_child_ids(
256        &self,
257        parent_session_id: &str,
258        candidates: &[String],
259    ) -> Vec<(String, String)> {
260        let _ = (parent_session_id, candidates);
261        Vec::new()
262    }
263
264    /// Find an existing resident agent in the same root tree by its stable
265    /// `resident_name`, returning its child session id if one exists. Used to
266    /// reuse a resident agent for a new task instead of minting a new child.
267    /// Index-backed (matches `root_session_id` + `metadata["resident_name"]`).
268    async fn find_resident_child(
269        &self,
270        root_session_id: &str,
271        resident_name: &str,
272    ) -> Option<String>;
273
274    /// Best-effort: ensure the child's session-index entry is visible
275    /// immediately after creation (the index is otherwise eventually
276    /// consistent). Failures are ignored by the caller.
277    async fn ensure_child_indexed(&self, child_session_id: &str);
278}
279
280fn normalize_child_workspace(requested_workspace: &str) -> Result<String, ChildSessionError> {
281    let requested_workspace = requested_workspace.trim();
282    if requested_workspace.is_empty() {
283        return Err(ChildSessionError::InvalidArguments(
284            "child workspace must be a non-empty path".to_string(),
285        ));
286    }
287    let requested = std::path::PathBuf::from(requested_workspace);
288    if requested.exists() && !requested.is_dir() {
289        return Err(ChildSessionError::InvalidArguments(format!(
290            "child workspace is not a directory: {requested_workspace}"
291        )));
292    }
293    let canonical = requested.canonicalize().unwrap_or(requested);
294    let final_workspace = bamboo_agent_core::workspace_state::resolve_workspace_path(canonical);
295    Ok(bamboo_config::paths::path_to_display_string(
296        &final_workspace,
297    ))
298}
299
300// ---------------------------------------------------------------------------
301// Subagent resolution port
302// ---------------------------------------------------------------------------
303
304/// Resolves subagent-type–specific configuration (model, runtime metadata)
305/// for the `SubAgent` tool.
306///
307/// Kept separate from [`ChildSessionPort`] (session CRUD/lifecycle/state): this
308/// port is pure `subagent_type` → config resolution (cross-provider model
309/// routing + actor/external-agent metadata). The server layer implements it;
310/// the tool depends only on the trait, carrying no `AppState` coupling.
311#[async_trait]
312pub trait SubagentResolutionPort: Send + Sync {
313    /// Provider+model ref for a `subagent_type`, or `None` to use defaults.
314    async fn resolve_subagent_model(
315        &self,
316        subagent_type: &str,
317    ) -> Option<bamboo_domain::ProviderModelRef>;
318
319    /// Runtime metadata (e.g. external-agent routing) for a `subagent_type`.
320    async fn resolve_runtime_metadata(&self, subagent_type: &str) -> HashMap<String, String>;
321}
322
323/// Models available from one configured provider (best-effort listing).
324#[derive(Debug, Clone, serde::Serialize)]
325pub struct ProviderModelList {
326    pub provider: String,
327    pub models: Vec<String>,
328    /// Set when this provider's listing failed (auth missing, network, …);
329    /// the provider is still usable with an explicitly known model id.
330    #[serde(skip_serializing_if = "Option::is_none")]
331    pub error: Option<String>,
332}
333
334/// Lists the models the parent can pin a child session to
335/// (`SubAgent` tool `action=list_models` / `create.model`).
336///
337/// Separate from [`SubagentResolutionPort`] because it is backed by the live
338/// provider registry rather than per-`subagent_type` config resolution.
339#[async_trait]
340pub trait ModelCatalogPort: Send + Sync {
341    /// Best-effort model listing per configured provider. Providers whose
342    /// listing fails are still returned (with `error` set) so the caller can
343    /// see they exist.
344    async fn list_models(&self) -> Vec<ProviderModelList>;
345
346    /// The default provider name (used to resolve a bare model id without a
347    /// `provider:` prefix).
348    fn default_provider(&self) -> String;
349}