rho-coding-agent 3.1.0

A fast Rust agent harness with a small footprint and opinionated defaults
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
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
//! A session's open input requests (#1660): the approvals, plan approvals,
//! and questions its turn waits on a person for, and the questions its
//! subagents ask (see `child_questions`), in the daemon rather than in any
//! client.
//!
//! Whoever asks opens and withdraws requests through its events; any client
//! answers one with `rho/session/answer`. The first answer takes the
//! request out, so a later one finds it gone. Nothing answers a request
//! because a client left: one with nobody attached stays open until someone
//! answers it or the turn withdraws it.
//!
//! The one exception is the user's own: with `[questionnaire]
//! timeout_seconds` set, a question whose agent offered fallback answers
//! times out, and the daemon answers it with them, unless a client answers
//! it first or holds it, as a client does once its user starts on it.

use std::{
    collections::{btree_map::Entry, BTreeMap},
    sync::{Arc, PoisonError},
    time::{Duration, SystemTime, UNIX_EPOCH},
};

use rho_protocol::{self as wire, ErrorCode, InputAnswer, InputRequestId, Resolution, RpcError};
use rho_sdk::{
    ApprovalDecision, HostInputId, HostInputRefusal, HostInputRequest, HostInputResponse,
    HostInputSource, ToolCallId,
};
use tokio::sync::mpsc;

use crate::{
    app::session_runtime::{ApprovalId, PlanApprovalId, SessionEvent, TurnControl},
    permission::{PermissionMode, DENIED_BY_USER},
    tools::plan_exit::PlanExitDecision,
};

use super::{super::jobs::JobEvent, LoadedSession};

mod asks;

/// The requests a session's turn has open, by the id clients know them by.
pub(super) struct Inputs {
    /// How long a question with fallback answers waits before the daemon
    /// answers it with them: the session's `[questionnaire]
    /// timeout_seconds`, if set.
    question_timeout: Option<Duration>,
    /// The id of the session's next request: ids are never reused while
    /// the daemon has the session loaded.
    next: u64,
    open: BTreeMap<InputRequestId, Open>,
    /// What attached clients learn of the changes since the last
    /// [`Self::take_events`].
    events: Vec<wire::SessionEvent>,
    /// Answers accepted but not yet handed to their turns: they go after
    /// clients learn of them ([`Self::send_answers`]), so nothing the turn
    /// does with an answer reaches clients before the answer does.
    answers: Vec<(mpsc::UnboundedSender<TurnControl>, TurnControl)>,
    /// Timeouts opened since the last [`Self::take_timeouts`]: each request
    /// times out after its duration unless it closes or is held first.
    timeouts: Vec<(InputRequestId, Duration)>,
}

/// One open request, and where its answer goes. The runtime's ids are
/// unique only within the model turn that asked, which `control` names.
struct Open {
    /// The answer channel of whoever asked.
    control: mpsc::UnboundedSender<TurnControl>,
    asker: Asker,
    waiting: Waiting,
    /// What the turn gets if the request times out; `None` when it has no
    /// timeout or a client held it.
    timeout: Option<TurnControl>,
}

/// Whose request it is, which says what ends it unanswered.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(super) enum Asker {
    /// The turn under way: its end withdraws the request, and the job
    /// waits for input while it is open.
    Turn,
    /// A subagent, which outlives the turn that started it: only the
    /// subagent withdraws the request, and no turn waits on it.
    Subagent,
}

/// A request as the runtime knows it, with what checking an answer needs.
enum Waiting {
    Approval(ApprovalId),
    Plan {
        id: PlanApprovalId,
        modes: Vec<PermissionMode>,
    },
    Question {
        id: HostInputId,
        request: HostInputRequest,
    },
}

impl Inputs {
    /// No requests open yet. Questions with fallback answers time out after
    /// `question_timeout`, if set.
    pub(super) fn new(question_timeout: Option<Duration>) -> Self {
        Self {
            question_timeout,
            next: 0,
            open: BTreeMap::new(),
            events: Vec::new(),
            answers: Vec::new(),
            timeouts: Vec::new(),
        }
    }

    /// Whether the turn waits on a person.
    pub(super) fn waiting(&self) -> bool {
        self.open.values().any(|open| open.asker == Asker::Turn)
    }

    /// What attached clients learn of the changes since the last call.
    pub(super) fn take_events(&mut self) -> Vec<wire::SessionEvent> {
        std::mem::take(&mut self.events)
    }

    /// The timeouts opened since the last call, for the caller to run:
    /// [`Self::time_out`] each request once its duration passes.
    pub(super) fn take_timeouts(&mut self) -> Vec<(InputRequestId, Duration)> {
        std::mem::take(&mut self.timeouts)
    }

    /// Hands the answers accepted since the last call to their turns.
    pub(super) fn send_answers(&mut self) {
        for (control, answer) in self.answers.drain(..) {
            // A turn that ended since takes no answer, as one that withdrew
            // the request at the same moment ignores it.
            let _ = control.send(answer);
        }
    }

    /// Opens or withdraws the request `event` names, if any, for `asker`,
    /// whose answers go to `control`, at `now`.
    pub(super) fn note(
        &mut self,
        asker: Asker,
        control: &mpsc::UnboundedSender<TurnControl>,
        event: &SessionEvent,
        now: SystemTime,
    ) {
        let (waiting, ask, tool_call) = match event {
            SessionEvent::ApprovalRequested { id, request } => (
                Waiting::Approval(*id),
                asks::approval(request),
                request.tool_call_id(),
            ),
            SessionEvent::PlanApprovalRequested { id, request } => (
                Waiting::Plan {
                    id: *id,
                    modes: request.targets.clone(),
                },
                asks::plan_approval(request),
                Some(&request.call_id),
            ),
            SessionEvent::QuestionAsked {
                id,
                call_id,
                request,
            } => (
                Waiting::Question {
                    id: id.clone(),
                    request: request.clone(),
                },
                asks::question(request),
                call_id.as_ref(),
            ),
            SessionEvent::ApprovalWithdrawn { id } => {
                return self.withdraw(
                    control,
                    |waiting| matches!(waiting, Waiting::Approval(open) if open == id),
                );
            }
            SessionEvent::PlanApprovalWithdrawn { id } => {
                return self.withdraw(
                    control,
                    |waiting| matches!(waiting, Waiting::Plan { id: open, .. } if open == id),
                );
            }
            SessionEvent::QuestionWithdrawn { id } => {
                return self.withdraw(
                    control,
                    |waiting| matches!(waiting, Waiting::Question { id: open, .. } if open == id),
                );
            }
            SessionEvent::MessageInserted(_)
            | SessionEvent::RunStarted
            | SessionEvent::Run(_)
            | SessionEvent::BoundaryApplied { .. }
            | SessionEvent::Notice { .. }
            | SessionEvent::RunClosed
            | SessionEvent::RunFinished { .. } => return,
        };
        let id = InputRequestId(self.next);
        self.next += 1;
        // Only a question whose agent offered fallback answers times out,
        // and only when the session's questions do.
        let (wire_timeout, timeout) = match (&waiting, self.question_timeout) {
            (Waiting::Question { id: asked, request }, Some(after)) => request
                .timeout_fallback()
                .zip(asks::timeout(request, deadline_ms(now, after)))
                .map(|(fallback, wire_timeout)| {
                    self.timeouts.push((id, after));
                    let answer = TurnControl::AnswerQuestion {
                        id: asked.clone(),
                        answer: Ok(fallback.clone()),
                    };
                    (wire_timeout, answer)
                }),
            (Waiting::Question { .. }, None) | (Waiting::Approval(_) | Waiting::Plan { .. }, _) => {
                None
            }
        }
        .unzip();
        self.open.insert(
            id,
            Open {
                control: control.clone(),
                asker,
                waiting,
                timeout,
            },
        );
        self.events.push(wire::SessionEvent::InputRequested {
            request: Box::new(wire::InputRequest {
                id,
                ask,
                tool_call: tool_call.map(wire_tool_call),
                timeout: wire_timeout,
                asker: match asker {
                    Asker::Turn => wire::InputAsker::Turn,
                    Asker::Subagent => wire::InputAsker::Subagent,
                },
            }),
        });
    }

    /// Takes out the request of the model turn whose answers go to
    /// `control` that `asked` matches, which the turn no longer waits for.
    /// An answered request is already out.
    fn withdraw(
        &mut self,
        control: &mpsc::UnboundedSender<TurnControl>,
        asked: impl Fn(&Waiting) -> bool,
    ) {
        let found = self
            .open
            .iter()
            .find(|(_, open)| open.control.same_channel(control) && asked(&open.waiting))
            .map(|(&id, _)| id);
        if let Some(id) = found {
            self.open.remove(&id);
            self.events.push(resolved(id, Resolution::Withdrawn));
        }
    }

    /// Takes out every request the turn opened, for a turn that ended. Its
    /// runtime settles each before it ends, so this finds some only when
    /// the turn failed or its task stopped.
    pub(super) fn withdraw_turn(&mut self) {
        let (ended, kept) = std::mem::take(&mut self.open)
            .into_iter()
            .partition(|(_, open)| open.asker == Asker::Turn);
        self.open = kept;
        let ended: BTreeMap<_, _> = ended;
        for id in ended.into_keys() {
            self.events.push(resolved(id, Resolution::Withdrawn));
        }
    }

    /// Answers request `id` with its timeout's answer, if it is still open
    /// with a timeout: a request answered, withdrawn, or held since is left
    /// as it is.
    pub(super) fn time_out(&mut self, id: InputRequestId) {
        let Entry::Occupied(mut open) = self.open.entry(id) else {
            return;
        };
        let Some(answer) = open.get_mut().timeout.take() else {
            return;
        };
        let Open { control, .. } = open.remove();
        if control.is_closed() {
            self.events.push(resolved(id, Resolution::Withdrawn));
            return;
        }
        self.events.push(resolved(id, Resolution::TimedOut));
        self.answers.push((control, answer));
    }

    /// Stops request `id`'s timeout for good, so it waits for an answer. A
    /// request without one, or already held, is left as it is.
    pub(super) fn hold(&mut self, id: InputRequestId) -> Result<(), RpcError> {
        let open = self.open.get_mut(&id).ok_or_else(|| not_open(id))?;
        if open.timeout.take().is_some() {
            self.events.push(wire::SessionEvent::InputHeld { id });
        }
        Ok(())
    }

    /// Takes request `id` out with `answer`, for [`Self::send_answers`]
    /// to hand to the turn that waits for it. An answer the request does
    /// not take leaves it open.
    pub(super) fn answer(
        &mut self,
        id: InputRequestId,
        answer: InputAnswer,
    ) -> Result<(), RpcError> {
        let Entry::Occupied(open) = self.open.entry(id) else {
            return Err(not_open(id));
        };
        let answer = control_for(&open.get().waiting, answer)?;
        let Open { control, .. } = open.remove();
        // The model turn that asked ended, so nobody waits for the request;
        // its withdrawal may still be on the way, and will find it gone.
        if control.is_closed() {
            self.events.push(resolved(id, Resolution::Withdrawn));
            return Err(not_open(id));
        }
        self.events.push(resolved(id, Resolution::Answered));
        self.answers.push((control, answer));
        Ok(())
    }
}

impl LoadedSession {
    /// Changes the session's open input requests with `change`, tells
    /// attached clients what it opened and resolved, moves the job between
    /// running and waiting for input to match, and only then hands the
    /// turns the answers it accepted. All under the requests' lock, so
    /// clients see requests open and close, and the job's state follow
    /// them, in the order they happened, and before anything the turn does
    /// with an answer. Starts the timeouts the change opened.
    pub(super) fn change_inputs<T>(self: &Arc<Self>, change: impl FnOnce(&mut Inputs) -> T) -> T {
        // A panic mid-change leaves the requests as they were or with one
        // request moved, which the turn's end clears.
        let mut inputs = self.inputs.lock().unwrap_or_else(PoisonError::into_inner);
        let was_waiting = inputs.waiting();
        let result = change(&mut inputs);
        self.feed.publish(inputs.take_events());
        match (was_waiting, inputs.waiting()) {
            (false, true) => self.record(JobEvent::InputOpened),
            (true, false) => self.record(JobEvent::InputSettled),
            (false, false) | (true, true) => {}
        }
        inputs.send_answers();
        for (id, after) in inputs.take_timeouts() {
            tokio::spawn(super::time_out(Arc::downgrade(self), id, after));
        }
        result
    }
}

/// `after` past `now`, in Unix milliseconds; saturates, as no deadline
/// that far out is ever reached.
fn deadline_ms(now: SystemTime, after: Duration) -> u64 {
    now.checked_add(after)
        .and_then(|deadline| deadline.duration_since(UNIX_EPOCH).ok())
        .map_or(u64::MAX, |deadline| {
            u64::try_from(deadline.as_millis()).unwrap_or(u64::MAX)
        })
}

fn resolved(id: InputRequestId, resolution: Resolution) -> wire::SessionEvent {
    wire::SessionEvent::InputResolved { id, resolution }
}

fn wire_tool_call(id: &ToolCallId) -> wire::ToolCallId {
    wire::ToolCallId::new(id.as_str())
}

pub(super) fn not_open(id: InputRequestId) -> RpcError {
    RpcError::new(
        ErrorCode::InputNotOpen,
        format!(
            "input request {id} is not open: another client answered it, it timed out, or the turn withdrew it"
        ),
    )
}

fn invalid(message: impl Into<String>) -> RpcError {
    RpcError::new(ErrorCode::InvalidParams, message)
}

/// What the turn gets for `answer` to the request `waiting`, or why the
/// request does not take it.
fn control_for(waiting: &Waiting, answer: InputAnswer) -> Result<TurnControl, RpcError> {
    match waiting {
        Waiting::Approval(id) => {
            let decision = match answer {
                InputAnswer::AllowOnce => ApprovalDecision::AllowOnce,
                InputAnswer::AllowForSession => ApprovalDecision::AllowForSession,
                InputAnswer::Deny { reason } => ApprovalDecision::Deny {
                    reason: reason.unwrap_or_else(|| DENIED_BY_USER.to_owned()),
                },
                // Another kind of request's answer, or a kind a newer protocol
                // adds.
                _ => {
                    return Err(invalid(
                        "an approval takes allow_once, allow_for_session, or deny",
                    ))
                }
            };
            Ok(TurnControl::RespondApproval { id: *id, decision })
        }
        Waiting::Plan { id, modes } => {
            let answer = match answer {
                InputAnswer::ApprovePlan { mode, feedback } => {
                    let mode = PermissionMode::try_from(mode)
                        .ok()
                        .filter(|mode| modes.contains(mode))
                        .ok_or_else(|| invalid("the plan approval does not offer that mode"))?;
                    PlanExitDecision::approve(mode).with_feedback(feedback)
                }
                InputAnswer::KeepPlanning { feedback } => {
                    PlanExitDecision::keep_planning().with_feedback(feedback)
                }
                // Another kind of request's answer, or a kind a newer protocol
                // adds.
                _ => {
                    return Err(invalid(
                        "a plan approval takes approve_plan or keep_planning",
                    ))
                }
            };
            Ok(TurnControl::AnswerPlan { id: *id, answer })
        }
        Waiting::Question { id, request } => {
            let answer = match answer {
                InputAnswer::Answers { answers } => Ok(answered(request, answers)?),
                InputAnswer::Decline => Err(HostInputRefusal::Declined),
                InputAnswer::Dismiss => Err(HostInputRefusal::Dismissed),
                // Another kind of request's answer, or a kind a newer protocol
                // adds.
                _ => return Err(invalid("a question takes answers, decline, or dismiss")),
            };
            Ok(TurnControl::AnswerQuestion {
                id: id.clone(),
                answer,
            })
        }
    }
}

/// The user's `answers` to `request`, checked against its questions.
fn answered(
    request: &HostInputRequest,
    answers: BTreeMap<String, Vec<String>>,
) -> Result<HostInputResponse, RpcError> {
    let response = answers.into_iter().fold(
        HostInputResponse::new().with_source(HostInputSource::User),
        |response, (question, values)| response.answer(question, values),
    );
    request
        .validate(&response)
        .map_err(|error| invalid(format!("the answers do not fit the questions: {error}")))?;
    Ok(response)
}

#[cfg(test)]
#[path = "inputs_tests.rs"]
mod tests;