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
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
//! What the agent of a session a person attends asks them during a turn
//! ([`crate::acp_runtime::person`]), as the session's input requests: a
//! tool approval, a plan approval, or questions, which any client answers
//! with `rho/session/answer` as it would Rho's own. The turn's end
//! withdraws whatever is still open.
//!
//! The tools of rho's the turn serves the agent (see `acp_tools.rs`) ask
//! through the same requests, in the same id space: an approval a call
//! needs, and a question a tool asks, whoever opened the session, as a Rho
//! session's do. A call that ends withdraws what it still asks.
//!
//! The agent is only ever answered `allow_once`, so nothing it would keep
//! (Claude writes `allow_always` into its settings) outlives the session.
//! An approval for the session is kept here instead, by the tool call's
//! title, for the session's later turns while the daemon has it loaded; a
//! tool call the agent gave no title is asked about every time.
use std::{collections::HashSet, sync::Arc, time::SystemTime};
use rho_protocol as wire;
use rho_sdk::{ApprovalDecision, HostInputId, HostInputRefusal, HostInputResponse, ToolCallId};
use tokio::sync::{mpsc, oneshot};
use super::{
acp_tools::{ServedApproval, ServedAsk, ServedQuestion},
LoadedSession,
};
use crate::{
acp_runtime::person::{Asked, PersonAnswer, PersonAsk},
app::session_runtime::{
ApprovalId, PlanApprovalId, PlanApprovalRequest, SessionEvent, TurnControl,
},
permission::PermissionMode,
tools::plan_exit::PlanExitDecision,
};
/// The tool calls a person allowed for the session, by title.
#[derive(Default)]
pub(super) struct AllowedForSession(HashSet<String>);
/// What an approval shows of a tool call the agent gave no title.
const UNTITLED: &str = "a tool call";
/// One turn's asks: what is open, and the answers on their way back.
pub(super) struct TurnAsks {
/// Names the agent's runtime to whoever answers.
runtime: String,
control: mpsc::UnboundedSender<TurnControl>,
answers: mpsc::UnboundedReceiver<TurnControl>,
open: OpenAsks,
/// Counts the agent's approvals and the served tools' alike, so their
/// ids never collide.
approvals: u64,
plans: u64,
}
/// The open asks, by kind and by the id their request carries.
#[derive(Default)]
struct OpenAsks {
approvals: Vec<(ApprovalId, ApprovalWaiter)>,
/// The agent's alone: a served tool never asks to leave plan mode.
plans: Vec<(PlanApprovalId, oneshot::Sender<PersonAnswer>)>,
questions: Vec<(HostInputId, QuestionWaiter)>,
}
enum ApprovalWaiter {
/// The agent's own.
Agent {
reply: oneshot::Sender<PersonAnswer>,
/// The title an approval for the session keeps: none for a tool
/// call the agent gave no title.
title: Option<String>,
},
/// A served call's.
Served(Box<ServedApproval>),
}
enum QuestionWaiter {
/// The agent's own form.
Agent(oneshot::Sender<PersonAnswer>),
/// A served call's.
Served(Box<ServedQuestion>),
}
/// A person's answer to an open ask, by the id its request carries: a
/// client's [`TurnControl`] as a turn of an agent's session reads it.
enum Answer {
Approval(ApprovalId, ApprovalDecision),
Plan(PlanApprovalId, PlanExitDecision),
Question(HostInputId, Result<HostInputResponse, HostInputRefusal>),
}
impl Answer {
/// What `control` answers; none for what only Rho's own loop is sent.
fn of(control: TurnControl) -> Option<Self> {
match control {
TurnControl::RespondApproval { id, decision } => Some(Self::Approval(id, decision)),
TurnControl::AnswerPlan { id, answer } => Some(Self::Plan(id, answer)),
TurnControl::AnswerQuestion { id, answer } => Some(Self::Question(id, answer)),
TurnControl::AnswerSecret { .. } | TurnControl::HostFailed { .. } => None,
}
}
}
/// Takes the waiter of `open` whose ask `id` names, if it is still open.
fn take<K: PartialEq, W>(open: &mut Vec<(K, W)>, id: &K) -> Option<W> {
let at = open.iter().position(|(open, _)| open == id)?;
Some(open.swap_remove(at).1)
}
impl OpenAsks {
/// Takes out what served call `ended` still asks, and the events that
/// withdraw it from the session's input requests. Dropping a served
/// approval denies it, and a dropped question fails the tool's ask, as
/// the call that asked is gone.
fn end_call(&mut self, ended: &ToolCallId) -> Vec<SessionEvent> {
let mut withdrawn = Vec::new();
self.approvals.retain(|(id, waiter)| {
let of_call = match waiter {
ApprovalWaiter::Served(served) => served.call.as_ref() == Some(ended),
ApprovalWaiter::Agent { .. } => false,
};
if of_call {
withdrawn.push(SessionEvent::ApprovalWithdrawn { id: *id });
}
!of_call
});
self.questions.retain(|(id, waiter)| {
let of_call = match waiter {
QuestionWaiter::Served(served) => served.call == *ended,
QuestionWaiter::Agent(_) => false,
};
if of_call {
withdrawn.push(SessionEvent::QuestionWithdrawn { id: id.clone() });
}
!of_call
});
withdrawn
}
}
impl TurnAsks {
pub(super) fn new(runtime: &str) -> Self {
let (control, answers) = mpsc::unbounded_channel();
Self {
runtime: runtime.to_owned(),
control,
answers,
open: OpenAsks::default(),
approvals: 0,
plans: 0,
}
}
/// The next answer a client gave.
pub(super) async fn answer(&mut self) -> Option<TurnControl> {
self.answers.recv().await
}
/// Opens `asked` as an input request of `session`, or answers it at
/// once: a tool call the person allowed for the session runs.
pub(super) fn put(
&mut self,
session: &Arc<LoadedSession>,
asked: Asked,
allowed: &AllowedForSession,
) {
let Asked { ask, reply } = asked;
let now = SystemTime::now();
match ask {
PersonAsk::Tool {
title: Some(title), ..
} if allowed.0.contains(&title) => {
let _ = reply.send(PersonAnswer::Allow);
}
PersonAsk::Tool { tool_call, title } => {
let id = ApprovalId::nth(self.approvals);
self.approvals += 1;
let ask = wire::ApprovalAsk {
source: wire::ApprovalSource::ExternalAgent {
runtime: self.runtime.clone(),
},
operation: wire::Operation::AgentTool {
title: title.clone().unwrap_or_else(|| UNTITLED.to_owned()),
},
reason: "the agent asks before this tool call".to_owned(),
};
let control = &self.control;
session.change_inputs(|inputs| {
inputs.open_agent_approval(
control,
id,
ask,
wire::ToolCallId::new(&tool_call),
now,
);
});
self.open
.approvals
.push((id, ApprovalWaiter::Agent { reply, title }));
}
PersonAsk::PlanExit {
tool_call,
plan,
to,
} => {
let id = PlanApprovalId::nth(self.plans);
self.plans += 1;
let Ok(call_id) = ToolCallId::from_string(tool_call) else {
// An agent's id Rho cannot name is no plan to approve.
let _ = reply.send(PersonAnswer::Deny);
return;
};
let request = PlanApprovalRequest {
call_id,
plan,
targets: vec![to],
};
self.note(
session,
&SessionEvent::PlanApprovalRequested { id, request },
now,
);
self.open.plans.push((id, reply));
}
PersonAsk::Form { tool_call, request } => {
let id = request.id().clone();
let call_id = tool_call.and_then(|id| ToolCallId::from_string(id).ok());
let event = SessionEvent::QuestionAsked {
id: id.clone(),
call_id,
request,
};
self.note(session, &event, now);
self.open.questions.push((id, QuestionWaiter::Agent(reply)));
}
}
}
/// Opens what `asked`, of a call of a tool the turn serves the agent,
/// asks as an input request of `session`, or withdraws what a call that
/// ended still asks.
pub(super) fn put_served(&mut self, session: &Arc<LoadedSession>, asked: ServedAsk) {
let now = SystemTime::now();
match asked {
ServedAsk::Approval(approval) => {
let id = ApprovalId::nth(self.approvals);
self.approvals += 1;
let request = approval.request().clone();
let call = request.tool_call_id().cloned();
self.note(
session,
&SessionEvent::ApprovalRequested { id, request },
now,
);
let waiter = ServedApproval { call, approval };
self.open
.approvals
.push((id, ApprovalWaiter::Served(Box::new(waiter))));
}
ServedAsk::Question { call, input } => {
let id = input.request().id().clone();
let event = SessionEvent::QuestionAsked {
id: id.clone(),
call_id: Some(call.clone()),
request: input.request().clone(),
};
self.note(session, &event, now);
let waiter = ServedQuestion { call, input };
self.open
.questions
.push((id, QuestionWaiter::Served(Box::new(waiter))));
}
ServedAsk::Ended(call) => {
for withdrawn in self.open.end_call(&call) {
self.note(session, &withdrawn, now);
}
}
}
}
fn note(&self, session: &Arc<LoadedSession>, event: &SessionEvent, now: SystemTime) {
let control = &self.control;
session
.change_inputs(|inputs| inputs.note(super::inputs::Asker::Turn, control, event, now));
}
/// Hands the agent, or the served call that asked, the person's
/// answer, `control`, keeping an agent's approval for the session in
/// `allowed`. An answer to an ask no longer open goes nowhere. A plan
/// the person approved is the caller's to tell the agent of
/// ([`ApprovedPlan::tell`]), once the turn runs in its mode.
#[must_use]
pub(super) fn answered(
&mut self,
control: TurnControl,
allowed: &mut AllowedForSession,
) -> Option<ApprovedPlan> {
let answer = Answer::of(control)?;
// A run that stopped asking takes no answer.
match answer {
Answer::Approval(id, decision) => match take(&mut self.open.approvals, &id) {
Some(ApprovalWaiter::Agent { reply, title }) => {
let (answer, keep) = match decision {
ApprovalDecision::AllowOnce => (PersonAnswer::Allow, false),
ApprovalDecision::AllowForSession => (PersonAnswer::Allow, true),
// Deny, or a decision a newer SDK adds.
_ => (PersonAnswer::Deny, false),
};
if let (true, Some(title)) = (keep, title) {
allowed.0.insert(title);
}
let _ = reply.send(answer);
}
Some(ApprovalWaiter::Served(served)) => served.answer(decision),
None => {}
},
// The plan's one target: the agent tells whether it left.
Answer::Plan(id, decision) => {
let reply = take(&mut self.open.plans, &id)?;
match decision.approved() {
Some(mode) => return Some(ApprovedPlan { mode, reply }),
None => {
let _ = reply.send(PersonAnswer::Deny);
}
}
}
Answer::Question(id, answer) => match take(&mut self.open.questions, &id) {
Some(QuestionWaiter::Agent(reply)) => {
let _ = reply.send(PersonAnswer::Form(answer));
}
Some(QuestionWaiter::Served(served)) => served.answer(answer),
None => {}
},
}
None
}
}
/// A plan the person approved, which the agent has yet to hear of.
pub(super) struct ApprovedPlan {
mode: PermissionMode,
reply: oneshot::Sender<PersonAnswer>,
}
impl ApprovedPlan {
/// The mode the plan is carried out in.
pub(super) fn mode(&self) -> PermissionMode {
self.mode
}
/// Tells the agent: it leaves plan mode, and the person hears it did
/// ([`crate::acp_runtime::person::Heard::LeftPlan`]).
pub(super) fn tell(self) {
// A run that stopped asking takes no answer.
let _ = self.reply.send(PersonAnswer::Allow);
}
}
#[cfg(test)]
#[path = "acp_asks_tests.rs"]
mod tests;