Skip to main content

ag_ui/server/emit/
subagent.rs

1//! Scoping a subagent invocation.
2
3use std::ops::{Deref, DerefMut};
4
5use crate::{Event, SubagentFinishedEvent, SubagentOutcome, SubagentRunId, SubagentStartedEvent};
6use serde_json::Value;
7
8use crate::server::context::RunContext;
9use crate::server::error::Result;
10
11/// One open subagent invocation.
12///
13/// Created by [`RunContext::subagent_events`](crate::server::RunContext::subagent_events).
14/// `SUBAGENT_STARTED` has already gone out. Finish, fail or suspend explicitly:
15/// dropping an unfinished scope restores attribution without inventing an outcome.
16///
17/// A subagent is a *scope*, like a step: everything emitted through the
18/// handle comes out attributed to it. The handle therefore dereferences to
19/// the run context — messages, tool calls, reasoning, steps and nested
20/// subagents all open through it, and every event they produce carries this
21/// invocation's `subagentRunId` without the agent saying so:
22///
23/// ```
24/// # use ag_ui::{Event, EventType, RunAgentInput, TextMessageRole};
25/// # use ag_ui::server::RunContext;
26/// # let (mut ctx, mut events) = RunContext::<()>::new(RunAgentInput::new("t", "r"))?;
27/// {
28///     let mut researcher = ctx.subagent_events("researcher")?;
29///     researcher.say("Three sources found.")?;   // attributed, through Deref
30///     researcher.finish_with(serde_json::json!({ "sources": 3 }))?;
31/// }
32/// ctx.say("Thanks.")?;                            // the parent's own, untagged
33///
34/// let events = events.drain();
35/// assert_eq!(events[0].event_type(), EventType::SubagentStarted);
36/// assert_eq!(events[1].subagent_run_id().map(|id| id.as_str()), Some("r-sub-1"));
37/// assert_eq!(events[4].event_type(), EventType::SubagentFinished);
38/// assert_eq!(events[5].subagent_run_id(), None);
39/// # Ok::<(), ag_ui::server::Error>(())
40/// ```
41///
42/// Nesting is automatic: a subagent opened through a handle gets the handle's
43/// id as its `parentSubagentRunId`. Two subagents cannot be open at once
44/// through handles — the second `subagent()` is a borrow-check error, as
45/// everything overlapping is here. For subagents that genuinely stream
46/// concurrently, tag events yourself and emit them interleaved; see the
47/// [module docs](crate::server::emit#subagents).
48///
49/// # Ending it
50///
51/// The terminator names the subagent it closes and is not itself attributed
52/// to it, so every method here restores the enclosing attribution *before*
53/// emitting. A parent error may terminate with the child still open. A successful
54/// or interrupted parent must explicitly close every announced child; otherwise
55/// the run driver reports a protocol error, including when `verify` is disabled.
56/// This handle records events; the application executes the work.
57#[derive(Debug)]
58pub struct SubagentHandle<'a, S> {
59    ctx: &'a mut RunContext<S>,
60    id: SubagentRunId,
61    name: String,
62    /// The attribution in force before this subagent, restored on close.
63    previous: Option<SubagentRunId>,
64    ended: bool,
65}
66
67impl<'a, S> SubagentHandle<'a, S> {
68    /// Emits `SUBAGENT_STARTED` and scopes the context to the new subagent.
69    ///
70    /// A `parent_subagent_run_id` the caller left absent is filled from the
71    /// enclosing scope, which is what makes nesting through `Deref` correct
72    /// without the agent naming the parent.
73    pub(crate) fn start(
74        ctx: &'a mut RunContext<S>,
75        mut started: SubagentStartedEvent,
76    ) -> Result<Self> {
77        if started.parent_subagent_run_id.is_none() {
78            started.parent_subagent_run_id = ctx.subagent_run_id().cloned();
79        }
80        let id = started.subagent_run_id.clone();
81        let name = started.name.clone();
82        ctx.emit(started.into())?;
83        let previous = ctx.set_attribution(Some(id.clone()));
84        Ok(Self {
85            ctx,
86            id,
87            name,
88            previous,
89            ended: false,
90        })
91    }
92
93    /// The id every event emitted through this handle carries.
94    pub fn id(&self) -> &SubagentRunId {
95        &self.id
96    }
97
98    /// The subagent's declared name, as announced.
99    pub fn name(&self) -> &str {
100        &self.name
101    }
102
103    /// Leaves the scope: the enclosing attribution is back in force, and the
104    /// terminator about to be emitted belongs to it.
105    fn leave(&mut self) {
106        self.ended = true;
107        let previous = self.previous.take();
108        self.ctx.set_attribution(previous);
109    }
110
111    /// Emits `SUBAGENT_FINISHED` with a success outcome and consumes the
112    /// handle.
113    ///
114    /// Unlike `Drop`, this explicitly reports successful completion.
115    pub fn finish(mut self) -> Result<()> {
116        self.leave();
117        self.ctx
118            .emit(Event::subagent_finished_success(self.id.clone()))
119    }
120
121    /// Emits `SUBAGENT_FINISHED` carrying a completion payload — the
122    /// subagent's counterpart of `RUN_FINISHED.result`.
123    pub fn finish_with(mut self, result: impl Into<Value>) -> Result<()> {
124        self.leave();
125        self.ctx.emit(
126            SubagentFinishedEvent::new(self.id.clone())
127                .with_result(result)
128                .with_outcome(SubagentOutcome::Success)
129                .into(),
130        )
131    }
132
133    /// Emits `SUBAGENT_FINISHED` with a suspended outcome: the subagent is
134    /// waiting on `interrupt_ids`, which the run is about to return in an
135    /// interrupt outcome.
136    ///
137    /// Build each interrupt with
138    /// [`Interrupt::with_subagent_run_id`](crate::Interrupt::with_subagent_run_id)
139    /// so a client can render it inside this subagent's group, and announce
140    /// the same id again on the resuming run to continue the invocation.
141    pub fn suspend(mut self, interrupt_ids: impl Into<Vec<String>>) -> Result<()> {
142        self.leave();
143        self.ctx.emit(Event::subagent_finished_suspended(
144            self.id.clone(),
145            interrupt_ids,
146        ))
147    }
148
149    /// Emits `SUBAGENT_ERROR` and consumes the handle.
150    pub fn fail(mut self, message: impl Into<String>) -> Result<()> {
151        self.leave();
152        self.ctx
153            .emit(Event::subagent_error(self.id.clone(), message))
154    }
155
156    /// Emits `SUBAGENT_ERROR` with a machine-readable code.
157    pub fn fail_with_code(
158        mut self,
159        message: impl Into<String>,
160        code: impl Into<String>,
161    ) -> Result<()> {
162        self.leave();
163        self.ctx.emit(
164            crate::SubagentErrorEvent::new(self.id.clone(), message)
165                .with_code(code)
166                .into(),
167        )
168    }
169}
170
171impl<S> Deref for SubagentHandle<'_, S> {
172    type Target = RunContext<S>;
173
174    fn deref(&self) -> &Self::Target {
175        self.ctx
176    }
177}
178
179impl<S> DerefMut for SubagentHandle<'_, S> {
180    fn deref_mut(&mut self) -> &mut Self::Target {
181        self.ctx
182    }
183}
184
185impl<S> Drop for SubagentHandle<'_, S> {
186    fn drop(&mut self) {
187        if !self.ended {
188            self.leave();
189        }
190    }
191}