Skip to main content

merry_runtime/subagent/
protocol.rs

1mod tolerant;
2
3use merry_core::{ErrorInfo, ModelUsage, SubagentId, SubagentTaskId, ToolName};
4use schemars::JsonSchema;
5use serde::{Deserialize, Deserializer, Serialize};
6use serde_json::json;
7
8use super::spec::{DEFAULT_MIN_MODEL_TURNS, MAX_TASK_BYTES};
9use tolerant::{
10    deserialize_optional_agent_ids_field, deserialize_optional_enum_tolerant,
11    deserialize_optional_paths_tolerant, deserialize_optional_string_tolerant, merge_agent_ids,
12};
13
14/// Filesystem isolation mode for a child subagent.
15#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize, JsonSchema)]
16#[serde(rename_all = "snake_case")]
17pub enum SubagentWorkspaceMode {
18    /// Run inside the parent's shared workspace directory (default).
19    #[default]
20    Shared,
21    /// Run inside an isolated detached Git worktree outside the main repository.
22    Worktree,
23}
24
25impl SubagentWorkspaceMode {
26    /// Returns the stable provider-visible mode string.
27    #[must_use]
28    pub const fn as_str(self) -> &'static str {
29        match self {
30            Self::Shared => "shared",
31            Self::Worktree => "worktree",
32        }
33    }
34}
35
36/// Snapshot source used when creating a child Git worktree.
37#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize, JsonSchema)]
38#[serde(rename_all = "snake_case")]
39pub enum SubagentWorktreeBase {
40    /// Snapshot the parent's current working tree (tracked diff + small untracked files) on top of `HEAD` (default).
41    #[default]
42    WorkingTree,
43    /// Checkout clean `HEAD` without uncommitted working-tree edits.
44    Head,
45}
46
47impl SubagentWorktreeBase {
48    /// Returns the stable provider-visible worktree base string.
49    #[must_use]
50    pub const fn as_str(self) -> &'static str {
51        match self {
52            Self::WorkingTree => "working_tree",
53            Self::Head => "head",
54        }
55    }
56}
57
58/// Metadata reported for a child subagent executed inside an isolated Git worktree.
59#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
60#[serde(deny_unknown_fields)]
61pub struct SubagentWorktreeView {
62    /// Absolute path to the isolated Git worktree directory.
63    pub path: String,
64    /// Baseline commit OID against which net child changes are diffed.
65    pub baseline_oid: String,
66    /// Compact `git diff --stat <baseline_oid>` summary when net changes exist.
67    #[serde(default, skip_serializing_if = "Option::is_none")]
68    pub diff_stat: Option<String>,
69    /// True when the worktree remains on disk (changes exist or cleanup skipped); false when auto-removed after zero net changes.
70    pub retained: bool,
71}
72
73/// Optional wait behavior for `spawn_subagents`.
74#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize, JsonSchema)]
75#[serde(rename_all = "snake_case")]
76pub enum SpawnWaitMode {
77    /// Return immediately after spawning (default asynchronous behavior).
78    #[default]
79    None,
80    /// Wait up to the foreground budget until all spawned children reach terminal state.
81    All,
82    /// Wait up to the foreground budget until any spawned child reaches terminal state.
83    Any,
84}
85
86/// Provider-visible input for `spawn_subagents`.
87///
88/// Accepts either `{ "tasks": [ ... ] }` or a single-task shorthand object
89/// `{ "task": "...", ... }` during deserialization while exposing the canonical
90/// `tasks` schema to providers.
91#[merry_tools_macros::tool(
92    crate = "crate",
93    name = "spawn_subagents",
94    description = "Spawn bounded child agents for parallel delegated tasks."
95)]
96#[derive(Debug, Clone, PartialEq, Eq, Serialize, JsonSchema)]
97pub struct SpawnSubagentsInput {
98    #[schemars(
99        description = "Child tasks to spawn. Each task is validated against the current child runtime limits."
100    )]
101    pub tasks: Vec<SpawnSubagentTaskInput>,
102    #[schemars(
103        description = "Optional concurrency cap for this batch. Omit it to use the runtime scheduler default; zero queues all tasks until capacity is available.",
104        range(min = 0)
105    )]
106    pub max_concurrency: Option<usize>,
107    #[schemars(
108        description = "Optional wait mode after spawning: `none` (default, return immediately), `all` (wait for every spawned child), or `any` (wait for the first terminal child). If the foreground budget expires or the turn is interrupted, running children stay alive in the background."
109    )]
110    #[serde(default)]
111    pub wait: Option<SpawnWaitMode>,
112    #[schemars(
113        description = "Optional foreground wait deadline in seconds when `wait` is `all` or `any`. Exceeding it hands running children off to the background without cancelling them.",
114        range(min = 1)
115    )]
116    #[serde(default)]
117    pub foreground_budget_secs: Option<u64>,
118}
119
120impl<'de> Deserialize<'de> for SpawnSubagentsInput {
121    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
122    where
123        D: Deserializer<'de>,
124    {
125        #[derive(Deserialize)]
126        #[serde(deny_unknown_fields)]
127        struct BatchWire {
128            tasks: Vec<SpawnSubagentTaskInput>,
129            #[serde(default)]
130            max_concurrency: Option<usize>,
131            #[serde(default)]
132            wait: Option<SpawnWaitMode>,
133            #[serde(default)]
134            foreground_budget_secs: Option<u64>,
135        }
136
137        #[derive(Deserialize)]
138        #[serde(deny_unknown_fields)]
139        struct SingleWire {
140            #[serde(flatten)]
141            task: SpawnSubagentTaskInput,
142            #[serde(default)]
143            max_concurrency: Option<usize>,
144            #[serde(default)]
145            wait: Option<SpawnWaitMode>,
146            #[serde(default)]
147            foreground_budget_secs: Option<u64>,
148        }
149
150        let value = serde_json::Value::deserialize(deserializer)?;
151        if value.get("tasks").is_some() {
152            let batch: BatchWire =
153                serde_json::from_value(value).map_err(serde::de::Error::custom)?;
154            Ok(Self {
155                tasks: batch.tasks,
156                max_concurrency: batch.max_concurrency,
157                wait: batch.wait,
158                foreground_budget_secs: batch.foreground_budget_secs,
159            })
160        } else if value.get("task").is_some() {
161            let single: SingleWire =
162                serde_json::from_value(value).map_err(serde::de::Error::custom)?;
163            Ok(Self {
164                tasks: vec![single.task],
165                max_concurrency: single.max_concurrency,
166                wait: single.wait,
167                foreground_budget_secs: single.foreground_budget_secs,
168            })
169        } else {
170            let batch: BatchWire =
171                serde_json::from_value(value).map_err(serde::de::Error::custom)?;
172            Ok(Self {
173                tasks: batch.tasks,
174                max_concurrency: batch.max_concurrency,
175                wait: batch.wait,
176                foreground_budget_secs: batch.foreground_budget_secs,
177            })
178        }
179    }
180}
181
182/// Provider-visible task item for `spawn_subagents`.
183#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
184#[serde(deny_unknown_fields)]
185pub struct SpawnSubagentTaskInput {
186    #[schemars(
187        description = "Non-blank delegated task brief. Include the goal, already ruled-out paths, and exact target files/symbols; scope belongs in structured scope fields.",
188        length(min = 1, max = MAX_TASK_BYTES)
189    )]
190    pub task: String,
191    #[schemars(description = "Optional short display name for this child task.")]
192    #[serde(default, deserialize_with = "deserialize_optional_string_tolerant")]
193    pub display_name: Option<String>,
194    #[schemars(
195        description = "Optional specialist role for this child (for example `explore` for read-only codebase research, `coder` for implementation and local checks, or `review` for independent skeptical verification). Omit to use the default coding role."
196    )]
197    #[serde(default, deserialize_with = "deserialize_optional_string_tolerant")]
198    pub role: Option<String>,
199    #[schemars(
200        schema_with = "max_model_turns_schema",
201        description = "Optional positive child model-turn budget. Omit to use the configured default. If reached, wake the same child with `send_subagent_message` and `extra_model_turns` instead of respawning from scratch."
202    )]
203    #[serde(default)]
204    pub max_model_turns: Option<u32>,
205    #[schemars(
206        description = "Optional wall-clock timeout in seconds for this child task. Omit to use the runtime default.",
207        range(min = 1)
208    )]
209    #[serde(default)]
210    pub timeout_secs: Option<u64>,
211    /// Exact registered Merry tool names the child may use. Names are copied
212    /// verbatim from the current tool list without provider namespace prefixes;
213    /// use `run_process`, never `functions.run_process`.
214    #[schemars(
215        description = "Optional exact registered Merry tool names copied verbatim from the current tool list. Do not add provider namespace prefixes: use `run_process`, never `functions.run_process`."
216    )]
217    #[serde(default)]
218    pub allowed_tools: Option<Vec<ToolName>>,
219    #[schemars(
220        schema_with = "optional_scope_paths_schema",
221        description = "Optional normalized workspace-relative paths the child may read. Omit to inherit parent scope. Empty array authorizes no workspace reads."
222    )]
223    #[serde(default, deserialize_with = "deserialize_optional_paths_tolerant")]
224    pub read_scope: Option<Vec<String>>,
225    #[schemars(
226        schema_with = "optional_scope_paths_schema",
227        description = "Optional normalized workspace-relative paths the child may write. Omit to inherit parent scope. Empty array makes the child read-only. Parallel writable children must have disjoint write scopes."
228    )]
229    #[serde(default, deserialize_with = "deserialize_optional_paths_tolerant")]
230    pub write_scope: Option<Vec<String>>,
231    #[schemars(
232        schema_with = "optional_scope_paths_schema",
233        description = "Optional normalized workspace-relative paths the child must not access. Further restricts read_scope and write_scope."
234    )]
235    #[serde(default, deserialize_with = "deserialize_optional_paths_tolerant")]
236    pub forbidden_paths: Option<Vec<String>>,
237    #[schemars(
238        schema_with = "optional_context_files_schema",
239        description = "Optional workspace-relative files or line ranges (`path/to/file.rs` or `path/to/file.rs:1-120`) to preload into the child's initial handoff context before turn 1."
240    )]
241    #[serde(default, deserialize_with = "deserialize_optional_paths_tolerant")]
242    pub context_files: Option<Vec<String>>,
243    #[schemars(
244        description = "Optional format or acceptance checklist for the child's final report (injected into `<merry_subagent_handoff>`)."
245    )]
246    #[serde(default, deserialize_with = "deserialize_optional_string_tolerant")]
247    pub expected_output: Option<String>,
248    #[schemars(
249        description = "Optional child model reasoning-effort override supported by the configured provider."
250    )]
251    #[serde(default, deserialize_with = "deserialize_optional_string_tolerant")]
252    pub reasoning_effort: Option<String>,
253    #[schemars(
254        description = "Optional filesystem isolation mode: `shared` (default, shares parent workspace) or `worktree` (isolated detached Git worktree outside the main repository; requires a Git workspace)."
255    )]
256    #[serde(default, deserialize_with = "deserialize_optional_enum_tolerant")]
257    pub workspace: Option<SubagentWorkspaceMode>,
258    #[schemars(
259        description = "Optional snapshot base when `workspace` is `worktree`: `working_tree` (default, includes parent's uncommitted tracked edits and small untracked files) or `head` (clean `HEAD`)."
260    )]
261    #[serde(default, deserialize_with = "deserialize_optional_enum_tolerant")]
262    pub worktree_base: Option<SubagentWorktreeBase>,
263}
264
265/// Notice returned when a foreground wait hands active children off to background execution.
266#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
267#[serde(deny_unknown_fields)]
268pub struct BackgroundHandoffNotice {
269    /// Child agent ids still running or queued in the background.
270    pub handed_off_agent_ids: Vec<SubagentId>,
271    /// Why the foreground wait ended (`foreground_budget_elapsed` or `parent_turn_interrupted`).
272    pub reason: String,
273    /// Explicit coordinator-facing note preventing duplicate spawns.
274    pub message: String,
275}
276
277/// Provider-visible output for `spawn_subagents`.
278#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
279#[serde(deny_unknown_fields)]
280pub struct SpawnSubagentsOutput {
281    /// Accepted child tasks.
282    pub spawned: Vec<SpawnedSubagentView>,
283    /// Rejected child tasks with compact reasons.
284    pub rejected: Vec<RejectedSubagentView>,
285    /// Optional wait result when `wait` was set to `all` or `any`.
286    #[serde(default, skip_serializing_if = "Option::is_none")]
287    pub wait_result: Option<WaitSubagentsOutput>,
288    /// Optional notice when foreground wait ended while children remain active in the background.
289    #[serde(default, skip_serializing_if = "Option::is_none")]
290    pub background_handoff: Option<BackgroundHandoffNotice>,
291}
292
293/// Compact provider-visible view of an accepted child task.
294#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
295#[serde(deny_unknown_fields)]
296pub struct SpawnedSubagentView {
297    /// Runtime-owned child agent id.
298    pub agent_id: SubagentId,
299    /// Runtime-owned child task id.
300    pub task_id: SubagentTaskId,
301    /// Optional compact display name.
302    pub display_name: Option<String>,
303    /// Optional role name requested for this child.
304    #[serde(default, skip_serializing_if = "Option::is_none")]
305    pub role: Option<String>,
306    /// Compact status label.
307    pub status: SpawnedSubagentStatusLabel,
308    /// Compact task anchor assigned to the child runtime.
309    pub task_anchor: String,
310    /// Workspace-relative paths the child may read.
311    pub read_scope: Vec<String>,
312    /// Workspace-relative paths the child may write.
313    pub write_scope: Vec<String>,
314}
315
316/// Provider-visible status labels possible immediately after spawn.
317#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
318#[serde(rename_all = "snake_case")]
319pub enum SpawnedSubagentStatusLabel {
320    /// Child task is accepted but has not begun running.
321    Queued,
322    /// Child task is currently running.
323    Running,
324}
325
326/// Compact provider-visible view of a rejected child task.
327#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
328#[serde(deny_unknown_fields)]
329pub struct RejectedSubagentView {
330    /// Index into the requested task batch.
331    pub task_index: usize,
332    /// Stable human-readable rejection reason.
333    pub reason: String,
334}
335
336/// Delivery policy for `send_subagent_message`.
337#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize, JsonSchema)]
338#[serde(rename_all = "snake_case")]
339pub enum SubagentMessageDelivery {
340    /// Inject at the next safe checkpoint (default; does not break active tool atomicity).
341    #[default]
342    Steer,
343    /// Queue behind any already-buffered follow-up messages.
344    Queue,
345}
346
347/// Provider-visible input for `send_subagent_message`.
348#[merry_tools_macros::tool(
349    crate = "crate",
350    name = "send_subagent_message",
351    description = "Send a follow-up instruction to a running child agent or wake a finished/blocked child with its prior context intact."
352)]
353#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
354#[serde(deny_unknown_fields)]
355pub struct SendSubagentMessageInput {
356    #[schemars(description = "Target child agent id (for example `agent-1`).")]
357    pub agent_id: SubagentId,
358    #[schemars(
359        description = "Non-blank follow-up instruction, new facts, or correction for the child agent.",
360        length(min = 1, max = MAX_TASK_BYTES)
361    )]
362    pub message: String,
363    #[schemars(
364        description = "Optional delivery mode when the child is active: `steer` (default, next safe checkpoint) or `queue` (after buffered follow-ups). Ignored when waking a terminal child."
365    )]
366    #[serde(default)]
367    pub delivery: Option<SubagentMessageDelivery>,
368    #[schemars(
369        description = "Optional positive model-turn budget for the resumed turn when waking a blocked or completed child.",
370        range(min = 1)
371    )]
372    #[serde(default)]
373    pub extra_model_turns: Option<u32>,
374    #[schemars(
375        description = "When true, wait up to `timeout_ms` (or the foreground budget) for the child to settle after delivering or waking."
376    )]
377    #[serde(default)]
378    pub wait: Option<bool>,
379    #[schemars(
380        description = "Optional wait observation deadline in milliseconds when `wait` is true.",
381        range(min = 0)
382    )]
383    #[serde(default)]
384    pub timeout_ms: Option<u64>,
385}
386
387/// Strongly typed, non-ambiguous delivery outcome for `send_subagent_message`.
388#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
389#[serde(rename_all = "snake_case")]
390pub enum SendSubagentMessageOutcome {
391    /// Message accepted for an active (`running` or `queued`) child.
392    Accepted,
393    /// Terminal (`completed`, `blocked`, `cancelled`, or `failed`) child woken with same `agent_id`.
394    Woken,
395    /// Unknown `agent_id` or child runtime cannot be woken.
396    NotFoundOrNotOwned,
397    /// Child follow-up queue is full.
398    Saturated,
399    /// Parent session is shutting down and no longer accepts messages.
400    SessionClosing,
401}
402
403/// Provider-visible output for `send_subagent_message`.
404#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
405#[serde(deny_unknown_fields)]
406pub struct SendSubagentMessageOutput {
407    /// Target child agent id.
408    pub agent_id: SubagentId,
409    /// Non-ambiguous typed delivery outcome.
410    pub outcome: SendSubagentMessageOutcome,
411    /// Current child status label, when known.
412    #[serde(default, skip_serializing_if = "Option::is_none")]
413    pub status: Option<SubagentStatusLabel>,
414    /// Optional wait result when `wait` was true.
415    #[serde(default, skip_serializing_if = "Option::is_none")]
416    pub wait_result: Option<WaitSubagentsOutput>,
417    /// Concise human/coordinator-readable explanation.
418    pub message: String,
419}
420
421/// Wait behavior for `wait_subagents`.
422#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
423#[serde(rename_all = "snake_case")]
424pub enum WaitMode {
425    /// Return after any selected child reaches a terminal status.
426    Any,
427    /// Return after all selected children reach terminal statuses.
428    All,
429}
430
431/// Provider-visible input for `wait_subagents`.
432///
433/// Tolerates both `agent_ids: [...]`, `agent_ids: "agent-1"`, and the singular
434/// alias `agent_id: "agent-1"`.
435#[merry_tools_macros::tool(
436    crate = "crate",
437    name = "wait_subagents",
438    description = "Inspect or wait for child agent statuses and compact results."
439)]
440#[derive(Debug, Clone, PartialEq, Eq, Serialize, JsonSchema)]
441pub struct WaitSubagentsInput {
442    #[schemars(
443        description = "Child agent ids to inspect or wait on. Provide at least one id; the result contains only these selected agents.",
444        length(min = 1)
445    )]
446    pub agent_ids: Vec<SubagentId>,
447    #[schemars(
448        description = "Optional completion mode. Use `any` for the first terminal child or `all` for every selected child; omit it for `all`."
449    )]
450    pub mode: Option<WaitMode>,
451    /// Optional observation deadline in milliseconds. This is not a task
452    /// budget and a timeout never means that the child completed.
453    #[schemars(
454        description = "Observation deadline in milliseconds, not a task budget. Zero returns an immediate status snapshot; omit it to wait until the selected completion condition. A timed-out result is only a status snapshot and must not be reported as completion.",
455        range(min = 0)
456    )]
457    pub timeout_ms: Option<u64>,
458}
459
460impl<'de> Deserialize<'de> for WaitSubagentsInput {
461    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
462    where
463        D: Deserializer<'de>,
464    {
465        #[derive(Deserialize)]
466        #[serde(deny_unknown_fields)]
467        struct Wire {
468            #[serde(default, deserialize_with = "deserialize_optional_agent_ids_field")]
469            agent_ids: Option<Vec<SubagentId>>,
470            #[serde(default)]
471            agent_id: Option<SubagentId>,
472            #[serde(default)]
473            mode: Option<WaitMode>,
474            #[serde(default)]
475            timeout_ms: Option<u64>,
476        }
477
478        let wire = Wire::deserialize(deserializer)?;
479        let agent_ids = merge_agent_ids(wire.agent_ids, wire.agent_id)?;
480        Ok(Self {
481            agent_ids,
482            mode: wire.mode,
483            timeout_ms: wire.timeout_ms,
484        })
485    }
486}
487
488/// Provider-visible input for `cancel_subagents`.
489///
490/// Tolerates both `agent_ids: [...]`, `agent_ids: "agent-1"`, and the singular
491/// alias `agent_id: "agent-1"`.
492#[merry_tools_macros::tool(
493    crate = "crate",
494    name = "cancel_subagents",
495    description = "Cancel selected child agents."
496)]
497#[derive(Debug, Clone, PartialEq, Eq, Serialize, JsonSchema)]
498pub struct CancelSubagentsInput {
499    #[schemars(
500        description = "Child agent ids to cancel. Provide at least one id; the result contains only these selected agents.",
501        length(min = 1)
502    )]
503    pub agent_ids: Vec<SubagentId>,
504}
505
506impl<'de> Deserialize<'de> for CancelSubagentsInput {
507    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
508    where
509        D: Deserializer<'de>,
510    {
511        #[derive(Deserialize)]
512        #[serde(deny_unknown_fields)]
513        struct Wire {
514            #[serde(default, deserialize_with = "deserialize_optional_agent_ids_field")]
515            agent_ids: Option<Vec<SubagentId>>,
516            #[serde(default)]
517            agent_id: Option<SubagentId>,
518        }
519
520        let wire = Wire::deserialize(deserializer)?;
521        let agent_ids = merge_agent_ids(wire.agent_ids, wire.agent_id)?;
522        Ok(Self { agent_ids })
523    }
524}
525
526fn optional_scope_paths_schema(_: &mut schemars::SchemaGenerator) -> schemars::Schema {
527    schemars::Schema::try_from(json!({
528        "description": "Optional normalized workspace-relative scope paths. Use `.` for the workspace root or a concrete relative path such as `crates/merry-runtime`.",
529        "anyOf": [
530            { "type": "null" },
531            {
532                "type": "array",
533                "items": {
534                    "type": "string",
535                    "minLength": 1,
536                    "description": "Normalized workspace-relative path. Do not use `..`, absolute paths, embedded `.` segments, empty segments, or backslashes.",
537                    "examples": [".", "crates/merry-runtime", "tmp/output"],
538                    "anyOf": [
539                        { "const": "." },
540                        { "allOf": [
541                            { "not": { "pattern": "(^|/)\\.\\.?(/|$)" } },
542                            { "not": { "pattern": "(^/|//|\\\\)" } },
543                            { "not": { "pattern": "[\\u0000-\\u001F\\u007F]" } }
544                        ] }
545                    ]
546                }
547            }
548        ]
549    }))
550    .expect("static optional subagent scope schema is valid")
551}
552
553fn optional_context_files_schema(_: &mut schemars::SchemaGenerator) -> schemars::Schema {
554    schemars::Schema::try_from(json!({
555        "description": "Optional workspace-relative files or line ranges (`path/to/file.rs` or `path/to/file.rs:1-120`) to preload into the child's handoff context.",
556        "anyOf": [
557            { "type": "null" },
558            {
559                "type": "array",
560                "items": {
561                    "type": "string",
562                    "minLength": 1,
563                    "description": "Normalized workspace-relative file path with optional `:start-end` 1-based line range."
564                }
565            }
566        ]
567    }))
568    .expect("static optional context_files schema is valid")
569}
570
571fn max_model_turns_schema(_: &mut schemars::SchemaGenerator) -> schemars::Schema {
572    schemars::Schema::try_from(json!({
573        "type": "integer",
574        "minimum": DEFAULT_MIN_MODEL_TURNS,
575        "default": super::spec::DEFAULT_MAX_MODEL_TURNS,
576        "description": "Optional positive child lifecycle model-turn budget. Omit for the configured default. If reached, wake the same child with `send_subagent_message` and `extra_model_turns`."
577    }))
578    .expect("static child model-turn schema is valid")
579}
580
581/// Provider-visible compact status output for `wait_subagents`.
582#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
583#[serde(deny_unknown_fields)]
584pub struct WaitSubagentsOutput {
585    /// Compact status views for selected child agents.
586    pub agents: Vec<SubagentStatusView>,
587    /// True when the observation deadline elapsed before the requested mode
588    /// became terminal.
589    pub timed_out: bool,
590    /// True when the requested wait mode is satisfied by the returned status
591    /// snapshot. Only terminal=true permits a completion claim.
592    pub terminal: bool,
593    /// Selected child ids that are still non-terminal in this snapshot.
594    pub pending_agent_ids: Vec<SubagentId>,
595    /// Explicit note when non-terminal children remain running in the background.
596    #[serde(default, skip_serializing_if = "Option::is_none")]
597    pub handoff_note: Option<String>,
598}
599
600impl WaitSubagentsOutput {
601    /// Creates wait output from compact child status views.
602    #[must_use]
603    pub fn new(agents: Vec<SubagentStatusView>) -> Self {
604        let terminal = agents.iter().all(SubagentStatusView::is_terminal);
605        Self::with_wait_state(agents, terminal, false)
606    }
607
608    pub(crate) fn with_wait_state(
609        agents: Vec<SubagentStatusView>,
610        terminal: bool,
611        timed_out: bool,
612    ) -> Self {
613        let pending_agent_ids = agents
614            .iter()
615            .filter(|agent| !agent.is_terminal())
616            .map(|agent| agent.agent_id.clone())
617            .collect::<Vec<_>>();
618        let handoff_note = (timed_out && !terminal && !pending_agent_ids.is_empty()).then(|| {
619            "Pending subagents were NOT cancelled and are still running in the background. Do not spawn them again; wait or rely on automatic completion notification.".to_owned()
620        });
621        Self {
622            agents,
623            timed_out,
624            terminal,
625            pending_agent_ids,
626            handoff_note,
627        }
628    }
629}
630
631/// Compact child lifecycle status.
632#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
633#[serde(rename_all = "snake_case")]
634pub enum SubagentStatusLabel {
635    /// Child task is accepted but has not begun running.
636    Queued,
637    /// Child task is currently running.
638    Running,
639    /// Child task completed successfully.
640    Completed,
641    /// Child task failed.
642    Failed,
643    /// Child task stopped before completion and can be woken or replaced.
644    Blocked,
645    /// Child task was cancelled.
646    Cancelled,
647}
648
649impl SubagentStatusLabel {
650    /// Returns the stable provider-visible status string.
651    #[must_use]
652    pub fn as_str(&self) -> &'static str {
653        match self {
654            Self::Queued => "queued",
655            Self::Running => "running",
656            Self::Completed => "completed",
657            Self::Failed => "failed",
658            Self::Blocked => "blocked",
659            Self::Cancelled => "cancelled",
660        }
661    }
662
663    pub(super) fn is_terminal(&self) -> bool {
664        matches!(
665            self,
666            Self::Completed | Self::Failed | Self::Blocked | Self::Cancelled
667        )
668    }
669}
670
671/// Provider-visible compact child status.
672#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
673#[serde(deny_unknown_fields)]
674pub struct SubagentStatusView {
675    /// Runtime-owned child agent id.
676    pub agent_id: SubagentId,
677    /// Runtime-owned child task id.
678    pub task_id: SubagentTaskId,
679    /// Optional short display name.
680    #[serde(default, skip_serializing_if = "Option::is_none")]
681    pub display_name: Option<String>,
682    /// Optional specialist role name.
683    #[serde(default, skip_serializing_if = "Option::is_none")]
684    pub role: Option<String>,
685    /// Compact lifecycle status.
686    pub status: SubagentStatusLabel,
687    /// Compact result or progress summary.
688    pub summary: String,
689    /// Explicit child result reported by the child loop, when it reached one.
690    pub result: Option<SubagentResultView>,
691    /// Shared-workspace output paths for exact follow-up reads.
692    pub output_paths: Vec<String>,
693    /// Shared-workspace paths changed by the child.
694    pub changed_paths: Vec<String>,
695    /// Optional compact failure/cancellation diagnostics.
696    pub diagnostics: Option<ErrorInfo>,
697    /// Cumulative model turns executed by this child.
698    #[serde(default)]
699    pub turns_used: u32,
700    /// Cumulative tool calls resolved by this child.
701    #[serde(default)]
702    pub tool_calls: u32,
703    /// Wall-clock elapsed execution time in milliseconds.
704    #[serde(default)]
705    pub elapsed_ms: u64,
706    /// Cumulative model token usage reported by this child, when available.
707    #[serde(default, skip_serializing_if = "Option::is_none")]
708    pub usage: Option<ModelUsage>,
709    /// Monotonic count of raw assistant and tool output bytes observed so far
710    /// (progress signature for polling loops).
711    #[serde(default)]
712    pub raw_output_bytes: u64,
713    /// Optional isolated Git worktree metadata when the child ran with `workspace: "worktree"`.
714    #[serde(default, skip_serializing_if = "Option::is_none")]
715    pub worktree: Option<SubagentWorktreeView>,
716}
717
718impl SubagentStatusView {
719    /// Creates a completed child status with compact paths and no transcript.
720    #[must_use]
721    pub fn completed(
722        agent_id: SubagentId,
723        task_id: SubagentTaskId,
724        summary: impl Into<String>,
725        output_paths: Vec<String>,
726        changed_paths: Vec<String>,
727    ) -> Self {
728        Self {
729            agent_id,
730            task_id,
731            display_name: None,
732            role: None,
733            status: SubagentStatusLabel::Completed,
734            summary: summary.into(),
735            result: None,
736            output_paths,
737            changed_paths,
738            diagnostics: None,
739            turns_used: 0,
740            tool_calls: 0,
741            elapsed_ms: 0,
742            usage: None,
743            raw_output_bytes: 0,
744            worktree: None,
745        }
746    }
747
748    pub(super) fn is_terminal(&self) -> bool {
749        self.status.is_terminal()
750    }
751}
752
753/// Explicit result returned by a child agent to its parent.
754#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
755#[serde(deny_unknown_fields)]
756pub struct SubagentResultView {
757    /// Child-authored conclusion. This is not truncated by runtime.
758    pub conclusion: String,
759}
760
761impl SubagentResultView {
762    pub(super) fn from_conclusion(conclusion: impl Into<String>) -> Option<Self> {
763        let conclusion = conclusion.into();
764        if conclusion.trim().is_empty() {
765            None
766        } else {
767            Some(Self { conclusion })
768        }
769    }
770}