mj_controller/controller/
subagents.rs1use std::path::{Component, Path, PathBuf};
4
5use anyhow::{Context, Result, bail, ensure};
6
7use super::{Controller, now};
8use mj_core::config::HarnessKind;
9use mj_core::state::{SessionRecord, SessionState, new_session_id};
10use mj_core::subagent::SubagentRecord;
11
12#[derive(Debug, Clone)]
13pub struct RegisterSubagentRequest {
14 pub parent_session_id: String,
15 pub task_name: String,
16 pub profile_id: String,
17 pub model: Option<String>,
18 pub effort: Option<String>,
19 pub working_directory: PathBuf,
21 pub initial_prompt: String,
22 pub request_key: String,
23}
24
25impl Controller {
26 pub fn register_subagent(
28 &mut self,
29 request: RegisterSubagentRequest,
30 ) -> Result<SubagentRecord> {
31 if let Some(existing) = crate::database::lookup_subagent_request(
32 &request.parent_session_id,
33 &request.request_key,
34 )? {
35 return Ok(existing);
36 }
37 ensure!(self.config.subagents.enabled, "sub-agents are disabled");
38 ensure!(
39 !request.request_key.trim().is_empty(),
40 "sub-agent request key cannot be empty"
41 );
42 ensure!(
43 !request.task_name.trim().is_empty(),
44 "sub-agent task name cannot be empty"
45 );
46 ensure!(
47 !request.initial_prompt.trim().is_empty(),
48 "sub-agent instructions cannot be empty"
49 );
50 ensure_safe_relative_directory(&request.working_directory)?;
51
52 let parent = self
53 .state
54 .sessions
55 .get(&request.parent_session_id)
56 .with_context(|| format!("unknown parent session {}", request.parent_session_id))?
57 .clone();
58 ensure!(
59 matches!(
60 parent.harness_kind,
61 HarnessKind::Claude | HarnessKind::Codex
62 ),
63 "only Claude and Codex sessions can spawn sub-agents"
64 );
65 ensure!(parent.state.is_active(), "parent session is not active");
66 ensure!(parent.target.is_some(), "parent session has no live target");
67 ensure!(
68 crate::database::load_subagent(&parent.id)?.is_none(),
69 "sub-agents cannot spawn other sub-agents"
70 );
71 ensure!(
72 self.config
73 .subagents
74 .profile_is_eligible(&parent.last_profile, &request.profile_id),
75 "profile {:?} is not eligible for sub-agent use",
76 request.profile_id
77 );
78 let profile = self
79 .config
80 .enabled_profile(&request.profile_id)
81 .with_context(|| {
82 format!("sub-agent profile {:?} is unavailable", request.profile_id)
83 })?;
84 if matches!(profile.kind, HarnessKind::Deepseek | HarnessKind::Muse) {
85 let multiple_roots = !parent.additional_mounts.is_empty()
86 || (parent.project_directory.is_none()
87 && self
88 .config
89 .bundles
90 .get(&parent.bundle_id)
91 .is_some_and(|bundle| bundle.repositories.len() > 1));
92 ensure!(
93 !multiple_roots,
94 "{} ACP supports one workspace root; this parent exposes multiple roots",
95 profile.kind.display_name()
96 );
97 }
98 let occupied = crate::database::list_subagents(&parent.id)?
99 .into_iter()
100 .filter(|child| {
101 self.subagent_occupies_slot(&child.child_session_id)
102 .unwrap_or(true)
103 })
104 .count();
105 ensure!(
106 occupied < self.config.subagents.max_concurrent,
107 "parent session already has the maximum {} active sub-agents",
108 self.config.subagents.max_concurrent
109 );
110
111 let child_id = new_session_id()?;
112 let target = borrowed_locator(
113 parent.target.as_ref().expect("live target checked above"),
114 &parent.id,
115 &child_id,
116 )?;
117 let created_at = now();
118 let session = SessionRecord {
119 create_managed_worktree: Some(false),
120 archived: false,
121 container_cpus: None,
122 container_memory: None,
123 id: child_id.clone(),
124 workspace_id: parent.workspace_id.clone(),
125 title: request.task_name.clone(),
126 harness_kind: profile.kind,
127 last_profile: request.profile_id.clone(),
128 bundle_id: parent.bundle_id.clone(),
129 project_directory: parent.project_directory.clone(),
130 managed_worktree: None,
131 target_template_id: parent.target_template_id.clone(),
132 resource_allocation: parent.resource_allocation.clone(),
133 additional_mounts: parent.additional_mounts.clone(),
134 state: SessionState::Provisioning,
135 target: Some(target),
136 native_session_id: None,
137 acp_session_title: None,
138 session_title_override: Some(request.task_name.clone()),
139 created_at: created_at.clone(),
140 updated_at: created_at.clone(),
141 viewed_through_event_ordinal: 0,
142 draft_input: String::new(),
143 last_error: None,
144 last_checkpoint_error: None,
145 checkpoint: None,
146 };
147 let relation = SubagentRecord {
148 child_session_id: child_id.clone(),
149 parent_session_id: parent.id,
150 task_name: request.task_name,
151 profile_id: request.profile_id,
152 model: request.model,
153 effort: request.effort,
154 working_directory: request.working_directory,
155 initial_prompt: request.initial_prompt,
156 request_key: request.request_key,
157 created_at,
158 delivered_turn: None,
159 };
160 crate::database::save_subagent_session(&session, &relation)?;
161 self.state.sessions.insert(child_id, session);
162 self.state
163 .subagents
164 .insert(relation.child_session_id.clone(), relation.clone());
165 Ok(relation)
166 }
167
168 pub fn ensure_subagent_slot_available(
169 &self,
170 parent_session_id: &str,
171 child_id: &str,
172 ) -> Result<()> {
173 let occupied = crate::database::list_subagents(parent_session_id)?
174 .into_iter()
175 .filter(|child| child.child_session_id != child_id)
176 .filter(|child| {
177 self.subagent_occupies_slot(&child.child_session_id)
178 .unwrap_or(true)
179 })
180 .count();
181 ensure!(
182 occupied < self.config.subagents.max_concurrent,
183 "parent session already has the maximum {} active sub-agents",
184 self.config.subagents.max_concurrent
185 );
186 Ok(())
187 }
188
189 fn subagent_occupies_slot(&self, child_id: &str) -> Result<bool> {
190 let Some(session) = self.state.sessions.get(child_id) else {
191 return Ok(false);
192 };
193 if matches!(
194 session.state,
195 SessionState::Provisioning | SessionState::Closing | SessionState::Checkpointing
196 ) {
197 return Ok(true);
198 }
199 if !session.state.is_active() {
200 return Ok(false);
201 }
202 Ok(
203 crate::database::load_materialized_session_summary(child_id)?.is_none_or(|summary| {
204 !matches!(
205 summary.execution,
206 mj_core::state::MaterializedExecutionState::Idle
207 )
208 }),
209 )
210 }
211}
212
213fn ensure_safe_relative_directory(path: &Path) -> Result<()> {
214 if path.is_absolute() || path.components().any(|part| part == Component::ParentDir) {
215 bail!("sub-agent working directory must be relative to the parent's workspace");
216 }
217 Ok(())
218}
219
220fn sibling_path(path: &Path, parent_id: &str, child_id: &str) -> Result<PathBuf> {
221 ensure!(
222 path.ends_with(parent_id),
223 "parent target path does not end in its session id"
224 );
225 Ok(path
226 .parent()
227 .context("parent target path has no parent")?
228 .join(child_id))
229}
230
231fn borrowed_locator(
232 target: &mj_core::state::TargetLocator,
233 parent_id: &str,
234 child_id: &str,
235) -> Result<mj_core::state::TargetLocator> {
236 use mj_core::state::TargetLocator;
237 Ok(match target {
238 TargetLocator::LocalBare { worker_root } => TargetLocator::LocalBare {
239 worker_root: sibling_path(worker_root, parent_id, child_id)?,
240 },
241 TargetLocator::SshBare {
242 host,
243 workspace,
244 worker_id: _,
245 } => TargetLocator::SshBare {
246 host: host.clone(),
247 workspace: workspace.clone(),
248 worker_id: Some(child_id.to_owned()),
249 },
250 other => other.clone(),
251 })
252}
253
254#[cfg(test)]
255mod tests {
256 use super::*;
257
258 #[test]
259 fn borrowed_bare_locator_gets_a_private_worker_identity() {
260 let locator = mj_core::state::TargetLocator::LocalBare {
261 worker_root: PathBuf::from("/workers/parent"),
262 };
263 assert_eq!(
264 borrowed_locator(&locator, "parent", "child").unwrap(),
265 mj_core::state::TargetLocator::LocalBare {
266 worker_root: PathBuf::from("/workers/child")
267 }
268 );
269 }
270
271 #[test]
272 fn borrowed_ssh_locator_keeps_parent_workspace_with_private_worker_identity() {
273 let locator = mj_core::state::TargetLocator::SshBare {
274 host: "builder".into(),
275 workspace: PathBuf::from(".local/share/hel/workspaces/parent-session"),
276 worker_id: None,
277 };
278 assert_eq!(
279 borrowed_locator(&locator, "parent-session", "child-session").unwrap(),
280 mj_core::state::TargetLocator::SshBare {
281 host: "builder".into(),
282 workspace: PathBuf::from(".local/share/hel/workspaces/parent-session"),
283 worker_id: Some("child-session".into()),
284 }
285 );
286 }
287}