mobius 0.15.5

A small, modular Rust framework for building coding agents
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
//! Durable asynchronous child-agent middleware.

use std::collections::BTreeMap;
use std::collections::BTreeSet;
use std::sync::Arc;

use serde::Deserialize;
use serde::Serialize;
use serde_json::Value;

use super::ActiveCommandContext;
use super::Middleware;
use super::MiddlewareCommandContext;
use super::MiddlewareCommandOutput;
use super::ModelContext;
use super::PromptSection;
use super::RuntimeContext;
use super::SessionStartContext;
use super::SessionStartSource;
use super::SubmissionResult;
use super::manifest::{MiddlewareManifest, MiddlewareSettingChoices, MiddlewareSettingManifest};
use super::tools::Catalog;
use super::tools::labeled_tool_heading;
use super::tools::render_tool_event;
use crate::BoxFuture;
use crate::Error;
use crate::Result;
use crate::agent::{Agent, AgentRole};
use crate::backend::checkpoint::Checkpoint;
use crate::backend::checkpoint::CheckpointStore;
use crate::backend::model::internal_user_message;
use crate::protocol::EventMsg;
use crate::protocol::FrontendBlock;
use crate::protocol::FrontendBlockUpdate;
use crate::protocol::FrontendCommand;
use crate::protocol::FrontendContribution;
use crate::protocol::FrontendEvent;
use crate::protocol::FrontendPreviewUpdate;
use crate::protocol::MessageAuthor;
use crate::protocol::Op;
use crate::protocol::internal_message_kind;
use crate::protocol::message_metadata;

use self::runtime::Shared;

mod runtime;
mod tools;

use self::tools::{InterruptAgent, ListAgents, SendMessage, SpawnAgent, WaitAgent, fork_context};
#[cfg(test)]
use self::tools::{cleanup_error, supervise, wait_parameters, wait_timeout};

const MAX_TASK_NAME_BYTES: usize = 64;
const IDENTITY_KEY: &str = "subagents.identity";
const SPAWN_CONTEXT_KEY: &str = "subagents.spawn_context";
mod text {
    pub const COMMAND_DESCRIPTION: &str = "open a subagent thread";
    pub const DEFAULTS_MAX_AGENTS: i64 = 101;
    pub const DEFAULTS_MAX_CONCURRENCY: i64 = 8;
    pub const DEFAULTS_MAX_DEPTH: i64 = 4;
    pub const DEFAULTS_WAIT_MS: i64 = 30000;
    pub const MANIFEST_DESCRIPTION: &str = "Delegate independent work to durable child agents";
    pub const MANIFEST_LABEL: &str = "Subagents";
    pub const PROMPT_DEFAULT: &str = "Complete the task and report concisely to your parent.";
    pub const PROMPT_ROOT: &str = "Delegate independent work to subagents when it can run in parallel. Spawn with fresh context by default; include recent turns only when the task requires them, and full history only when essential. They share your workspace; continue your own work while they run, and wait only when you need their results.";
    pub const RENDER_AGENT: &str = "Agent";
    pub const RENDER_AGENTS: &str = "Agents";
    pub const RENDER_EMPTY: &str = "no subagents";
    pub const RENDER_INTERRUPT: &str = "Interrupt";
    pub const RENDER_MESSAGE: &str = "Message";
    pub const RENDER_OPEN: &str = "Open subagent";
    pub const RENDER_WAIT: &str = "Wait";
    pub const SETTING_MAX_AGENTS_DESCRIPTION: &str = "Maximum retained agents, including the root";
    pub const SETTING_MAX_AGENTS_LABEL: &str = "Maximum agents";
    pub const SETTING_MAX_AGENTS_STEP: i64 = 1;
    pub const SETTING_MAX_CONCURRENCY_DESCRIPTION: &str =
        "Maximum active agents, including the root";
    pub const SETTING_MAX_CONCURRENCY_LABEL: &str = "Maximum concurrency";
    pub const SETTING_MAX_CONCURRENCY_STEP: i64 = 1;
    pub const SETTING_MAX_DEPTH_DESCRIPTION: &str = "Maximum child-agent nesting depth";
    pub const SETTING_MAX_DEPTH_LABEL: &str = "Maximum depth";
    pub const SETTING_MAX_DEPTH_STEP: i64 = 1;
    pub const SETTING_MODEL_ROUTE_DESCRIPTION: &str =
        "Model route used by child agents when a spawn does not select one";
    pub const SETTING_MODEL_ROUTE_LABEL: &str = "Default model";
    pub const SETTING_MODEL_ROUTE_UNSET_LABEL: &str = "Inherit parent";
    pub const TOOL_INTERRUPT_AGENT_DESCRIPTION: &str = "Interrupt a subagent in this chat's task tree and return its prior status. Cannot target /root.";
    pub const TOOL_LIST_AGENTS_DESCRIPTION: &str =
        "List this chat's subagents and their canonical task paths; does not list peer Bots.";
    pub const TOOL_PARAMETER_TARGET_DESCRIPTION: &str = "Exact canonical task path from spawn_agent or list_agents, such as /root/reviewer; not a Bot handle or Bot ID.";
    pub const TOOL_SEND_MESSAGE_DESCRIPTION: &str = "Send collaboration context to an agent in this chat's subagent task tree; completed or interrupted children are started again for the message. A child may message its parent at the parent's canonical path, including /root. The root agent is never restarted.";
    pub const TOOL_SPAWN_AGENT_DESCRIPTION: &str = "Start an async child for independent work in this chat's subagent task tree; return its canonical task path.";
    pub const TOOL_SPAWN_AGENT_PARAMETER_FORK_TURNS_DESCRIPTION: &str = "`none` for a fresh child (default), a positive integer for required recent turns, or `all` only when full history is essential.";
    pub const TOOL_SPAWN_AGENT_PARAMETER_MODEL_DESCRIPTION: &str =
        "Registered route; defaults to the child route, then parent.";
    pub const TOOL_SPAWN_AGENT_PARAMETER_REASONING_EFFORT_DESCRIPTION: &str =
        "Reasoning effort for the selected model; defaults to middleware configuration.";
    pub const TOOL_SPAWN_AGENT_PARAMETER_TASK_NAME_DESCRIPTION: &str =
        "1-64 lowercase letters, digits, or underscores.";
    pub const TOOL_WAIT_AGENT_DESCRIPTION: &str =
        "Wait for an update from this chat's subagent task tree.";
}
const MIN_WAIT_MS: u64 = 10_000;
const MAX_WAIT_MS: u64 = 120_000;
const MAX_CONFIGURED_DEPTH: u8 = 16;
const MAX_CONFIGURED_CONCURRENCY: usize = 64;
const MAX_CONFIGURED_AGENTS: usize = 256;
const _: () = {
    assert!(text::DEFAULTS_WAIT_MS >= MIN_WAIT_MS as i64);
    assert!(text::DEFAULTS_WAIT_MS <= MAX_WAIT_MS as i64);
    assert!(text::DEFAULTS_MAX_DEPTH >= 1);
    assert!(text::DEFAULTS_MAX_DEPTH <= MAX_CONFIGURED_DEPTH as i64);
    assert!(text::DEFAULTS_MAX_CONCURRENCY >= 2);
    assert!(text::DEFAULTS_MAX_CONCURRENCY <= MAX_CONFIGURED_CONCURRENCY as i64);
    assert!(text::DEFAULTS_MAX_AGENTS >= text::DEFAULTS_MAX_CONCURRENCY);
    assert!(text::DEFAULTS_MAX_AGENTS <= MAX_CONFIGURED_AGENTS as i64);
    assert!(text::SETTING_MAX_DEPTH_STEP > 0);
    assert!(text::SETTING_MAX_CONCURRENCY_STEP > 0);
    assert!(text::SETTING_MAX_AGENTS_STEP > 0);
};
const DEFAULT_WAIT_MS: u64 = text::DEFAULTS_WAIT_MS as u64;
/// Default maximum child-agent nesting depth.
pub const DEFAULT_MAX_DEPTH: u8 = text::DEFAULTS_MAX_DEPTH as u8;
/// Default number of concurrently active agents, including the root.
pub const DEFAULT_MAX_CONCURRENCY: usize = text::DEFAULTS_MAX_CONCURRENCY as usize;
/// Default number of retained agents, including the root.
pub const DEFAULT_MAX_AGENTS: usize = text::DEFAULTS_MAX_AGENTS as usize;
const SETTINGS: &[MiddlewareSettingManifest] = &[
    MiddlewareSettingManifest::Select {
        id: "model_route",
        label: text::SETTING_MODEL_ROUTE_LABEL,
        description: text::SETTING_MODEL_ROUTE_DESCRIPTION,
        choices: MiddlewareSettingChoices::ModelRoutes,
        unset_label: Some(text::SETTING_MODEL_ROUTE_UNSET_LABEL),
        default: None,
        max_bytes: 4 * 1024,
        composer: false,
    },
    MiddlewareSettingManifest::Integer {
        id: "max_depth",
        label: text::SETTING_MAX_DEPTH_LABEL,
        description: text::SETTING_MAX_DEPTH_DESCRIPTION,
        min: 1,
        max: Some(MAX_CONFIGURED_DEPTH as i64),
        step: text::SETTING_MAX_DEPTH_STEP,
        default: DEFAULT_MAX_DEPTH as i64,
    },
    MiddlewareSettingManifest::Integer {
        id: "max_concurrency",
        label: text::SETTING_MAX_CONCURRENCY_LABEL,
        description: text::SETTING_MAX_CONCURRENCY_DESCRIPTION,
        min: 2,
        max: Some(MAX_CONFIGURED_CONCURRENCY as i64),
        step: text::SETTING_MAX_CONCURRENCY_STEP,
        default: DEFAULT_MAX_CONCURRENCY as i64,
    },
    MiddlewareSettingManifest::Integer {
        id: "max_agents",
        label: text::SETTING_MAX_AGENTS_LABEL,
        description: text::SETTING_MAX_AGENTS_DESCRIPTION,
        min: 2,
        max: Some(MAX_CONFIGURED_AGENTS as i64),
        step: text::SETTING_MAX_AGENTS_STEP,
        default: DEFAULT_MAX_AGENTS as i64,
    },
];

/// Configuration and presentation metadata for child-agent collaboration.
pub const MANIFEST: MiddlewareManifest = MiddlewareManifest {
    id: "subagents",
    label: text::MANIFEST_LABEL,
    description: text::MANIFEST_DESCRIPTION,
    required: false,
    default_enabled: true,
    settings: SETTINGS,
};

/// Child-agent parameters owned by the subagent capability.
#[derive(Clone)]
pub struct SubagentLaunch {
    pub session_id: String,
    pub model: String,
    pub reasoning_effort: Option<String>,
    pub metadata: BTreeMap<String, Value>,
    pub role: AgentRole,
}

/// Creates one child agent for this capability.
pub type SubagentLauncher =
    Arc<dyn Fn(SubagentLaunch) -> BoxFuture<'static, Result<Agent>> + Send + Sync>;

#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
enum ForkTurns {
    #[default]
    None,
    All,
    Last(usize),
}

impl ForkTurns {
    fn label(self) -> String {
        match self {
            Self::None => "No context".into(),
            Self::All => "Full context".into(),
            Self::Last(1) => "Last 1 turn".into(),
            Self::Last(turns) => format!("Last {turns} turns"),
        }
    }
}

#[derive(Clone, Deserialize)]
#[serde(deny_unknown_fields)]
struct AgentIdentity {
    root_session_id: String,
    agent_path: String,
    depth: u8,
}

#[derive(Debug, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
struct PreviewCursor {
    path: String,
    before_sequence: u64,
}

impl AgentIdentity {
    fn read(session_id: &str, metadata: &BTreeMap<String, Value>) -> Result<Self> {
        let Some(value) = metadata.get(IDENTITY_KEY) else {
            return Ok(Self {
                root_session_id: session_id.into(),
                agent_path: "/root".into(),
                depth: 0,
            });
        };
        Ok(serde_json::from_value(value.clone())?)
    }

    fn metadata(&self, mut metadata: BTreeMap<String, Value>) -> BTreeMap<String, Value> {
        metadata.insert(
            IDENTITY_KEY.into(),
            serde_json::json!({
                "root_session_id": self.root_session_id,
                "agent_path": self.agent_path,
                "depth": self.depth,
            }),
        );
        metadata
    }
}

#[derive(Clone)]
struct AgentScope {
    checkpoints: Arc<dyn CheckpointStore>,
    launch_agent: SubagentLauncher,
    session_id: String,
    root_session_id: String,
    agent_path: String,
    depth: u8,
    model: String,
    metadata: BTreeMap<String, Value>,
}

impl AgentScope {
    fn new(runtime: &RuntimeContext, launch_agent: SubagentLauncher) -> Result<Self> {
        let identity = AgentIdentity::read(&runtime.session_id, &runtime.metadata)?;
        Ok(Self {
            checkpoints: Arc::clone(&runtime.checkpoints),
            launch_agent,
            session_id: runtime.session_id.clone(),
            root_session_id: identity.root_session_id,
            agent_path: identity.agent_path,
            depth: identity.depth,
            model: runtime.model_route.clone(),
            metadata: runtime.metadata.clone(),
        })
    }

    async fn fork(
        &self,
        session_id: String,
        agent_path: String,
        model: String,
        reasoning_effort: Option<String>,
        turns: ForkTurns,
        parent_turn_id: String,
    ) -> Result<Agent> {
        let parent = self
            .checkpoints
            .load(&self.session_id)
            .await?
            .ok_or_else(|| Error::Checkpoint("parent checkpoint is missing".into()))?;
        let parent_sequence = parent.sequence;
        let pending = parent
            .pending_tools
            .iter()
            .map(|call| call.call_id.clone())
            .collect::<BTreeSet<_>>();
        let context = parent
            .context
            .into_iter()
            .filter(|item| {
                item.get("type").and_then(Value::as_str) != Some("function_call")
                    || item
                        .get("call_id")
                        .and_then(Value::as_str)
                        .is_none_or(|call_id| !pending.contains(call_id))
            })
            .collect::<Vec<_>>();
        let mut checkpoint = Checkpoint::empty(&session_id);
        checkpoint.catalog_visible = false;
        checkpoint.context = fork_context(&context, turns);
        checkpoint.session_context = parent.session_context;
        let mut metadata = AgentIdentity {
            root_session_id: self.root_session_id.clone(),
            agent_path: agent_path.clone(),
            depth: self.depth + 1,
        }
        .metadata(self.metadata.clone());
        metadata.insert(SPAWN_CONTEXT_KEY.into(), Value::String(turns.label()));
        checkpoint.metadata.clone_from(&metadata);
        self.checkpoints
            .fork(&self.session_id, parent_sequence, &checkpoint)
            .await?;
        (self.launch_agent)(SubagentLaunch {
            role: AgentRole::Subagent {
                parent_session_id: self.session_id.clone(),
                parent_turn_id,
            },
            session_id,
            model,
            reasoning_effort,
            metadata,
        })
        .await
    }

    async fn resume(
        &self,
        session_id: String,
        agent_path: String,
        depth: u8,
        model: String,
        parent_turn_id: String,
    ) -> Result<Agent> {
        let checkpoint = self.checkpoints.load(&session_id).await?.ok_or_else(|| {
            Error::Checkpoint(format!("checkpoint for `{agent_path}` is missing"))
        })?;
        (self.launch_agent)(SubagentLaunch {
            role: AgentRole::Subagent {
                parent_session_id: self.session_id.clone(),
                parent_turn_id,
            },
            session_id,
            model,
            reasoning_effort: None,
            metadata: AgentIdentity {
                root_session_id: self.root_session_id.clone(),
                agent_path,
                depth,
            }
            .metadata(checkpoint.metadata),
        })
        .await
    }
}

/// Contributes asynchronous collaboration tools.
pub struct Subagents {
    max_depth: u8,
    launch_agent: SubagentLauncher,
    default_model: Option<String>,
    default_reasoning: Option<String>,
    prompt: String,
    shared: Arc<Shared>,
}

impl Subagents {
    /// Creates a child-agent capability with hard depth, concurrency, and agent limits.
    ///
    /// `max_concurrency` counts active agents and `max_agents` counts retained agents;
    /// both include the root.
    pub fn new(
        max_depth: u8,
        max_concurrency: usize,
        max_agents: usize,
        launch_agent: SubagentLauncher,
    ) -> Result<Self> {
        if max_depth == 0 || max_depth > MAX_CONFIGURED_DEPTH {
            return Err(Error::Config(format!(
                "subagent max depth must be between 1 and {MAX_CONFIGURED_DEPTH}"
            )));
        }
        if max_concurrency > MAX_CONFIGURED_CONCURRENCY {
            return Err(Error::Config(format!(
                "subagent max concurrency cannot exceed {MAX_CONFIGURED_CONCURRENCY}"
            )));
        }
        if max_agents > MAX_CONFIGURED_AGENTS {
            return Err(Error::Config(format!(
                "subagent max agents cannot exceed {MAX_CONFIGURED_AGENTS}"
            )));
        }
        Ok(Self {
            max_depth,
            launch_agent,
            default_model: None,
            default_reasoning: None,
            prompt: text::PROMPT_DEFAULT.into(),
            shared: Arc::new(Shared::new(max_concurrency, max_agents)?),
        })
    }

    /// Reports whether this root session has a pending or running child agent.
    pub async fn has_active_children(&self, root_session_id: &str) -> Result<bool> {
        self.shared.has_active_children(root_session_id).await
    }

    /// Selects a registered provider/model route for children by default.
    #[must_use]
    pub fn default_model(mut self, model: impl Into<String>) -> Self {
        self.default_model = Some(model.into());
        self
    }

    /// Selects a reasoning effort for children by default.
    pub fn default_reasoning(mut self, reasoning: impl Into<String>) -> Result<Self> {
        let reasoning = reasoning.into();
        if reasoning.trim().is_empty() {
            return Err(Error::Config(
                "subagent reasoning effort cannot be empty".into(),
            ));
        }
        self.default_reasoning = Some(reasoning);
        Ok(self)
    }

    /// Overrides the instruction given to child agents.
    pub fn prompt(mut self, prompt: impl Into<String>) -> Result<Self> {
        let prompt = prompt.into();
        if prompt.trim().is_empty() {
            return Err(Error::Config("subagent prompt cannot be empty".into()));
        }
        self.prompt = prompt;
        Ok(self)
    }

    fn section(&self, identity: &AgentIdentity) -> PromptSection {
        let body = if identity.depth == 0 {
            text::PROMPT_ROOT.into()
        } else {
            format!(
                "You are `{}`, a child agent.\n{}",
                identity.agent_path,
                self.prompt.trim()
            )
        };
        PromptSection::new(body)
    }

    async fn read_command(
        &self,
        session_id: &str,
        metadata: &BTreeMap<String, Value>,
        arguments: &str,
    ) -> Result<MiddlewareCommandOutput> {
        let path = arguments.trim();
        if path.starts_with('{') {
            return self.read_preview_page(session_id, metadata, path).await;
        }
        let identity = AgentIdentity::read(session_id, metadata)?;
        if !path.is_empty() {
            return self
                .preview_page(&identity.root_session_id, path, None)
                .await;
        }
        let options = self
            .shared
            .resume_options(&identity.root_session_id)
            .await?;
        if options.is_empty() {
            return Ok(MiddlewareCommandOutput::events(vec![
                FrontendEvent::Picker {
                    title: format!("{} · {}", text::RENDER_OPEN, text::RENDER_EMPTY),
                    options,
                },
            ]));
        }
        Ok(MiddlewareCommandOutput::events(vec![
            FrontendEvent::Picker {
                title: text::RENDER_OPEN.into(),
                options,
            },
        ]))
    }

    async fn read_preview_page(
        &self,
        session_id: &str,
        metadata: &BTreeMap<String, Value>,
        arguments: &str,
    ) -> Result<MiddlewareCommandOutput> {
        let identity = AgentIdentity::read(session_id, metadata)?;
        let cursor: PreviewCursor = serde_json::from_str(arguments)
            .map_err(|_| Error::Tool("invalid subagent preview cursor".into()))?;
        if cursor.path.trim() != cursor.path
            || cursor.path.is_empty()
            || cursor.before_sequence == 0
        {
            return Err(Error::Tool("invalid subagent preview cursor".into()));
        }
        self.preview_page(
            &identity.root_session_id,
            &cursor.path,
            Some(cursor.before_sequence),
        )
        .await
    }

    async fn preview_page(
        &self,
        root_session_id: &str,
        path: &str,
        before_sequence: Option<u64>,
    ) -> Result<MiddlewareCommandOutput> {
        let page = self
            .shared
            .preview(root_session_id, path, before_sequence)
            .await?;
        let next = page
            .next
            .map(|before_sequence| -> Result<Op> {
                Ok(Op::CapabilityCommand {
                    capability: MANIFEST.id.into(),
                    command: "subagents".into(),
                    arguments: serde_json::to_string(&PreviewCursor {
                        path: path.into(),
                        before_sequence,
                    })?,
                    input: None,
                    target: None,
                })
            })
            .transpose()?;
        Ok(MiddlewareCommandOutput::events(vec![
            FrontendEvent::Preview {
                id: path.into(),
                title: path.rsplit('/').next().unwrap_or(path).into(),
                subtitle: page.subtitle,
                page_id: page.page_id,
                update: if before_sequence.is_some() {
                    FrontendPreviewUpdate::Prepend
                } else {
                    FrontendPreviewUpdate::Replace
                },
                events: page.events,
                next,
            },
        ]))
    }
}

impl Middleware for Subagents {
    fn name(&self) -> &'static str {
        MANIFEST.id
    }

    fn session_start<'a>(
        &'a self,
        context: &'a mut SessionStartContext<'_>,
    ) -> BoxFuture<'a, Result<()>> {
        if context.source() == SessionStartSource::Compact {
            return Box::pin(async { Ok(()) });
        }
        Box::pin(self.shared.session_start((*context.runtime).clone()))
    }

    fn register(&self, catalog: &mut Catalog, runtime: &RuntimeContext) -> Result<()> {
        let scope = Arc::new(AgentScope::new(runtime, Arc::clone(&self.launch_agent))?);
        if scope.depth < self.max_depth {
            catalog.register(Arc::new(SpawnAgent {
                default_model: self.default_model.clone(),
                default_reasoning: self.default_reasoning.clone(),
                shared: Arc::clone(&self.shared),
                scope: Arc::clone(&scope),
            }))?;
        }
        catalog.register(Arc::new(SendMessage {
            shared: Arc::clone(&self.shared),
            scope: Arc::clone(&scope),
        }))?;
        catalog.register(Arc::new(ListAgents {
            shared: Arc::clone(&self.shared),
            scope: Arc::clone(&scope),
        }))?;
        catalog.register(Arc::new(InterruptAgent {
            shared: Arc::clone(&self.shared),
            scope: Arc::clone(&scope),
        }))?;
        catalog.register(Arc::new(WaitAgent {
            shared: Arc::clone(&self.shared),
            scope,
        }))
    }

    fn prompt_section(&self, runtime: &RuntimeContext) -> Result<Option<PromptSection>> {
        let identity = AgentIdentity::read(&runtime.session_id, &runtime.metadata)?;
        Ok(Some(self.section(&identity)))
    }

    fn frontend(&self) -> FrontendContribution {
        FrontendContribution {
            capability: self.name().into(),
            accepts_file_attachments: false,
            count: None,
            commands: vec![FrontendCommand {
                name: "subagents".into(),
                arguments: String::new(),
                description: text::COMMAND_DESCRIPTION.into(),
                requires_idle: false,
            }],
            widgets: Vec::new(),
            references: Vec::new(),
        }
    }

    fn render(&self, event: &EventMsg, _session_id: &str) -> Option<FrontendBlock> {
        let mut block = render_tool_event(
            event,
            |name| {
                matches!(
                    name,
                    "spawn_agent"
                        | "send_message"
                        | "list_agents"
                        | "interrupt_agent"
                        | "wait_agent"
                )
            },
            |name, arguments| match name {
                _ if matches!(event, EventMsg::ToolCallEnd(_)) => name.into(),
                "spawn_agent" => labeled_tool_heading(text::RENDER_AGENT, "task_name", arguments),
                "send_message" => labeled_tool_heading(text::RENDER_MESSAGE, "target", arguments),
                "list_agents" => {
                    labeled_tool_heading(text::RENDER_AGENTS, "path_prefix", arguments)
                }
                "interrupt_agent" => {
                    labeled_tool_heading(text::RENDER_INTERRUPT, "target", arguments)
                }
                "wait_agent" => labeled_tool_heading(text::RENDER_WAIT, "timeout_ms", arguments),
                _ => name.to_string().into(),
            },
        )?;
        if let EventMsg::ToolCallBegin(call) = event
            && call.name == "send_message"
            && let Some(message) = call.arguments.get("text").and_then(Value::as_str)
        {
            FrontendBlockUpdate::Append.apply(&mut block.text, message);
        }
        Some(block)
    }

    fn command<'a>(
        &'a self,
        context: MiddlewareCommandContext<'a>,
    ) -> BoxFuture<'a, Result<MiddlewareCommandOutput>> {
        Box::pin(async move {
            match context.command {
                "subagents" => {
                    self.read_command(
                        context.session_id,
                        &context.checkpoint.metadata,
                        context.arguments,
                    )
                    .await
                }
                command => Err(Error::Unknown(format!("subagents command `{command}`"))),
            }
        })
    }

    fn active_command<'a>(
        &'a self,
        context: &'a mut ActiveCommandContext<'_>,
    ) -> BoxFuture<'a, Result<Option<SubmissionResult>>> {
        Box::pin(async move {
            let output = match context.command {
                "subagents" => {
                    self.read_command(context.session_id, context.metadata, context.arguments)
                        .await
                }
                _ => return Ok(None),
            };
            match output {
                Ok(output) => {
                    context
                        .events
                        .extend(output.events.into_iter().map(EventMsg::Frontend));
                    Ok(Some(SubmissionResult::Handled))
                }
                Err(error) => Ok(Some(SubmissionResult::Rejected(error.to_string()))),
            }
        })
    }

    fn pre_model<'a>(&'a self, context: &'a mut ModelContext<'_>) -> BoxFuture<'a, Result<()>> {
        Box::pin(async move {
            let identity = AgentIdentity::read(context.session_id, context.metadata)?;
            let acknowledged = context
                .input()
                .iter()
                .filter_map(internal_message_kind)
                .filter_map(|kind| kind.strip_prefix("subagent_update:"))
                .map(str::to_owned)
                .collect();
            let delivered_message_ids = context
                .input()
                .iter()
                .filter_map(message_metadata)
                .filter_map(|message| match message.author {
                    MessageAuthor::Peer { message_id, .. } => Some(message_id),
                    MessageAuthor::User => None,
                })
                .collect();
            let updates = self
                .shared
                .receive_updates(
                    &identity.root_session_id,
                    &identity.agent_path,
                    &acknowledged,
                )
                .await?;
            for update in updates {
                context.push_input(internal_user_message(
                    &update.internal_kind(),
                    &update.render(&delivered_message_ids),
                ))?;
            }
            Ok(())
        })
    }

    fn session_end<'a>(&'a self, runtime: &'a RuntimeContext) -> BoxFuture<'a, Result<()>> {
        Box::pin(async move {
            let identity = AgentIdentity::read(&runtime.session_id, &runtime.metadata)?;
            if matches!(runtime.role, AgentRole::Main) && identity.depth == 0 {
                self.shared.remove_root(&identity.root_session_id).await?;
            } else {
                self.shared
                    .remove_sender(&identity.root_session_id, &identity.agent_path)
                    .await;
            }
            Ok(())
        })
    }
}

#[cfg(test)]
mod tests;