Skip to main content

merry_runtime/subagent/
messaging.rs

1//! Coordinator-to-subagent messaging and wake/resume lifecycle.
2
3use super::{
4    ChildRuntimeInput, ChildWorkspaceScope, ResumableChildSession, SubagentManager,
5    SubagentStatusLabel,
6    child::{
7        ResumeChildLaunch, apply_built_task_overrides, build_child_offloaded,
8        generation_config_for_child_task_with_parent,
9    },
10    events::child_session_id_for_agent,
11    protocol::{SendSubagentMessageOutcome, SendSubagentMessageOutput, SubagentMessageDelivery},
12    spec::validate_task_max_model_turns,
13};
14use crate::{LoadedSession, RuntimeError};
15use merry_core::SubagentId;
16use std::sync::Arc;
17
18/// Maximum queued follow-up messages buffered per active child before reporting `Saturated`.
19const MAX_PENDING_FOLLOW_UPS: usize = 16;
20
21/// Delivery options for [`SubagentManager::send_message_with_options`].
22#[derive(Debug, Clone, Copy, PartialEq, Eq)]
23pub struct SendSubagentMessageOptions {
24    /// Whether to steer at the next safe checkpoint (front of queue) or append.
25    pub delivery: SubagentMessageDelivery,
26    /// Optional additional/override turn budget when waking a terminal child.
27    pub extra_model_turns: Option<u32>,
28}
29
30impl Default for SendSubagentMessageOptions {
31    fn default() -> Self {
32        Self {
33            delivery: SubagentMessageDelivery::Steer,
34            extra_model_turns: None,
35        }
36    }
37}
38
39impl SubagentManager {
40    /// Sends a follow-up message directly to a subagent session (used by TUI Takeover).
41    ///
42    /// If the subagent is currently running or queued, the message is queued and
43    /// executes after the current turn settles. If the subagent has reached a
44    /// terminal state with a retained runtime, a new turn is launched on that
45    /// same child session.
46    pub async fn send_message(
47        &self,
48        agent_id: &SubagentId,
49        message: String,
50    ) -> Result<(), RuntimeError> {
51        let output = self
52            .send_message_with_options(agent_id, message, SendSubagentMessageOptions::default())
53            .await?;
54        match output.outcome {
55            SendSubagentMessageOutcome::Accepted | SendSubagentMessageOutcome::Woken => Ok(()),
56            SendSubagentMessageOutcome::NotFoundOrNotOwned
57            | SendSubagentMessageOutcome::Saturated
58            | SendSubagentMessageOutcome::SessionClosing => {
59                Err(RuntimeError::InvalidSubagentSelection {
60                    operation: "send_subagent_message",
61                })
62            }
63        }
64    }
65
66    /// Sends a follow-up instruction to a running child or wakes a terminal
67    /// child with its retained transcript and `agent_id`, returning a typed,
68    /// non-ambiguous delivery outcome.
69    pub async fn send_message_with_options(
70        &self,
71        agent_id: &SubagentId,
72        message: String,
73        options: SendSubagentMessageOptions,
74    ) -> Result<SendSubagentMessageOutput, RuntimeError> {
75        let trimmed = message.trim();
76        if trimmed.is_empty() {
77            return Err(RuntimeError::InvalidSubagentSelection {
78                operation: "send_subagent_message",
79            });
80        }
81        if self.session_token.is_cancelled() {
82            return Ok(SendSubagentMessageOutput {
83                agent_id: agent_id.clone(),
84                outcome: SendSubagentMessageOutcome::SessionClosing,
85                status: None,
86                wait_result: None,
87                message: "parent session is closing; subagent cannot accept new messages"
88                    .to_owned(),
89            });
90        }
91        if let Some(extra_turns) = options.extra_model_turns {
92            validate_task_max_model_turns(extra_turns, 1, self.max_model_turns()).map_err(
93                |_| RuntimeError::InvalidSubagentSelection {
94                    operation: "send_subagent_message",
95                },
96            )?;
97        }
98
99        let message = trimmed.to_owned();
100        let mut launch_now = None;
101        let mut rehydrate_candidate = None;
102        let outcome = {
103            let mut state = self.state.lock().await;
104            let Some(agent) = state.agents.get_mut(agent_id) else {
105                return Ok(SendSubagentMessageOutput {
106                    agent_id: agent_id.clone(),
107                    outcome: SendSubagentMessageOutcome::NotFoundOrNotOwned,
108                    status: None,
109                    wait_result: None,
110                    message: format!("unknown subagent id: {agent_id}"),
111                });
112            };
113            if !agent.status.is_terminal() {
114                if agent.pending_follow_ups.len() >= MAX_PENDING_FOLLOW_UPS {
115                    return Ok(SendSubagentMessageOutput {
116                        agent_id: agent_id.clone(),
117                        outcome: SendSubagentMessageOutcome::Saturated,
118                        status: Some(agent.status.clone()),
119                        wait_result: None,
120                        message: format!(
121                            "subagent {agent_id} already has {MAX_PENDING_FOLLOW_UPS} queued messages"
122                        ),
123                    });
124                }
125                let position = match options.delivery {
126                    SubagentMessageDelivery::Steer => {
127                        agent.pending_follow_ups.push_front(message.clone());
128                        0
129                    }
130                    SubagentMessageDelivery::Queue => {
131                        let pos = agent.pending_follow_ups.len();
132                        agent.pending_follow_ups.push_back(message.clone());
133                        pos
134                    }
135                };
136                if let Some(extra_turns) = options.extra_model_turns {
137                    agent.resume_turn_override = Some(extra_turns);
138                }
139                let _ = agent
140                    .event_tx
141                    .send(merry_core::RuntimeEvent::QueuedInputAccepted {
142                        inputs: vec![merry_core::QueuedInputView {
143                            id: 0,
144                            text: message.clone(),
145                            position,
146                        }],
147                    });
148                (
149                    SendSubagentMessageOutcome::Accepted,
150                    agent.status.clone(),
151                    match options.delivery {
152                        SubagentMessageDelivery::Steer => {
153                            "steering message accepted for next safe checkpoint".to_owned()
154                        }
155                        SubagentMessageDelivery::Queue => {
156                            "follow-up message queued after current turn".to_owned()
157                        }
158                    },
159                )
160            } else if let (Some(runtime), Some(generation_config)) =
161                (agent.runtime.clone(), agent.generation_config.clone())
162            {
163                let token = self.session_token.child_token();
164                agent.cancellation_token = token.clone();
165                agent.status = SubagentStatusLabel::Running;
166                agent.summary = "handling follow-up".to_owned();
167                agent.diagnostics = None;
168                agent.completion_notification_acknowledged = false;
169                let mut wake_task = agent.task.clone();
170                if let Some(extra_turns) = options.extra_model_turns {
171                    wake_task = wake_task.with_max_model_turns_unchecked(extra_turns);
172                }
173                let _ = agent
174                    .event_tx
175                    .send(merry_core::RuntimeEvent::QueuedInputAccepted {
176                        inputs: vec![merry_core::QueuedInputView {
177                            id: 0,
178                            text: message.clone(),
179                            position: 0,
180                        }],
181                    });
182                launch_now = Some(ResumeChildLaunch {
183                    agent_id: agent_id.clone(),
184                    task_id: agent.task_id.clone(),
185                    task: wake_task,
186                    token,
187                    runtime,
188                    generation_config,
189                    event_tx: agent.event_tx.clone(),
190                    prompt: message.clone(),
191                });
192                (
193                    SendSubagentMessageOutcome::Woken,
194                    SubagentStatusLabel::Running,
195                    format!("woke subagent {agent_id} with its retained transcript and context"),
196                )
197            } else if self.attached_child_session_store().is_some()
198                || agent.worktree.as_ref().is_some_and(|w| !w.retained)
199            {
200                // Restored from parent session resume (or worktree auto-cleaned after
201                // zero net changes): claim the Running state BEFORE dropping the lock
202                // so concurrent wake calls queue cleanly instead of double-spawning.
203                let previous_state = (
204                    agent.status.clone(),
205                    agent.summary.clone(),
206                    agent.diagnostics.clone(),
207                    agent.completion_notification_acknowledged,
208                );
209                agent.status = SubagentStatusLabel::Running;
210                agent.summary = "waking persisted subagent".to_owned();
211                agent.diagnostics = None;
212                agent.completion_notification_acknowledged = false;
213
214                let mut wake_task = agent.task.clone();
215                if let Some(extra_turns) = options.extra_model_turns {
216                    wake_task = wake_task.with_max_model_turns_unchecked(extra_turns);
217                }
218                let existing_worktree = agent.worktree.clone().filter(|worktree| worktree.retained);
219                rehydrate_candidate = Some((
220                    agent.task_id.clone(),
221                    wake_task,
222                    agent.task_anchor.clone(),
223                    agent.event_tx.clone(),
224                    existing_worktree,
225                    previous_state,
226                ));
227                (
228                    SendSubagentMessageOutcome::Woken,
229                    SubagentStatusLabel::Running,
230                    format!("woke persisted subagent {agent_id} from its saved child journal"),
231                )
232            } else {
233                return Ok(SendSubagentMessageOutput {
234                    agent_id: agent_id.clone(),
235                    outcome: SendSubagentMessageOutcome::NotFoundOrNotOwned,
236                    status: Some(agent.status.clone()),
237                    wait_result: None,
238                    message: format!(
239                        "subagent {agent_id} never started a child runtime and cannot be woken"
240                    ),
241                });
242            }
243        };
244
245        if let Some((
246            task_id,
247            wake_task,
248            task_anchor,
249            event_tx,
250            existing_worktree,
251            previous_state,
252        )) = rehydrate_candidate
253        {
254            let store = self.attached_child_session_store();
255            let child_session_id = child_session_id_for_agent(agent_id);
256            let loaded_session = match store.as_ref() {
257                Some(store) => LoadedSession::load(store, &child_session_id)
258                    .await
259                    .ok()
260                    .map(ResumableChildSession::new),
261                None => None,
262            };
263            let parent_primary_model = self.live_parent_model_snapshot();
264            let parent_generation_config = self.live_parent_generation_snapshot();
265            let default_generation_config =
266                generation_config_for_child_task_with_parent(&wake_task, &parent_generation_config);
267            let allowed_tools = if wake_task.allowed_tools_are_explicit() {
268                wake_task.allowed_tools().to_vec()
269            } else {
270                self.parent_allowed_tools().unwrap_or_default()
271            };
272            let built = match build_child_offloaded(
273                Arc::clone(&self.factory),
274                ChildRuntimeInput {
275                    parent_session_id: self.parent_session_id.clone(),
276                    agent_id: Some(agent_id.clone()),
277                    session_id: child_session_id,
278                    session_store: store,
279                    loaded_session,
280                    existing_worktree,
281                    task_anchor,
282                    task: wake_task.clone(),
283                    allowed_tools,
284                    workspace_scope: ChildWorkspaceScope::from_task(&wake_task),
285                    depth: self.depth.saturating_add(1),
286                    generation_config: default_generation_config.clone(),
287                    parent_primary_model,
288                    parent_generation_config,
289                    activity_hub: self.attached_activity_hub(),
290                },
291            )
292            .await
293            {
294                Ok(built) => built,
295                Err(error) => {
296                    let mut state = self.state.lock().await;
297                    if let Some(agent) = state.agents.get_mut(agent_id) {
298                        agent.status = previous_state.0;
299                        agent.summary = previous_state.1;
300                        agent.diagnostics = previous_state.2;
301                        agent.completion_notification_acknowledged = previous_state.3;
302                    }
303                    return Err(error);
304                }
305            };
306            let wake_task = apply_built_task_overrides(
307                wake_task,
308                &built,
309                self.default_timeout_secs(),
310                self.max_total_tokens(),
311            );
312            let workspace_lifecycle = built.workspace_lifecycle;
313            let worktree_metadata = workspace_lifecycle.as_ref().map(|hook| hook.metadata());
314            let runtime = built.runtime;
315            let generation_config = built.generation_config.unwrap_or(default_generation_config);
316            let token = self.session_token.child_token();
317            {
318                let mut state = self.state.lock().await;
319                if let Some(agent) = state.agents.get_mut(agent_id) {
320                    agent.cancellation_token = token.clone();
321                    agent.status = SubagentStatusLabel::Running;
322                    agent.summary = "handling follow-up".to_owned();
323                    agent.diagnostics = None;
324                    agent.completion_notification_acknowledged = false;
325                    agent.task = wake_task.clone();
326                    agent.runtime = Some(runtime.clone());
327                    agent.generation_config = Some(generation_config.clone());
328                    agent.workspace_lifecycle = workspace_lifecycle;
329                    if let Some(metadata) = worktree_metadata {
330                        agent.worktree = Some(metadata);
331                    }
332                    agent.started_at = Some(tokio::time::Instant::now());
333                    let _ = agent
334                        .event_tx
335                        .send(merry_core::RuntimeEvent::QueuedInputAccepted {
336                            inputs: vec![merry_core::QueuedInputView {
337                                id: 0,
338                                text: message.clone(),
339                                position: 0,
340                            }],
341                        });
342                }
343            }
344            launch_now = Some(ResumeChildLaunch {
345                agent_id: agent_id.clone(),
346                task_id,
347                task: wake_task,
348                token,
349                runtime,
350                generation_config,
351                event_tx,
352                prompt: message,
353            });
354        }
355
356        if let Some(launch) = launch_now {
357            self.resume_child(launch).await;
358        }
359
360        Ok(SendSubagentMessageOutput {
361            agent_id: agent_id.clone(),
362            outcome: outcome.0,
363            status: Some(outcome.1),
364            wait_result: None,
365            message: outcome.2,
366        })
367    }
368}