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 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 pub tag: Option<String>,
50 pub spend: Option<Arc<crate::interface::budget_policy::SpendNode>>,
53 pub mode: DelegateMode,
54}
55
56impl DelegateRequest {
57 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 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 Worktree(String),
97 At(PathBuf),
98 Linked(crate::paths::LinkedWorktree),
100}
101
102#[derive(Debug, Clone)]
103pub enum StopsWith {
104 Call(CancellationToken),
106 Session,
108}
109
110#[derive(Debug, Clone, PartialEq, Eq)]
112pub struct CallSite {
113 pub turn: u32,
114 pub tool_use_id: String,
115}
116
117#[derive(Debug, Clone, Copy, PartialEq, Eq)]
119pub enum AskRoute {
120 Host,
121 Refuse,
123}
124
125pub enum DelegateMode {
128 Wait,
130 Background { notify_parent: bool },
132 TeamMember {
133 seat: TeamSeat,
134 permission_mode: Option<PermissionMode>,
137 lifetime: MemberLifetime,
138 },
139 Host { notify_parent: bool },
141 Hook { judged_session: String },
143}
144
145pub enum MemberLifetime {
146 Stage {
149 stage: String,
150 extra_tools: Vec<Arc<dyn Tool>>,
151 },
152 Persistent,
154}
155
156pub enum Delegated {
157 Finished(DelegateOutcome),
158 Started(StartedAgent),
159}
160
161#[derive(Debug, Clone, PartialEq, Eq)]
163pub struct TeamSeat {
164 pub team: String,
165 pub member: String,
166}
167
168#[derive(Debug, Clone, PartialEq, Eq)]
170pub struct LiveMember {
171 pub id: String,
172 pub seat: TeamSeat,
173 pub started_ms: i64,
175}
176
177#[derive(Debug, Clone)]
178#[non_exhaustive]
179pub struct StartedAgent {
180 pub task_id: String,
181 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 CutShort(&'static str, Option<String>),
209}
210
211#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
212#[non_exhaustive]
213pub enum DelegateError {
214 #[error("{0}")]
216 Limit(String),
217 #[error("{0}")]
219 Depth(String),
220 #[error("{0}")]
221 Unsupported(String),
222 #[error("{0}")]
223 Build(String),
224 #[error("{0}")]
225 Invalid(String),
226 #[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 async fn stop_member(&self, seat: &TeamSeat);
238
239 fn live_members(&self) -> Vec<LiveMember>;
242
243 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}