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/// A cancelled run is the exception: every method here still works after
57/// cancellation, and the driver closes each child left active with
58/// `SUBAGENT_ERROR`, code `CANCELLED`, before `RUN_FINISHED`.
59/// This handle records events; the application executes the work.
60#[derive(Debug)]
61pub struct SubagentHandle<'a, S> {
62    ctx: &'a mut RunContext<S>,
63    id: SubagentRunId,
64    name: String,
65    /// The attribution in force before this subagent, restored on close.
66    previous: Option<SubagentRunId>,
67    ended: bool,
68}
69
70impl<'a, S> SubagentHandle<'a, S> {
71    /// Emits `SUBAGENT_STARTED` and scopes the context to the new subagent.
72    ///
73    /// A `parent_subagent_run_id` the caller left absent is filled from the
74    /// enclosing scope, which is what makes nesting through `Deref` correct
75    /// without the agent naming the parent.
76    pub(crate) fn start(
77        ctx: &'a mut RunContext<S>,
78        mut started: SubagentStartedEvent,
79    ) -> Result<Self> {
80        if started.parent_subagent_run_id.is_none() {
81            started.parent_subagent_run_id = ctx.subagent_run_id().cloned();
82        }
83        let id = started.subagent_run_id.clone();
84        let name = started.name.clone();
85        ctx.emit(started.into())?;
86        let previous = ctx.set_attribution(Some(id.clone()));
87        Ok(Self {
88            ctx,
89            id,
90            name,
91            previous,
92            ended: false,
93        })
94    }
95
96    /// The id every event emitted through this handle carries.
97    pub fn id(&self) -> &SubagentRunId {
98        &self.id
99    }
100
101    /// The subagent's declared name, as announced.
102    pub fn name(&self) -> &str {
103        &self.name
104    }
105
106    /// Leaves the scope: the enclosing attribution is back in force, and the
107    /// terminator about to be emitted belongs to it.
108    fn leave(&mut self) {
109        self.ended = true;
110        let previous = self.previous.take();
111        self.ctx.set_attribution(previous);
112    }
113
114    /// Emits `SUBAGENT_FINISHED` with a success outcome and consumes the
115    /// handle.
116    ///
117    /// Unlike `Drop`, this explicitly reports successful completion.
118    pub fn finish(mut self) -> Result<()> {
119        self.leave();
120        self.ctx
121            .emit_forced(Event::subagent_finished_success(self.id.clone()))
122    }
123
124    /// Emits `SUBAGENT_FINISHED` carrying a completion payload — the
125    /// subagent's counterpart of `RUN_FINISHED.result`.
126    pub fn finish_with(mut self, result: impl Into<Value>) -> Result<()> {
127        self.leave();
128        self.ctx.emit_forced(
129            SubagentFinishedEvent::new(self.id.clone())
130                .with_result(result)
131                .with_outcome(SubagentOutcome::Success)
132                .into(),
133        )
134    }
135
136    /// Emits `SUBAGENT_FINISHED` with a suspended outcome: the subagent is
137    /// waiting on `interrupt_ids`, which the run is about to return in an
138    /// interrupt outcome.
139    ///
140    /// Build each interrupt with
141    /// [`Interrupt::with_subagent_run_id`](crate::Interrupt::with_subagent_run_id)
142    /// so a client can render it inside this subagent's group, and announce
143    /// the same id again on the resuming run to continue the invocation.
144    pub fn suspend(mut self, interrupt_ids: impl Into<Vec<String>>) -> Result<()> {
145        self.leave();
146        self.ctx.emit_forced(Event::subagent_finished_suspended(
147            self.id.clone(),
148            interrupt_ids,
149        ))
150    }
151
152    /// Emits `SUBAGENT_ERROR` and consumes the handle.
153    pub fn fail(mut self, message: impl Into<String>) -> Result<()> {
154        self.leave();
155        self.ctx
156            .emit_forced(Event::subagent_error(self.id.clone(), message))
157    }
158
159    /// Emits `SUBAGENT_ERROR` with a machine-readable code.
160    pub fn fail_with_code(
161        mut self,
162        message: impl Into<String>,
163        code: impl Into<String>,
164    ) -> Result<()> {
165        self.leave();
166        self.ctx.emit_forced(
167            crate::SubagentErrorEvent::new(self.id.clone(), message)
168                .with_code(code)
169                .into(),
170        )
171    }
172}
173
174impl<S> Deref for SubagentHandle<'_, S> {
175    type Target = RunContext<S>;
176
177    fn deref(&self) -> &Self::Target {
178        self.ctx
179    }
180}
181
182impl<S> DerefMut for SubagentHandle<'_, S> {
183    fn deref_mut(&mut self) -> &mut Self::Target {
184        self.ctx
185    }
186}
187
188impl<S> Drop for SubagentHandle<'_, S> {
189    fn drop(&mut self) {
190        if !self.ended {
191            self.leave();
192        }
193    }
194}