use super::handoff::{ContextFileRef, MAX_CONTEXT_FILE_REFS};
use super::protocol::{SubagentWorkspaceMode, SubagentWorktreeBase};
use merry_core::ToolName;
use merry_llm::ReasoningEffort;
use std::{
collections::BTreeSet,
path::{Path, PathBuf},
};
use thiserror::Error;
pub const DEFAULT_FOREGROUND_WAIT_BUDGET_SECS: u64 = 120;
pub(crate) const MAX_TASK_BYTES: usize = 16 * 1024;
pub const DEFAULT_MIN_MODEL_TURNS: u32 = 1;
pub const DEFAULT_MAX_MODEL_TURNS: u32 = 1024;
pub(crate) const DEFAULT_MAX_THREADS: usize = 6;
pub(crate) const DEFAULT_MAX_DEPTH: u8 = 1;
#[derive(Debug, Error, Clone, PartialEq, Eq)]
pub enum SubagentError {
#[error("task must not be blank")]
BlankTask,
#[error("task is longer than the allowed maximum")]
TaskTooLong,
#[error("max_model_turns must be greater than zero")]
ZeroMaxModelTurns,
#[error("max_model_turns {requested} exceeds configured maximum {maximum}")]
ExceedsConfiguredMaxModelTurns { requested: u32, maximum: u32 },
#[error("max_model_turns {requested} is below configured minimum {minimum}")]
BelowConfiguredMinModelTurns { requested: u32, minimum: u32 },
#[error("minimum max_model_turns must be greater than zero")]
ZeroMinModelTurns,
#[error("minimum max_model_turns {minimum} exceeds configured maximum {maximum}")]
MinExceedsMaxModelTurns { minimum: u32, maximum: u32 },
#[error("scope path must be relative and normalized: {path}")]
InvalidScopePath {
path: String,
},
#[error("overlapping write scope between task {first_index} and task {second_index}: {path}")]
OverlappingWriteScope {
first_index: usize,
second_index: usize,
path: String,
},
#[error("child task capability expansion is not allowed for {field}: {value}")]
CapabilityExpansion {
field: &'static str,
value: String,
},
#[error("subagent max_threads must be greater than zero")]
ZeroMaxThreads,
#[error("subagent max_depth must be greater than zero")]
ZeroMaxDepth,
#[error("invalid context_files entry (expected relative path or path:start-end): {value}")]
InvalidContextFileRef {
value: String,
},
#[error("context_files exceeds maximum of {maximum} entries")]
TooManyContextFiles {
maximum: usize,
},
#[error("timeout_secs must be greater than zero")]
ZeroTimeoutSecs,
#[error("foreground_wait_budget_secs must be greater than zero")]
ZeroForegroundBudgetSecs,
#[error("max_total_tokens must be greater than zero")]
ZeroMaxTotalTokens,
#[error("invalid subagent role name: {role}")]
InvalidRoleName {
role: String,
},
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum SubagentLimitBehavior {
#[default]
Queue,
Fail,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct SubagentConfig {
max_threads: usize,
max_depth: u8,
min_model_turns: u32,
max_model_turns: u32,
default_timeout_secs: Option<u64>,
foreground_wait_budget_secs: u64,
limit_behavior: SubagentLimitBehavior,
max_total_tokens: Option<u64>,
}
impl SubagentConfig {
pub fn new(max_threads: usize, max_depth: u8) -> Result<Self, SubagentError> {
if max_threads == 0 {
return Err(SubagentError::ZeroMaxThreads);
}
if max_depth == 0 {
return Err(SubagentError::ZeroMaxDepth);
}
Ok(Self {
max_threads,
max_depth,
min_model_turns: DEFAULT_MIN_MODEL_TURNS,
max_model_turns: DEFAULT_MAX_MODEL_TURNS,
default_timeout_secs: None,
foreground_wait_budget_secs: DEFAULT_FOREGROUND_WAIT_BUDGET_SECS,
limit_behavior: SubagentLimitBehavior::Queue,
max_total_tokens: None,
})
}
#[must_use]
pub fn with_limit_behavior(mut self, behavior: SubagentLimitBehavior) -> Self {
self.limit_behavior = behavior;
self
}
pub fn with_max_total_tokens(
mut self,
max_total_tokens: Option<u64>,
) -> Result<Self, SubagentError> {
if max_total_tokens == Some(0) {
return Err(SubagentError::ZeroMaxTotalTokens);
}
self.max_total_tokens = max_total_tokens;
Ok(self)
}
pub fn with_default_timeout_secs(
mut self,
timeout_secs: Option<u64>,
) -> Result<Self, SubagentError> {
if timeout_secs == Some(0) {
return Err(SubagentError::ZeroTimeoutSecs);
}
self.default_timeout_secs = timeout_secs;
Ok(self)
}
pub fn with_foreground_wait_budget_secs(
mut self,
budget_secs: u64,
) -> Result<Self, SubagentError> {
if budget_secs == 0 {
return Err(SubagentError::ZeroForegroundBudgetSecs);
}
self.foreground_wait_budget_secs = budget_secs;
Ok(self)
}
pub fn with_max_model_turns(mut self, max_model_turns: u32) -> Result<Self, SubagentError> {
if max_model_turns == 0 {
return Err(SubagentError::ZeroMaxModelTurns);
}
if self.min_model_turns > max_model_turns {
return Err(SubagentError::MinExceedsMaxModelTurns {
minimum: self.min_model_turns,
maximum: max_model_turns,
});
}
self.max_model_turns = max_model_turns;
Ok(self)
}
pub fn with_min_model_turns(mut self, min_model_turns: u32) -> Result<Self, SubagentError> {
if min_model_turns == 0 {
return Err(SubagentError::ZeroMinModelTurns);
}
if min_model_turns > self.max_model_turns {
return Err(SubagentError::MinExceedsMaxModelTurns {
minimum: min_model_turns,
maximum: self.max_model_turns,
});
}
self.min_model_turns = min_model_turns;
Ok(self)
}
pub fn with_model_turn_bounds(
mut self,
min_model_turns: u32,
max_model_turns: u32,
) -> Result<Self, SubagentError> {
if min_model_turns == 0 {
return Err(SubagentError::ZeroMinModelTurns);
}
if max_model_turns == 0 {
return Err(SubagentError::ZeroMaxModelTurns);
}
if min_model_turns > max_model_turns {
return Err(SubagentError::MinExceedsMaxModelTurns {
minimum: min_model_turns,
maximum: max_model_turns,
});
}
self.min_model_turns = min_model_turns;
self.max_model_turns = max_model_turns;
Ok(self)
}
pub fn validate_task_max_model_turns(self, requested: u32) -> Result<(), SubagentError> {
validate_task_max_model_turns(requested, self.min_model_turns, self.max_model_turns)
}
#[must_use]
pub fn min_model_turns(self) -> u32 {
self.min_model_turns
}
#[must_use]
pub fn max_threads(self) -> usize {
self.max_threads
}
#[must_use]
pub fn max_depth(self) -> u8 {
self.max_depth
}
#[must_use]
pub fn max_model_turns(self) -> u32 {
self.max_model_turns
}
#[must_use]
pub fn default_timeout_secs(self) -> Option<u64> {
self.default_timeout_secs
}
#[must_use]
pub fn foreground_wait_budget_secs(self) -> u64 {
self.foreground_wait_budget_secs
}
#[must_use]
pub fn limit_behavior(self) -> SubagentLimitBehavior {
self.limit_behavior
}
#[must_use]
pub fn max_total_tokens(self) -> Option<u64> {
self.max_total_tokens
}
}
impl Default for SubagentConfig {
fn default() -> Self {
Self {
max_threads: DEFAULT_MAX_THREADS,
max_depth: DEFAULT_MAX_DEPTH,
min_model_turns: DEFAULT_MIN_MODEL_TURNS,
max_model_turns: DEFAULT_MAX_MODEL_TURNS,
default_timeout_secs: None,
foreground_wait_budget_secs: DEFAULT_FOREGROUND_WAIT_BUDGET_SECS,
limit_behavior: SubagentLimitBehavior::Queue,
max_total_tokens: None,
}
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct SubagentTaskSpec {
display_name: Option<String>,
role: Option<String>,
task: String,
max_model_turns: u32,
max_model_turns_explicit: bool,
timeout_secs: Option<u64>,
max_total_tokens: Option<u64>,
allowed_tools: Vec<ToolName>,
allowed_tools_explicit: bool,
read_scope: Vec<PathBuf>,
read_scope_explicit: bool,
write_scope: Vec<PathBuf>,
write_scope_explicit: bool,
forbidden_paths: Vec<PathBuf>,
forbidden_paths_explicit: bool,
context_files: Vec<ContextFileRef>,
expected_output: Option<String>,
reasoning_effort: Option<ReasoningEffort>,
workspace_mode: SubagentWorkspaceMode,
worktree_base: SubagentWorktreeBase,
}
pub(crate) fn validate_task_max_model_turns(
requested: u32,
minimum: u32,
maximum: u32,
) -> Result<(), SubagentError> {
if requested == 0 {
return Err(SubagentError::ZeroMaxModelTurns);
}
if requested < minimum {
return Err(SubagentError::BelowConfiguredMinModelTurns { requested, minimum });
}
if requested > maximum {
return Err(SubagentError::ExceedsConfiguredMaxModelTurns { requested, maximum });
}
Ok(())
}
impl SubagentTaskSpec {
pub fn new(task: impl Into<String>, max_model_turns: u32) -> Result<Self, SubagentError> {
let task = task.into();
validate_task_text(&task)?;
if max_model_turns == 0 {
return Err(SubagentError::ZeroMaxModelTurns);
}
Ok(Self {
display_name: None,
role: None,
task,
max_model_turns,
max_model_turns_explicit: true,
timeout_secs: None,
max_total_tokens: None,
allowed_tools: Vec::new(),
allowed_tools_explicit: false,
read_scope: Vec::new(),
read_scope_explicit: false,
write_scope: Vec::new(),
write_scope_explicit: false,
forbidden_paths: Vec::new(),
forbidden_paths_explicit: false,
context_files: Vec::new(),
expected_output: None,
reasoning_effort: None,
workspace_mode: SubagentWorkspaceMode::Shared,
worktree_base: SubagentWorktreeBase::WorkingTree,
})
}
pub(crate) fn with_max_model_turns_unchecked(mut self, max_model_turns: u32) -> Self {
self.max_model_turns = max_model_turns;
self
}
#[must_use]
pub fn with_max_model_turns_explicit(mut self, explicit: bool) -> Self {
self.max_model_turns_explicit = explicit;
self
}
#[must_use]
pub const fn max_model_turns_is_explicit(&self) -> bool {
self.max_model_turns_explicit
}
#[must_use]
pub const fn max_total_tokens(&self) -> Option<u64> {
self.max_total_tokens
}
#[must_use]
pub fn with_max_total_tokens(mut self, max_total_tokens: Option<u64>) -> Self {
self.max_total_tokens = max_total_tokens.filter(|value| *value > 0);
self
}
#[must_use]
pub fn role(&self) -> Option<&str> {
self.role.as_deref()
}
#[must_use]
pub const fn timeout_secs(&self) -> Option<u64> {
self.timeout_secs
}
#[must_use]
pub fn context_files(&self) -> &[ContextFileRef] {
&self.context_files
}
#[must_use]
pub fn task(&self) -> &str {
&self.task
}
#[must_use]
pub fn max_model_turns(&self) -> u32 {
self.max_model_turns
}
#[must_use]
pub fn allowed_tools(&self) -> &[ToolName] {
&self.allowed_tools
}
#[must_use]
pub fn allowed_tools_are_explicit(&self) -> bool {
self.allowed_tools_explicit
}
pub(crate) fn read_scope_is_explicit(&self) -> bool {
self.read_scope_explicit
}
#[must_use]
pub fn write_scope_is_explicit(&self) -> bool {
self.write_scope_explicit
}
pub(crate) fn forbidden_paths_are_explicit(&self) -> bool {
self.forbidden_paths_explicit
}
#[must_use]
pub fn display_name(&self) -> Option<&str> {
self.display_name.as_deref()
}
#[must_use]
pub fn read_scope(&self) -> &[PathBuf] {
&self.read_scope
}
#[must_use]
pub fn write_scope(&self) -> &[PathBuf] {
&self.write_scope
}
#[must_use]
pub fn forbidden_paths(&self) -> &[PathBuf] {
&self.forbidden_paths
}
#[must_use]
pub fn expected_output(&self) -> Option<&str> {
self.expected_output.as_deref()
}
#[must_use]
pub fn reasoning_effort(&self) -> Option<&ReasoningEffort> {
self.reasoning_effort.as_ref()
}
#[must_use]
pub const fn workspace_mode(&self) -> SubagentWorkspaceMode {
self.workspace_mode
}
#[must_use]
pub const fn worktree_base(&self) -> SubagentWorktreeBase {
self.worktree_base
}
#[must_use]
pub fn with_allowed_tools<I>(mut self, tools: I) -> Self
where
I: IntoIterator<Item = ToolName>,
{
self.allowed_tools = tools.into_iter().collect();
self.allowed_tools_explicit = true;
self
}
#[must_use]
pub fn with_display_name(mut self, display_name: Option<String>) -> Self {
self.display_name = display_name.filter(|value| !value.trim().is_empty());
self
}
pub fn with_role(mut self, role: Option<String>) -> Result<Self, SubagentError> {
let Some(role) = role
.map(|value| value.trim().to_owned())
.filter(|value| !value.is_empty())
else {
self.role = None;
return Ok(self);
};
if role.len() > 64
|| !role
.bytes()
.all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'_' | b'-'))
{
return Err(SubagentError::InvalidRoleName { role });
}
self.role = Some(role);
Ok(self)
}
pub fn with_timeout_secs(mut self, timeout_secs: Option<u64>) -> Result<Self, SubagentError> {
if timeout_secs == Some(0) {
return Err(SubagentError::ZeroTimeoutSecs);
}
self.timeout_secs = timeout_secs;
Ok(self)
}
pub fn with_context_files<I, S>(mut self, entries: I) -> Result<Self, SubagentError>
where
I: IntoIterator<Item = S>,
S: AsRef<str>,
{
let mut parsed = Vec::new();
for entry in entries {
if parsed.len() >= MAX_CONTEXT_FILE_REFS {
return Err(SubagentError::TooManyContextFiles {
maximum: MAX_CONTEXT_FILE_REFS,
});
}
parsed.push(ContextFileRef::parse(entry.as_ref())?);
}
self.context_files = parsed;
Ok(self)
}
pub fn with_read_scope<I, P>(mut self, paths: I) -> Result<Self, SubagentError>
where
I: IntoIterator<Item = P>,
P: Into<PathBuf>,
{
self.read_scope = validate_scope_paths(paths)?;
self.read_scope_explicit = true;
Ok(self)
}
pub fn with_write_scope<I, P>(mut self, paths: I) -> Result<Self, SubagentError>
where
I: IntoIterator<Item = P>,
P: Into<PathBuf>,
{
self.write_scope = validate_scope_paths(paths)?;
self.write_scope_explicit = true;
Ok(self)
}
pub fn with_forbidden_paths<I, P>(mut self, paths: I) -> Result<Self, SubagentError>
where
I: IntoIterator<Item = P>,
P: Into<PathBuf>,
{
self.forbidden_paths = validate_scope_paths(paths)?;
self.forbidden_paths_explicit = true;
Ok(self)
}
#[must_use]
pub fn with_expected_output(mut self, expected_output: Option<String>) -> Self {
self.expected_output = expected_output.filter(|value| !value.trim().is_empty());
self
}
#[must_use]
pub fn with_reasoning_effort(mut self, reasoning_effort: Option<ReasoningEffort>) -> Self {
self.reasoning_effort = reasoning_effort;
self
}
#[must_use]
pub const fn with_workspace_mode(mut self, workspace_mode: SubagentWorkspaceMode) -> Self {
self.workspace_mode = workspace_mode;
self
}
#[must_use]
pub const fn with_worktree_base(mut self, worktree_base: SubagentWorktreeBase) -> Self {
self.worktree_base = worktree_base;
self
}
}
fn validate_task_text(task: &str) -> Result<(), SubagentError> {
if task.trim().is_empty() {
return Err(SubagentError::BlankTask);
}
if task.len() > MAX_TASK_BYTES {
return Err(SubagentError::TaskTooLong);
}
Ok(())
}
fn validate_scope_paths<I, P>(paths: I) -> Result<Vec<PathBuf>, SubagentError>
where
I: IntoIterator<Item = P>,
P: Into<PathBuf>,
{
let paths = paths
.into_iter()
.map(|path| validate_scope_path(path.into()))
.collect::<Result<BTreeSet<_>, _>>()?;
Ok(paths.into_iter().collect())
}
pub(super) fn validate_scope_path(path: PathBuf) -> Result<PathBuf, SubagentError> {
let path_label = path.display().to_string();
if !crate::workspace_scope::is_valid_workspace_scope(&path) {
return Err(SubagentError::InvalidScopePath { path: path_label });
}
Ok(path)
}
pub fn validate_no_write_scope_conflicts(tasks: &[SubagentTaskSpec]) -> Result<(), SubagentError> {
for (first_index, first) in tasks.iter().enumerate() {
if first.workspace_mode() != SubagentWorkspaceMode::Shared {
continue;
}
for (second_offset, second) in tasks[first_index + 1..].iter().enumerate() {
if second.workspace_mode() != SubagentWorkspaceMode::Shared {
continue;
}
let second_index = first_index + 1 + second_offset;
for first_path in first.write_scope() {
for second_path in second.write_scope() {
if paths_overlap(first_path, second_path) {
return Err(SubagentError::OverlappingWriteScope {
first_index,
second_index,
path: first_path.display().to_string(),
});
}
}
}
}
}
Ok(())
}
#[must_use]
fn paths_overlap(first: &Path, second: &Path) -> bool {
crate::workspace_scope::workspace_scopes_overlap(first, second)
}