1use super::handoff::{ContextFileRef, MAX_CONTEXT_FILE_REFS};
2use super::protocol::{SubagentWorkspaceMode, SubagentWorktreeBase};
3use merry_core::ToolName;
4use merry_llm::ReasoningEffort;
5use std::{
6 collections::BTreeSet,
7 path::{Path, PathBuf},
8};
9use thiserror::Error;
10
11pub const DEFAULT_FOREGROUND_WAIT_BUDGET_SECS: u64 = 120;
13
14pub(crate) const MAX_TASK_BYTES: usize = 16 * 1024;
16pub const DEFAULT_MIN_MODEL_TURNS: u32 = 1;
18pub const DEFAULT_MAX_MODEL_TURNS: u32 = 1024;
25pub(crate) const DEFAULT_MAX_THREADS: usize = 6;
27pub(crate) const DEFAULT_MAX_DEPTH: u8 = 1;
29
30#[derive(Debug, Error, Clone, PartialEq, Eq)]
32pub enum SubagentError {
33 #[error("task must not be blank")]
35 BlankTask,
36 #[error("task is longer than the allowed maximum")]
38 TaskTooLong,
39 #[error("max_model_turns must be greater than zero")]
41 ZeroMaxModelTurns,
42 #[error("max_model_turns {requested} exceeds configured maximum {maximum}")]
44 ExceedsConfiguredMaxModelTurns { requested: u32, maximum: u32 },
45 #[error("max_model_turns {requested} is below configured minimum {minimum}")]
47 BelowConfiguredMinModelTurns { requested: u32, minimum: u32 },
48 #[error("minimum max_model_turns must be greater than zero")]
50 ZeroMinModelTurns,
51 #[error("minimum max_model_turns {minimum} exceeds configured maximum {maximum}")]
53 MinExceedsMaxModelTurns { minimum: u32, maximum: u32 },
54 #[error("scope path must be relative and normalized: {path}")]
56 InvalidScopePath {
57 path: String,
59 },
60 #[error("overlapping write scope between task {first_index} and task {second_index}: {path}")]
62 OverlappingWriteScope {
63 first_index: usize,
65 second_index: usize,
67 path: String,
69 },
70 #[error("child task capability expansion is not allowed for {field}: {value}")]
72 CapabilityExpansion {
73 field: &'static str,
75 value: String,
77 },
78 #[error("subagent max_threads must be greater than zero")]
80 ZeroMaxThreads,
81 #[error("subagent max_depth must be greater than zero")]
83 ZeroMaxDepth,
84 #[error("invalid context_files entry (expected relative path or path:start-end): {value}")]
86 InvalidContextFileRef {
87 value: String,
89 },
90 #[error("context_files exceeds maximum of {maximum} entries")]
92 TooManyContextFiles {
93 maximum: usize,
95 },
96 #[error("timeout_secs must be greater than zero")]
98 ZeroTimeoutSecs,
99 #[error("foreground_wait_budget_secs must be greater than zero")]
101 ZeroForegroundBudgetSecs,
102 #[error("max_total_tokens must be greater than zero")]
104 ZeroMaxTotalTokens,
105 #[error("invalid subagent role name: {role}")]
107 InvalidRoleName {
108 role: String,
110 },
111}
112
113#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
115pub enum SubagentLimitBehavior {
116 #[default]
118 Queue,
119 Fail,
121}
122
123#[derive(Debug, Clone, Copy, PartialEq, Eq)]
125pub struct SubagentConfig {
126 max_threads: usize,
127 max_depth: u8,
128 min_model_turns: u32,
129 max_model_turns: u32,
130 default_timeout_secs: Option<u64>,
131 foreground_wait_budget_secs: u64,
132 limit_behavior: SubagentLimitBehavior,
133 max_total_tokens: Option<u64>,
134}
135
136impl SubagentConfig {
137 pub fn new(max_threads: usize, max_depth: u8) -> Result<Self, SubagentError> {
139 if max_threads == 0 {
140 return Err(SubagentError::ZeroMaxThreads);
141 }
142 if max_depth == 0 {
143 return Err(SubagentError::ZeroMaxDepth);
144 }
145 Ok(Self {
146 max_threads,
147 max_depth,
148 min_model_turns: DEFAULT_MIN_MODEL_TURNS,
149 max_model_turns: DEFAULT_MAX_MODEL_TURNS,
150 default_timeout_secs: None,
151 foreground_wait_budget_secs: DEFAULT_FOREGROUND_WAIT_BUDGET_SECS,
152 limit_behavior: SubagentLimitBehavior::Queue,
153 max_total_tokens: None,
154 })
155 }
156
157 #[must_use]
159 pub fn with_limit_behavior(mut self, behavior: SubagentLimitBehavior) -> Self {
160 self.limit_behavior = behavior;
161 self
162 }
163
164 pub fn with_max_total_tokens(
166 mut self,
167 max_total_tokens: Option<u64>,
168 ) -> Result<Self, SubagentError> {
169 if max_total_tokens == Some(0) {
170 return Err(SubagentError::ZeroMaxTotalTokens);
171 }
172 self.max_total_tokens = max_total_tokens;
173 Ok(self)
174 }
175
176 pub fn with_default_timeout_secs(
178 mut self,
179 timeout_secs: Option<u64>,
180 ) -> Result<Self, SubagentError> {
181 if timeout_secs == Some(0) {
182 return Err(SubagentError::ZeroTimeoutSecs);
183 }
184 self.default_timeout_secs = timeout_secs;
185 Ok(self)
186 }
187
188 pub fn with_foreground_wait_budget_secs(
191 mut self,
192 budget_secs: u64,
193 ) -> Result<Self, SubagentError> {
194 if budget_secs == 0 {
195 return Err(SubagentError::ZeroForegroundBudgetSecs);
196 }
197 self.foreground_wait_budget_secs = budget_secs;
198 Ok(self)
199 }
200
201 pub fn with_max_model_turns(mut self, max_model_turns: u32) -> Result<Self, SubagentError> {
204 if max_model_turns == 0 {
205 return Err(SubagentError::ZeroMaxModelTurns);
206 }
207 if self.min_model_turns > max_model_turns {
208 return Err(SubagentError::MinExceedsMaxModelTurns {
209 minimum: self.min_model_turns,
210 maximum: max_model_turns,
211 });
212 }
213 self.max_model_turns = max_model_turns;
214 Ok(self)
215 }
216
217 pub fn with_min_model_turns(mut self, min_model_turns: u32) -> Result<Self, SubagentError> {
219 if min_model_turns == 0 {
220 return Err(SubagentError::ZeroMinModelTurns);
221 }
222 if min_model_turns > self.max_model_turns {
223 return Err(SubagentError::MinExceedsMaxModelTurns {
224 minimum: min_model_turns,
225 maximum: self.max_model_turns,
226 });
227 }
228 self.min_model_turns = min_model_turns;
229 Ok(self)
230 }
231
232 pub fn with_model_turn_bounds(
234 mut self,
235 min_model_turns: u32,
236 max_model_turns: u32,
237 ) -> Result<Self, SubagentError> {
238 if min_model_turns == 0 {
239 return Err(SubagentError::ZeroMinModelTurns);
240 }
241 if max_model_turns == 0 {
242 return Err(SubagentError::ZeroMaxModelTurns);
243 }
244 if min_model_turns > max_model_turns {
245 return Err(SubagentError::MinExceedsMaxModelTurns {
246 minimum: min_model_turns,
247 maximum: max_model_turns,
248 });
249 }
250 self.min_model_turns = min_model_turns;
251 self.max_model_turns = max_model_turns;
252 Ok(self)
253 }
254
255 pub fn validate_task_max_model_turns(self, requested: u32) -> Result<(), SubagentError> {
257 validate_task_max_model_turns(requested, self.min_model_turns, self.max_model_turns)
258 }
259
260 #[must_use]
262 pub fn min_model_turns(self) -> u32 {
263 self.min_model_turns
264 }
265
266 #[must_use]
268 pub fn max_threads(self) -> usize {
269 self.max_threads
270 }
271
272 #[must_use]
274 pub fn max_depth(self) -> u8 {
275 self.max_depth
276 }
277
278 #[must_use]
280 pub fn max_model_turns(self) -> u32 {
281 self.max_model_turns
282 }
283
284 #[must_use]
286 pub fn default_timeout_secs(self) -> Option<u64> {
287 self.default_timeout_secs
288 }
289
290 #[must_use]
292 pub fn foreground_wait_budget_secs(self) -> u64 {
293 self.foreground_wait_budget_secs
294 }
295
296 #[must_use]
298 pub fn limit_behavior(self) -> SubagentLimitBehavior {
299 self.limit_behavior
300 }
301
302 #[must_use]
304 pub fn max_total_tokens(self) -> Option<u64> {
305 self.max_total_tokens
306 }
307}
308
309impl Default for SubagentConfig {
310 fn default() -> Self {
311 Self {
312 max_threads: DEFAULT_MAX_THREADS,
313 max_depth: DEFAULT_MAX_DEPTH,
314 min_model_turns: DEFAULT_MIN_MODEL_TURNS,
315 max_model_turns: DEFAULT_MAX_MODEL_TURNS,
316 default_timeout_secs: None,
317 foreground_wait_budget_secs: DEFAULT_FOREGROUND_WAIT_BUDGET_SECS,
318 limit_behavior: SubagentLimitBehavior::Queue,
319 max_total_tokens: None,
320 }
321 }
322}
323
324#[derive(Debug, Clone, PartialEq, Eq)]
326pub struct SubagentTaskSpec {
327 display_name: Option<String>,
328 role: Option<String>,
329 task: String,
330 max_model_turns: u32,
331 max_model_turns_explicit: bool,
332 timeout_secs: Option<u64>,
333 max_total_tokens: Option<u64>,
334 allowed_tools: Vec<ToolName>,
335 allowed_tools_explicit: bool,
336 read_scope: Vec<PathBuf>,
337 read_scope_explicit: bool,
338 write_scope: Vec<PathBuf>,
339 write_scope_explicit: bool,
340 forbidden_paths: Vec<PathBuf>,
341 forbidden_paths_explicit: bool,
342 context_files: Vec<ContextFileRef>,
343 expected_output: Option<String>,
344 reasoning_effort: Option<ReasoningEffort>,
345 workspace_mode: SubagentWorkspaceMode,
346 worktree_base: SubagentWorktreeBase,
347}
348
349pub(crate) fn validate_task_max_model_turns(
350 requested: u32,
351 minimum: u32,
352 maximum: u32,
353) -> Result<(), SubagentError> {
354 if requested == 0 {
355 return Err(SubagentError::ZeroMaxModelTurns);
356 }
357 if requested < minimum {
358 return Err(SubagentError::BelowConfiguredMinModelTurns { requested, minimum });
359 }
360 if requested > maximum {
361 return Err(SubagentError::ExceedsConfiguredMaxModelTurns { requested, maximum });
362 }
363 Ok(())
364}
365
366impl SubagentTaskSpec {
367 pub fn new(task: impl Into<String>, max_model_turns: u32) -> Result<Self, SubagentError> {
369 let task = task.into();
370 validate_task_text(&task)?;
371 if max_model_turns == 0 {
372 return Err(SubagentError::ZeroMaxModelTurns);
373 }
374 Ok(Self {
375 display_name: None,
376 role: None,
377 task,
378 max_model_turns,
379 max_model_turns_explicit: true,
380 timeout_secs: None,
381 max_total_tokens: None,
382 allowed_tools: Vec::new(),
383 allowed_tools_explicit: false,
384 read_scope: Vec::new(),
385 read_scope_explicit: false,
386 write_scope: Vec::new(),
387 write_scope_explicit: false,
388 forbidden_paths: Vec::new(),
389 forbidden_paths_explicit: false,
390 context_files: Vec::new(),
391 expected_output: None,
392 reasoning_effort: None,
393 workspace_mode: SubagentWorkspaceMode::Shared,
394 worktree_base: SubagentWorktreeBase::WorkingTree,
395 })
396 }
397
398 pub(crate) fn with_max_model_turns_unchecked(mut self, max_model_turns: u32) -> Self {
399 self.max_model_turns = max_model_turns;
400 self
401 }
402
403 #[must_use]
406 pub fn with_max_model_turns_explicit(mut self, explicit: bool) -> Self {
407 self.max_model_turns_explicit = explicit;
408 self
409 }
410
411 #[must_use]
413 pub const fn max_model_turns_is_explicit(&self) -> bool {
414 self.max_model_turns_explicit
415 }
416
417 #[must_use]
419 pub const fn max_total_tokens(&self) -> Option<u64> {
420 self.max_total_tokens
421 }
422
423 #[must_use]
425 pub fn with_max_total_tokens(mut self, max_total_tokens: Option<u64>) -> Self {
426 self.max_total_tokens = max_total_tokens.filter(|value| *value > 0);
427 self
428 }
429
430 #[must_use]
432 pub fn role(&self) -> Option<&str> {
433 self.role.as_deref()
434 }
435
436 #[must_use]
438 pub const fn timeout_secs(&self) -> Option<u64> {
439 self.timeout_secs
440 }
441
442 #[must_use]
444 pub fn context_files(&self) -> &[ContextFileRef] {
445 &self.context_files
446 }
447
448 #[must_use]
453 pub fn task(&self) -> &str {
454 &self.task
455 }
456
457 #[must_use]
459 pub fn max_model_turns(&self) -> u32 {
460 self.max_model_turns
461 }
462
463 #[must_use]
465 pub fn allowed_tools(&self) -> &[ToolName] {
466 &self.allowed_tools
467 }
468
469 #[must_use]
470 pub fn allowed_tools_are_explicit(&self) -> bool {
471 self.allowed_tools_explicit
472 }
473
474 pub(crate) fn read_scope_is_explicit(&self) -> bool {
475 self.read_scope_explicit
476 }
477
478 #[must_use]
481 pub fn write_scope_is_explicit(&self) -> bool {
482 self.write_scope_explicit
483 }
484
485 pub(crate) fn forbidden_paths_are_explicit(&self) -> bool {
486 self.forbidden_paths_explicit
487 }
488
489 #[must_use]
491 pub fn display_name(&self) -> Option<&str> {
492 self.display_name.as_deref()
493 }
494
495 #[must_use]
497 pub fn read_scope(&self) -> &[PathBuf] {
498 &self.read_scope
499 }
500
501 #[must_use]
503 pub fn write_scope(&self) -> &[PathBuf] {
504 &self.write_scope
505 }
506
507 #[must_use]
509 pub fn forbidden_paths(&self) -> &[PathBuf] {
510 &self.forbidden_paths
511 }
512
513 #[must_use]
515 pub fn expected_output(&self) -> Option<&str> {
516 self.expected_output.as_deref()
517 }
518
519 #[must_use]
521 pub fn reasoning_effort(&self) -> Option<&ReasoningEffort> {
522 self.reasoning_effort.as_ref()
523 }
524
525 #[must_use]
527 pub const fn workspace_mode(&self) -> SubagentWorkspaceMode {
528 self.workspace_mode
529 }
530
531 #[must_use]
533 pub const fn worktree_base(&self) -> SubagentWorktreeBase {
534 self.worktree_base
535 }
536
537 #[must_use]
539 pub fn with_allowed_tools<I>(mut self, tools: I) -> Self
540 where
541 I: IntoIterator<Item = ToolName>,
542 {
543 self.allowed_tools = tools.into_iter().collect();
544 self.allowed_tools_explicit = true;
545 self
546 }
547
548 #[must_use]
550 pub fn with_display_name(mut self, display_name: Option<String>) -> Self {
551 self.display_name = display_name.filter(|value| !value.trim().is_empty());
552 self
553 }
554
555 pub fn with_role(mut self, role: Option<String>) -> Result<Self, SubagentError> {
557 let Some(role) = role
558 .map(|value| value.trim().to_owned())
559 .filter(|value| !value.is_empty())
560 else {
561 self.role = None;
562 return Ok(self);
563 };
564 if role.len() > 64
565 || !role
566 .bytes()
567 .all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'_' | b'-'))
568 {
569 return Err(SubagentError::InvalidRoleName { role });
570 }
571 self.role = Some(role);
572 Ok(self)
573 }
574
575 pub fn with_timeout_secs(mut self, timeout_secs: Option<u64>) -> Result<Self, SubagentError> {
577 if timeout_secs == Some(0) {
578 return Err(SubagentError::ZeroTimeoutSecs);
579 }
580 self.timeout_secs = timeout_secs;
581 Ok(self)
582 }
583
584 pub fn with_context_files<I, S>(mut self, entries: I) -> Result<Self, SubagentError>
586 where
587 I: IntoIterator<Item = S>,
588 S: AsRef<str>,
589 {
590 let mut parsed = Vec::new();
591 for entry in entries {
592 if parsed.len() >= MAX_CONTEXT_FILE_REFS {
593 return Err(SubagentError::TooManyContextFiles {
594 maximum: MAX_CONTEXT_FILE_REFS,
595 });
596 }
597 parsed.push(ContextFileRef::parse(entry.as_ref())?);
598 }
599 self.context_files = parsed;
600 Ok(self)
601 }
602
603 pub fn with_read_scope<I, P>(mut self, paths: I) -> Result<Self, SubagentError>
605 where
606 I: IntoIterator<Item = P>,
607 P: Into<PathBuf>,
608 {
609 self.read_scope = validate_scope_paths(paths)?;
610 self.read_scope_explicit = true;
611 Ok(self)
612 }
613
614 pub fn with_write_scope<I, P>(mut self, paths: I) -> Result<Self, SubagentError>
616 where
617 I: IntoIterator<Item = P>,
618 P: Into<PathBuf>,
619 {
620 self.write_scope = validate_scope_paths(paths)?;
621 self.write_scope_explicit = true;
622 Ok(self)
623 }
624
625 pub fn with_forbidden_paths<I, P>(mut self, paths: I) -> Result<Self, SubagentError>
627 where
628 I: IntoIterator<Item = P>,
629 P: Into<PathBuf>,
630 {
631 self.forbidden_paths = validate_scope_paths(paths)?;
632 self.forbidden_paths_explicit = true;
633 Ok(self)
634 }
635
636 #[must_use]
638 pub fn with_expected_output(mut self, expected_output: Option<String>) -> Self {
639 self.expected_output = expected_output.filter(|value| !value.trim().is_empty());
640 self
641 }
642
643 #[must_use]
645 pub fn with_reasoning_effort(mut self, reasoning_effort: Option<ReasoningEffort>) -> Self {
646 self.reasoning_effort = reasoning_effort;
647 self
648 }
649
650 #[must_use]
652 pub const fn with_workspace_mode(mut self, workspace_mode: SubagentWorkspaceMode) -> Self {
653 self.workspace_mode = workspace_mode;
654 self
655 }
656
657 #[must_use]
659 pub const fn with_worktree_base(mut self, worktree_base: SubagentWorktreeBase) -> Self {
660 self.worktree_base = worktree_base;
661 self
662 }
663}
664
665fn validate_task_text(task: &str) -> Result<(), SubagentError> {
666 if task.trim().is_empty() {
667 return Err(SubagentError::BlankTask);
668 }
669 if task.len() > MAX_TASK_BYTES {
670 return Err(SubagentError::TaskTooLong);
671 }
672 Ok(())
673}
674
675fn validate_scope_paths<I, P>(paths: I) -> Result<Vec<PathBuf>, SubagentError>
676where
677 I: IntoIterator<Item = P>,
678 P: Into<PathBuf>,
679{
680 let paths = paths
681 .into_iter()
682 .map(|path| validate_scope_path(path.into()))
683 .collect::<Result<BTreeSet<_>, _>>()?;
684 Ok(paths.into_iter().collect())
685}
686
687pub(super) fn validate_scope_path(path: PathBuf) -> Result<PathBuf, SubagentError> {
688 let path_label = path.display().to_string();
689 if !crate::workspace_scope::is_valid_workspace_scope(&path) {
690 return Err(SubagentError::InvalidScopePath { path: path_label });
691 }
692
693 Ok(path)
694}
695
696pub fn validate_no_write_scope_conflicts(tasks: &[SubagentTaskSpec]) -> Result<(), SubagentError> {
701 for (first_index, first) in tasks.iter().enumerate() {
702 if first.workspace_mode() != SubagentWorkspaceMode::Shared {
703 continue;
704 }
705 for (second_offset, second) in tasks[first_index + 1..].iter().enumerate() {
706 if second.workspace_mode() != SubagentWorkspaceMode::Shared {
707 continue;
708 }
709 let second_index = first_index + 1 + second_offset;
710 for first_path in first.write_scope() {
711 for second_path in second.write_scope() {
712 if paths_overlap(first_path, second_path) {
713 return Err(SubagentError::OverlappingWriteScope {
714 first_index,
715 second_index,
716 path: first_path.display().to_string(),
717 });
718 }
719 }
720 }
721 }
722 }
723 Ok(())
724}
725
726#[must_use]
728fn paths_overlap(first: &Path, second: &Path) -> bool {
729 crate::workspace_scope::workspace_scopes_overlap(first, second)
730}