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