Skip to main content

mj_controller/controller/
subagents.rs

1//! Registration and ownership rules for child sessions on a parent's target.
2
3use std::path::{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    /// Empty means the parent's working directory. An absolute path is used
20    /// as-is; a relative path is resolved against the parent's working
21    /// directory. The path is interpreted on the parent's target and must
22    /// exist there; no other restriction applies.
23    pub working_directory: PathBuf,
24    pub initial_prompt: String,
25    pub request_key: String,
26}
27
28impl Controller {
29    /// Register a child without provisioning another target or checkout.
30    pub fn register_subagent(
31        &mut self,
32        request: RegisterSubagentRequest,
33    ) -> Result<SubagentRecord> {
34        if let Some(existing) = crate::database::lookup_subagent_request(
35            &request.parent_session_id,
36            &request.request_key,
37        )? {
38            return Ok(existing);
39        }
40        ensure!(
41            !request.request_key.trim().is_empty(),
42            "sub-agent request key cannot be empty"
43        );
44        ensure!(
45            !request.task_name.trim().is_empty(),
46            "sub-agent task name cannot be empty"
47        );
48        ensure!(
49            !request.initial_prompt.trim().is_empty(),
50            "sub-agent instructions cannot be empty"
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_may_delegate(&parent, self.config.subagents.enabled)?;
66        ensure!(parent.state.is_active(), "parent session is not active");
67        ensure!(parent.target.is_some(), "parent session has no live target");
68        ensure!(
69            crate::database::load_subagent(&parent.id)?.is_none(),
70            "sub-agents cannot spawn other sub-agents"
71        );
72        ensure!(
73            self.config
74                .subagents
75                .profile_is_eligible(&parent.last_profile, &request.profile_id),
76            "profile {:?} is not eligible for sub-agent use",
77            request.profile_id
78        );
79        let profile = self
80            .config
81            .enabled_profile(&request.profile_id)
82            .with_context(|| {
83                format!("sub-agent profile {:?} is unavailable", request.profile_id)
84            })?;
85        if profile.kind == HarnessKind::Muse {
86            let multiple_roots = !parent.additional_mounts.is_empty()
87                || (parent.project_directory.is_none()
88                    && self
89                        .config
90                        .bundles
91                        .get(&parent.bundle_id)
92                        .is_some_and(|bundle| bundle.repositories.len() > 1));
93            ensure!(
94                !multiple_roots,
95                "{} ACP supports one workspace root; this parent exposes multiple roots",
96                profile.kind.display_name()
97            );
98        }
99        let occupied = crate::database::list_subagents(&parent.id)?
100            .into_iter()
101            .filter(|child| {
102                self.subagent_occupies_slot(&child.child_session_id)
103                    .unwrap_or(true)
104            })
105            .count();
106        ensure!(
107            occupied < self.config.subagents.max_concurrent,
108            "parent session already has the maximum {} active sub-agents",
109            self.config.subagents.max_concurrent
110        );
111
112        let child_id = new_session_id()?;
113        let target = borrowed_locator(
114            parent.target.as_ref().expect("live target checked above"),
115            &parent.id,
116            &child_id,
117        )?;
118        let created_at = now();
119        let session = SessionRecord {
120            // A child shares its parent's container, so it shares the build
121            // cache that container was created with.
122            build_cache: parent.build_cache.clone(),
123            // A child never receives the Mjolnir sub-agent tools, so it can
124            // never spawn a grandchild.
125            mjolnir_subagents: Some(false),
126            create_managed_worktree: Some(false),
127            archived: false,
128            container_cpus: None,
129            container_memory: None,
130            // A child runs inside its parent's container, so it works in the
131            // parent's workspace, including the legacy shared one.
132            container_workspace: parent.container_workspace.clone(),
133            id: child_id.clone(),
134            workspace_id: parent.workspace_id.clone(),
135            title: request.task_name.clone(),
136            harness_kind: profile.kind,
137            last_profile: request.profile_id.clone(),
138            bundle_id: parent.bundle_id.clone(),
139            project_directory: parent.project_directory.clone(),
140            managed_worktree: None,
141            target_template_id: parent.target_template_id.clone(),
142            resource_allocation: parent.resource_allocation.clone(),
143            additional_mounts: parent.additional_mounts.clone(),
144            state: SessionState::Provisioning,
145            target: Some(target),
146            native_session_id: None,
147            acp_session_title: None,
148            session_title_override: Some(request.task_name.clone()),
149            created_at: created_at.clone(),
150            updated_at: created_at.clone(),
151            viewed_through_event_ordinal: 0,
152            draft_input: String::new(),
153            last_error: None,
154            last_checkpoint_error: None,
155            checkpoint: None,
156        };
157        let relation = SubagentRecord {
158            child_session_id: child_id.clone(),
159            parent_session_id: parent.id,
160            task_name: request.task_name,
161            profile_id: request.profile_id,
162            model: request.model,
163            effort: request.effort,
164            working_directory: request.working_directory,
165            initial_prompt: request.initial_prompt,
166            request_key: request.request_key,
167            created_at,
168            noticed_turn: None,
169        };
170        crate::database::save_subagent_session(&session, &relation)?;
171        self.state.sessions.insert(child_id, session);
172        self.state
173            .subagents
174            .insert(relation.child_session_id.clone(), relation.clone());
175        Ok(relation)
176    }
177
178    pub fn ensure_subagent_slot_available(
179        &self,
180        parent_session_id: &str,
181        child_id: &str,
182    ) -> Result<()> {
183        let occupied = crate::database::list_subagents(parent_session_id)?
184            .into_iter()
185            .filter(|child| child.child_session_id != child_id)
186            .filter(|child| {
187                self.subagent_occupies_slot(&child.child_session_id)
188                    .unwrap_or(true)
189            })
190            .count();
191        ensure!(
192            occupied < self.config.subagents.max_concurrent,
193            "parent session already has the maximum {} active sub-agents",
194            self.config.subagents.max_concurrent
195        );
196        Ok(())
197    }
198
199    fn subagent_occupies_slot(&self, child_id: &str) -> Result<bool> {
200        let Some(session) = self.state.sessions.get(child_id) else {
201            return Ok(false);
202        };
203        if matches!(
204            session.state,
205            SessionState::Provisioning | SessionState::Closing | SessionState::Checkpointing
206        ) {
207            return Ok(true);
208        }
209        if !session.state.is_active() {
210            return Ok(false);
211        }
212        Ok(
213            crate::database::load_materialized_session_summary(child_id)?.is_none_or(|summary| {
214                !matches!(
215                    summary.execution,
216                    mj_core::state::MaterializedExecutionState::Idle
217                )
218            }),
219        )
220    }
221}
222
223fn sibling_path(path: &Path, parent_id: &str, child_id: &str) -> Result<PathBuf> {
224    ensure!(
225        path.ends_with(parent_id),
226        "parent target path does not end in its session id"
227    );
228    Ok(path
229        .parent()
230        .context("parent target path has no parent")?
231        .join(child_id))
232}
233
234fn borrowed_locator(
235    target: &mj_core::state::TargetLocator,
236    parent_id: &str,
237    child_id: &str,
238) -> Result<mj_core::state::TargetLocator> {
239    use mj_core::state::TargetLocator;
240    Ok(match target {
241        TargetLocator::LocalBare { worker_root } => TargetLocator::LocalBare {
242            worker_root: sibling_path(worker_root, parent_id, child_id)?,
243        },
244        TargetLocator::SshBare {
245            host,
246            workspace,
247            worker_id: _,
248        } => TargetLocator::SshBare {
249            host: host.clone(),
250            workspace: workspace.clone(),
251            worker_id: Some(child_id.to_owned()),
252        },
253        // A container child runs its own worker inside the parent's container
254        // and records the parent as the container's owner, so cleanup and
255        // whole-target operations stay with the parent.
256        TargetLocator::LocalPodman {
257            container_id,
258            workspace_storage,
259            ..
260        } => TargetLocator::LocalPodman {
261            container_id: container_id.clone(),
262            workspace_storage: workspace_storage.clone(),
263            borrowed_from: Some(parent_id.to_owned()),
264        },
265        TargetLocator::LocalDocker { container_id, .. } => TargetLocator::LocalDocker {
266            container_id: container_id.clone(),
267            borrowed_from: Some(parent_id.to_owned()),
268        },
269        TargetLocator::AppleContainer { container_id, .. } => TargetLocator::AppleContainer {
270            container_id: container_id.clone(),
271            borrowed_from: Some(parent_id.to_owned()),
272        },
273        TargetLocator::SshPodman {
274            host,
275            container_id,
276            workspace_storage,
277            ..
278        } => TargetLocator::SshPodman {
279            host: host.clone(),
280            container_id: container_id.clone(),
281            workspace_storage: workspace_storage.clone(),
282            borrowed_from: Some(parent_id.to_owned()),
283        },
284        TargetLocator::SshDocker {
285            host, container_id, ..
286        } => TargetLocator::SshDocker {
287            host: host.clone(),
288            container_id: container_id.clone(),
289            borrowed_from: Some(parent_id.to_owned()),
290        },
291        // EC2 children keep the parent's locator unchanged, as they did before
292        // container borrowing was recorded.
293        other @ TargetLocator::AwsEc2 { .. } => other.clone(),
294    })
295}
296
297/// A parent may delegate to Mjolnir children only if its own stored choice
298/// says so; `None` follows the global `[subagents] enabled` setting. A parent
299/// using its harness's native delegation never received the Mjolnir tools, so
300/// a request from it is stale.
301fn ensure_parent_may_delegate(parent: &SessionRecord, global_enabled: bool) -> Result<()> {
302    match parent.mjolnir_subagents {
303        Some(false) => bail!("this session uses native sub-agents"),
304        None if !global_enabled => bail!("sub-agents are disabled"),
305        _ => Ok(()),
306    }
307}
308
309#[cfg(test)]
310mod tests {
311    use super::*;
312
313    #[test]
314    fn a_container_child_borrows_its_parents_container() {
315        use mj_core::state::{PodmanWorkspaceLocator, TargetLocator};
316
317        let parent_id = "0123456789abcdef0123456789abcdef";
318        let child_id = "fedcba9876543210fedcba9876543210";
319        let container = mj_core::targets::resource_name(parent_id).unwrap();
320
321        let local = borrowed_locator(
322            &TargetLocator::LocalPodman {
323                container_id: container.clone(),
324                workspace_storage: PodmanWorkspaceLocator::Volume {
325                    name: "parent-volume".to_owned(),
326                },
327                borrowed_from: None,
328            },
329            parent_id,
330            child_id,
331        )
332        .unwrap();
333        assert_eq!(
334            local,
335            TargetLocator::LocalPodman {
336                container_id: container.clone(),
337                workspace_storage: PodmanWorkspaceLocator::Volume {
338                    name: "parent-volume".to_owned(),
339                },
340                borrowed_from: Some(parent_id.to_owned()),
341            }
342        );
343
344        let remote = borrowed_locator(
345            &TargetLocator::SshPodman {
346                host: "builder".to_owned(),
347                container_id: container.clone(),
348                workspace_storage: PodmanWorkspaceLocator::ContainerLayer,
349                borrowed_from: None,
350            },
351            parent_id,
352            child_id,
353        )
354        .unwrap();
355        assert_eq!(
356            remote,
357            TargetLocator::SshPodman {
358                host: "builder".to_owned(),
359                container_id: container,
360                workspace_storage: PodmanWorkspaceLocator::ContainerLayer,
361                borrowed_from: Some(parent_id.to_owned()),
362            }
363        );
364    }
365
366    #[test]
367    fn a_parent_using_native_delegation_cannot_spawn_mjolnir_children() {
368        let parent = |choice| {
369            let mut session = crate::controller::test_support::checkpoint_test_session("parent");
370            session.mjolnir_subagents = choice;
371            session
372        };
373
374        assert_eq!(
375            ensure_parent_may_delegate(&parent(Some(false)), true)
376                .unwrap_err()
377                .to_string(),
378            "this session uses native sub-agents"
379        );
380        assert_eq!(
381            ensure_parent_may_delegate(&parent(None), false)
382                .unwrap_err()
383                .to_string(),
384            "sub-agents are disabled"
385        );
386        // An explicit opt-in outlives the global setting being turned off.
387        assert!(ensure_parent_may_delegate(&parent(Some(true)), false).is_ok());
388        assert!(ensure_parent_may_delegate(&parent(None), true).is_ok());
389    }
390
391    #[test]
392    fn borrowed_bare_locator_gets_a_private_worker_identity() {
393        let locator = mj_core::state::TargetLocator::LocalBare {
394            worker_root: PathBuf::from("/workers/parent"),
395        };
396        assert_eq!(
397            borrowed_locator(&locator, "parent", "child").unwrap(),
398            mj_core::state::TargetLocator::LocalBare {
399                worker_root: PathBuf::from("/workers/child")
400            }
401        );
402    }
403
404    #[test]
405    fn borrowed_ssh_locator_keeps_parent_workspace_with_private_worker_identity() {
406        let locator = mj_core::state::TargetLocator::SshBare {
407            host: "builder".into(),
408            workspace: PathBuf::from(".local/share/hel/workspaces/parent-session"),
409            worker_id: None,
410        };
411        assert_eq!(
412            borrowed_locator(&locator, "parent-session", "child-session").unwrap(),
413            mj_core::state::TargetLocator::SshBare {
414                host: "builder".into(),
415                workspace: PathBuf::from(".local/share/hel/workspaces/parent-session"),
416                worker_id: Some("child-session".into()),
417            }
418        );
419    }
420}