Skip to main content

base/interface/
delegate.rs

1//! Delegation: one request type for every way a session starts a sub-agent —
2//! the model's `Agent` call, a team member, an `"agent"` hook, a forked skill,
3//! a host's `session.startAgent` — and the one trait that serves it. The mode
4//! says how the delegate runs; everything else about it is in the request.
5//!
6//! The implementation lives in `agents`; this sits below `team`, `skills` and
7//! `hooks`, which consume it.
8
9use std::path::PathBuf;
10use std::sync::Arc;
11
12use async_trait::async_trait;
13use serde_json::Value;
14use tokio_util::sync::CancellationToken;
15
16use super::permission::Grant;
17use super::tool::Tool;
18use super::tool_selector::ToolSelector;
19use crate::permission::PermissionMode;
20use crate::permission::PermissionRule;
21
22#[non_exhaustive]
23pub struct DelegateRequest {
24    pub prompt: String,
25    pub description: Option<String>,
26    pub agent_type: Option<String>,
27    /// Over the agent type's model, or the parent's.
28    pub model: Option<String>,
29    /// The provider its calls go to first, over the agent type's.
30    pub provider: Option<String>,
31    /// Narrows what the delegate would otherwise have; never widens it.
32    pub tools: ToolSelector,
33    /// Only their `deny` takes effect: a delegate can be refused more than
34    /// its parent, never permitted more.
35    pub deny_rules: Vec<PermissionRule>,
36    /// Turn grants that hold in the delegate's own session and are not
37    /// handed back to the parent.
38    pub grants: Vec<Grant>,
39    pub output_schema: Option<Value>,
40    pub workdir: Workdir,
41    pub stops_with: StopsWith,
42    pub called_from: Option<CallSite>,
43    pub asks: AskRoute,
44    /// The caller's own label, carried on the delegate's task untouched.
45    pub tag: Option<String>,
46    /// The turn the delegate spends into and judges its budget by; `None`
47    /// gives each of its turns a spend of its own.
48    pub spend: Option<Arc<crate::interface::budget_policy::SpendNode>>,
49    pub mode: DelegateMode,
50}
51
52impl DelegateRequest {
53    /// `prompt` run in `mode` until `stops_with` says stop, with nothing else
54    /// narrowed: the parent's tools and working directory, questions asked
55    /// of the host.
56    pub fn new(prompt: impl Into<String>, mode: DelegateMode, stops_with: StopsWith) -> Self {
57        Self {
58            prompt: prompt.into(),
59            description: None,
60            agent_type: None,
61            model: None,
62            provider: None,
63            tools: ToolSelector::all(),
64            deny_rules: Vec::new(),
65            grants: Vec::new(),
66            output_schema: None,
67            workdir: Workdir::Inherit,
68            stops_with,
69            called_from: None,
70            asks: AskRoute::Host,
71            tag: None,
72            spend: None,
73            mode,
74        }
75    }
76
77    /// Started by the tool call of `ctx`: called from it, spending into its turn.
78    pub fn started_by(&mut self, ctx: &super::tool::ToolContext) {
79        self.called_from = Some(CallSite {
80            turn: ctx.turn_no,
81            tool_use_id: ctx.tool_use_id.clone(),
82        });
83        self.spend = Some(ctx.turn.spend().clone());
84    }
85}
86
87#[derive(Debug, Clone, PartialEq, Eq)]
88pub enum Workdir {
89    Inherit,
90    /// A git worktree of the parent's project, by name.
91    Worktree(String),
92    At(PathBuf),
93    /// A worktree the caller made, with the git directory it found then.
94    Linked(crate::paths::LinkedWorktree),
95}
96
97#[derive(Debug, Clone)]
98pub enum StopsWith {
99    /// The caller's token: the delegate stops on a child of it.
100    Call(CancellationToken),
101    /// The parent session's end.
102    Session,
103}
104
105/// The parent's tool call that started the delegate.
106#[derive(Debug, Clone, PartialEq, Eq)]
107pub struct CallSite {
108    pub turn: u32,
109    pub tool_use_id: String,
110}
111
112/// Where a question the delegate's permission leaves open goes.
113#[derive(Debug, Clone, Copy, PartialEq, Eq)]
114pub enum AskRoute {
115    Host,
116    /// Refused instead: a program's delegate has nobody to ask.
117    Refuse,
118}
119
120/// Matched exhaustively by the one dispatch in `agents`, across crates, so a
121/// new mode cannot compile without its rules.
122pub enum DelegateMode {
123    /// Run it and wait for its answer.
124    Wait,
125    /// A task of the parent session, started at once.
126    Background { notify_parent: bool },
127    TeamMember {
128        seat: TeamSeat,
129        /// Held to the parent's mode: it can make the member stricter, never
130        /// freer. `None` keeps the parent's.
131        permission_mode: Option<PermissionMode>,
132        lifetime: MemberLifetime,
133    },
134    /// What a host asked for, as a task of the parent session.
135    Host { notify_parent: bool },
136    /// The judge for an `"agent"` hook on an event of `judged_session`.
137    Hook { judged_session: String },
138}
139
140pub enum MemberLifetime {
141    /// One stage of a team, by name; `extra_tools` go to this member's
142    /// registry only.
143    Stage {
144        stage: String,
145        extra_tools: Vec<Arc<dyn Tool>>,
146    },
147    /// Kept across messages until stopped.
148    Persistent,
149}
150
151pub enum Delegated {
152    Finished(DelegateOutcome),
153    Started(StartedAgent),
154}
155
156/// Which team a member works in, and its name there.
157#[derive(Debug, Clone, PartialEq, Eq)]
158pub struct TeamSeat {
159    pub team: String,
160    pub member: String,
161}
162
163/// A persistent member alive under a delegator, idle or running a message.
164#[derive(Debug, Clone, PartialEq, Eq)]
165pub struct LiveMember {
166    pub id: String,
167    pub seat: TeamSeat,
168    /// When the member was spawned, in Unix milliseconds.
169    pub started_ms: i64,
170}
171
172#[derive(Debug, Clone)]
173#[non_exhaustive]
174pub struct StartedAgent {
175    pub task_id: String,
176    /// The sidechain session the agent runs in.
177    pub agent_session_id: String,
178}
179
180impl StartedAgent {
181    pub fn new(task_id: impl Into<String>, agent_session_id: impl Into<String>) -> Self {
182        Self {
183            task_id: task_id.into(),
184            agent_session_id: agent_session_id.into(),
185        }
186    }
187}
188
189#[derive(Debug, Clone, PartialEq)]
190pub struct DelegateOutcome {
191    pub text: String,
192    pub end: DelegateEnd,
193    pub structured: Option<Value>,
194    pub session_id: String,
195}
196
197#[derive(Debug, Clone, PartialEq, Eq)]
198pub enum DelegateEnd {
199    Completed,
200    Cancelled,
201    Failed(String),
202    /// Cut short by a ceiling (`max_turns`, say), and what its turn said of it.
203    CutShort(&'static str, Option<String>),
204}
205
206#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
207#[non_exhaustive]
208pub enum DelegateError {
209    /// As many delegates are running as the session allows.
210    #[error("{0}")]
211    Limit(String),
212    /// As deep as delegation goes.
213    #[error("{0}")]
214    Depth(String),
215    #[error("{0}")]
216    Unsupported(String),
217    #[error("{0}")]
218    Build(String),
219    #[error("{0}")]
220    Invalid(String),
221    /// A `Hook` delegate asked to judge an event of a hook agent or one of
222    /// its descendants: agent hooks do not judge those.
223    #[error("{0}")]
224    NotJudged(String),
225}
226
227#[async_trait]
228pub trait Delegator: Send + Sync {
229    async fn delegate(&self, req: DelegateRequest) -> Result<Delegated, DelegateError>;
230
231    /// Stop a persistent member; nothing when there is no such member.
232    async fn stop_member(&self, seat: &TeamSeat);
233
234    /// The persistent members alive, sorted by id. They run under the engine
235    /// that holds this delegator and stop with it.
236    fn live_members(&self) -> Vec<LiveMember>;
237
238    /// `Err`, naming the types there are, when a request naming `name` would be refused for it.
239    fn check_agent_type(&self, _name: &str) -> Result<(), DelegateError> {
240        Ok(())
241    }
242}
243
244#[cfg(test)]
245mod tests {
246    use super::*;
247
248    struct Echo;
249
250    #[async_trait]
251    impl Delegator for Echo {
252        async fn delegate(&self, req: DelegateRequest) -> Result<Delegated, DelegateError> {
253            match req.mode {
254                DelegateMode::Wait | DelegateMode::Hook { .. } => {
255                    Ok(Delegated::Finished(DelegateOutcome {
256                        text: req.prompt,
257                        end: DelegateEnd::Completed,
258                        structured: None,
259                        session_id: "s".into(),
260                    }))
261                }
262                DelegateMode::Background { .. }
263                | DelegateMode::Host { .. }
264                | DelegateMode::TeamMember { .. } => {
265                    Err(DelegateError::Unsupported("echo only waits".into()))
266                }
267            }
268        }
269
270        async fn stop_member(&self, _: &TeamSeat) {}
271
272        fn live_members(&self) -> Vec<LiveMember> {
273            Vec::new()
274        }
275    }
276
277    #[test]
278    fn a_new_request_narrows_nothing() {
279        let req = DelegateRequest::new("go", DelegateMode::Wait, StopsWith::Session);
280        assert_eq!(req.tools, ToolSelector::all());
281        assert!(req.deny_rules.is_empty() && req.grants.is_empty());
282        assert_eq!(req.workdir, Workdir::Inherit);
283        assert_eq!(req.asks, AskRoute::Host);
284        assert!(req.called_from.is_none() && req.tag.is_none());
285    }
286
287    #[tokio::test]
288    async fn a_delegator_answers_by_mode() {
289        let waited = Echo
290            .delegate(DelegateRequest::new(
291                "hello",
292                DelegateMode::Wait,
293                StopsWith::Call(CancellationToken::new()),
294            ))
295            .await;
296        match waited {
297            Ok(Delegated::Finished(outcome)) => {
298                assert_eq!(outcome.text, "hello");
299                assert_eq!(outcome.end, DelegateEnd::Completed);
300            }
301            _ => panic!("a waited delegate finishes"),
302        }
303        let refused = Echo
304            .delegate(DelegateRequest::new(
305                "x",
306                DelegateMode::Background {
307                    notify_parent: true,
308                },
309                StopsWith::Session,
310            ))
311            .await;
312        assert!(matches!(refused, Err(DelegateError::Unsupported(m)) if m == "echo only waits"));
313    }
314}