1use 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 pub model: Option<String>,
29 pub provider: Option<String>,
31 pub tools: ToolSelector,
33 pub deny_rules: Vec<PermissionRule>,
36 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 pub tag: Option<String>,
46 pub spend: Option<Arc<crate::interface::budget_policy::SpendNode>>,
49 pub mode: DelegateMode,
50}
51
52impl DelegateRequest {
53 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 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 Worktree(String),
92 At(PathBuf),
93 Linked(crate::paths::LinkedWorktree),
95}
96
97#[derive(Debug, Clone)]
98pub enum StopsWith {
99 Call(CancellationToken),
101 Session,
103}
104
105#[derive(Debug, Clone, PartialEq, Eq)]
107pub struct CallSite {
108 pub turn: u32,
109 pub tool_use_id: String,
110}
111
112#[derive(Debug, Clone, Copy, PartialEq, Eq)]
114pub enum AskRoute {
115 Host,
116 Refuse,
118}
119
120pub enum DelegateMode {
123 Wait,
125 Background { notify_parent: bool },
127 TeamMember {
128 seat: TeamSeat,
129 permission_mode: Option<PermissionMode>,
132 lifetime: MemberLifetime,
133 },
134 Host { notify_parent: bool },
136 Hook { judged_session: String },
138}
139
140pub enum MemberLifetime {
141 Stage {
144 stage: String,
145 extra_tools: Vec<Arc<dyn Tool>>,
146 },
147 Persistent,
149}
150
151pub enum Delegated {
152 Finished(DelegateOutcome),
153 Started(StartedAgent),
154}
155
156#[derive(Debug, Clone, PartialEq, Eq)]
158pub struct TeamSeat {
159 pub team: String,
160 pub member: String,
161}
162
163#[derive(Debug, Clone, PartialEq, Eq)]
165pub struct LiveMember {
166 pub id: String,
167 pub seat: TeamSeat,
168 pub started_ms: i64,
170}
171
172#[derive(Debug, Clone)]
173#[non_exhaustive]
174pub struct StartedAgent {
175 pub task_id: String,
176 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 CutShort(&'static str, Option<String>),
204}
205
206#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
207#[non_exhaustive]
208pub enum DelegateError {
209 #[error("{0}")]
211 Limit(String),
212 #[error("{0}")]
214 Depth(String),
215 #[error("{0}")]
216 Unsupported(String),
217 #[error("{0}")]
218 Build(String),
219 #[error("{0}")]
220 Invalid(String),
221 #[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 async fn stop_member(&self, seat: &TeamSeat);
233
234 fn live_members(&self) -> Vec<LiveMember>;
237
238 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}