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 async fn load_root_session(&self, root_id: &str) -> Result<Session, ChildSessionError>;
164 async fn load_child_for_parent(
165 &self,
166 parent_id: &str,
167 child_id: &str,
168 ) -> Result<Session, ChildSessionError>;
169 async fn save_child_session(&self, child: &mut Session) -> Result<(), ChildSessionError>;
170 /// Save a child session whose `agent_runtime_state` posture flags
171 /// (`bypass_permissions` / `no_human_approver`) the caller just set
172 /// authoritatively (the #74 resident-reuse re-seed) — persists them as-is
173 /// instead of adopting the child's stale on-disk value, unlike
174 /// [`Self::save_child_session`], which protects a concurrent `PATCH` to a
175 /// running child. Use ONLY right after deliberately writing those flags. #540.
176 async fn save_child_session_authoritative_flags(
177 &self,
178 child: &mut Session,
179 ) -> Result<(), ChildSessionError>;
180 async fn is_child_running(&self, child_id: &str) -> bool;
181 async fn list_children(&self, parent_id: &str) -> Vec<ChildSessionEntry>;
182 async fn enqueue_child_run(
183 &self,
184 parent: &Session,
185 child: &Session,
186 ) -> Result<(), ChildSessionError>;
187 async fn cancel_child_run_and_wait(&self, child_id: &str) -> Result<(), ChildSessionError>;
188 async fn delete_child_session(
189 &self,
190 parent_id: &str,
191 child_id: &str,
192 ) -> Result<DeleteChildResult, ChildSessionError>;
193 /// Return live diagnostic info for a running child session, if available.
194 async fn get_child_runner_info(&self, child_id: &str) -> Option<ChildRunnerInfo>;
195
196 /// Register a durable parent wait for a single enqueued child. Idempotent
197 /// and coalesced per parent (concurrent sibling spawns merge into one write).
198 async fn register_parent_wait_for_child(
199 &self,
200 parent_session_id: &str,
201 child_session_id: &str,
202 tool_call_id: Option<&str>,
203 ) -> Result<(), ChildSessionError>;
204
205 /// Register a durable parent wait over an explicit set of children with a
206 /// chosen policy (the `SubAgent.wait` action). Returns the number of
207 /// children the wait now covers (0 = nothing to wait on).
208 async fn register_parent_wait_for_children(
209 &self,
210 parent_session_id: &str,
211 child_session_ids: &[String],
212 policy: ChildWaitPolicy,
213 ) -> Result<usize, ChildSessionError>;
214
215 /// The parent's currently-active (non-terminal) child session ids.
216 async fn active_child_ids(&self, parent_session_id: &str) -> Vec<String>;
217
218 /// The subset of `candidates` the session index POSITIVELY reports as
219 /// terminal children of this parent, as `(child_id, status)` pairs
220 /// (issue #546). `SubAgent.wait` uses this to avoid arming a wait over a
221 /// child that fires no further completion — and, policy-permitting, to
222 /// short-circuit a wait the terminal statuses already satisfy. Unknown
223 /// ids are NOT reported (index-less backends can't distinguish "terminal"
224 /// from "not yet indexed"); the child-wait watchdog rescues those at
225 /// runtime. Default: empty (no filtering).
226 async fn terminal_child_ids(
227 &self,
228 parent_session_id: &str,
229 candidates: &[String],
230 ) -> Vec<(String, String)> {
231 let _ = (parent_session_id, candidates);
232 Vec::new()
233 }
234
235 /// Find an existing resident agent in the same root tree by its stable
236 /// `resident_name`, returning its child session id if one exists. Used to
237 /// reuse a resident agent for a new task instead of minting a new child.
238 /// Index-backed (matches `root_session_id` + `metadata["resident_name"]`).
239 async fn find_resident_child(
240 &self,
241 root_session_id: &str,
242 resident_name: &str,
243 ) -> Option<String>;
244
245 /// Best-effort: ensure the child's session-index entry is visible
246 /// immediately after creation (the index is otherwise eventually
247 /// consistent). Failures are ignored by the caller.
248 async fn ensure_child_indexed(&self, child_session_id: &str);
249}
250
251// ---------------------------------------------------------------------------
252// Subagent resolution port
253// ---------------------------------------------------------------------------
254
255/// Resolves subagent-type–specific configuration (model, runtime metadata)
256/// for the `SubAgent` tool.
257///
258/// Kept separate from [`ChildSessionPort`] (session CRUD/lifecycle/state): this
259/// port is pure `subagent_type` → config resolution (cross-provider model
260/// routing + actor/external-agent metadata). The server layer implements it;
261/// the tool depends only on the trait, carrying no `AppState` coupling.
262#[async_trait]
263pub trait SubagentResolutionPort: Send + Sync {
264 /// Provider+model ref for a `subagent_type`, or `None` to use defaults.
265 async fn resolve_subagent_model(
266 &self,
267 subagent_type: &str,
268 ) -> Option<bamboo_domain::ProviderModelRef>;
269
270 /// Runtime metadata (e.g. external-agent routing) for a `subagent_type`.
271 async fn resolve_runtime_metadata(&self, subagent_type: &str) -> HashMap<String, String>;
272}
273
274/// Models available from one configured provider (best-effort listing).
275#[derive(Debug, Clone, serde::Serialize)]
276pub struct ProviderModelList {
277 pub provider: String,
278 pub models: Vec<String>,
279 /// Set when this provider's listing failed (auth missing, network, …);
280 /// the provider is still usable with an explicitly known model id.
281 #[serde(skip_serializing_if = "Option::is_none")]
282 pub error: Option<String>,
283}
284
285/// Lists the models the parent can pin a child session to
286/// (`SubAgent` tool `action=list_models` / `create.model`).
287///
288/// Separate from [`SubagentResolutionPort`] because it is backed by the live
289/// provider registry rather than per-`subagent_type` config resolution.
290#[async_trait]
291pub trait ModelCatalogPort: Send + Sync {
292 /// Best-effort model listing per configured provider. Providers whose
293 /// listing fails are still returned (with `error` set) so the caller can
294 /// see they exist.
295 async fn list_models(&self) -> Vec<ProviderModelList>;
296
297 /// The default provider name (used to resolve a bare model id without a
298 /// `provider:` prefix).
299 fn default_provider(&self) -> String;
300}