Skip to main content

merry_runtime/subagent/tools/
schema.rs

1use crate::subagent::{
2    CANCEL_SUBAGENTS_TOOL_NAME, SEND_SUBAGENT_MESSAGE_TOOL_NAME, SPAWN_SUBAGENTS_TOOL_NAME,
3    WAIT_SUBAGENTS_TOOL_NAME,
4    protocol::{
5        CancelSubagentsInput, SendSubagentMessageInput, SpawnSubagentsInput, WaitSubagentsInput,
6    },
7};
8use merry_core::{ToolInputSchema, ToolSpec};
9use serde_json::Value;
10
11pub(super) const WAIT_SEMANTIC_CHECKPOINT_GUIDANCE: &str = "Observe child statuses at semantic or terminal checkpoints; do not poll for high-frequency progress.";
12const CHILD_MODEL_TURN_GUIDANCE: &str = "Omit max_model_turns to use the configured default. If a child reaches its turn limit or times out, it stops as blocked with its transcript intact: resume that same child with send_subagent_message(agent_id, extra_model_turns=...) instead of respawning from scratch.";
13const SEND_MESSAGE_ANTI_MICROMANAGE_GUIDANCE: &str = "Send a follow-up instruction to an active subagent or wake a completed, blocked, or cancelled subagent with its full prior transcript and agent_id intact. Use delivery=\"steer\" (default) to redirect at the next safe checkpoint or \"queue\" to append after buffered follow-ups, and set extra_model_turns when extending a blocked child. Do NOT send status checks, progress nudges, or \"hurry up / stop reading\" messages — use this only to supply new facts, correct a wrong target, extend a blocked child, or continue work with a finished child.";
14
15/// Returns provider-visible subagent tool specs.
16pub fn subagent_tool_specs() -> Result<[ToolSpec; 4], merry_core::CoreError> {
17    subagent_tool_specs_with_bounds_and_roles(
18        crate::subagent::DEFAULT_MIN_MODEL_TURNS,
19        crate::subagent::DEFAULT_MAX_MODEL_TURNS,
20        &[],
21    )
22}
23
24pub(super) fn subagent_tool_specs_with_bounds_and_roles(
25    min_model_turns: u32,
26    max_model_turns: u32,
27    role_summaries: &[(String, String)],
28) -> Result<[ToolSpec; 4], merry_core::CoreError> {
29    let roles_clause = if role_summaries.is_empty() {
30        "Use `role` to pick a specialist (`explore` for fast read-only search, `coder` for scoped implementation and checks, `review` for independent skeptical verification) and `context_files` to preload key file slices before turn 1.".to_owned()
31    } else {
32        let list = role_summaries
33            .iter()
34            .map(|(name, desc)| format!("`{name}` ({desc})"))
35            .collect::<Vec<_>>()
36            .join(", ");
37        format!(
38            "Use `role` to pick an enabled specialist role ({list}) and `context_files` to preload key file slices before turn 1."
39        )
40    };
41    let spawn_description = format!(
42        "Spawn one or more bounded child agents for independent, parallel, or context-heavy tasks. \
43         Terminal child results are delivered automatically on the next model turn as a `<subagent-notification>` block with inlined conclusions and changed_paths; set `wait` to `all` or `any` only when you need results inline before continuing (if the foreground wait budget expires or the turn is interrupted, children keep running in the background — do not spawn duplicates). \
44         {roles_clause} \
45         {CHILD_MODEL_TURN_GUIDANCE} Configured child model-turn range: {min_model_turns}..={max_model_turns}. \
46         Keep `tasks[].task` focused on the objective and ruled-out paths; declare path boundaries in `read_scope`, `write_scope`, and `forbidden_paths`. \
47         Set `tasks[].workspace` to `worktree` when a child needs an isolated detached Git worktree (for parallel edits or speculative changes; `worktree_base` defaults to `working_tree`). \
48         In `tasks[].allowed_tools`, copy exact registered Merry tool names without provider namespace prefixes: use `run_process`, never `functions.run_process`."
49    );
50    let spawn_spec =
51        SpawnSubagentsInput::tool_spec_with(SPAWN_SUBAGENTS_TOOL_NAME, &spawn_description)?;
52    let mut spawn_schema = spawn_spec.input_schema().as_schema().clone();
53    if !set_model_turns_schema_bounds(&mut spawn_schema, min_model_turns, max_model_turns) {
54        return Err(merry_core::CoreError::InvalidSchema {
55            kind: "SpawnSubagentsInput",
56            reason: "generated schema is missing the max_model_turns property",
57        });
58    }
59    let spawn_spec = spawn_spec.with_input_schema(ToolInputSchema::new(spawn_schema)?)?;
60
61    Ok([
62        spawn_spec,
63        SendSubagentMessageInput::tool_spec_with(
64            SEND_SUBAGENT_MESSAGE_TOOL_NAME,
65            SEND_MESSAGE_ANTI_MICROMANAGE_GUIDANCE,
66        )?,
67        WaitSubagentsInput::tool_spec_with(
68            WAIT_SUBAGENTS_TOOL_NAME,
69            format!(
70                "Inspect or wait for child agent statuses, stats, and full conclusions. {WAIT_SEMANTIC_CHECKPOINT_GUIDANCE} timeout_ms is an observation deadline, not a task budget; zero returns an immediate status snapshot, while omission waits for the selected completion condition. A timed_out=true result is only a status snapshot, never completion. Claim completion only when terminal=true and the relevant statuses are terminal."
71            ),
72        )?,
73        CancelSubagentsInput::tool_spec_with(
74            CANCEL_SUBAGENTS_TOOL_NAME,
75            "Cancel selected child agents.",
76        )?,
77    ])
78}
79
80fn set_model_turns_schema_bounds(
81    schema: &mut schemars::Schema,
82    min_model_turns: u32,
83    max_model_turns: u32,
84) -> bool {
85    set_model_turns_schema_bounds_in_value(schema.as_object_mut(), min_model_turns, max_model_turns)
86}
87
88fn set_model_turns_schema_bounds_in_value(
89    object: Option<&mut serde_json::Map<String, Value>>,
90    min_model_turns: u32,
91    max_model_turns: u32,
92) -> bool {
93    let Some(object) = object else {
94        return false;
95    };
96
97    let mut found = false;
98    if let Some(properties) = object.get_mut("properties").and_then(Value::as_object_mut)
99        && let Some(field) = properties
100            .get_mut("max_model_turns")
101            .and_then(Value::as_object_mut)
102    {
103        field.insert("minimum".to_owned(), serde_json::json!(min_model_turns));
104        field.insert("default".to_owned(), serde_json::json!(max_model_turns));
105        field.insert("maximum".to_owned(), serde_json::json!(max_model_turns));
106        found = true;
107    }
108
109    for child in object.values_mut() {
110        if set_model_turns_schema_bounds_in_value(
111            child.as_object_mut(),
112            min_model_turns,
113            max_model_turns,
114        ) {
115            found = true;
116        }
117    }
118    found
119}