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