Skip to main content

merry_coding/
subagent_roles.rs

1//! Pure, typed subagent role catalog and 4-level dynamic runtime resolver.
2//!
3//! `merry-coding` owns built-in coding roles (`explore`, `coder`, `review`),
4//! capability intersection, orphaned tool pruning, and dynamic model/generation
5//! inheritance so `merry-runtime` stays free of coding-domain roles.
6
7use crate::policy_prompt::builtin_subagent_role_instructions;
8use merry_core::ToolName;
9use merry_llm::{GenerationConfig, ModelName, ModelProvider, ModelRetryPolicy, ReasoningEffort};
10use merry_runtime::{ChildWorkspaceScope, ParentPrimaryModel, SubagentTaskSpec};
11use std::{
12    collections::{BTreeMap, BTreeSet},
13    fs,
14    path::Path,
15    sync::Arc,
16};
17use thiserror::Error;
18
19/// Maximum UTF-8 bytes allowed for one role prompt file.
20pub const MAX_ROLE_PROMPT_FILE_BYTES: usize = 32 * 1024;
21
22/// Orthogonal OS sandbox workspace access mode for a subagent role.
23#[derive(Debug, Clone, Copy, PartialEq, Eq)]
24pub enum SubagentWorkspaceAccess {
25    /// OS-enforced read-only workspace (e.g. `explore`).
26    ReadOnlyWorkspace,
27    /// Full read-write workspace (e.g. `coder`, `review`).
28    ReadWriteWorkspace,
29}
30
31/// Optional concrete provider/model override attached to `[subagents.default]`
32/// or `[subagents.roles.<name>]`.
33#[derive(Clone)]
34pub struct SubagentModelOverride {
35    /// Resolved provider implementation.
36    pub provider: Arc<dyn ModelProvider>,
37    /// Target model identifier.
38    pub model: ModelName,
39    /// Optional provider retry policy override.
40    pub retry_policy: Option<ModelRetryPolicy>,
41}
42
43/// Global `[subagents.default]` overrides applied below role overrides and
44/// above live parent runtime inheritance.
45#[derive(Clone, Default)]
46pub struct SubagentDefaultOverride {
47    /// Optional default provider/model for all subagents.
48    pub model_override: Option<SubagentModelOverride>,
49    /// Optional default reasoning effort for all subagents.
50    pub reasoning_effort: Option<ReasoningEffort>,
51    /// Optional default model-turn budget for subagents.
52    pub max_model_turns: Option<u32>,
53    /// Optional default wall-clock timeout in seconds.
54    pub timeout_secs: Option<u64>,
55    /// Optional cumulative per-child token circuit breaker.
56    pub max_total_tokens: Option<u64>,
57}
58
59/// Resolved definition for one subagent role in [`SubagentRoleCatalog`].
60#[derive(Clone)]
61pub struct SubagentRoleSpec {
62    /// Stable role identifier (e.g. `explore`, `coder`, `review`, `browser`).
63    pub name: String,
64    /// Short one-line description advertised in `spawn_subagents`.
65    pub description: String,
66    /// Whether this role is currently enabled.
67    pub enabled: bool,
68    /// Orthogonal sandbox access mode for this role.
69    pub workspace_access: SubagentWorkspaceAccess,
70    /// Optional allowlist of tools for this role; `None` inherits parent tools.
71    pub default_allowed_tools: Option<Vec<ToolName>>,
72    /// Default model-turn budget when neither task nor `[subagents.default]` overrides it.
73    pub default_max_model_turns: u32,
74    /// Explicit role-level `max_model_turns` overlay (takes precedence over `[subagents.default]`).
75    pub max_model_turns_override: Option<u32>,
76    /// Default wall-clock timeout in seconds when omitted.
77    pub default_timeout_secs: Option<u64>,
78    /// Optional cumulative per-child token circuit breaker.
79    pub max_total_tokens: Option<u64>,
80    /// Role-specific prompt instructions rendered into `<merry_subagent_role>`.
81    pub instructions: Option<String>,
82    /// Optional provider/model override for this role.
83    pub model_override: Option<SubagentModelOverride>,
84    /// Optional reasoning-effort override for this role.
85    pub reasoning_effort: Option<ReasoningEffort>,
86}
87
88/// User- or project-supplied overlay for defining or customizing a role.
89#[derive(Clone, Default)]
90pub struct SubagentRoleOverlay {
91    /// Optional base role to inherit defaults from (`explore`, `coder`, `review`).
92    pub base: Option<String>,
93    /// Optional enabled toggle.
94    pub enabled: Option<bool>,
95    /// Optional one-line description override.
96    pub description: Option<String>,
97    /// Optional workspace access mode override.
98    pub workspace_access: Option<SubagentWorkspaceAccess>,
99    /// Optional provider/model override.
100    pub model_override: Option<SubagentModelOverride>,
101    /// Optional reasoning-effort override.
102    pub reasoning_effort: Option<ReasoningEffort>,
103    /// Optional default turn budget override.
104    pub max_model_turns: Option<u32>,
105    /// Optional default wall-clock timeout override.
106    pub timeout_secs: Option<u64>,
107    /// Optional token circuit breaker override.
108    pub max_total_tokens: Option<u64>,
109    /// Optional tool allowlist override.
110    pub allowed_tools: Option<Vec<ToolName>>,
111    /// Optional custom instructions (already combined with any loaded `prompt_file`).
112    pub instructions: Option<String>,
113}
114
115/// Errors raised while validating or resolving subagent roles.
116#[derive(Debug, Error, Clone, PartialEq, Eq)]
117pub enum SubagentRoleError {
118    /// Role identifier is empty or contains unsupported characters.
119    #[error("invalid subagent role name {role:?}: use ASCII letters, digits, '_' or '-'")]
120    InvalidRoleName { role: String },
121    /// Referenced base role does not exist.
122    #[error("unknown base role {base:?} for subagent role {role:?}")]
123    UnknownBaseRole { role: String, base: String },
124    /// Spawn requested an unknown role.
125    #[error("unknown subagent role {role:?}; available roles: {available}")]
126    UnknownRole { role: String, available: String },
127    /// Spawn requested a role that is disabled via config or toggle.
128    #[error("subagent role {role:?} is disabled")]
129    DisabledRole { role: String },
130    /// Role turn budget or timeout was zero.
131    #[error("invalid {field} for subagent role {role:?}: must be greater than zero")]
132    ZeroBudget { role: String, field: &'static str },
133    /// Prompt file could not be loaded safely from the workspace.
134    #[error("failed to load prompt_file {path:?} for subagent role {role:?}: {reason}")]
135    InvalidPromptFile {
136        role: String,
137        path: String,
138        reason: String,
139    },
140}
141
142/// Validated catalog of built-in and configured subagent roles plus global defaults.
143#[derive(Clone)]
144pub struct SubagentRoleCatalog {
145    default_override: SubagentDefaultOverride,
146    roles: BTreeMap<String, SubagentRoleSpec>,
147}
148
149impl Default for SubagentRoleCatalog {
150    fn default() -> Self {
151        Self::builtin()
152    }
153}
154
155impl SubagentRoleCatalog {
156    /// Builds the default catalog containing Merry's 3 built-in roles:
157    /// `explore`, `coder`, and `review`.
158    #[must_use]
159    pub fn builtin() -> Self {
160        let mut roles = BTreeMap::new();
161        roles.insert(
162            "explore".to_owned(),
163            SubagentRoleSpec {
164                name: "explore".to_owned(),
165                description: "fast read-only codebase researcher".to_owned(),
166                enabled: true,
167                workspace_access: SubagentWorkspaceAccess::ReadOnlyWorkspace,
168                default_allowed_tools: Some(tool_names(&["read_file", "run_process", "web_fetch"])),
169                default_max_model_turns: 30,
170                max_model_turns_override: None,
171                default_timeout_secs: Some(180),
172                max_total_tokens: None,
173                instructions: builtin_subagent_role_instructions("explore").map(str::to_owned),
174                model_override: None,
175                reasoning_effort: None,
176            },
177        );
178        roles.insert(
179            "coder".to_owned(),
180            SubagentRoleSpec {
181                name: "coder".to_owned(),
182                description: "scoped implementation and local verification".to_owned(),
183                enabled: true,
184                workspace_access: SubagentWorkspaceAccess::ReadWriteWorkspace,
185                default_allowed_tools: None,
186                default_max_model_turns: 80,
187                max_model_turns_override: None,
188                default_timeout_secs: Some(600),
189                max_total_tokens: None,
190                instructions: builtin_subagent_role_instructions("coder").map(str::to_owned),
191                model_override: None,
192                reasoning_effort: None,
193            },
194        );
195        roles.insert(
196            "review".to_owned(),
197            SubagentRoleSpec {
198                name: "review".to_owned(),
199                description: "independent skeptical code review and verification".to_owned(),
200                enabled: true,
201                workspace_access: SubagentWorkspaceAccess::ReadWriteWorkspace,
202                default_allowed_tools: Some(tool_names(&[
203                    "read_file",
204                    "run_process",
205                    "request_permissions",
206                    "web_fetch",
207                    "browser_tab",
208                    "browser_network",
209                    "read_background_process",
210                    "stop_background_process",
211                ])),
212                default_max_model_turns: 40,
213                max_model_turns_override: None,
214                default_timeout_secs: Some(300),
215                max_total_tokens: None,
216                instructions: builtin_subagent_role_instructions("review").map(str::to_owned),
217                model_override: None,
218                reasoning_effort: None,
219            },
220        );
221        Self {
222            default_override: SubagentDefaultOverride::default(),
223            roles,
224        }
225    }
226
227    /// Replaces the `[subagents.default]` override layer.
228    #[must_use]
229    pub fn with_default_override(mut self, default_override: SubagentDefaultOverride) -> Self {
230        self.default_override = default_override;
231        self
232    }
233
234    /// Returns the configured `[subagents.default]` override layer.
235    #[must_use]
236    pub fn default_override(&self) -> &SubagentDefaultOverride {
237        &self.default_override
238    }
239
240    /// Applies one role overlay on top of an existing role or its declared `base`
241    /// role (defaulting to `coder` for new custom roles).
242    pub fn apply_role_overlay(
243        &mut self,
244        name: &str,
245        overlay: SubagentRoleOverlay,
246    ) -> Result<(), SubagentRoleError> {
247        validate_role_name(name)?;
248        if overlay.max_model_turns == Some(0) {
249            return Err(SubagentRoleError::ZeroBudget {
250                role: name.to_owned(),
251                field: "max_model_turns",
252            });
253        }
254        if overlay.timeout_secs == Some(0) {
255            return Err(SubagentRoleError::ZeroBudget {
256                role: name.to_owned(),
257                field: "timeout_secs",
258            });
259        }
260        if overlay.max_total_tokens == Some(0) {
261            return Err(SubagentRoleError::ZeroBudget {
262                role: name.to_owned(),
263                field: "max_total_tokens",
264            });
265        }
266
267        let mut spec = if let Some(base_name) = overlay.base.as_deref() {
268            let mut inherited = self.roles.get(base_name).cloned().ok_or_else(|| {
269                SubagentRoleError::UnknownBaseRole {
270                    role: name.to_owned(),
271                    base: base_name.to_owned(),
272                }
273            })?;
274            inherited.name = name.to_owned();
275            inherited
276        } else if let Some(existing) = self.roles.get(name) {
277            existing.clone()
278        } else {
279            SubagentRoleSpec {
280                name: name.to_owned(),
281                description: format!("custom {name} specialist"),
282                enabled: true,
283                workspace_access: SubagentWorkspaceAccess::ReadWriteWorkspace,
284                default_allowed_tools: None,
285                default_max_model_turns: 80,
286                max_model_turns_override: None,
287                default_timeout_secs: Some(600),
288                max_total_tokens: None,
289                instructions: None,
290                model_override: None,
291                reasoning_effort: None,
292            }
293        };
294
295        if let Some(enabled) = overlay.enabled {
296            spec.enabled = enabled;
297        }
298        if let Some(description) = overlay.description {
299            spec.description = description;
300        }
301        if let Some(access) = overlay.workspace_access {
302            spec.workspace_access = access;
303        }
304        if let Some(model_override) = overlay.model_override {
305            spec.model_override = Some(model_override);
306        }
307        if let Some(reasoning_effort) = overlay.reasoning_effort {
308            spec.reasoning_effort = Some(reasoning_effort);
309        }
310        if let Some(turns) = overlay.max_model_turns {
311            spec.default_max_model_turns = turns;
312            spec.max_model_turns_override = Some(turns);
313        }
314        if let Some(timeout) = overlay.timeout_secs {
315            spec.default_timeout_secs = Some(timeout);
316        }
317        if let Some(tokens) = overlay.max_total_tokens {
318            spec.max_total_tokens = Some(tokens);
319        }
320        if let Some(tools) = overlay.allowed_tools {
321            spec.default_allowed_tools = Some(tools);
322        }
323        if let Some(instructions) = overlay.instructions {
324            spec.instructions = Some(instructions);
325        }
326
327        self.roles.insert(name.to_owned(), spec);
328        Ok(())
329    }
330
331    /// Applies `[subagents.toggle]` flags for known roles.
332    pub fn apply_toggles(
333        &mut self,
334        toggles: &BTreeMap<String, bool>,
335    ) -> Result<(), SubagentRoleError> {
336        for (name, enabled) in toggles {
337            let Some(spec) = self.roles.get_mut(name) else {
338                return Err(SubagentRoleError::UnknownRole {
339                    role: name.clone(),
340                    available: self.available_role_list(),
341                });
342            };
343            spec.enabled = *enabled;
344        }
345        Ok(())
346    }
347
348    /// Looks up a role by name.
349    #[must_use]
350    pub fn role(&self, name: &str) -> Option<&SubagentRoleSpec> {
351        self.roles.get(name)
352    }
353
354    /// Returns `(name, description)` summaries for all enabled roles in deterministic order.
355    #[must_use]
356    pub fn enabled_role_summaries(&self) -> Vec<(String, String)> {
357        self.roles
358            .values()
359            .filter(|spec| spec.enabled)
360            .map(|spec| (spec.name.clone(), spec.description.clone()))
361            .collect()
362    }
363
364    fn available_role_list(&self) -> String {
365        self.roles
366            .values()
367            .filter(|spec| spec.enabled)
368            .map(|spec| spec.name.as_str())
369            .collect::<Vec<_>>()
370            .join(", ")
371    }
372}
373
374/// Inputs to the pure [`resolve_subagent_runtime`] resolver.
375pub struct SubagentResolutionInput<'a> {
376    /// Delegated child task contract.
377    pub task: &'a SubagentTaskSpec,
378    /// Tools already bounded by the parent's admitted catalog.
379    pub parent_allowed_tools: &'a [ToolName],
380    /// Child workspace scope validated against the parent.
381    pub workspace_scope: &'a ChildWorkspaceScope,
382    /// Whether the parent workspace itself is writable.
383    pub parent_workspace_writable: bool,
384    /// Delegation depth assigned to this child (`parent.depth + 1`).
385    pub depth: u8,
386    /// Maximum allowed delegation depth.
387    pub max_depth: u8,
388    /// Maximum configured child model-turn cap.
389    pub max_model_turns_cap: u32,
390    /// Live snapshot of the parent's currently active primary provider/model.
391    pub parent_primary_model: Option<&'a ParentPrimaryModel>,
392    /// Fallback provider/model from initial composition when no live snapshot exists.
393    pub fallback_provider: Arc<dyn ModelProvider>,
394    /// Fallback model identifier from initial composition.
395    pub fallback_model: &'a ModelName,
396    /// Live parent generation config (including `reasoning_effort` & `service_tier`).
397    pub parent_generation_config: &'a GenerationConfig,
398}
399
400/// Deterministic, fully resolved runtime specification for one child agent.
401pub struct ResolvedSubagentRuntime {
402    /// Effective resolved role name.
403    pub role_name: String,
404    /// Resolved provider handle.
405    pub provider: Arc<dyn ModelProvider>,
406    /// Resolved model identifier.
407    pub model: ModelName,
408    /// Optional provider retry policy override.
409    pub retry_policy: Option<ModelRetryPolicy>,
410    /// Resolved generation config (4-level inheritance).
411    pub generation_config: GenerationConfig,
412    /// Effective OS sandbox writability (capability intersection).
413    pub workspace_writable: bool,
414    /// Effective allowed tools after capability intersection and orphan pruning.
415    pub allowed_tools: Vec<ToolName>,
416    /// Effective model-turn budget.
417    pub max_model_turns: u32,
418    /// Effective wall-clock timeout in seconds.
419    pub timeout_secs: Option<u64>,
420    /// Effective cumulative per-child token circuit breaker.
421    pub max_total_tokens: Option<u64>,
422    /// Effective role prompt instructions for `<merry_subagent_role>`.
423    pub role_instructions: Option<String>,
424}
425
426/// Pure function resolving role, capability intersection, orphaned tool
427/// pruning, and 4-level dynamic model/generation inheritance for one child.
428pub fn resolve_subagent_runtime(
429    catalog: &SubagentRoleCatalog,
430    input: &SubagentResolutionInput<'_>,
431) -> Result<ResolvedSubagentRuntime, SubagentRoleError> {
432    let requested_role = input.task.role().unwrap_or("coder");
433    let Some(role) = catalog.role(requested_role) else {
434        return Err(SubagentRoleError::UnknownRole {
435            role: requested_role.to_owned(),
436            available: catalog.available_role_list(),
437        });
438    };
439    if !role.enabled {
440        return Err(SubagentRoleError::DisabledRole {
441            role: role.name.clone(),
442        });
443    }
444
445    // 1. Workspace writability = strict capability intersection.
446    let task_forbids_writes =
447        input.task.write_scope_is_explicit() && input.workspace_scope.write_scope().is_empty();
448    let workspace_writable = input.parent_workspace_writable
449        && role.workspace_access == SubagentWorkspaceAccess::ReadWriteWorkspace
450        && !task_forbids_writes;
451
452    // 2. Allowed tools = capability intersection + orphaned tool pruning.
453    let mut allowed_tools = if input.task.allowed_tools_are_explicit() {
454        input.parent_allowed_tools.to_vec()
455    } else if let Some(role_tools) = role.default_allowed_tools.as_deref() {
456        let role_set: BTreeSet<&str> = role_tools.iter().map(ToolName::as_str).collect();
457        input
458            .parent_allowed_tools
459            .iter()
460            .filter(|tool| role_set.contains(tool.as_str()))
461            .cloned()
462            .collect()
463    } else {
464        input.parent_allowed_tools.to_vec()
465    };
466
467    if !workspace_writable {
468        allowed_tools.retain(|tool| tool.as_str() != "apply_patch");
469    }
470    allowed_tools = prune_orphaned_tools(allowed_tools, input.depth, input.max_depth);
471
472    // 3. 4-level dynamic model & provider routing:
473    //    Level 2: role.model_override
474    //    Level 3: catalog.default_override.model_override
475    //    Level 4: live parent_primary_model (or initial fallback)
476    let (provider, model, retry_policy) = if let Some(override_cfg) = role.model_override.as_ref() {
477        (
478            Arc::clone(&override_cfg.provider),
479            override_cfg.model.clone(),
480            override_cfg.retry_policy,
481        )
482    } else if let Some(default_cfg) = catalog.default_override.model_override.as_ref() {
483        (
484            Arc::clone(&default_cfg.provider),
485            default_cfg.model.clone(),
486            default_cfg.retry_policy,
487        )
488    } else if let Some(live) = input.parent_primary_model {
489        (
490            Arc::clone(&live.provider),
491            live.model.clone(),
492            Some(live.retry_policy),
493        )
494    } else {
495        (
496            Arc::clone(&input.fallback_provider),
497            input.fallback_model.clone(),
498            None,
499        )
500    };
501
502    // 4. 4-level dynamic GenerationConfig inheritance:
503    //    Base: live parent_generation_config (Level 4)
504    //    Overlay reasoning_effort: default (Level 3) -> role (Level 2) -> task (Level 1)
505    let mut generation_config = input.parent_generation_config.clone();
506    if let Some(effort) = catalog.default_override.reasoning_effort.as_ref() {
507        generation_config = generation_config.with_reasoning_effort(Some(effort.clone()));
508    }
509    if let Some(effort) = role.reasoning_effort.as_ref() {
510        generation_config = generation_config.with_reasoning_effort(Some(effort.clone()));
511    }
512    if let Some(effort) = input.task.reasoning_effort() {
513        generation_config = generation_config.with_reasoning_effort(Some(effort.clone()));
514    }
515
516    // 5. Effective turn budget, timeout, and token circuit breaker:
517    //    task explicit -> role explicit overlay -> [subagents.default] -> built-in role default.
518    let max_model_turns = if input.task.max_model_turns_is_explicit() {
519        input.task.max_model_turns()
520    } else {
521        role.max_model_turns_override
522            .or(catalog.default_override.max_model_turns)
523            .unwrap_or(role.default_max_model_turns)
524            .min(input.max_model_turns_cap.max(1))
525    };
526    let timeout_secs = input
527        .task
528        .timeout_secs()
529        .or(role.default_timeout_secs)
530        .or(catalog.default_override.timeout_secs);
531    let max_total_tokens = input
532        .task
533        .max_total_tokens()
534        .or(role.max_total_tokens)
535        .or(catalog.default_override.max_total_tokens);
536
537    Ok(ResolvedSubagentRuntime {
538        role_name: role.name.clone(),
539        provider,
540        model,
541        retry_policy,
542        generation_config,
543        workspace_writable,
544        allowed_tools,
545        max_model_turns,
546        timeout_secs,
547        max_total_tokens,
548        role_instructions: role.instructions.clone(),
549    })
550}
551
552/// Removes control tools whose backing capability is absent from the child.
553fn prune_orphaned_tools(mut tools: Vec<ToolName>, depth: u8, max_depth: u8) -> Vec<ToolName> {
554    let can_spawn = depth < max_depth && tools.iter().any(|t| t.as_str() == "spawn_subagents");
555    if !can_spawn {
556        tools.retain(|tool| {
557            !matches!(
558                tool.as_str(),
559                "spawn_subagents" | "send_subagent_message" | "wait_subagents" | "cancel_subagents"
560            )
561        });
562    }
563    let can_run_process = tools.iter().any(|t| t.as_str() == "run_process");
564    if !can_run_process {
565        tools.retain(|tool| {
566            !matches!(
567                tool.as_str(),
568                "read_background_process" | "stop_background_process"
569            )
570        });
571    }
572    tools
573}
574
575/// Loads a workspace-relative `prompt_file` safely, enforcing containment under
576/// `workspace_root` and [`MAX_ROLE_PROMPT_FILE_BYTES`].
577pub fn load_workspace_prompt_file(
578    workspace_root: &Path,
579    role: &str,
580    relative_path: &str,
581) -> Result<String, SubagentRoleError> {
582    let trimmed = relative_path.trim();
583    let rel = Path::new(trimmed);
584    if trimmed.is_empty()
585        || rel.is_absolute()
586        || rel
587            .components()
588            .any(|c| matches!(c, std::path::Component::ParentDir))
589    {
590        return Err(SubagentRoleError::InvalidPromptFile {
591            role: role.to_owned(),
592            path: relative_path.to_owned(),
593            reason: "path must be workspace-relative without parent traversal".to_owned(),
594        });
595    }
596    let full_path = workspace_root.join(rel);
597    let canonical_root =
598        fs::canonicalize(workspace_root).map_err(|error| SubagentRoleError::InvalidPromptFile {
599            role: role.to_owned(),
600            path: relative_path.to_owned(),
601            reason: error.to_string(),
602        })?;
603    let canonical_file =
604        fs::canonicalize(&full_path).map_err(|error| SubagentRoleError::InvalidPromptFile {
605            role: role.to_owned(),
606            path: relative_path.to_owned(),
607            reason: error.to_string(),
608        })?;
609    if !canonical_file.starts_with(&canonical_root) {
610        return Err(SubagentRoleError::InvalidPromptFile {
611            role: role.to_owned(),
612            path: relative_path.to_owned(),
613            reason: "prompt_file symlink escapes workspace root".to_owned(),
614        });
615    }
616    let bytes =
617        fs::read(&canonical_file).map_err(|error| SubagentRoleError::InvalidPromptFile {
618            role: role.to_owned(),
619            path: relative_path.to_owned(),
620            reason: error.to_string(),
621        })?;
622    if bytes.len() > MAX_ROLE_PROMPT_FILE_BYTES {
623        return Err(SubagentRoleError::InvalidPromptFile {
624            role: role.to_owned(),
625            path: relative_path.to_owned(),
626            reason: format!("exceeds {MAX_ROLE_PROMPT_FILE_BYTES} bytes"),
627        });
628    }
629    let text = String::from_utf8(bytes).map_err(|error| SubagentRoleError::InvalidPromptFile {
630        role: role.to_owned(),
631        path: relative_path.to_owned(),
632        reason: error.to_string(),
633    })?;
634    if text.trim().is_empty() {
635        return Err(SubagentRoleError::InvalidPromptFile {
636            role: role.to_owned(),
637            path: relative_path.to_owned(),
638            reason: "prompt_file must not be blank".to_owned(),
639        });
640    }
641    Ok(text)
642}
643
644fn validate_role_name(name: &str) -> Result<(), SubagentRoleError> {
645    if name.is_empty()
646        || name.len() > 64
647        || !name
648            .bytes()
649            .all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'_' | b'-'))
650    {
651        return Err(SubagentRoleError::InvalidRoleName {
652            role: name.to_owned(),
653        });
654    }
655    Ok(())
656}
657
658fn tool_names(names: &[&str]) -> Vec<ToolName> {
659    names
660        .iter()
661        .map(|name| ToolName::new(name).expect("static built-in tool name is valid"))
662        .collect()
663}
664
665#[cfg(test)]
666mod tests;