rho-coding-agent 3.11.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
//! One connection of this process to the rho daemon. Most frontends hold
//! one; the TUI opens another for the session it switches to, then drops
//! the old one.
//!
//! Every session the client attaches attaches on the same connection: the
//! daemon keeps one attachment per session, not per connection. The
//! connection opens on the first request that needs it, starting the daemon
//! when none runs, as `rho run --detach` does.
//!
//! One task per connection drains its notifications in order and routes
//! them: a session's events and detach to that session's route, a login's
//! prompt and outcome to the login waiting on them, settings and model
//! list changes to the settings route, and job changes to the jobs route. When the daemon closes
//! the connection, every route hears [`Routed::Lost`], and the next request
//! connects again. A session the daemon detached as restarting routes
//! itself again once the connection closed ([`Link::closed`]), then attaches
//! on the next one, which waits for the restarted daemon.

use std::{
    collections::HashMap,
    sync::{Arc, Mutex, PoisonError},
};

use rho_protocol::{
    methods::Method, BuildSkew, Client, ClientError, ConfigChangedParams, DaemonFeature,
    DaemonInfo, DaemonNotification, DetachReason, JobChangedParams, LoginId, LoginOutcome,
    LoginPrompt, ModelList, ModelListRefresh, Notifications, Seq, SessionEvent, SessionId,
};
use rho_sdk::CancellationToken;
use tokio::sync::{mpsc, oneshot};

use crate::{
    app::daemon_cli::{self, Unreachable},
    daemon::{ConnectAs, Connection},
};

/// Why a request to the daemon failed.
#[derive(Debug, thiserror::Error)]
pub(crate) enum DaemonError {
    /// No daemon could be reached to send it to.
    #[error(transparent)]
    Unreachable(#[from] Unreachable),
    /// The daemon refused it, or the connection failed under it.
    #[error(transparent)]
    Request(#[from] ClientError),
}

/// What the router reads for a session.
pub(crate) enum Routed {
    /// One event of the session's stream, with its sequence number.
    Event { seq: Seq, event: SessionEvent },
    /// The daemon ended the session's attachment.
    Detached(DetachReason),
    /// The connection the session was attached on closed.
    Lost,
}

/// Where the router hands what it reads for one session, in order.
pub(crate) type SessionRoute = Box<dyn Fn(Routed) + Send>;

/// What the router hands the login in flight.
pub(crate) enum LoginEvent {
    Prompt {
        login: LoginId,
        prompt: LoginPrompt,
    },
    Finished {
        login: LoginId,
        outcome: LoginOutcome,
        /// The model lists the daemon fetched once it saved the login.
        refreshed: Vec<ModelListRefresh>,
    },
    Lost,
}

/// What the router hands the settings route: what the settings and model
/// lists this process read became.
pub(crate) enum SettingsChange {
    /// `rho/config/changed`.
    Config(ConfigChangedParams),
    /// `rho/model/changed`: the whole model list.
    Models(ModelList),
}

/// Where the router sends what it reads. Shared across connections, so a
/// session that reattaches after a reconnect keeps its route.
#[derive(Default)]
struct Routes {
    sessions: HashMap<SessionId, SessionRoute>,
    login: Option<mpsc::UnboundedSender<LoginEvent>>,
    /// Where `rho/config/changed` and `rho/model/changed` go, for the
    /// settings and models this process read.
    settings: Option<mpsc::UnboundedSender<SettingsChange>>,
    /// Where `rho/job/changed` goes, for the job list this process
    /// follows.
    jobs: Option<mpsc::UnboundedSender<JobChangedParams>>,
}

/// The daemon as this process reaches it. It has no default: each owner
/// says what its connections declare.
pub(crate) struct Daemon {
    link: tokio::sync::Mutex<Option<Arc<Link>>>,
    routes: Arc<Mutex<Routes>>,
    reach: daemon_cli::Reach,
    /// What its connections declare.
    connect_as: ConnectAs,
}

/// One open connection.
pub(crate) struct Link {
    client: Client,
    /// The daemon process the connection's hello reached.
    daemon: DaemonInfo,
    /// Set when that daemon is another build than this process.
    skew: Option<BuildSkew>,
    /// Whether that daemon answers a prompt sent again with its key as
    /// sent again ([`DaemonFeature::PromptRetries`]).
    answers_retries: bool,
    /// Whether that daemon applies a setup's system prompt
    /// ([`DaemonFeature::SystemPrompts`]).
    applies_system_prompts: bool,
    /// Whether that daemon opens a new session on its setup's model
    /// ([`DaemonFeature::SetupModels`]).
    applies_setup_models: bool,
    /// Whether that daemon follows a job list ([`DaemonFeature::JobChanges`]).
    follows_jobs: bool,
    /// Whether that daemon takes attachments in a steer
    /// ([`DaemonFeature::SteerAttachments`]).
    steers_attachments: bool,
    /// Cancelled by the router once the connection closed, after it handed
    /// every route [`Routed::Lost`].
    closed: CancellationToken,
    fences: mpsc::UnboundedSender<oneshot::Sender<()>>,
}

impl Daemon {
    /// A daemon for a person's frontend, which answers their sessions'
    /// approvals and questions, started when none runs.
    pub(crate) fn for_frontend() -> Self {
        Self::reaching(daemon_cli::Reach::StartIfNeeded, ConnectAs::Frontend)
    }

    /// A daemon reached as `reach` allows, by connections that declare
    /// what `connect_as` does.
    pub(crate) fn reaching(reach: daemon_cli::Reach, connect_as: ConnectAs) -> Self {
        Self {
            link: tokio::sync::Mutex::default(),
            routes: Arc::default(),
            reach,
            connect_as,
        }
    }

    /// The open connection, connecting first when there is none or the last
    /// one closed. The error names what failed, such as a daemon that could
    /// not start, with its log file.
    pub(crate) async fn link(&self) -> Result<Arc<Link>, Unreachable> {
        let mut current = self.link.lock().await;
        if let Some(link) = current.as_ref().filter(|link| link.is_alive()) {
            return Ok(Arc::clone(link));
        }
        let Connection {
            client,
            notifications,
            hello,
        } = daemon_cli::connect_with(self.reach, self.connect_as).await?;
        let closed = CancellationToken::new();
        let (fences, fence_receiver) = mpsc::unbounded_channel();
        tokio::spawn(tokio::task::unconstrained(route(
            notifications,
            fence_receiver,
            Arc::clone(&self.routes),
            closed.clone(),
        )));
        let features = client.daemon_features();
        let answers_retries = features.contains(&DaemonFeature::PromptRetries);
        let applies_system_prompts = features.contains(&DaemonFeature::SystemPrompts);
        let applies_setup_models = features.contains(&DaemonFeature::SetupModels);
        let follows_jobs = features.contains(&DaemonFeature::JobChanges);
        let steers_attachments = features.contains(&DaemonFeature::SteerAttachments);
        let link = Arc::new(Link {
            client,
            daemon: hello.daemon,
            skew: hello.skew,
            answers_retries,
            applies_system_prompts,
            applies_setup_models,
            follows_jobs,
            steers_attachments,
            closed,
            fences,
        });
        *current = Some(Arc::clone(&link));
        Ok(link)
    }

    /// The open connection, if there is one; never connects. For requests
    /// that matter only to an attachment that still delivers, such as a
    /// detach or a cancel: a closed connection already ended it.
    pub(crate) async fn current(&self) -> Option<Arc<Link>> {
        let current = self.link.lock().await;
        current.as_ref().filter(|link| link.is_alive()).cloned()
    }

    /// Sends `M` on the open connection, connecting first if needed.
    pub(crate) async fn request<M: Method>(
        &self,
        params: &M::Params,
    ) -> Result<M::Result, DaemonError> {
        let link = self.link().await?;
        Ok(link.request::<M>(params).await?)
    }

    /// Routes session `session`'s notifications to `route`, replacing any
    /// earlier route.
    pub(crate) fn route(&self, session: &SessionId, route: SessionRoute) {
        lock(&self.routes).sessions.insert(session.clone(), route);
    }

    /// Routes session `session`'s notifications to the receiver this
    /// returns, replacing any earlier route.
    pub(crate) fn route_channel(&self, session: &SessionId) -> mpsc::UnboundedReceiver<Routed> {
        let (sender, routed) = mpsc::unbounded_channel();
        self.route(
            session,
            Box::new(move |routed| {
                let _ = sender.send(routed);
            }),
        );
        routed
    }

    /// Drops session `session`'s route; what the daemon still sends for it
    /// is discarded.
    pub(crate) fn unroute(&self, session: &SessionId) {
        lock(&self.routes).sessions.remove(session);
    }

    /// Routes login notifications to `sender`, replacing an earlier login's
    /// route. A connection runs one login at a time.
    pub(crate) fn route_login(&self, sender: mpsc::UnboundedSender<LoginEvent>) {
        lock(&self.routes).login = Some(sender);
    }

    pub(crate) fn unroute_login(&self) {
        lock(&self.routes).login = None;
    }

    /// Routes settings and model list changes to `sender`, replacing an
    /// earlier route.
    pub(crate) fn route_settings(&self, sender: mpsc::UnboundedSender<SettingsChange>) {
        lock(&self.routes).settings = Some(sender);
    }

    /// Routes job changes to `sender`, replacing an earlier route. The
    /// connection's end drops it, so the follower lists again on the next.
    pub(crate) fn route_jobs(&self, sender: mpsc::UnboundedSender<JobChangedParams>) {
        lock(&self.routes).jobs = Some(sender);
    }
}

impl Link {
    pub(crate) fn is_alive(&self) -> bool {
        !self.closed.is_cancelled()
    }

    /// Resolves once the connection closed and the router handed every
    /// route it had [`Routed::Lost`], so a route installed after belongs to
    /// the next connection.
    pub(crate) async fn closed(&self) {
        self.closed.cancelled().await;
    }

    /// The daemon process this connection reached.
    pub(crate) fn daemon(&self) -> &DaemonInfo {
        &self.daemon
    }

    /// Set when the daemon this connection reached is another build than
    /// this process: requests may fail, and it says what a restart costs.
    pub(crate) fn skew(&self) -> Option<BuildSkew> {
        self.skew
    }

    /// Whether the daemon knows a prompt's idempotency key for as long as
    /// its message is saved, says when a prompt was sent again, and answers
    /// `rho/session/prompt_sent`. An earlier daemon does none of these.
    pub(crate) fn answers_retries(&self) -> bool {
        self.answers_retries
    }

    pub(crate) fn applies_system_prompts(&self) -> bool {
        self.applies_system_prompts
    }

    /// Whether the daemon opens a new session on its setup's `model`; an
    /// earlier one ignores it, so its client switches after the open.
    pub(crate) fn applies_setup_models(&self) -> bool {
        self.applies_setup_models
    }

    /// Whether the daemon follows a job list with `rho/job/changed`; an
    /// earlier daemon answers it once, so its client polls.
    pub(crate) fn follows_jobs(&self) -> bool {
        self.follows_jobs
    }

    /// Whether the daemon takes attachments in a steer; an earlier one
    /// ignores them and steers with the text alone.
    pub(crate) fn steers_attachments(&self) -> bool {
        self.steers_attachments
    }

    pub(crate) async fn request<M: Method>(
        &self,
        params: &M::Params,
    ) -> Result<M::Result, ClientError> {
        self.client.request::<M>(params).await
    }

    /// Returns once the router has routed every notification this
    /// connection read before the call, such as the events of an attachment
    /// whose detach already answered. Nothing to wait for on a closed
    /// connection.
    pub(crate) async fn fence(&self) {
        let (done, fenced) = oneshot::channel();
        if self.fences.send(done).is_ok() {
            let _ = fenced.await;
        }
    }
}

/// The router: one per connection, so a session's notifications reach its
/// route in the order the daemon sent them.
///
/// The client's reader queues a response's notifications before it answers
/// the request, so once a response arrived, everything sent before it is
/// queued here. Polling notifications first (`biased`, and unconstrained so
/// the cooperative budget never makes a ready queue look empty) is what lets
/// a fence vouch for them.
async fn route(
    mut notifications: Notifications,
    mut fences: mpsc::UnboundedReceiver<oneshot::Sender<()>>,
    routes: Arc<Mutex<Routes>>,
    closed: CancellationToken,
) {
    loop {
        tokio::select! {
            biased;
            notification = notifications.recv() => match notification {
                Some(notification) => deliver(&routes, notification),
                None => break,
            },
            Some(fence) = fences.recv() => {
                let _ = fence.send(());
            }
        }
    }
    // One step under the lock: a route installed after it belongs to the
    // next connection, which `link` opens only once this one is dead, so
    // this router never takes it.
    let Routes {
        sessions, login, ..
    } = {
        let mut routes = lock(&routes);
        closed.cancel();
        std::mem::take(&mut *routes)
    };
    for route in sessions.into_values() {
        route(Routed::Lost);
    }
    if let Some(login) = login {
        let _ = login.send(LoginEvent::Lost);
    }
}

fn deliver(routes: &Mutex<Routes>, notification: DaemonNotification) {
    let routes = lock(routes);
    let (session, routed) = match notification {
        DaemonNotification::SessionEvent(params) => (
            params.session,
            Routed::Event {
                seq: params.seq,
                event: params.event,
            },
        ),
        DaemonNotification::SessionDetached(params) => {
            (params.session, Routed::Detached(params.reason))
        }
        DaemonNotification::LoginPrompt(params) => {
            if let Some(login) = &routes.login {
                let _ = login.send(LoginEvent::Prompt {
                    login: params.login,
                    prompt: params.prompt,
                });
            }
            return;
        }
        DaemonNotification::LoginFinished(params) => {
            if let Some(login) = &routes.login {
                let _ = login.send(LoginEvent::Finished {
                    login: params.login,
                    outcome: params.outcome,
                    refreshed: params.refreshed,
                });
            }
            return;
        }
        DaemonNotification::ConfigChanged(params) => {
            if let Some(settings) = &routes.settings {
                let _ = settings.send(SettingsChange::Config(params));
            }
            return;
        }
        DaemonNotification::ModelsChanged(list) => {
            if let Some(settings) = &routes.settings {
                let _ = settings.send(SettingsChange::Models(list));
            }
            return;
        }
        DaemonNotification::JobChanged(params) => {
            if let Some(jobs) = &routes.jobs {
                let _ = jobs.send(params);
            }
            return;
        }
        // Each session's route hears why from its own `rho/session/detached`,
        // which comes first, and the connection's end follows.
        DaemonNotification::DaemonStopping(_) => return,
        // `Unknown`, or a notification a newer protocol adds.
        _ => {
            tracing::debug!("skipping a daemon notification this rho does not know");
            return;
        }
    };
    if let Some(route) = routes.sessions.get(&session) {
        route(routed);
    }
}

fn lock(routes: &Mutex<Routes>) -> std::sync::MutexGuard<'_, Routes> {
    routes.lock().unwrap_or_else(PoisonError::into_inner)
}