Skip to main content

merry_runtime/subagent/
manager.rs

1use super::child::{error_info, publish_terminal_activity_snapshot};
2use super::events::{
3    PersistedSubagentRecord, SubagentEventSink, emit_terminal_event_and_persist,
4    to_public_subagent_status,
5};
6use super::protocol::{
7    RejectedSubagentView, SpawnSubagentsOutput, SpawnedSubagentStatusLabel, SpawnedSubagentView,
8    WaitMode, WaitSubagentsOutput,
9};
10use super::scheduler::{self, ChildScheduler, ReservedChildStart};
11use super::scheduler::{
12    batch_running_child_count, reserve_queued_starts_locked, running_child_count,
13};
14use super::scope::ParentCapabilities;
15use super::spec::{validate_no_write_scope_conflicts, validate_task_max_model_turns};
16use super::{
17    ChildRuntimeFactory, ChildWorkspaceLifecycle, ChildWorkspaceScope, ParentPrimaryModel,
18    SubagentActivityHub, SubagentConfig, SubagentError, SubagentLimitBehavior, SubagentResultView,
19    SubagentStatusLabel, SubagentStatusView, SubagentTaskSpec, SubagentWorktreeView,
20};
21use crate::{FileSessionStore, RuntimeError, TaskAnchor};
22use merry_core::{ErrorInfo, SubagentActivityPhase, SubagentId, SubagentTaskId, ToolName};
23use std::{
24    collections::{BTreeMap, VecDeque},
25    sync::{
26        Arc, Mutex as StdMutex,
27        atomic::{AtomicBool, AtomicU32, AtomicU64, AtomicUsize, Ordering},
28    },
29    time::Duration,
30};
31use tokio::sync::{Mutex, Notify, broadcast};
32use tokio_util::sync::CancellationToken;
33
34pub(super) const SUBAGENT_EVENT_CHANNEL_CAPACITY: usize = 256;
35
36/// Lazy inspection handle returned when a product surface drills into a subagent.
37pub struct SubagentInspectSession {
38    /// Current compact status snapshot for the subagent.
39    pub status: SubagentStatusView,
40    /// Original delegated task prompt.
41    pub task: String,
42    /// Durable transcript items recorded in the child runtime so far.
43    pub transcript: Vec<crate::SessionTranscriptItem>,
44    /// Live runtime event stream emitted while the child executes.
45    pub events: broadcast::Receiver<merry_core::RuntimeEvent>,
46}
47
48/// Runtime-owned manager for bounded child agent execution.
49#[derive(Clone)]
50pub struct SubagentManager {
51    pub(super) parent_session_id: merry_core::SessionId,
52    pub(super) enabled: Arc<AtomicBool>,
53    pub(super) max_threads: Arc<AtomicUsize>,
54    pub(super) min_model_turns: Arc<AtomicU32>,
55    pub(super) max_model_turns: Arc<AtomicU32>,
56    pub(super) default_timeout_secs: Arc<AtomicU64>,
57    pub(super) foreground_wait_budget_secs: Arc<AtomicU64>,
58    pub(super) max_total_tokens: Arc<AtomicU64>,
59    pub(super) limit_behavior: Arc<StdMutex<SubagentLimitBehavior>>,
60    pub(super) has_agents: Arc<AtomicBool>,
61    pub(super) factory: Arc<dyn ChildRuntimeFactory>,
62    pub(super) state: Arc<Mutex<SubagentManagerState>>,
63    pub(super) notify: Arc<Notify>,
64    pub(super) completion_notifications: Arc<Mutex<VecDeque<SubagentStatusView>>>,
65    pub(super) completion_notify: Arc<Notify>,
66    pub(super) next_id: Arc<AtomicU64>,
67    pub(super) next_batch_id: Arc<AtomicU64>,
68    pub(super) depth: u8,
69    pub(super) max_depth: u8,
70    pub(super) parent_capabilities: Arc<StdMutex<Option<ParentCapabilities>>>,
71    pub(super) activity_hub: Arc<StdMutex<Option<Arc<SubagentActivityHub>>>>,
72    pub(super) event_sink: Arc<StdMutex<Option<SubagentEventSink>>>,
73    pub(super) child_session_store: Arc<StdMutex<Option<FileSessionStore>>>,
74    pub(super) live_parent_model: Arc<StdMutex<Option<ParentPrimaryModel>>>,
75    pub(super) live_parent_generation: Arc<StdMutex<merry_llm::GenerationConfig>>,
76    pub(super) session_token: CancellationToken,
77}
78
79#[derive(Default)]
80pub(super) struct SubagentManagerState {
81    pub(super) agents: BTreeMap<SubagentId, ManagedSubagent>,
82    pub(super) batches: BTreeMap<u64, SubagentBatch>,
83    pub(super) handles: BTreeMap<SubagentId, tokio::task::JoinHandle<()>>,
84}
85
86#[derive(Debug, Clone)]
87pub(super) struct SubagentBatch {
88    pub(super) max_concurrency: usize,
89}
90pub(super) async fn enqueue_completion_notification_if_needed(
91    state: &Arc<Mutex<SubagentManagerState>>,
92    completion_notifications: &Arc<Mutex<VecDeque<SubagentStatusView>>>,
93    completion_notify: &Arc<Notify>,
94    status: SubagentStatusView,
95) {
96    // Queue and acknowledgement paths all take these locks in this order. The
97    // state check closes the race where wait() observes a terminal child just
98    // before its completion notification is enqueued.
99    let mut notifications = completion_notifications.lock().await;
100    let state_guard = state.lock().await;
101    if state_guard
102        .agents
103        .get(&status.agent_id)
104        .is_some_and(|agent| agent.completion_notification_acknowledged)
105    {
106        return;
107    }
108    notifications.push_back(status);
109    drop(state_guard);
110    drop(notifications);
111    completion_notify.notify_waiters();
112}
113#[derive(Clone)]
114pub(super) struct ManagedSubagent {
115    pub(super) batch_id: u64,
116    pub(super) agent_id: SubagentId,
117    pub(super) task_id: SubagentTaskId,
118    pub(super) task: SubagentTaskSpec,
119    pub(super) task_anchor: TaskAnchor,
120    pub(super) status: SubagentStatusLabel,
121    pub(super) summary: String,
122    pub(super) result: Option<SubagentResultView>,
123    pub(super) output_paths: Vec<String>,
124    pub(super) changed_paths: Vec<String>,
125    pub(super) diagnostics: Option<ErrorInfo>,
126    pub(super) cancellation_token: CancellationToken,
127    pub(super) completion_notification_acknowledged: bool,
128    pub(super) runtime: Option<crate::Runtime>,
129    pub(super) generation_config: Option<merry_llm::GenerationConfig>,
130    pub(super) event_tx: broadcast::Sender<merry_core::RuntimeEvent>,
131    pub(super) pending_follow_ups: VecDeque<String>,
132    pub(super) resume_turn_override: Option<u32>,
133    pub(super) started_at: Option<tokio::time::Instant>,
134    pub(super) turns_used: u32,
135    pub(super) tool_calls: u32,
136    pub(super) elapsed_ms: u64,
137    pub(super) usage: Option<merry_core::ModelUsage>,
138    pub(super) raw_output_bytes: u64,
139    pub(super) workspace_lifecycle: Option<Arc<dyn ChildWorkspaceLifecycle>>,
140    pub(super) worktree: Option<SubagentWorktreeView>,
141}
142
143impl SubagentManager {
144    /// Creates a subagent manager for one parent session.
145    #[must_use]
146    pub fn new(
147        parent_session_id: merry_core::SessionId,
148        config: SubagentConfig,
149        factory: Arc<dyn ChildRuntimeFactory>,
150    ) -> Self {
151        Self::runtime_controlled(parent_session_id, config, factory, true)
152    }
153
154    /// Creates a manager whose spawn policy can be changed by interactive runtime control.
155    #[must_use]
156    pub fn runtime_controlled(
157        parent_session_id: merry_core::SessionId,
158        config: SubagentConfig,
159        factory: Arc<dyn ChildRuntimeFactory>,
160        enabled: bool,
161    ) -> Self {
162        Self::runtime_controlled_at_depth(parent_session_id, config, factory, enabled, 0)
163    }
164
165    /// Creates a manager for a child runtime at a known delegation depth.
166    #[must_use]
167    pub fn runtime_controlled_at_depth(
168        parent_session_id: merry_core::SessionId,
169        config: SubagentConfig,
170        factory: Arc<dyn ChildRuntimeFactory>,
171        enabled: bool,
172        depth: u8,
173    ) -> Self {
174        Self {
175            parent_session_id,
176            enabled: Arc::new(AtomicBool::new(enabled)),
177            max_threads: Arc::new(AtomicUsize::new(config.max_threads())),
178            min_model_turns: Arc::new(AtomicU32::new(config.min_model_turns())),
179            max_model_turns: Arc::new(AtomicU32::new(config.max_model_turns())),
180            default_timeout_secs: Arc::new(AtomicU64::new(
181                config.default_timeout_secs().unwrap_or(0),
182            )),
183            foreground_wait_budget_secs: Arc::new(AtomicU64::new(
184                config.foreground_wait_budget_secs(),
185            )),
186            max_total_tokens: Arc::new(AtomicU64::new(config.max_total_tokens().unwrap_or(0))),
187            limit_behavior: Arc::new(StdMutex::new(config.limit_behavior())),
188            has_agents: Arc::new(AtomicBool::new(false)),
189            factory,
190            state: Arc::new(Mutex::new(SubagentManagerState::default())),
191            notify: Arc::new(Notify::new()),
192            completion_notifications: Arc::new(Mutex::new(VecDeque::new())),
193            completion_notify: Arc::new(Notify::new()),
194            next_id: Arc::new(AtomicU64::new(1)),
195            next_batch_id: Arc::new(AtomicU64::new(1)),
196            depth,
197            max_depth: config.max_depth(),
198            parent_capabilities: Arc::new(StdMutex::new(None)),
199            activity_hub: Arc::new(StdMutex::new(None)),
200            event_sink: Arc::new(StdMutex::new(None)),
201            child_session_store: Arc::new(StdMutex::new(None)),
202            live_parent_model: Arc::new(StdMutex::new(None)),
203            live_parent_generation: Arc::new(StdMutex::new(merry_llm::GenerationConfig::default())),
204            session_token: CancellationToken::new(),
205        }
206    }
207
208    /// Updates the live parent primary model snapshot read when building new children.
209    pub(crate) fn update_parent_primary_model(&self, model: ParentPrimaryModel) {
210        *self
211            .live_parent_model
212            .lock()
213            .expect("subagent live parent model mutex is not poisoned") = Some(model);
214    }
215
216    /// Updates the live parent generation config snapshot read when building new children.
217    pub(crate) fn update_parent_generation_config(&self, config: merry_llm::GenerationConfig) {
218        *self
219            .live_parent_generation
220            .lock()
221            .expect("subagent live parent generation mutex is not poisoned") = config;
222    }
223
224    pub(super) fn live_parent_model_snapshot(&self) -> Option<ParentPrimaryModel> {
225        self.live_parent_model
226            .lock()
227            .expect("subagent live parent model mutex is not poisoned")
228            .clone()
229    }
230
231    pub(super) fn live_parent_generation_snapshot(&self) -> merry_llm::GenerationConfig {
232        self.live_parent_generation
233            .lock()
234            .expect("subagent live parent generation mutex is not poisoned")
235            .clone()
236    }
237
238    /// Returns the optional default per-child cumulative token circuit breaker.
239    pub(crate) fn max_total_tokens(&self) -> Option<u64> {
240        match self.max_total_tokens.load(Ordering::Acquire) {
241            0 => None,
242            limit => Some(limit),
243        }
244    }
245
246    fn effective_limit_behavior(&self) -> SubagentLimitBehavior {
247        *self
248            .limit_behavior
249            .lock()
250            .expect("subagent limit behavior mutex is not poisoned")
251    }
252
253    /// Returns the optional default wall-clock timeout in seconds for child tasks.
254    pub(crate) fn default_timeout_secs(&self) -> Option<u64> {
255        match self.default_timeout_secs.load(Ordering::Acquire) {
256            0 => None,
257            secs => Some(secs),
258        }
259    }
260
261    /// Returns the configured foreground wait budget before handing off to background.
262    pub(crate) fn foreground_wait_budget(&self) -> Duration {
263        Duration::from_secs(
264            self.foreground_wait_budget_secs
265                .load(Ordering::Acquire)
266                .max(1),
267        )
268    }
269
270    /// Returns the session-scoped cancellation token that owns all children
271    /// spawned through runtime tools, decoupled from any single tool phase.
272    #[must_use]
273    pub(crate) fn session_token(&self) -> &CancellationToken {
274        &self.session_token
275    }
276
277    /// Returns true while any managed child is queued or running.
278    pub async fn has_active_agents(&self) -> bool {
279        let state = self.state.lock().await;
280        state
281            .agents
282            .values()
283            .any(|agent| !agent.status.is_terminal())
284    }
285
286    pub(crate) fn attach_parent_capabilities(
287        &self,
288        allowed_tools: Vec<ToolName>,
289        workspace_scope: ChildWorkspaceScope,
290    ) {
291        *self
292            .parent_capabilities
293            .lock()
294            .expect("subagent parent capabilities mutex is not poisoned") =
295            Some(ParentCapabilities {
296                allowed_tools,
297                workspace_scope,
298            });
299    }
300
301    pub(crate) fn attach_activity_hub(&self, hub: Arc<SubagentActivityHub>) {
302        *self
303            .activity_hub
304            .lock()
305            .expect("subagent activity hub mutex is not poisoned") = Some(hub);
306    }
307
308    pub(super) fn attached_activity_hub(&self) -> Option<Arc<SubagentActivityHub>> {
309        self.activity_hub
310            .lock()
311            .expect("subagent activity hub mutex is not poisoned")
312            .clone()
313    }
314
315    pub(super) fn parent_allowed_tools(&self) -> Option<Vec<ToolName>> {
316        self.parent_capabilities
317            .lock()
318            .expect("subagent parent capabilities mutex is not poisoned")
319            .as_ref()
320            .map(|capabilities| capabilities.allowed_tools.clone())
321    }
322
323    pub(super) fn apply_parent_capabilities(
324        &self,
325        mut task: SubagentTaskSpec,
326    ) -> Result<SubagentTaskSpec, SubagentError> {
327        let capabilities = self
328            .parent_capabilities
329            .lock()
330            .expect("subagent parent capabilities mutex is not poisoned")
331            .clone();
332        let Some(capabilities) = capabilities else {
333            return Ok(task);
334        };
335
336        if task.allowed_tools_are_explicit() {
337            for tool in task.allowed_tools() {
338                if !capabilities.allowed_tools.contains(tool) {
339                    return Err(SubagentError::CapabilityExpansion {
340                        field: "allowed_tools",
341                        value: tool.to_string(),
342                    });
343                }
344            }
345        } else {
346            task = task.with_allowed_tools(capabilities.allowed_tools);
347        }
348
349        if task.read_scope_is_explicit() {
350            ensure_scope_within_parent(
351                "read_scope",
352                task.read_scope(),
353                capabilities.workspace_scope.read_scope(),
354            )?;
355        } else {
356            task = task.with_read_scope(capabilities.workspace_scope.read_scope().to_vec())?;
357        }
358
359        if task.write_scope_is_explicit() {
360            ensure_scope_within_parent(
361                "write_scope",
362                task.write_scope(),
363                capabilities.workspace_scope.write_scope(),
364            )?;
365        } else {
366            task = task.with_write_scope(capabilities.workspace_scope.write_scope().to_vec())?;
367        }
368
369        let inherited_forbidden = capabilities.workspace_scope.forbidden_paths();
370        if task.forbidden_paths_are_explicit() {
371            let mut forbidden = inherited_forbidden.to_vec();
372            forbidden.extend(task.forbidden_paths().iter().cloned());
373            forbidden.sort();
374            forbidden.dedup();
375            task = task.with_forbidden_paths(forbidden)?;
376        } else {
377            task = task.with_forbidden_paths(inherited_forbidden.to_vec())?;
378        }
379
380        Ok(task)
381    }
382
383    pub(crate) async fn update_policy(
384        &self,
385        enabled: bool,
386        config: SubagentConfig,
387    ) -> Result<(), RuntimeError> {
388        self.max_threads
389            .store(config.max_threads(), Ordering::Release);
390        self.min_model_turns
391            .store(config.min_model_turns(), Ordering::Release);
392        self.max_model_turns
393            .store(config.max_model_turns(), Ordering::Release);
394        self.default_timeout_secs.store(
395            config.default_timeout_secs().unwrap_or(0),
396            Ordering::Release,
397        );
398        self.foreground_wait_budget_secs
399            .store(config.foreground_wait_budget_secs(), Ordering::Release);
400        self.max_total_tokens
401            .store(config.max_total_tokens().unwrap_or(0), Ordering::Release);
402        *self
403            .limit_behavior
404            .lock()
405            .expect("subagent limit behavior mutex is not poisoned") = config.limit_behavior();
406        self.enabled.store(enabled, Ordering::Release);
407        if enabled {
408            let mut state = self.state.lock().await;
409            let starts = self.reserve_queued_starts_locked(&mut state);
410            drop(state);
411            self.start_reserved_children(starts).await?;
412        }
413        Ok(())
414    }
415
416    fn effective_max_threads(&self) -> usize {
417        if self.enabled.load(Ordering::Acquire) {
418            self.max_threads.load(Ordering::Acquire)
419        } else {
420            0
421        }
422    }
423
424    /// Returns compact status views for all managed children.
425    pub async fn snapshot(&self) -> Vec<SubagentStatusView> {
426        let state = self.state.lock().await;
427        state
428            .agents
429            .values()
430            .map(ManagedSubagent::status_view)
431            .collect()
432    }
433
434    /// Returns the configured minimum model-turn budget for explicit child task
435    /// inputs.
436    pub(crate) fn min_model_turns(&self) -> u32 {
437        self.min_model_turns.load(Ordering::Acquire)
438    }
439
440    /// Returns the configured maximum model-turn budget for explicit child task
441    /// inputs and the default for omitted budgets.
442    pub(crate) fn max_model_turns(&self) -> u32 {
443        self.max_model_turns.load(Ordering::Acquire)
444    }
445
446    /// Returns the notification primitive used to wake a parent continuation
447    /// when a child reaches a terminal state.
448    pub(crate) fn completion_notify(&self) -> Arc<Notify> {
449        Arc::clone(&self.completion_notify)
450    }
451
452    /// Drains terminal child notifications for delivery to the parent model.
453    pub(crate) async fn take_completion_notifications(&self) -> Vec<SubagentStatusView> {
454        let mut notifications = self.completion_notifications.lock().await;
455        let statuses = notifications.drain(..).collect::<Vec<_>>();
456        if statuses.is_empty() {
457            return statuses;
458        }
459
460        let mut state = self.state.lock().await;
461        for status in &statuses {
462            if let Some(agent) = state.agents.get_mut(&status.agent_id) {
463                agent.completion_notification_acknowledged = true;
464            }
465        }
466        statuses
467    }
468
469    pub(crate) async fn has_completion_notifications(&self) -> bool {
470        !self.completion_notifications.lock().await.is_empty()
471    }
472
473    pub(super) async fn enqueue_completion_notification(&self, status: SubagentStatusView) {
474        enqueue_completion_notification_if_needed(
475            &self.state,
476            &self.completion_notifications,
477            &self.completion_notify,
478            status,
479        )
480        .await;
481    }
482
483    async fn acknowledge_completion_notifications(&self, agent_ids: &[SubagentId]) {
484        let mut notifications = self.completion_notifications.lock().await;
485        notifications.retain(|status| !agent_ids.contains(&status.agent_id));
486
487        let mut state = self.state.lock().await;
488        for agent_id in agent_ids {
489            if let Some(agent) = state.agents.get_mut(agent_id) {
490                agent.completion_notification_acknowledged = true;
491            }
492        }
493    }
494
495    /// Accepts a batch of child tasks, starting only the initial bounded slice.
496    pub async fn spawn(
497        &self,
498        tasks: Vec<SubagentTaskSpec>,
499        max_concurrency: Option<usize>,
500        parent_token: CancellationToken,
501    ) -> Result<SpawnSubagentsOutput, RuntimeError> {
502        if self.depth >= self.max_depth {
503            return Ok(SpawnSubagentsOutput {
504                spawned: Vec::new(),
505                rejected: (0..tasks.len())
506                    .map(|task_index| RejectedSubagentView {
507                        task_index,
508                        reason: "maximum subagent delegation depth reached".to_owned(),
509                    })
510                    .collect(),
511                wait_result: None,
512                background_handoff: None,
513            });
514        }
515        if !self.enabled.load(Ordering::Acquire) {
516            return Ok(SpawnSubagentsOutput {
517                spawned: Vec::new(),
518                rejected: (0..tasks.len())
519                    .map(|task_index| RejectedSubagentView {
520                        task_index,
521                        reason: "subagent spawning is disabled".to_owned(),
522                    })
523                    .collect(),
524                wait_result: None,
525                background_handoff: None,
526            });
527        }
528        let mut inherited_tasks = Vec::with_capacity(tasks.len());
529        let mut rejected = Vec::new();
530        for (task_index, task) in tasks.into_iter().enumerate() {
531            if let Err(error) = validate_task_max_model_turns(
532                task.max_model_turns(),
533                self.min_model_turns(),
534                self.max_model_turns(),
535            ) {
536                rejected.push(RejectedSubagentView {
537                    task_index,
538                    reason: error.to_string(),
539                });
540                continue;
541            }
542            match self.apply_parent_capabilities(task) {
543                Ok(task) => inherited_tasks.push((task_index, task)),
544                Err(error) => rejected.push(RejectedSubagentView {
545                    task_index,
546                    reason: error.to_string(),
547                }),
548            }
549        }
550        let conflict_tasks = inherited_tasks
551            .iter()
552            .map(|(_, task)| task.clone())
553            .collect::<Vec<_>>();
554        if let Err(error) = validate_no_write_scope_conflicts(&conflict_tasks) {
555            let reason = error.to_string();
556            rejected.extend(
557                inherited_tasks
558                    .iter()
559                    .map(|(task_index, _)| RejectedSubagentView {
560                        task_index: *task_index,
561                        reason: reason.clone(),
562                    }),
563            );
564            return Ok(SpawnSubagentsOutput {
565                spawned: Vec::new(),
566                rejected,
567                wait_result: None,
568                background_handoff: None,
569            });
570        }
571
572        let task_inputs = inherited_tasks
573            .into_iter()
574            .map(|(task_index, task)| {
575                TaskAnchor::new(task.task())
576                    .map(|task_anchor| (task_index, task, task_anchor))
577                    .map_err(RuntimeError::from)
578            })
579            .collect::<Result<Vec<_>, _>>()?;
580        let mut accepted_tasks = Vec::with_capacity(task_inputs.len());
581        let batch_id = self.next_batch_id.fetch_add(1, Ordering::SeqCst);
582        for (task_index, task, task_anchor) in task_inputs {
583            let number = self.next_id.fetch_add(1, Ordering::SeqCst);
584            let agent_id = SubagentId::new(&format!("agent-{number}"))?;
585            let task_id = SubagentTaskId::new(&format!("task-{number}"))?;
586            accepted_tasks.push((task_index, agent_id, task_id, task, task_anchor));
587        }
588
589        if accepted_tasks.is_empty() {
590            return Ok(SpawnSubagentsOutput {
591                spawned: Vec::new(),
592                rejected,
593                wait_result: None,
594                background_handoff: None,
595            });
596        }
597
598        self.has_agents.store(true, Ordering::Release);
599        let batch_max_concurrency = max_concurrency
600            .unwrap_or(accepted_tasks.len())
601            .min(accepted_tasks.len());
602        let mut spawned = Vec::with_capacity(accepted_tasks.len());
603        let mut to_start = Vec::new();
604        let mut state = self.state.lock().await;
605        state.batches.insert(
606            batch_id,
607            SubagentBatch {
608                max_concurrency: batch_max_concurrency,
609            },
610        );
611
612        for (task_index, agent_id, task_id, task, task_anchor) in accepted_tasks {
613            let child_token = parent_token.child_token();
614            let starts_now = running_child_count(&state) < self.effective_max_threads()
615                && batch_running_child_count(&state, batch_id) < batch_max_concurrency;
616            if !starts_now && self.effective_limit_behavior() == SubagentLimitBehavior::Fail {
617                rejected.push(RejectedSubagentView {
618                    task_index,
619                    reason: format!(
620                        "maximum concurrent subagents ({}) reached (limit_behavior = fail)",
621                        self.effective_max_threads()
622                    ),
623                });
624                continue;
625            }
626            let managed_status = if starts_now {
627                SubagentStatusLabel::Running
628            } else {
629                SubagentStatusLabel::Queued
630            };
631
632            let (event_tx, _) = broadcast::channel(SUBAGENT_EVENT_CHANNEL_CAPACITY);
633            let managed = ManagedSubagent {
634                batch_id,
635                agent_id: agent_id.clone(),
636                task_id: task_id.clone(),
637                task: task.clone(),
638                task_anchor: task_anchor.clone(),
639                status: managed_status.clone(),
640                summary: initial_summary(managed_status),
641                result: None,
642                output_paths: Vec::new(),
643                changed_paths: Vec::new(),
644                diagnostics: None,
645                cancellation_token: child_token.clone(),
646                completion_notification_acknowledged: false,
647                runtime: None,
648                generation_config: None,
649                event_tx,
650                pending_follow_ups: VecDeque::new(),
651                resume_turn_override: None,
652                started_at: starts_now.then(tokio::time::Instant::now),
653                turns_used: 0,
654                tool_calls: 0,
655                elapsed_ms: 0,
656                usage: None,
657                raw_output_bytes: 0,
658                workspace_lifecycle: None,
659                worktree: None,
660            };
661            state.agents.insert(agent_id.clone(), managed);
662
663            spawned.push(SpawnedSubagentView {
664                agent_id: agent_id.clone(),
665                task_id: task_id.clone(),
666                display_name: task.display_name().map(str::to_owned),
667                role: task.role().map(str::to_owned),
668                status: if starts_now {
669                    SpawnedSubagentStatusLabel::Running
670                } else {
671                    SpawnedSubagentStatusLabel::Queued
672                },
673                task_anchor: task.task().to_owned(),
674                read_scope: paths_to_strings(task.read_scope()),
675                write_scope: paths_to_strings(task.write_scope()),
676            });
677
678            if starts_now {
679                to_start.push((agent_id, task_id, task, task_anchor, child_token));
680            }
681        }
682        let spawned_records = spawned
683            .iter()
684            .filter_map(|view| {
685                let agent = state.agents.get(&view.agent_id)?;
686                Some((
687                    view.clone(),
688                    PersistedSubagentRecord::from_status_view(
689                        agent.task.task().to_owned(),
690                        &agent.status_view(),
691                    ),
692                ))
693            })
694            .collect::<Vec<_>>();
695        drop(state);
696
697        if let Some(sink) = self.attached_event_sink() {
698            for (view, record) in spawned_records {
699                sink.emit_journal_payload(merry_core::RuntimeJournalPayload::SubagentSpawned {
700                    agent_id: view.agent_id.clone(),
701                    task_id: view.task_id.clone(),
702                    task_anchor: view.task_anchor.clone(),
703                    display_name: view.display_name.clone(),
704                    role: view.role.clone(),
705                })
706                .await;
707                if matches!(view.status, SpawnedSubagentStatusLabel::Queued) {
708                    sink.emit_journal_payload(
709                        merry_core::RuntimeJournalPayload::SubagentStatusChanged {
710                            agent_id: view.agent_id.clone(),
711                            task_id: view.task_id.clone(),
712                            status: to_public_subagent_status(&SubagentStatusLabel::Queued),
713                        },
714                    )
715                    .await;
716                }
717                sink.upsert_persisted_subagent(record).await;
718            }
719        }
720
721        for (agent_id, task_id, task, task_anchor, child_token) in to_start {
722            self.start_child(agent_id, task_id, task, task_anchor, child_token)
723                .await;
724        }
725
726        Ok(SpawnSubagentsOutput {
727            spawned,
728            rejected,
729            wait_result: None,
730            background_handoff: None,
731        })
732    }
733
734    /// Waits for selected children or returns their latest compact statuses on timeout.
735    pub async fn wait(
736        &self,
737        agent_ids: &[SubagentId],
738        mode: WaitMode,
739        timeout: Option<Duration>,
740    ) -> Result<WaitSubagentsOutput, RuntimeError> {
741        if agent_ids.is_empty() {
742            return Err(RuntimeError::InvalidSubagentSelection {
743                operation: "wait_subagents",
744            });
745        }
746        let deadline = timeout.map(|duration| tokio::time::Instant::now() + duration);
747        loop {
748            let notified = self.notify.notified();
749            tokio::pin!(notified);
750            notified.as_mut().enable();
751            let agents = self.status_for(agent_ids).await;
752            let ready = wait_mode_satisfied(mode, &agents);
753            if ready {
754                self.acknowledge_waited_statuses(&agents).await;
755                return Ok(WaitSubagentsOutput::with_wait_state(agents, true, false));
756            }
757
758            match deadline {
759                Some(deadline) => {
760                    if tokio::time::Instant::now() >= deadline {
761                        self.acknowledge_waited_statuses(&agents).await;
762                        return Ok(WaitSubagentsOutput::with_wait_state(agents, false, true));
763                    }
764                    if tokio::time::timeout_at(deadline, notified.as_mut())
765                        .await
766                        .is_err()
767                    {
768                        let agents = self.status_for(agent_ids).await;
769                        self.acknowledge_waited_statuses(&agents).await;
770                        return Ok(WaitSubagentsOutput::with_wait_state(agents, false, true));
771                    }
772                }
773                None => notified.as_mut().await,
774            }
775        }
776    }
777
778    /// Cancels selected children and returns their compact statuses.
779    pub async fn cancel(
780        &self,
781        agent_ids: &[SubagentId],
782    ) -> Result<WaitSubagentsOutput, RuntimeError> {
783        if agent_ids.is_empty() {
784            return Err(RuntimeError::InvalidSubagentSelection {
785                operation: "cancel_subagents",
786            });
787        }
788        let mut state = self.state.lock().await;
789        let mut terminal_activities = Vec::new();
790        let mut cancelled_events = Vec::new();
791        for agent_id in agent_ids {
792            if let Some(agent) = state.agents.get_mut(agent_id) {
793                if agent.status.is_terminal() {
794                    continue;
795                }
796                agent.cancellation_token.cancel();
797                agent.status = SubagentStatusLabel::Cancelled;
798                agent.summary = "child cancelled by parent".to_owned();
799                agent.diagnostics = Some(error_info(
800                    "subagent_cancelled",
801                    "child cancellation requested by parent",
802                ));
803                terminal_activities.push((
804                    agent.agent_id.clone(),
805                    agent.task_id.clone(),
806                    SubagentActivityPhase::Cancelled,
807                    agent.summary.clone(),
808                ));
809                cancelled_events.push((agent.task.task().to_owned(), agent.status_view()));
810            }
811        }
812        let agents = selected_statuses(&state, agent_ids);
813        let to_start = self.reserve_queued_starts_locked(&mut state);
814        drop(state);
815        let activity_hub = self.attached_activity_hub();
816        for (agent_id, task_id, phase, summary) in terminal_activities {
817            publish_terminal_activity_snapshot(
818                activity_hub.clone(),
819                agent_id,
820                task_id,
821                phase,
822                &summary,
823            );
824        }
825        let sink = self.attached_event_sink();
826        for (task, view) in cancelled_events {
827            emit_terminal_event_and_persist(sink.as_ref(), task, &view).await;
828        }
829        self.notify.notify_waiters();
830        self.completion_notify.notify_waiters();
831        self.start_reserved_children(to_start).await?;
832        Ok(WaitSubagentsOutput::new(agents))
833    }
834
835    pub(super) fn reserve_queued_starts_locked(
836        &self,
837        state: &mut SubagentManagerState,
838    ) -> Vec<ReservedChildStart> {
839        reserve_queued_starts_locked(state, self.effective_max_threads())
840    }
841
842    pub(super) fn child_scheduler(&self) -> ChildScheduler {
843        ChildScheduler {
844            parent_session_id: self.parent_session_id.clone(),
845            factory: Arc::clone(&self.factory),
846            state: Arc::clone(&self.state),
847            notify: Arc::clone(&self.notify),
848            completion_notifications: Arc::clone(&self.completion_notifications),
849            completion_notify: Arc::clone(&self.completion_notify),
850            enabled: Arc::clone(&self.enabled),
851            max_threads: Arc::clone(&self.max_threads),
852            default_timeout_secs: Arc::clone(&self.default_timeout_secs),
853            max_total_tokens: Arc::clone(&self.max_total_tokens),
854            depth: self.depth,
855            activity_hub: Arc::clone(&self.activity_hub),
856            event_sink: Arc::clone(&self.event_sink),
857            child_session_store: Arc::clone(&self.child_session_store),
858            live_parent_model: Arc::clone(&self.live_parent_model),
859            live_parent_generation: Arc::clone(&self.live_parent_generation),
860        }
861    }
862
863    pub(super) async fn start_reserved_children(
864        &self,
865        starts: Vec<ReservedChildStart>,
866    ) -> Result<(), RuntimeError> {
867        scheduler::start_reserved_children_iteratively(self.child_scheduler(), starts).await;
868        Ok(())
869    }
870
871    pub(super) async fn status_for(&self, agent_ids: &[SubagentId]) -> Vec<SubagentStatusView> {
872        let state = self.state.lock().await;
873        selected_statuses(&state, agent_ids)
874    }
875
876    pub(super) async fn acknowledge_waited_statuses(&self, agents: &[SubagentStatusView]) {
877        let agent_ids = agents
878            .iter()
879            .filter(|agent| agent.is_terminal())
880            .map(|agent| agent.agent_id.clone())
881            .collect::<Vec<_>>();
882        self.acknowledge_completion_notifications(&agent_ids).await;
883    }
884
885    #[cfg(test)]
886    pub(super) async fn cancellation_token_for_test(
887        &self,
888        agent_id: &SubagentId,
889    ) -> Option<CancellationToken> {
890        let state = self.state.lock().await;
891        state
892            .agents
893            .get(agent_id)
894            .map(|agent| agent.cancellation_token.clone())
895    }
896}
897
898pub(super) use super::manager_helpers::{
899    ensure_scope_within_parent, initial_summary, paths_to_strings, selected_statuses,
900    wait_mode_satisfied,
901};