rho-coding-agent 3.13.0

A fast Rust agent harness with a small footprint and opinionated defaults
Documentation
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
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
//! A started session's turn in the daemon-wide agent budget (#1714).
//!
//! The turns of a session another session started share
//! `behavior.agent_concurrency` with subagent runs: each waits `queued` for
//! a slot before it runs. Unlike a subagent run, such a turn can wait on
//! others: on a person's answer, or on the sessions and subagents it
//! started, which may need a slot from the same budget. So it holds its slot
//! only while it runs alone (`JobRegistry::runs_alone`): `running`, with
//! nothing it started under way. Otherwise it may lend the slot back to the
//! budget and work on without one: its tools run, and its subagents and the
//! sessions it started take the slot.
//!
//! A Rho turn lends whenever it does not run alone
//! ([`Lending::WhileWaiting`]). A Rho turn without a slot takes one, in
//! line, before each model request and compaction its run makes
//! ([`ModelSlot`], the runtime's [`rho_sdk::ModelRequestGate`]): its job is
//! requeued, `queued` to clients with its place in line, until it has one.
//! It gives the slot back once the request ends, or keeps it for the turn
//! when the turn runs alone again. So no more than `agent_concurrency`
//! budgeted Rho runs make those requests at once; the turn's smaller side
//! calls (its title, the permission classifier, the advisor) go ungated. A
//! Rho turn holds a slot only while it waits on no other job, or for one
//! request, which waits on no job.
//!
//! A subagent run gives its slot back while it waits for an answer to its
//! question, and takes one again before its next request
//! (`agent_concurrency::RunSlot`), so the session that would answer it
//! through `sessions answer` can take the slot to do so.
//!
//! A Claude Code or Antigravity turn's agent makes its own model requests,
//! which rho cannot hold back, so such a turn lends its slot only while it
//! does not run alone and the agent waits on rho's served tools alone
//! ([`Lending::WhileAgentBlocked`], `agent_activity`): blocked on one of its
//! requests to them, a `tools/call` or, for Antigravity, an `await` of a
//! call still running, with no tool call of its own in progress, since a
//! Claude Code Task subagent makes model requests while its agent waits.
//! Not running alone, for such a turn, means waiting on sessions or
//! subagents it started, or on a person: a served call's approval or
//! question puts its job waiting for input, so a turn whose agent waits in
//! that call lends.
//! The turn decides to lend under the slot's lock, where a request's answer
//! looks for a lent slot to take back ([`ModelSlot::give_back_if`]). Each
//! request takes a slot back for the turn, in line, its job requeued while
//! it waits, before its answer goes back to the agent
//! ([`ModelSlot::retake`]), an Antigravity call's answer that it is still
//! running included, since agy goes on while that call runs; the turn then
//! keeps the slot until it lends again, at once if the agent still waits on
//! another request.
//!
//! So no request of the agent's runs without its turn holding a slot,
//! except:
//! - when the run ends first, which drops a request's wait for a slot (the
//!   answer then reaches nobody);
//! - after the budget ended a wait without a slot ([`in_line`]'s `None`),
//!   which it should never do;
//! - after an answer its transport sent before the slot came back, past the
//!   transport's deadline, as each Antigravity answer goes back ahead of
//!   agy's limit on an MCP call ([`ModelSlot::overdue`]): the turn runs over
//!   the budget, logged and shown in its transcript once, until a later
//!   answer finds a slot free, its answers waiting in no line meanwhile;
//! - while a call of the agent's own that it started after the turn lent
//!   runs, until a later answer takes a slot back;
//! - while a call of the agent's own that it reported completed goes on in
//!   the background, as a Claude Code `run_in_background` Bash or Task call
//!   may (not verified against the agent): the call no longer counts as in
//!   progress (`OwnCalls`), so the turn may lend while that work makes
//!   model requests.

use std::{
    convert::Infallible,
    future::Future,
    sync::{Arc, Mutex, MutexGuard, PoisonError, Weak},
};

use futures_util::FutureExt;
use rho_sdk::{CancellationToken, ModelRequestGate, ModelRequestGateFuture, ModelRequestPermit};
use tokio::sync::Notify;

use super::{
    super::{
        jobs::{JobEvent, JobId, JobRegistry, JobState},
        subagents::{TurnBudget, TurnLine},
        wire::state_event,
    },
    agent_activity::AgentActivity,
    turn::DaemonView,
    LoadedSession,
};
use crate::{
    acp_runtime::agent_tools::AgentRequest,
    app::agent_concurrency::{Budget, RuntimePermits},
};

/// A turn cancelled, or stopped by the daemon's stop, while it waited for
/// its first slot.
pub(super) struct Withdrawn;

/// What a turn runs with in the budget.
pub(super) enum Slot {
    /// Nothing: a person's session's turn.
    Unbudgeted,
    /// The slot it was admitted with, and the line to take one again.
    Budgeted {
        permits: RuntimePermits,
        line: TurnLine,
    },
}

/// Waits for the turn's first slot, its job `queued` until it has one and
/// then `running`; at once without a `budget`. The request that sent the
/// prompt learns the turn began as soon as it must wait, so it does not wait
/// for capacity; a slot free at once, or a cancel already sent, leaves that
/// to the turn, as for a person's session.
pub(super) async fn admit(
    view: &mut DaemonView,
    budget: Option<Box<TurnBudget>>,
    cancel: &CancellationToken,
    stopping: &CancellationToken,
) -> Result<Slot, Withdrawn> {
    let Some(budget) = budget else {
        return Ok(Slot::Unbudgeted);
    };
    let TurnBudget {
        queued,
        line,
        listing: _listing,
    } = *budget;
    let acquire = queued.acquire(cancel);
    tokio::pin!(acquire);
    let permits = match acquire.as_mut().now_or_never() {
        Some(permits) => permits,
        None => {
            // Answered as begun, but not recorded so: nothing ran yet, so
            // a later daemon runs the prompt when it is sent again.
            view.accepted();
            tokio::select! {
                biased;
                () = stopping.cancelled() => None,
                permits = &mut acquire => permits,
            }
        }
    }
    .ok_or(Withdrawn)?;
    view.session.admitted();
    Ok(Slot::Budgeted { permits, line })
}

/// When a budgeted turn lends its slot, on top of not running alone.
#[derive(Clone, Copy)]
pub(super) enum Lending {
    /// Whenever: a Rho turn, whose runtime takes a slot back before each
    /// model request ([`ModelSlot`] as its [`ModelRequestGate`]).
    WhileWaiting,
    /// Only while the session's agent waits on the served tools alone
    /// ([`super::agent_activity::Activity::waits_on_served_tools`]): a
    /// Claude Code or Antigravity turn, whose agent makes its own model
    /// requests. Each request takes a slot back before its answer goes
    /// back ([`ModelSlot::retake`]).
    WhileAgentBlocked,
}

impl Lending {
    /// Whether the turn of job `job` in `jobs` may lend now: it does not
    /// run alone, and the agent, whose activity is `activity` as it stands
    /// now, allows.
    fn lends_now(self, activity: &AgentActivity, jobs: &JobRegistry, job: &JobId) -> bool {
        let agent_allows = match self {
            Self::WhileWaiting => true,
            Self::WhileAgentBlocked => activity.now().waits_on_served_tools(),
        };
        agent_allows && !jobs.runs_alone(job)
    }
}

impl Slot {
    /// Runs `turn`, the turn of `session`, lending the slot whenever the
    /// turn does not run alone and `lending` allows; the session's
    /// [`ModelSlot`] takes one again for the turn while it is lent.
    pub(super) async fn run_budgeted<T>(
        self,
        session: &Arc<LoadedSession>,
        lending: Lending,
        turn: impl Future<Output = T>,
    ) -> T {
        match self {
            Self::Unbudgeted => turn.await,
            Self::Budgeted { permits, line } => {
                let budgeted = Budgeted::admitted(permits, line, Arc::downgrade(session));
                let model = &session.model_slot;
                run_on_slot(model, &session.jobs, &session.job, budgeted, lending, turn).await
            }
        }
    }
}

/// [`Slot::run_budgeted`] without a loaded session, the seam the tests run
/// a turn through: runs `turn`, budgeted on `model` as `budgeted`, while
/// [`lend_when_waiting`] lends its slot for job `job` in `jobs`.
async fn run_on_slot<T>(
    model: &ModelSlot,
    jobs: &JobRegistry,
    job: &JobId,
    budgeted: Budgeted,
    lending: Lending,
    turn: impl Future<Output = T>,
) -> T {
    let _turn = model.budget(budgeted);
    tokio::select! {
        biased;
        ended = turn => ended,
        never = lend_when_waiting(model, jobs, job, lending) => match never {},
    }
}

/// Gives the turn's slot back whenever `job` does not run alone and
/// `lending` allows, looking again whenever the jobs, the agent's activity
/// or the slot change. Decides under the slot's lock
/// ([`ModelSlot::give_back_if`]), so a request whose answer stopped it
/// blocking the agent either finds the slot lent and takes it back, or
/// keeps the turn from lending it. Runs until the turn drops it.
async fn lend_when_waiting(
    model: &ModelSlot,
    jobs: &JobRegistry,
    job: &JobId,
    lending: Lending,
) -> Infallible {
    let mut activity = model.activity.watch();
    loop {
        let changed = jobs.changed();
        tokio::pin!(changed);
        changed.as_mut().enable();
        let retaken = model.retaken.notified();
        tokio::pin!(retaken);
        retaken.as_mut().enable();
        // Seen: the decision reads the activity as it stands then.
        activity.mark_unchanged();
        if model.give_back_if(|| lending.lends_now(&model.activity, jobs, job)) {
            tracing::debug!(%job, "lent a started session's slot while it waits");
        }
        tokio::select! {
            () = changed => {}
            () = retaken => {}
            // The slot keeps the activity's sender, so this never ends
            // closed.
            _ = activity.changed() => {}
        }
    }
}

/// The agent budget's say over a session's model requests (see the module
/// doc). Budgeted only while a turn another session started runs; a
/// person's turn sends its requests at once.
///
/// It also keeps what the session's agent of another runtime does with the
/// served tools ([`Self::activity`]), which its turns lend by, and which
/// the session's background delivery holds back by: one per session,
/// shared by the session's turns and its served tools.
#[derive(Default)]
pub(super) struct ModelSlot {
    turn: Mutex<Option<Budgeted>>,
    /// Held by the agent's request taking the slot back for the turn, so
    /// requests answered together take one slot, not one each
    /// ([`Self::retake`]).
    retaking: tokio::sync::Mutex<()>,
    /// Wakes the turn's lending once a request took the slot back, so a
    /// turn whose agent still waits on another request lends it again.
    retaken: Notify,
    activity: AgentActivity,
}

/// The budgeted turn under way.
pub(super) struct Budgeted {
    /// Its slot, while it holds one.
    held: Option<RuntimePermits>,
    line: TurnLine,
    /// Its session, whose job shows it queued while it waits for a slot.
    session: Weak<LoadedSession>,
    /// Whether it runs over the budget, told already ([`ModelSlot::overdue`]),
    /// until it holds a slot again.
    over_budget: bool,
}

impl Budgeted {
    /// The turn admitted with `held`, its slot.
    fn admitted(held: RuntimePermits, line: TurnLine, session: Weak<LoadedSession>) -> Self {
        Self {
            held: Some(held),
            line,
            session,
            over_budget: false,
        }
    }

    /// The turn holds `permits` again, back within the budget.
    fn hold(&mut self, permits: RuntimePermits) {
        self.held = Some(permits);
        self.over_budget = false;
    }
}

/// The budgeted turn's time on a [`ModelSlot`], which ends, and gives back
/// any slot it holds, when dropped.
struct BudgetedTurn<'a>(&'a ModelSlot);

impl Drop for BudgetedTurn<'_> {
    fn drop(&mut self) {
        *self.0.state() = None;
    }
}

impl ModelSlot {
    fn budget(&self, turn: Budgeted) -> BudgetedTurn<'_> {
        *self.state() = Some(turn);
        BudgetedTurn(self)
    }

    /// What the session's agent does with the served tools.
    pub(super) fn activity(&self) -> &AgentActivity {
        &self.activity
    }

    /// Gives the turn's slot back if it holds one and `lend` says so; whether
    /// it gave one back. `lend` is asked under the lock [`Self::retake`]
    /// looks for a lent slot under, so a request's answer either stopped
    /// blocking the agent before `lend` looks, or takes back the slot it
    /// lent.
    fn give_back_if(&self, lend: impl FnOnce() -> bool) -> bool {
        let mut state = self.state();
        let Some(turn) = state.as_mut().filter(|turn| turn.held.is_some()) else {
            return false;
        };
        if !lend() {
            return false;
        }
        turn.held = None;
        true
    }

    /// One of the agent's requests to the served tools, outstanding
    /// ([`crate::acp_runtime::agent_tools::AgentTools::request`]). It
    /// counts twice. As blocking the agent, which the turn lends by, until
    /// its answer readies, which stops it blocking and then takes a slot
    /// back for a turn that lent its own, in line ([`Self::retake`]), so
    /// the agent's next model request, which may follow the answer, runs on
    /// the turn's slot. Both, in that order, as one step: a turn that took
    /// its slot back while the agent was still blocked would lend it again
    /// at once. And as an answer yet to go back, which the background
    /// delivery holds back by, until the slot is back or the wait for it
    /// ends: a result sent into the turn meanwhile would reach the agent
    /// ahead of the answer. Dropped unanswered, as when the run ends, it
    /// counts as neither; an answer its transport sends before the slot
    /// came back runs the turn over the budget ([`Self::overdue`]).
    pub(super) fn request(self: &Arc<Self>) -> AgentRequest {
        let blocking = self.activity.request_outstanding();
        let pending = self.activity.answer_pending();
        let (slot, overdue) = (Arc::clone(self), Arc::clone(self));
        AgentRequest::new(
            Box::pin(async move {
                // Moved in, so it drops as the slot is back, or with the
                // wait, not before.
                let _pending = pending;
                drop(blocking);
                slot.retake().await;
            }),
            Box::new(move || overdue.overdue()),
        )
    }

    /// A request's answer went back before [`Self::retake`] took a slot
    /// back for the turn, as its transport's deadline came first: a turn
    /// still without one runs over the budget until a later answer finds
    /// a slot free, its answers waiting in no line meanwhile
    /// ([`Self::retake`]). Says so in the daemon's log, and returns the notice the
    /// turn's run shows, only as the turn first runs over: each of agy's
    /// `await`s of a long call may miss its deadline again, and the turn
    /// says nothing more until it holds a slot again. Nothing for a turn
    /// that holds a slot after all, as when another request took it back.
    fn overdue(&self) -> Option<String> {
        let (line, session) = {
            let mut state = self.state();
            let turn = state
                .as_mut()
                .filter(|turn| turn.held.is_none() && !turn.over_budget)?;
            turn.over_budget = true;
            (turn.line.clone(), turn.session.clone())
        };
        let budget = Budget::AgentConcurrency.setting();
        let limit = line.limit();
        let job = session.upgrade().map(|session| session.job.clone());
        tracing::warn!(
            budget,
            limit,
            job = ?job,
            "an answer went back to a started session's agent before its turn got a slot \
             again: the turn runs over the budget until a later answer finds one free"
        );
        Some(format!(
            "rho answered the agent before this turn got a slot in `{budget}` (limit {limit}) \
             again, so that it reached the agent in time: the agent's requests run over the \
             budget until a later answer of rho's tools finds a slot free"
        ))
    }

    /// The budgeted turn's line, its session, and whether it runs over the
    /// budget, while it lent its slot; `None` while it holds one, or while
    /// no budgeted turn runs.
    fn lent(&self) -> Option<(TurnLine, Weak<LoadedSession>, bool)> {
        match &*self.state() {
            Some(Budgeted {
                held: None,
                line,
                session,
                over_budget,
            }) => Some((line.clone(), session.clone(), *over_budget)),
            Some(Budgeted { held: Some(_), .. }) | None => None,
        }
    }

    /// Takes a slot back for the budgeted turn when it lent its own, in
    /// line, its job requeued while it waits; the turn then keeps it until
    /// it lends again, and its lending looks again at once. At once while
    /// it holds one, and for a person's turn. Only dropping the wait, as
    /// the end of the turn's run or the transport's deadline for the answer
    /// does, ends it early. A turn that runs over the budget already
    /// ([`Self::overdue`]) waits in no line: it takes a slot only if one is
    /// free at once, back within the budget then, and otherwise goes on
    /// over it, so each later answer is not held to its deadline again.
    pub(super) async fn retake(&self) {
        // A request that finds the slot taken back while it waited behind
        // another waits no more.
        let _retaking = self.retaking.lock().await;
        let Some((line, session, over_budget)) = self.lent() else {
            return;
        };
        let permits = if over_budget {
            free_at_once(&line)
        } else {
            in_line(&line, &session).await
        };
        let Some(permits) = permits else {
            return;
        };
        // A turn that ended meanwhile takes none; the permits go back.
        if let Some(turn) = self.state().as_mut().filter(|turn| turn.held.is_none()) {
            turn.hold(permits);
            self.retaken.notify_waiters();
        }
    }

    fn state(&self) -> MutexGuard<'_, Option<Budgeted>> {
        self.turn.lock().unwrap_or_else(PoisonError::into_inner)
    }
}

/// A slot in `line` if one is free at once, ahead of no one waiting; the
/// line is left at once otherwise.
fn free_at_once(line: &TurnLine) -> Option<RuntimePermits> {
    let (queued, _listing) = line.join();
    queued
        .acquire(&CancellationToken::new())
        .now_or_never()
        .flatten()
}

/// Waits in `line` for a slot, `session`'s job requeued while it waits.
/// Only dropping the wait ends it early; `None` only if the budget ends an
/// uncancelled wait without a slot, which it should never do.
async fn in_line(line: &TurnLine, session: &Weak<LoadedSession>) -> Option<RuntimePermits> {
    let (queued, listing) = line.join();
    // Only dropping this wait, as a cancel does, ends it.
    let never = CancellationToken::new();
    let acquire = queued.acquire(&never);
    tokio::pin!(acquire);
    let permits = match acquire.as_mut().now_or_never() {
        Some(permits) => permits,
        None => {
            let _requeued = session.upgrade().and_then(Requeued::of);
            acquire.await
        }
    };
    drop(listing);
    if permits.is_none() {
        tracing::error!(
            "an uncancelled wait for a slot ended without one; the turn goes on unbudgeted"
        );
    }
    permits
}

impl ModelRequestGate for ModelSlot {
    fn admit<'a>(&'a self, _session_id: &'a rho_sdk::SessionId) -> ModelRequestGateFuture<'a> {
        Box::pin(async move {
            // A request made while the turn holds its slot runs on it, even
            // if the turn lends it before the request ends: only a job the
            // turn did not start, such as a person's prompt to a session it
            // started, can make it lend mid-request.
            // Only a turn that waits on served tools runs over the budget,
            // and its requests do not come through this gate.
            let Some((line, session, _over_budget)) = self.lent() else {
                return ModelRequestPermit::free();
            };
            let Some(permits) = in_line(&line, &session).await else {
                return ModelRequestPermit::free();
            };
            match (&mut *self.state(), session.upgrade()) {
                (Some(turn), Some(session))
                    if turn.held.is_none() && session.jobs.runs_alone(&session.job) =>
                {
                    turn.hold(permits);
                    ModelRequestPermit::free()
                }
                (Some(_) | None, _) => ModelRequestPermit::holding(permits),
            }
        })
    }
}

/// A turn's job requeued while its request waits for a slot, running again
/// when dropped, as the wait ends or is dropped.
struct Requeued(Arc<LoadedSession>);

impl Requeued {
    /// Requeues `session`'s job, when it is running; one waiting for input
    /// stays so.
    fn of(session: Arc<LoadedSession>) -> Option<Self> {
        session
            .record_from(&JobState::Running, JobEvent::SlotWanted)
            .then_some(Self(session))
    }
}

impl Drop for Requeued {
    fn drop(&mut self) {
        // A requeued turn whose background tool asked meanwhile stays
        // waiting for its answer.
        self.0.record_from(&JobState::Requeued, JobEvent::Admitted);
    }
}

impl LoadedSession {
    /// Records `event` on the session's job while it is `from`, and tells
    /// attached clients where it left the job; whether it applied. Under
    /// the turn lock, as the turn's start and end are told, and with the
    /// feed's (see [`super::feed::Feed::publish_change`]), as its progress
    /// is.
    fn record_from(&self, from: &JobState, event: JobEvent) -> bool {
        let _turn = self.turn();
        self.feed.publish_change(|| {
            let moved = self
                .jobs
                .record_from(&self.job, from, event)
                .inspect_err(|error| {
                    tracing::warn!(job = %self.job, %error, "could not record a turn's progress");
                })
                .ok()
                .flatten();
            (moved.is_some(), moved.map(|moved| state_event(&moved)))
        })
    }
}

#[cfg(test)]
#[path = "budget_test_support.rs"]
pub(super) mod test_support;

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