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
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
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
//! `rho/session/configure`: one change to a session, applied between its
//! turns: a setting, through the session runtime's settings cores, the same
//! ACP's `session/set_mode` and `session/set_config_option` and the TUI's
//! controls use (#1670, #1667), or context added for the model's next turn.
//!
//! A change sent while a turn is under way, waiting for input included,
//! waits for the turn to end, then applies and answers, as the TUI and ACP
//! queue settings behind a turn (#1685). A change and a prompt's turn each
//! join the queue on the session's runtime under the turn lock, so they
//! take it in the order they started under that lock. The daemon's stop
//! answers a change still queued `DaemonStopping`. A change applies even
//! when its client disconnects meanwhile: the protocol server runs every
//! request it read to completion.
//!
//! A permission mode change still waiting when an approved plan switches
//! the mode is dropped: the approval, at the end of the turn the change was
//! sent during, sets the mode the session ends in.
//!
//! `rho/session/rewind` takes the same queue, through [`Sessions::apply_change`],
//! so a rewind keeps that order too and answers with what it did.
//!
//! Only a loaded session takes a change: a client attaches first, which
//! loads it. A change that applies is kept with the session's file, so a
//! session the daemon unloads while idle reopens with it.
//!
//! What the sessions a session starts open with is a choice of the
//! starting session, kept with its file apart from its own settings, so
//! setting it leaves the session following the config, or keeping its
//! settings, as before. Like every change, one sent during the session's
//! turn waits for that turn's end, so the sessions that turn starts
//! meanwhile open with the choice as it was. `new.rs` applies the choice to
//! each session it starts, with [`set_up_started_session`], through these
//! same changes.

use std::path::PathBuf;

use rho_protocol::{
    self as wire, ErrorCode, RpcError, SessionConfigureParams, SessionConfigureResponse,
};
use rho_providers::model::catalog::ModelSelection;
use rho_sdk::{model::Message, ReasoningLevel};

use super::{acp_turns::AcpTurns, capabilities, engine::Engine, LoadedSession};
use super::{being_deleted, options::available_auths, queued::Queued, stopping, Held, Sessions};
use crate::{
    agent::AgentRuntime,
    app::{
        daemon_host::runtimes,
        session_options::{reasoning_from_wire, resolve_model, AuthPick},
        session_runtime::{
            AddDirError, RewoundConversation, SelectNodeError, SessionRuntime, SettingChangeError,
            StartedMode, StartedModel, StartedSessionDefaults,
        },
        workspace_rewind::rewind_audit_text,
    },
    config::Config,
    permission::PermissionMode,
    session::tree::NodeId,
};

/// A change this daemon knows how to apply.
enum Change {
    Model {
        model: wire::ModelRef,
        auth: Option<String>,
        setup: bool,
    },
    Reasoning(ReasoningLevel),
    FastMode {
        enabled: bool,
    },
    PermissionMode(PermissionMode),
    /// What the sessions this one starts open in; `None` clears it.
    StartedSessionPermissionMode(Option<PermissionMode>),
    /// What the sessions this one starts open on: `runtime`, and `model`,
    /// that runtime's default when `None`. Rho's loop with no model clears
    /// the choice. Both wire changes that choose them parse to it.
    StartedSessionRuntime {
        runtime: AgentRuntime,
        model: Option<wire::ModelRef>,
    },
    Context {
        text: String,
        display: String,
    },
    AgentCatalog,
    AddDirectory(PathBuf),
    ModelCatalog,
    SelectNode(NodeId),
    RewindWorkspace {
        checkpoint: NodeId,
        /// The node the requester's preview was planned at, which the
        /// conversation must still be at.
        // NEXT_MAJOR(rho-protocol): make tip required once SessionChange::RewindWorkspace is removed.
        tip: Option<NodeId>,
    },
}

impl Sessions {
    /// Applies `params`' change to its loaded session, once the turn under
    /// way and the changes queued before it are done, and answers with the
    /// session's options.
    pub(in crate::app::daemon_host) async fn configure(
        &self,
        params: SessionConfigureParams,
    ) -> Result<SessionConfigureResponse, RpcError> {
        self.refuse_when_stopping()?;
        // A model change that waits on a `/compact`, which the turn under
        // way or last done must be.
        let after_compaction = matches!(
            params.change,
            wire::SessionChange::ModelAfterCompaction { .. }
        );
        let change = Change::parse(params.change)?;
        let (options, _) = self
            .apply_change(&params.session, change, after_compaction)
            .await?;
        Ok(SessionConfigureResponse { options })
    }

    /// Rewinds `params`' loaded session's workspace as its preview showed,
    /// held to the preview's tip, once the turn under way and the changes
    /// queued before it are done, as a change is (`rho/session/rewind`).
    pub(in crate::app::daemon_host) async fn rewind(
        &self,
        params: wire::SessionRewindParams,
    ) -> Result<wire::SessionRewindResponse, RpcError> {
        self.refuse_when_stopping()?;
        let change = Change::RewindWorkspace {
            checkpoint: super::tree::node_from_wire(&params.checkpoint)?,
            tip: Some(super::tree::node_from_wire(&params.tip)?),
        };
        match self
            .apply_change(&params.session, change, /*after_compaction*/ false)
            .await?
        {
            (_, Some(rewound)) => Ok(rewound),
            // Only a mode change or one after a compaction is superseded.
            (_, None) => Err(RpcError::new(
                ErrorCode::InternalError,
                "the rewind was applied but said nothing",
            )),
        }
    }

    /// Applies `change` to session `id`, once the turn under way and the
    /// changes queued before it are done, and answers with the session's
    /// options and, for a rewind, what it did.
    async fn apply_change(
        &self,
        id: &wire::SessionId,
        change: Change,
        after_compaction: bool,
    ) -> Result<(wire::SessionOptions, Option<wire::SessionRewindResponse>), RpcError> {
        let not_loaded = || {
            RpcError::new(
                ErrorCode::SessionNotLoaded,
                "the daemon has not loaded the session; attach to it first",
            )
        };
        let session = self.loaded_session(id).await?.ok_or_else(not_loaded)?;
        // Refused here, typed, rather than behind the turn under way. A
        // change after a `/compact` belongs to rho's compaction too.
        if after_compaction {
            session.require(wire::SessionCapability::Compact)?;
        }
        let needs = change.capability(session.runtime);
        session.require(needs)?;
        #[cfg(test)]
        drop(self.hold_changes.read().await);
        let (held, queued, plan_switches, prompt) = {
            // `None` once the idle unload took the session after the lookup.
            let mut turn = session.enter().ok_or_else(not_loaded)?;
            let held = Held::change(&session, &mut turn).ok_or_else(being_deleted)?;
            // Queued on the runtime under the turn lock a prompt starts its
            // turn under, as the change counts: a turn started before this
            // runs first, even one not holding the runtime yet, and a prompt
            // that sees the count starts a turn that queues behind it.
            (
                held,
                Queued::join(&session.engine),
                turn.plan_switches,
                turn.prompts,
            )
        };
        super::line::took_place(id);
        // Behind the turn under way and the changes queued before this one.
        // The stop first: a turn that outlives the stop's drain must not
        // keep this request, and so the daemon, from exiting.
        let mut runtime = tokio::select! {
            biased;
            () = self.stopping.cancelled() => return Err(stopping()),
            runtime = queued.acquire() => runtime,
        };
        // Only the daemon's stop takes the runtime of a session in use.
        let Some(runtime) = runtime.as_mut() else {
            return Err(stopping());
        };
        let runtime = match runtime {
            Engine::Rho(runtime) => runtime,
            Engine::Acp(turns) => {
                let mode_change = matches!(change, Change::PermissionMode(_));
                let changed = agent_change(&session, turns, change);
                // The tools the session serves its agent take the mode now,
                // reading the classifier models as they are now, as a Rho
                // session's mode change does.
                if let (true, Ok(_)) = (mode_change, &changed) {
                    let config = session.config_for_permission_change().await;
                    turns.reapply_served_mode((*config).clone()).await;
                }
                drop(held);
                return changed.map(|options| (options, None));
            }
        };
        // Read under the runtime's lock, which a credential write's refresh
        // waits for (see `Sessions::models_changed`): a refresh queued
        // before this ran first, and one queued after runs once this is
        // done, so the options this publishes are never older than one.
        let auths = available_auths(runtime.credentials()).await;
        let superseded = {
            let turn = session.turn();
            match change {
                Change::PermissionMode(_) => turn.plan_switches != plan_switches,
                // Dropped unless that turn compacted.
                _ if after_compaction => turn.compacted_prompt != Some(prompt),
                _ => false,
            }
        };
        let applied = if superseded {
            Ok(Applied::Superseded)
        } else {
            match change {
                // The started sessions' mode is checked against the
                // classifier models as they are now, as a mode change is;
                // the session's own config does not change.
                Change::StartedSessionPermissionMode(_) => {
                    let config = session.config_for_permission_change().await;
                    change.apply(runtime, &config, &auths).await
                }
                Change::PermissionMode(_) => {
                    let config = session.config_for_permission_change().await;
                    let applied = change.apply(runtime, &config, &auths).await;
                    // Only a mode the session took keeps the models it read.
                    if applied.is_ok() {
                        session.keep_config(config);
                    }
                    applied
                }
                _ => change.apply(runtime, &session.config(), &auths).await,
            }
        };
        let mut rewound = None;
        let applied = match applied {
            // The session keeps a setting with its file from its first
            // change on.
            Ok(Applied::Setting { notice }) => {
                session
                    .feed
                    .publish(notice.map(|text| wire::SessionEvent::Notice { text }));
                runtime.keep_settings().map_err(|error| {
                    RpcError::new(
                        ErrorCode::InternalError,
                        format!("could not save the session's settings: {error:#}"),
                    )
                })
            }
            // What it saved joins the transcript a reset replays; no turn's
            // end would move it there before the next prompt. The turn
            // before it stops replaying its end, as when a turn follows.
            Ok(Applied::Rows { notice }) => {
                // Told live first; a later reset replays the saved rows.
                session
                    .feed
                    .publish(notice.map(|text| wire::SessionEvent::Notice { text }));
                super::turn::save_transcript(&session, runtime);
                Ok(())
            }
            // Every client replays the conversation as it now stands.
            Ok(Applied::Restarted) => {
                super::turn::restart_transcript(&session, runtime).await;
                Ok(())
            }
            // A rewind that moved the conversation restarts the transcript
            // as a node selection does, before the notice, so the clients
            // it detached replay it; one that kept it saved rows, which
            // join the transcript after the notice is told live.
            Ok(Applied::Rewound {
                moved,
                notice,
                response,
            }) => {
                if moved {
                    super::turn::restart_transcript(&session, runtime).await;
                }
                session
                    .feed
                    .publish(Some(wire::SessionEvent::Notice { text: notice }));
                if !moved {
                    super::turn::save_transcript(&session, runtime);
                }
                rewound = Some(*response);
                Ok(())
            }
            Ok(Applied::SharedOptions) => {
                // Each session's, once its runtime is free; this one's
                // also follow below.
                self.models_changed().await;
                Ok(())
            }
            // Saved by the runtime, apart from the session's settings.
            Ok(Applied::StartedSessionDefaults | Applied::Superseded) => Ok(()),
            Err(error) => Err(error),
        };
        // Even after a failure: a model switch can fail partway, after it
        // changed what the session reports.
        let options = session.refresh_options(runtime, &auths);
        drop(held);
        applied.map(|()| (options, rewound))
    }
}

/// Applies `change` to `turns`, an agent's session, for its next turn on:
/// its permission mode, or its model, of its agent's provider. Anything
/// else is the agent's own. Answers with the session's options, which its
/// clients are told.
fn agent_change(
    session: &LoadedSession,
    turns: &mut AcpTurns,
    change: Change,
) -> Result<wire::SessionOptions, RpcError> {
    // What the capability table refuses was refused before the change
    // queued (see `Sessions::apply_change`); these arms back it up.
    let needs = change.capability(session.runtime);
    let changed = match change {
        Change::PermissionMode(mode) => turns.set_permission_mode(mode),
        Change::Model { model, .. } if needs == wire::SessionCapability::SwitchModel => {
            turns.set_model(model.model)
        }
        Change::Model { .. }
        | Change::Reasoning(_)
        | Change::FastMode { .. }
        | Change::StartedSessionPermissionMode(_)
        | Change::StartedSessionRuntime { .. }
        | Change::Context { .. }
        | Change::AgentCatalog
        | Change::AddDirectory(_)
        | Change::ModelCatalog
        | Change::SelectNode(_)
        | Change::RewindWorkspace { .. } => {
            return Err(capabilities::rho_only(session.runtime, needs))
        }
    };
    changed.map_err(|error| {
        RpcError::new(
            ErrorCode::InvalidParams,
            format!("could not change the session: {error:#}"),
        )
    })?;
    session.feed.update_options(turns.options());
    Ok(session.feed.options())
}

/// What applying a change left to do.
enum Applied {
    /// A setting changed, which the session now keeps, with a notice to
    /// tell the session's clients now.
    Setting { notice: Option<String> },
    /// Rows may have been saved, which the transcript takes, with a notice
    /// to tell the session's clients now.
    Rows { notice: Option<String> },
    /// The conversation moved to another node of the session's tree.
    Restarted,
    /// A rewind put back files, and `moved` the conversation or saved rows,
    /// as `response` says, with a notice telling the session's clients
    /// what became of each file.
    Rewound {
        moved: bool,
        notice: String,
        response: Box<wire::SessionRewindResponse>,
    },
    /// What every loaded session's options show was read again.
    SharedOptions,
    /// What the sessions this one starts open with changed, and the
    /// runtime saved it, apart from the session's own settings, which keep
    /// following the config or stay kept as they were.
    StartedSessionDefaults,
    /// Nothing: a plan approved after the change was sent set the
    /// permission mode it asked for, or the `/compact` a model change
    /// waited on did not reduce the conversation.
    Superseded,
}

impl Change {
    /// What a session `engine` runs must be able to do to take the change:
    /// a model of another runtime is a switch of runtime.
    fn capability(&self, engine: AgentRuntime) -> wire::SessionCapability {
        use wire::SessionCapability as Needs;
        match self {
            Self::Model { model, .. } if runtimes::model_runtime(model) != engine => {
                Needs::SwitchRuntime
            }
            Self::Model { .. } => Needs::SwitchModel,
            Self::Reasoning(_) | Self::FastMode { .. } | Self::ModelCatalog => Needs::ModelSettings,
            Self::PermissionMode(_) => Needs::PermissionMode,
            Self::StartedSessionPermissionMode(_)
            | Self::StartedSessionRuntime { .. }
            | Self::AgentCatalog => Needs::Delegation,
            Self::Context { .. } => Needs::AddContext,
            Self::AddDirectory(_) => Needs::AddDirectory,
            Self::SelectNode(_) => Needs::Fork,
            Self::RewindWorkspace { .. } => Needs::Rewind,
        }
    }

    fn parse(change: wire::SessionChange) -> Result<Self, RpcError> {
        match change {
            wire::SessionChange::Model { model, auth, setup } => {
                Ok(Self::Model { model, auth, setup })
            }
            wire::SessionChange::ModelAfterCompaction { model, auth } => Ok(Self::Model {
                model,
                auth,
                setup: false,
            }),
            wire::SessionChange::Reasoning { level } => reasoning_from_wire(level)
                .map(Self::Reasoning)
                .ok_or_else(|| invalid("unknown reasoning level")),
            wire::SessionChange::FastMode { enabled } => Ok(Self::FastMode { enabled }),
            wire::SessionChange::PermissionMode { mode } => PermissionMode::try_from(mode)
                .map(Self::PermissionMode)
                .map_err(|_| invalid("unknown permission mode")),
            wire::SessionChange::StartedSessionPermissionMode { mode } => mode
                .map(PermissionMode::try_from)
                .transpose()
                .map(Self::StartedSessionPermissionMode)
                .map_err(|_| invalid("unknown permission mode")),
            wire::SessionChange::StartedSessionModel { model } => Ok(Self::StartedSessionRuntime {
                runtime: AgentRuntime::Rho,
                model,
            }),
            wire::SessionChange::StartedSessionRuntime { runtime, model } => {
                AgentRuntime::try_from(runtime)
                    .map(|runtime| Self::StartedSessionRuntime { runtime, model })
                    .map_err(|_| invalid("unknown runtime"))
            }
            wire::SessionChange::Context { text, .. } if text.trim().is_empty() => {
                Err(invalid("context to add must not be empty"))
            }
            wire::SessionChange::Context { text, display } => Ok(Self::Context { text, display }),
            wire::SessionChange::AgentCatalog => Ok(Self::AgentCatalog),
            wire::SessionChange::AddDirectory { path } if !path.is_absolute() => {
                Err(invalid("the directory to add must be an absolute path"))
            }
            wire::SessionChange::AddDirectory { path } => Ok(Self::AddDirectory(path)),
            wire::SessionChange::ModelCatalog => Ok(Self::ModelCatalog),
            wire::SessionChange::SelectNode { node } => NodeId::from_string(node)
                .map(Self::SelectNode)
                .map_err(|error| invalid(format!("{error:#}"))),
            wire::SessionChange::RewindWorkspace { checkpoint } => NodeId::from_string(checkpoint)
                .map(|checkpoint| Self::RewindWorkspace {
                    checkpoint,
                    tip: None,
                })
                .map_err(|error| invalid(format!("{error:#}"))),
            // A change of a later protocol minor fails to decode before it
            // gets here; the arm keeps the match open to new variants.
            _ => Err(invalid("unknown change")),
        }
    }

    async fn apply(
        self,
        runtime: &mut SessionRuntime,
        config: &Config,
        auths: &[String],
    ) -> Result<Applied, RpcError> {
        let applied = match self {
            Self::Context { text, display } => {
                return runtime
                    .append_context(
                        text,
                        Message::user_text(display),
                        /*display_key*/ None,
                        [],
                    )
                    .map(|_| Applied::Rows { notice: None })
                    .map_err(|error| {
                        RpcError::new(
                            ErrorCode::InternalError,
                            format!("could not save the context: {error:#}"),
                        )
                    });
            }
            Self::AgentCatalog => {
                return runtime
                    .sync_agent_catalog()
                    .map(|notice| Applied::Rows {
                        notice: notice.map(str::to_owned),
                    })
                    .map_err(|error| {
                        RpcError::new(
                            ErrorCode::InternalError,
                            format!("could not read the agent definitions: {error:#}"),
                        )
                    })
            }
            Self::AddDirectory(path) => {
                // Canonical, as the session compares the roots it has.
                let dir = crate::added_dirs::resolve(&path, runtime.cwd(), /*home*/ None)
                    .map_err(|error| invalid(format!("{error:#}")))?;
                let notice = format!("added directory {}", crate::paths::display(&dir));
                return match runtime.add_dir(dir, config).await {
                    Ok(()) => Ok(Applied::Rows {
                        notice: Some(notice),
                    }),
                    Err(error @ AddDirError::Covered { .. }) => Err(invalid(error.to_string())),
                    Err(AddDirError::Change(error)) => Err(setting_error(error)),
                };
            }
            Self::ModelCatalog => {
                // Names this process resolved, or failed to, before the
                // client rewrote the catalogs.
                rho_providers::model::forget_model_display_names();
                return Ok(Applied::SharedOptions);
            }
            Self::SelectNode(node) => {
                return match runtime.select_node(&node, config).await {
                    Ok(()) => Ok(Applied::Restarted),
                    Err(SelectNodeError::Change(error)) => Err(setting_error(error)),
                    Err(error @ (SelectNodeError::Unsaved | SelectNodeError::UnknownNode(_))) => {
                        Err(invalid(error.to_string()))
                    }
                };
            }
            Self::RewindWorkspace { checkpoint, tip } => {
                let rewind = runtime
                    .rewind_workspace(&checkpoint, tip.as_ref(), config)
                    .await
                    .map_err(|error| super::tree::rewind_error(error, "rewind the workspace"))?;
                let audit = |restored| rewind_audit_text(&rewind.audit, runtime.cwd(), restored);
                let moved = matches!(rewind.conversation, RewoundConversation::Moved { .. });
                let notice = match &rewind.conversation {
                    RewoundConversation::Moved { .. } => audit(true),
                    RewoundConversation::Stayed => audit(false),
                    // The files changed all the same, which every client
                    // must learn, then why the conversation stayed.
                    RewoundConversation::MoveFailed(error) => format!(
                        "{}\ncould not restore the conversation: {error}",
                        audit(false)
                    ),
                };
                return Ok(Applied::Rewound {
                    moved,
                    notice,
                    response: Box::new(super::tree::rewind_to_wire(rewind)),
                });
            }
            Self::Model { model, auth, setup } => {
                let selection = model_selection(runtime, &model, auth.as_deref(), auths)?;
                let previous = runtime.current_model();
                return runtime
                    .switch_model(&selection, config)
                    .await
                    .map(|()| {
                        let current = runtime.current_model();
                        // The prompt follows the model alone: a change that
                        // kept the model has no other prompt file to report.
                        let moved = !setup
                            && (current.provider, current.model)
                                != (previous.provider, previous.model);
                        Applied::Setting {
                            notice: moved.then(|| runtime.model_prompt_notice()).flatten(),
                        }
                    })
                    .map_err(setting_error);
            }
            Self::Reasoning(level) => runtime.set_reasoning_level(level, config),
            Self::FastMode { enabled } => runtime.set_fast_mode(enabled),
            Self::PermissionMode(mode) => runtime.reapply_permission_mode(mode, config).await,
            Self::StartedSessionPermissionMode(mode) => {
                return runtime
                    .set_started_session_permission_mode(mode, config)
                    .map(|()| Applied::StartedSessionDefaults)
                    .map_err(setting_error);
            }
            Self::StartedSessionRuntime { runtime: on, model } => {
                // Refused now rather than in each session it starts: on
                // rho's loop a model this session could not switch to, on
                // another runtime one its list does not carry.
                let model = match (on, model) {
                    (_, None) => None,
                    (AgentRuntime::Rho, Some(model)) => {
                        let selection =
                            model_selection(runtime, &model, /*auth*/ None, auths)?;
                        Some(StartedModel {
                            provider: selection.provider,
                            model: selection.model,
                        })
                    }
                    (on @ (AgentRuntime::ClaudeCli | AgentRuntime::Antigravity), Some(model)) => {
                        runtimes::check_listed_model(on, &model).map_err(invalid)?;
                        Some(model.into())
                    }
                };
                return runtime
                    .set_started_session_runtime(on, model)
                    .map(|()| Applied::StartedSessionDefaults)
                    .map_err(setting_error);
            }
        };
        applied
            .map(|()| Applied::Setting { notice: None })
            .map_err(setting_error)
    }
}

/// Applies to `turns`, a new session on `engine`, another runtime than
/// rho's, that `choosing`'s choice applies to, what `chosen` holds, as a
/// person's changes would: its model, when chosen for `engine` (a model of
/// another runtime is not the agent's), then its permission mode, and the
/// choice itself, which the session keeps, so the sessions its agent starts
/// open with it too. A part the agent's runtime refuses, as Supervised in a
/// session nobody attends, or one this rho cannot read, fails the open
/// rather than run looser or on another model. The agent checks the model
/// as its first turn starts.
pub(super) fn set_up_started_agent_session(
    turns: &mut AcpTurns,
    engine: AgentRuntime,
    choosing: &rho_sdk::SessionId,
    chosen: wire::StartedSessionDefaults,
) -> Result<(), RpcError> {
    let refused = |part: &str, message: String| {
        RpcError::new(
            ErrorCode::SessionOpenFailed,
            format!(
                "could not open the session {part} chosen for the sessions {choosing} starts: {message}"
            ),
        )
    };
    let (mode, chosen_runtime) =
        decode_choice(&chosen).map_err(|part| refused(part, UNREADABLE_CHOICE.to_owned()))?;
    if let Some(model) = chosen.model.as_ref().filter(|_| chosen_runtime == engine) {
        let part = format!("on the model {}/{}", model.provider, model.model);
        turns
            .set_model(model.model.clone())
            .map_err(|error| refused(&part, format!("{error:#}")))?;
    }
    if let Some(mode) = mode {
        turns
            .set_permission_mode(mode)
            .map_err(|error| refused("in the permission mode", format!("{error:#}")))?;
    }
    turns
        .keep_started_sessions(StartedSessionDefaults {
            permission_mode: mode.map(StartedMode::Known),
            runtime: chosen_runtime,
            model: chosen.model.map(Into::into),
        })
        .map_err(|error| refused("with the copy of the choice", format!("{error:#}")))
}

/// Why a choice [`decode_choice`] refuses does not open the session.
const UNREADABLE_CHOICE: &str =
    "this rho could not read the saved choice, as when a newer rho saved it";

/// The permission mode and runtime of `chosen`, a choice for the sessions
/// a session starts; for one this rho cannot read, the part of the session
/// it would open, for the refusal to name.
fn decode_choice(
    chosen: &wire::StartedSessionDefaults,
) -> Result<(Option<PermissionMode>, AgentRuntime), &'static str /*part*/> {
    let mode = chosen
        .permission_mode
        .map(PermissionMode::try_from)
        .transpose()
        .map_err(|_| "in the permission mode")?;
    let runtime = chosen
        .runtime
        .map(AgentRuntime::try_from)
        .transpose()
        .map_err(|_| "on the runtime")?
        .unwrap_or_default();
    Ok((mode, runtime))
}

/// Who chose a change a new session opens with, which its refusal names.
#[derive(Clone, Copy)]
enum ChosenBy {
    /// The session that starts it, for the sessions it starts.
    Starter,
    /// Its client, in [`wire::SessionSetup::model`].
    Client,
}

/// Sets up `runtime`, a session opening for `rho/session/new`, before its
/// first turn, through the changes a person's client would send. `started`
/// is the session whose choice applies to it (see `new.rs`), with that
/// choice: its model, as a setup [`Change::Model`], unless its agent names
/// its own, then its permission mode, and the choice itself, which the
/// session keeps, so the sessions it starts in turn open with it too. A
/// model its agent replaces, or a choice of another runtime, which its
/// `new` replaced with rho's loop, is kept for those sessions without
/// resolving it here. `asked` is the model its client named in
/// [`wire::SessionSetup::model`], which replaces a chosen one. When a part
/// changed its own settings, it keeps them, so a reopen restores them. A
/// part it cannot take fails the open, naming it, rather than leave the
/// session on the config's: the mode a person chose may be stricter. With
/// nothing chosen or asked, it changes and keeps nothing, as any new
/// session.
pub(super) async fn set_up_new_session(
    runtime: &mut SessionRuntime,
    config: &Config,
    started: Option<(&rho_sdk::SessionId, wire::StartedSessionDefaults)>,
    asked: Option<&wire::SetupModel>,
) -> Result<(), RpcError> {
    let (choosing, chosen) = match started {
        Some((choosing, chosen)) => (Some(choosing), chosen),
        None => (None, wire::StartedSessionDefaults::default()),
    };
    if chosen == wire::StartedSessionDefaults::default() && asked.is_none() {
        return Ok(());
    }
    // A part the starting session chose fails the open naming that choice;
    // the model the client asked for keeps its refusal's code.
    let refused = |part: &str, by: ChosenBy, error: RpcError| match (by, choosing) {
        (ChosenBy::Starter, Some(choosing)) => RpcError::new(
            ErrorCode::SessionOpenFailed,
            format!(
                "could not open the session {part} chosen for the sessions {choosing} starts: {}",
                error.message
            ),
        ),
        (ChosenBy::Client, _) | (ChosenBy::Starter, None) => RpcError {
            message: format!("could not open the session {part}: {}", error.message),
            ..error
        },
    };
    let (mode, chosen_runtime) = decode_choice(&chosen).map_err(|part| {
        refused(
            part,
            ChosenBy::Starter,
            RpcError::new(ErrorCode::SessionOpenFailed, UNREADABLE_CHOICE),
        )
    })?;
    let model = chosen.model;
    let mut changes = Vec::new();
    // Kept as the choosing session checked it, for the sessions this one
    // starts, but not applied here: a choice of another runtime, as this
    // session runs on rho's loop because its `new` named its own runtime,
    // agent or model (see `new.rs`), or a model its agent replaces with its
    // own, which therefore must not fail it when it no longer resolves.
    let kept = match (chosen_runtime, &model) {
        (on @ (AgentRuntime::ClaudeCli | AgentRuntime::Antigravity), _) => {
            Some(format!("on {}", on.display_name()))
        }
        (AgentRuntime::Rho, Some(model)) if runtime.agent_pins_model() => {
            Some(format!("on the model {}/{}", model.provider, model.model))
        }
        (AgentRuntime::Rho, _) => None,
    };
    if let Some(part) = kept {
        runtime
            .set_started_session_runtime(chosen_runtime, model.map(Into::into))
            .map_err(|error| refused(&part, ChosenBy::Starter, setting_error(error)))?;
    } else if let Some(model) = model {
        let part = format!("on the model {}/{}", model.provider, model.model);
        // The client's own pick replaces the starting session's.
        if asked.is_none() {
            let switch = Change::Model {
                model: model.clone(),
                auth: None,
                setup: true,
            };
            changes.push((part.clone(), ChosenBy::Starter, switch));
        }
        changes.push((
            part,
            ChosenBy::Starter,
            Change::StartedSessionRuntime {
                runtime: AgentRuntime::Rho,
                model: Some(model),
            },
        ));
    }
    if let Some(mode) = mode {
        let part = format!("in the permission mode {}", mode.as_str());
        changes.push((
            part.clone(),
            ChosenBy::Starter,
            Change::PermissionMode(mode),
        ));
        changes.push((
            part,
            ChosenBy::Starter,
            Change::StartedSessionPermissionMode(Some(mode)),
        ));
    }
    if let Some(asked) = asked {
        // As the client would switch it, so an agent that names its own
        // model runs this one too.
        let switch = Change::Model {
            model: asked.model.clone(),
            auth: asked.auth.clone(),
            setup: true,
        };
        let part = format!(
            "on the model {}/{}",
            asked.model.provider, asked.model.model
        );
        changes.insert(0, (part, ChosenBy::Client, switch));
    }
    if changes.is_empty() {
        // Only what it keeps without applying was chosen: none of the
        // session's own settings changed, so it goes on following the
        // config.
        return Ok(());
    }
    let auths = available_auths(runtime.credentials()).await;
    for (part, by, change) in changes {
        change
            .apply(runtime, config, &auths)
            .await
            .map_err(|error| refused(&part, by, error))?;
    }
    runtime.keep_settings().map_err(|error| {
        RpcError::new(
            ErrorCode::InternalError,
            format!("could not save the session's settings: {error:#}"),
        )
    })
}

/// The selection `model` names for `runtime`'s session, on `auth` when the
/// change names one, else with an auth in `auths`.
fn model_selection(
    runtime: &SessionRuntime,
    model: &wire::ModelRef,
    auth: Option<&str>,
    auths: &[String],
) -> Result<ModelSelection, RpcError> {
    let auth = auth.map_or(AuthPick::AnyOf(auths), AuthPick::Named);
    resolve_model(
        &model.provider,
        &model.model,
        Some(&runtime.current_model()),
        auth,
    )
    .map_err(|refused| invalid(refused.to_string()))
}

/// The error a refused change answers; the session keeps its old setting.
fn setting_error(error: SettingChangeError) -> RpcError {
    match error {
        SettingChangeError::Unsupported(message) => invalid(message),
        // No turn runs while the change holds the runtime.
        SettingChangeError::Busy => RpcError::new(
            ErrorCode::InternalError,
            "could not change the session's settings: a turn ran while the change held the session's runtime, a daemon bug",
        ),
        SettingChangeError::Apply(error) => RpcError::new(
            ErrorCode::InternalError,
            format!("could not change the session's settings: {error:#}"),
        ),
    }
}

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

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