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
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
//! Opening a session: a new one, or one saved earlier, which the daemon
//! reopens as the agent it was saved as (#1661). The config is the user's
//! global config as it is when the session is opened, so a config edit
//! applies to the next session opened without a daemon restart; a session
//! already open keeps its config until it reopens. A new session fails to
//! open on a config that does not load, rather than run on the last good
//! values; a reopened one, which a person may be in the middle of, runs on
//! them. The
//! agents and instructions are those of the session's workspace, as `rho`
//! launched there would find them.
//!
//! A new session runs as the agent its client names, else the default
//! agent, with the configured model, reasoning, fast mode, and permission
//! mode; one opened under a `parent` then takes the permission mode and
//! model a person chose for the sessions its choosing session starts (see
//! `new.rs`). A reopened one runs as the agent it was saved as, which must still
//! be defined as it was, and with the settings a client last chose for it
//! (`rho/session/configure`), else the configured ones. Either way it takes
//! the setup of the request that opens it, on top of the directories and
//! parts left out its file keeps (see `setup.rs`). Its host answers
//! approvals and questions (both reach the daemon as turn events), its
//! children run in the daemon on the daemon-wide budget, each a child job
//! of the session's (see `subagents.rs`), unless its setup has the client's
//! host run them as its own threads, and an MCP server's browser login
//! is refused rather than left waiting for a terminal nobody watches.
//! A session whose model has no usable credentials opens only when its
//! setup's `sign_in` is `later`, signed out as the TUI starts; otherwise
//! the open fails with `SignInRequired`.
//!
//! A fork (`rho/session/fork`) opens new, from the saved session it forks:
//! as the agent that session was saved as, with the parts it leaves out and
//! the directories it adds, its conversation as last saved, and its
//! settings, then in supervised mode (see `fork.rs`).
//!
//! The session's processes, MCP servers, hooks, OpenAPI sources, CLI agents,
//! and workflow runs use its client's environment, not the daemon's (#1659):
//! the opening client's, then each prompting client's (see
//! [`session_environment`]). Its project trust (`RHO_TRUST_PROJECT_*`) is
//! the opening client's for as long as the daemon has it loaded (#1779).

use std::{
    path::{Path, PathBuf},
    sync::Arc,
};

use rho_protocol::{ClientEnvironment, ErrorCode, RpcError, SessionSetup};

use super::{
    super::{jobs::JobId, settings::ConfigStore, subagents::Subagents},
    acp_background, acp_tools,
    acp_turns::{self, Opener},
    budget::ModelSlot,
    engine::Engine,
    pull_request_wake::PullRequestWake,
    setup::{Base, Setup},
    Owner,
};
use crate::{
    agent::{
        session_agent_runtime, AgentCapabilities, AgentCatalog, AgentDefinition, AgentRuntime,
        DEFAULT_AGENT_ID,
    },
    app::{
        agent_binding::{
            root_host_tools, AgentBinder, AgentInvocation, AgentRole, BoundAgent, LaunchTools,
        },
        cli_config::{settle_bound_config, ProviderRefreshStatus, SettledConfig},
        peer_sessions::PeerInbox,
        prompt_content::PromptContext,
        session_assembly::SignIn,
        session_runtime::{
            ApprovalPolicy, BackgroundWait, CacheWarming, ChildAgents, CredentialFailure,
            HostCapabilities, IdleTurns, RunShape, SessionBuild, SessionLaunch, SessionOpening,
            SessionRole, SessionRuntime, SessionUse,
        },
        subagent_pool::SubagentPool,
        tools_prompt::ToolSourceLoad,
    },
    browser::Browsers,
    browser::SessionBrowser,
    caller_context::CallerContext,
    config::Config,
    session::{Session as StoredSession, SessionPersistence},
    session_environment::{Ambient, SessionEnvironment},
    session_temp_dir::{self, SessionTempDir},
    tools::mcp::McpAuthorizationMode,
    workspace::{ProjectTrust, ProjectTrusts},
};

/// The directory a session works in: an existing directory, canonicalized
/// to the form its commands take as a working directory and other `rho`
/// processes name it by. Parsed once from the request's `cwd`.
pub(in crate::app::daemon_host) struct Workspace(PathBuf);

impl Workspace {
    /// The workspace `cwd`, the request's `param`, names. A relative path, a
    /// path that does not resolve, and one that is not a directory are
    /// invalid params, named by `param` in the error.
    pub(in crate::app::daemon_host) fn parse(param: &str, cwd: &Path) -> Result<Self, RpcError> {
        let invalid = |reason: String| {
            RpcError::new(
                ErrorCode::InvalidParams,
                format!("invalid {param} {}: {reason}", cwd.display()),
            )
        };
        if !cwd.is_absolute() {
            return Err(invalid("not an absolute path".to_owned()));
        }
        let path = crate::paths::canonicalize(cwd).map_err(|error| invalid(error.to_string()))?;
        if !path.is_dir() {
            return Err(invalid("not a directory".to_owned()));
        }
        Ok(Self(path))
    }

    pub(in crate::app::daemon_host) fn path(&self) -> &Path {
        &self.0
    }
}

/// What a session opens from.
pub(super) enum Opening {
    /// Nothing yet: a new session in `workspace`, running as agent `agent`,
    /// the default agent when `None`, which session `started_by` started
    /// through session control, if one did, on `model` in place of the
    /// conversation model when one names it.
    New {
        workspace: Workspace,
        agent: Option<String>,
        started_by: Option<rho_sdk::SessionId>,
        model: Option<OpensOn>,
    },
    /// The session saved here, opened in its own workspace as the agent it
    /// was saved as.
    Saved(StoredSession),
    /// A new fork of the session saved here, in that session's workspace
    /// as the agent it was saved as (see `fork.rs`).
    Fork(StoredSession),
}

impl Opening {
    pub(super) fn cwd(&self) -> &Path {
        match self {
            Self::New {
                workspace: Workspace(cwd),
                ..
            } => cwd,
            Self::Saved(stored) | Self::Fork(stored) => stored.cwd(),
        }
    }
}

/// A model a new session opens on in place of the conversation model, so
/// it opens even while that is unset. `new.rs` switches the session to it
/// once it opens, as a client would, which an agent that names its own
/// model takes too.
pub(super) enum OpensOn {
    /// Its client's [`SessionSetup::model`]; one the session cannot run
    /// fails the open with `InvalidParams`.
    Asked(rho_protocol::SetupModel),
    /// The one the session that starts it chose for the sessions it starts.
    /// One that no longer resolves is left to the switch that follows,
    /// which reports it, unless the session's agent names its own model.
    Chosen(rho_protocol::ModelRef),
}

/// Puts on `config` the model the session `opening` opens on in place of
/// the conversation model: a new session's [`OpensOn`], or, while the
/// conversation model is unset, the model a saved session or the session a
/// fork starts from keeps as its own, which it then restores. Only binding
/// reads it, so its agent's checks and sign-in see the model it runs on.
async fn open_on_own_model(
    opening: &Opening,
    config: &mut Config,
    environment: &SessionEnvironment,
) -> anyhow::Result<()> {
    use crate::{
        app::session_options::{available_auths, resolve_model, AuthPick},
        config::AuthOrigin,
    };
    // Resolved as a switch from the conversation model, or from none.
    let current = config
        .conversation_model
        .as_ref()
        .map(crate::app::session_runtime::CurrentModel::from);
    let (model, auth, refusable) = match opening {
        Opening::New { model: None, .. } => return Ok(()),
        Opening::New {
            model: Some(OpensOn::Asked(asked)),
            ..
        } => (&asked.model, asked.auth.as_deref(), true),
        Opening::New {
            model: Some(OpensOn::Chosen(chosen)),
            ..
        } => (chosen, None, false),
        Opening::Saved(stored) | Opening::Fork(stored) => {
            if config.conversation_model.is_some() {
                return Ok(());
            }
            if let Some(saved) = crate::app::session_runtime::saved_model(stored) {
                config.set_conversation_model(
                    saved.provider,
                    saved.model,
                    saved.auth,
                    AuthOrigin::Configured,
                );
            }
            return Ok(());
        }
    };
    // The empty reference the wire advertises while no model is set up
    // picks none, so binding reports that no model is set up.
    if current.is_none() && auth.is_none() && model.provider.is_empty() && model.model.is_empty() {
        return Ok(());
    }
    let auths = available_auths(environment.credentials()).await;
    let pick = auth.map_or(AuthPick::AnyOf(&auths), AuthPick::Named);
    match resolve_model(&model.provider, &model.model, current.as_ref(), pick) {
        Ok(selection) => {
            let origin = match auth {
                Some(_) => AuthOrigin::Configured,
                None => AuthOrigin::Inferred,
            };
            config.set_conversation_model(
                selection.provider,
                selection.model,
                selection.auth,
                origin,
            );
            Ok(())
        }
        Err(refused) if refusable => Err(refused.into()),
        Err(_) => Ok(()),
    }
}

/// What a request brings for the session it names, which applies only when
/// that request opens the session: a new session, or a saved one it
/// reopens. A session the daemon has loaded keeps what it opened with, so a
/// request for it leaves this unused.
pub(super) struct OpenWith {
    /// The environment the session's children start in.
    pub(super) environment: Ambient,
    /// The client's choices for the session.
    pub(super) setup: SessionSetup,
    /// What a turn the request starts may do through session control, which
    /// `environment` carries too (see `grant.rs`).
    pub(super) grant: CallerContext,
}

/// A session, open, and the config it runs with.
pub(super) struct OpenedSession {
    /// What runs its turns.
    pub(super) engine: Engine,
    /// The config the session was built with, which every prompt reads.
    pub(super) config: Config,
    /// The global config it was built from, before its agent's own.
    pub(super) global: Arc<Config>,
    /// The environment the session's children see, which each prompt
    /// replaces with its client's.
    pub(super) environment: SessionEnvironment,
    /// The setup the opening request brought, but its system prompt, which
    /// the session's file keeps: what the session reopens with when pull
    /// request news wakes it unloaded (see `pull_request_wake.rs`).
    pub(super) setup: SessionSetup,
    /// The session whose delete takes it: the one it forks, for a fork, new
    /// or reopened, or the one that started it, for a subagent's.
    pub(super) owner: Option<Owner>,
    /// Prompt context its next model turn sends (see `held_context.rs`):
    /// none from here; a new fork's opener sets its word to the model
    /// before adding it.
    pub(super) held_context: PromptContext,
    /// The session's way to the daemon's browser, shared with its browser
    /// tools, when the daemon has a browser (see `browser.rs`).
    pub(super) browser: Option<SessionBrowser>,
    /// The agent budget's say over the model requests of its turns, which
    /// every runtime it builds waits on (see `budget.rs`).
    pub(super) model_slot: Arc<ModelSlot>,
}

/// What a session is opened for.
enum Purpose<'a> {
    /// Running turns, signed in as `sign_in` says, with the opening
    /// request's `setup` and the daemon's `services`.
    Run {
        sign_in: SignIn,
        /// Boxed: a setup is several times the size of the rest.
        setup: Box<SessionSetup>,
        services: RunServices<'a>,
        /// Who opens it, which an agent of another runtime that runs the
        /// session asks what its policy leaves to a person.
        opener: Opener,
    },
    /// Only reading what it saved.
    Read,
}

/// The daemon's services that a session it runs serves its tools from.
#[derive(Clone, Copy)]
pub(super) struct RunServices<'a> {
    pub(super) pull_requests: &'a PullRequestWake,
    /// `None` in a build without the browser.
    pub(super) browsers: Option<&'a Arc<Browsers>>,
}

/// The environment a client's `environment` gives a session's children:
/// exactly the client's variables; its [`SessionEnvironment`] keeps provider
/// credentials from its tools' processes. A variable no process
/// could be given is invalid params, naming it, so it fails the request
/// rather than every later command (#1659).
pub(in crate::app::daemon_host) fn session_environment(
    environment: &ClientEnvironment,
) -> Result<Ambient, RpcError> {
    let variables = environment
        .iter()
        .map(|(name, value)| {
            if name.is_empty() || name.contains(['=', '\0']) || value.contains('\0') {
                return Err(RpcError::new(
                    ErrorCode::InvalidParams,
                    format!(
                        "invalid environment variable {name:?}: a name must be nonempty without `=` or NUL, and a value without NUL"
                    ),
                ));
            }
            Ok((name.to_owned(), value.to_owned()))
        })
        .collect::<Result<_, _>>()?;
    Ok(Ambient::Client(Arc::new(variables)))
}

/// The global config a new session opens with: `config.toml` as it is
/// now. One that does not load is `SessionOpenFailed`, naming each problem,
/// rather than the last good values. Read before anything the open cannot
/// undo, such as adding the session's worktree.
pub(super) async fn config_for_new(settings: &ConfigStore) -> Result<Arc<Config>, RpcError> {
    settings
        .config_to_open()
        .await
        .map_err(|error| open_failed(error.into()))
}

/// The global config a saved session reopens with, to run or only to read:
/// the last that loaded, as its turns read while it stays loaded, so a hand
/// edit that broke `config.toml` does not break a conversation the daemon
/// unloaded while it sat idle. Fails only if none ever loaded.
pub(super) async fn config_for_saved(settings: &ConfigStore) -> Result<Arc<Config>, RpcError> {
    settings
        .agent_config()
        .await
        .map_err(|error| open_failed(error.into()))
}

/// Opens the session `opening` says, whose turns are job `job`, with what
/// `with` brings and `global`, read from `settings` by [`config_for_new`]
/// or [`config_for_saved`].
/// A new session's file is written with its first prompt. A setup the
/// session cannot take is invalid params (see `setup.rs`); any other
/// failure is `SessionOpenFailed`.
pub(super) async fn open_session(
    opening: Opening,
    with: &OpenWith,
    subagents: &Subagents,
    services: RunServices<'_>,
    settings: &ConfigStore,
    global: Arc<Config>,
    job: &JobId,
) -> Result<OpenedSession, RpcError> {
    let base = match &opening {
        Opening::New { .. } => Base::New,
        Opening::Saved(stored) => Base::Reopened(stored),
        Opening::Fork(parent) => Base::Forked(parent),
    };
    let setup = Setup::resolve(&with.setup, opening.cwd(), base)?;
    let opener = match with.grant.is_root() {
        true => Opener::Person,
        false => Opener::SessionControl,
    };
    let sign_in = match with.setup.sign_in {
        rho_protocol::SignIn::Required => SignIn::Required,
        rho_protocol::SignIn::Later => SignIn::Optional,
    };
    open_runtime(
        opening,
        SessionEnvironment::new(with.environment.clone()),
        setup,
        Purpose::Run {
            sign_in,
            setup: Box::new(with.setup.clone()),
            services,
            opener,
        },
        subagents.pool_for(job.clone()),
        settings,
        global,
    )
    .await
    .map_err(open_failed)
}

/// The error for a session the daemon could not open: `ModelRequired` when
/// it needed the conversation model and nobody has chosen one,
/// `InvalidParams` for a [`SessionSetup::model`] it cannot run,
/// `SignInRequired` when signing in can fix it, in Rho's words with the
/// full cause only in the daemon's log, else `SessionOpenFailed`.
pub(super) fn open_failed(error: anyhow::Error) -> RpcError {
    if let Some(required) = error.downcast_ref::<crate::config::ModelRequired>() {
        return RpcError::new(
            ErrorCode::ModelRequired,
            format!("could not open session: {required}"),
        );
    }
    if let Some(refused) = error.downcast_ref::<crate::app::session_options::ModelRefused>() {
        return RpcError::new(
            ErrorCode::InvalidParams,
            format!("could not open session: {refused}"),
        );
    }
    if let Some(refused) = error.downcast_ref::<NotForSessions>() {
        let data =
            rho_protocol::AgentNotForSessions::new(refused.agent.clone(), refused.runtime.into());
        return RpcError::new(
            ErrorCode::AgentNotForSessions,
            format!("could not open session: {refused}"),
        )
        .with_data(serde_json::to_value(data).expect("an agent refusal serializes"));
    }
    match CredentialFailure::find(&error) {
        Some(failure) => {
            tracing::warn!(error = format!("{error:#}"), "session needs a sign-in");
            RpcError::new(
                ErrorCode::SignInRequired,
                format!("could not open session: {}", failure.message()),
            )
        }
        None => RpcError::new(
            ErrorCode::SessionOpenFailed,
            format!("could not open session: {error:#}"),
        ),
    }
}

/// The project trust `stored` is read under, which no client is there to
/// grant: none when the agents it was saved as are found without, so a
/// project file never stands in for an agent saved without trust; else the
/// project's agents and plugins, which a session saved as one of them
/// needs. A read only parses them: it starts no hooks, tool sources, or
/// turns.
fn reading_trust(stored: &StoredSession) -> anyhow::Result<ProjectTrusts> {
    let catalog = AgentCatalog::discover(stored.cwd(), ProjectTrusts::UNTRUSTED)?;
    let found = |id: &str, accepts: &dyn Fn(&AgentDefinition) -> bool| {
        catalog
            .find(id)
            .is_ok_and(|entry| accepts(&entry.definition))
    };
    let root = stored.root_agent()?;
    let delegated = stored.delegated_agent_id()?;
    let found_untrusted = root
        .as_ref()
        .is_none_or(|root| found(&root.id, &|definition| root.validate(definition).is_ok()))
        && delegated.as_deref().is_none_or(|id| {
            found(id, &|definition| {
                stored
                    .validate_agent_definition_identity(definition)
                    .is_ok()
            })
        });
    Ok(if found_untrusted {
        ProjectTrusts::UNTRUSTED
    } else {
        ProjectTrusts {
            agents: ProjectTrust::Trusted,
            plugins: ProjectTrust::Trusted,
            ..ProjectTrusts::UNTRUSTED
        }
    })
}

/// Opens `stored` only to read what it saved, its turns recorded on job
/// `job`: it starts none of its MCP servers, OpenAPI sources, or hooks, sees
/// no client's environment (see [`SessionEnvironment::for_reading`]), and
/// takes no setup but what its file keeps. Its agents are found under
/// [`reading_trust`], with [`config_for_saved`]. Fails as [`open_session`]
/// does.
pub(super) async fn open_to_read(
    stored: StoredSession,
    subagents: &Subagents,
    settings: &ConfigStore,
    job: &JobId,
) -> Result<OpenedSession, RpcError> {
    let project_trust = reading_trust(&stored).map_err(open_failed)?;
    let setup = Setup::resolve(
        &SessionSetup::default(),
        stored.cwd(),
        Base::Reopened(&stored),
    )?;
    let global = config_for_saved(settings).await?;
    open_runtime(
        Opening::Saved(stored),
        SessionEnvironment::for_reading(project_trust),
        setup,
        Purpose::Read,
        subagents.pool_for(job.clone()),
        settings,
        global,
    )
    .await
    .map_err(open_failed)
}

/// [`open_session`] and [`open_to_read`] once the setup resolved and
/// `global` was read from `settings`, for `purpose`. The session's children
/// share `subagent_pool`; its agent is found under `environment`'s project
/// trust (#1779).
async fn open_runtime(
    opening: Opening,
    environment: SessionEnvironment,
    setup: Setup,
    purpose: Purpose<'_>,
    subagent_pool: SubagentPool,
    settings: &ConfigStore,
    global: Arc<Config>,
) -> anyhow::Result<OpenedSession> {
    // A session opened to read takes no setup but what its file keeps.
    let (session_use, requested, services, opener) = match purpose {
        Purpose::Run {
            sign_in,
            setup,
            services,
            opener,
        } => (
            SessionUse::Run(sign_in),
            *setup,
            Some(services),
            Some(opener),
        ),
        Purpose::Read => (SessionUse::Read, SessionSetup::default(), None, None),
    };
    let cwd = &opening.cwd().to_path_buf();
    let config_path = settings.agent_path().to_path_buf();
    let Setup {
        left_out,
        host_prompt,
        questions,
        surfaces,
        secret_asks,
        children,
        idle_turns,
        added_dirs,
        host_mcp,
        persistence,
        adds_to_saved,
    } = setup;
    // Whether the daemon wakes the idle session for its background results,
    // whatever runs its turns: it gates what news the session takes and
    // the tools that need a wake, for Rho's loop and an agent of another
    // runtime alike.
    let background_wait = BackgroundWait::of(children, idle_turns);
    // The config each session opens with publishes its custom providers to
    // the daemon, as each rho process publishes its own at startup.
    global.providers.activate()?;
    // And its credential store: `rho credential-store set` and an edit of
    // `config.toml` choose one from outside the daemon, as the way out of
    // an OS store it cannot reach. A store that cannot be opened fails the
    // credential reads below with the same error.
    if let Err(error) = crate::credential_store::activate_from_config(&global, &config_path) {
        tracing::warn!(error = %format!("{error:#}"), "could not open the credential store");
    }
    let mut config = (*global).clone();
    open_on_own_model(&opening, &mut config, &environment).await?;
    let available_tools = root_host_tools(
        &config,
        LaunchTools::from_flags(left_out.tools, left_out.subagents),
    );
    let (opening, agent) = {
        let (config, available_tools, environment) =
            (config.clone(), available_tools.clone(), environment.clone());
        crate::credential_store::read_off_workers(move || -> anyhow::Result<_> {
            let cwd = opening.cwd();
            let agent = match &opening {
                Opening::New { agent, .. } => bind_agent(
                    cwd,
                    &config,
                    agent.as_deref().unwrap_or(DEFAULT_AGENT_ID),
                    available_tools,
                    &environment,
                )?,
                Opening::Saved(stored) | Opening::Fork(stored) => {
                    bind_saved_agent(cwd, &config, stored, available_tools, &environment)?
                }
            };
            Ok((opening, agent))
        })
        .await??
    };
    // An agent on another runtime runs the session's turns itself, with
    // none of what Rho's loop builds below.
    let agent = match agent.into_external() {
        Ok(external) => {
            // What Rho's loop alone takes, refused rather than left unused.
            let refused =
                |what: &str| anyhow::anyhow!("an agent of another runtime takes no {what}");
            let (Some(opener), Some(services)) = (opener, services) else {
                anyhow::bail!("an agent's session is read from its journal, not opened");
            };
            // Its agent keeps its own tools and instructions, which a client
            // that leaves Rho's out must not get instead.
            if left_out != crate::app::session_runtime::LeftOut::default() {
                return Err(refused("leaving out tools, subagents or the system prompt"));
            }
            if !added_dirs.as_slice().is_empty() {
                return Err(refused("added directories"));
            }
            if !host_mcp.is_empty() {
                return Err(refused("MCP servers of its client's"));
            }
            if host_prompt.is_some() {
                return Err(refused("system prompt of its client's"));
            }
            if let SessionPersistence::Ephemeral = persistence {
                return Err(refused(
                    "unsaved session: it keeps its conversation between turns",
                ));
            }
            // Rho's tools the agent is served, from what the session's
            // config leaves it, as a Rho session's are. The daemon wakes it
            // for their results as it would a Rho session opened so, which
            // gates `watch_pull_request` and peer notices as below.
            // Shared with the served tools, which count the agent's activity
            // on it and take a slot back for a turn that lent it before each
            // answer to the agent (see `budget.rs`).
            let model_slot = Arc::new(ModelSlot::default());
            let tools = acp_tools::ToolsSetup {
                config: config.clone(),
                config_path: config_path.clone(),
                environment: environment.clone(),
                subagent_pool: subagent_pool.clone(),
                services,
                available: available_tools,
                questions,
                surfaces,
                idle: acp_background::idle_delivery(background_wait),
                model_slot: Arc::clone(&model_slot),
            };
            let turns = acp_turns::open(opening, external, opener, tools)?;
            return Ok(OpenedSession {
                engine: Engine::Acp(Box::new(turns)),
                config,
                global,
                environment,
                setup: SessionSetup {
                    system_prompt: None,
                    ..requested
                },
                owner: None,
                held_context: PromptContext::default(),
                browser: None,
                // Its agent's own process calls the model, so no runtime
                // waits on it: its turns lend and take back their slot
                // around the agent's requests to the served tools instead.
                model_slot,
            });
        }
        Err(rho) => rho,
    };
    // The agent's own config, which may pin a model and reasoning, replaces
    // the loaded one.
    let config = agent.rho_config().cloned().unwrap_or(config);
    let SettledConfig {
        config,
        diagnostics,
    } = settle_bound_config(
        config,
        &agent,
        environment.credentials(),
        &ProviderRefreshStatus::NotAttempted,
        rho_providers::model::ReasoningRequestSource::PersistedOrDefault,
    )
    .await?;
    // Warming is for a model that ends its turn and sits idle on a process,
    // which only a session whose turns do not wait for one does. Decided as
    // the session opens: the setting's later changes stop or resume the
    // warming, not the offer.
    let cache_warming = match idle_turns {
        IdleTurns::Host if config.keep_cache_warm => CacheWarming::Host(Default::default()),
        IdleTurns::Host | IdleTurns::Never => CacheWarming::None,
    };
    // Bound before the tools are built, so the session's pull request inbox
    // is keyed by the id it opens with, and its processes' temp dir named
    // by it.
    let id = match &opening {
        Opening::New { .. } | Opening::Fork(_) => rho_sdk::SessionId::new(),
        Opening::Saved(stored) => rho_sdk::SessionId::from_string(stored.id())?,
    };
    if let SessionUse::Run(_) = session_use {
        match SessionTempDir::prepare(&session_temp_dir::temp_root(), &id) {
            Ok(temp_dir) => environment.use_temp_dir(temp_dir),
            Err(error) => tracing::warn!(
                session = %id,
                error = %format!("{error:#}"),
                "could not make the session's temp dir; its processes keep the client's"
            ),
        }
    }
    // Only a session whose idle turns the daemon starts links and watches
    // pull requests, since news could wake no other: one that waits as
    // `HostTurns`. A T3 Code session (`HostWakes`) has T3's own. A client
    // that takes no daemon turns (`rho run --detach`, ACP, `idle_wake:
    // never`) gets no tools, so its agent waits as a headless run does. A
    // session an agent of another runtime runs is gated by the same wait,
    // above (`acp_background::idle_delivery`). Likewise, only such a session
    // hears of the turns it starts in other sessions through session
    // control (see `peer_wake`).
    let (pull_requests, peer_sessions) = match background_wait {
        BackgroundWait::HostTurns => (
            services.map(|services| services.pull_requests.inbox(&id, cwd)),
            Some(PeerInbox::default()),
        ),
        BackgroundWait::HostWakes | BackgroundWait::HoldPrompt => (None, None),
    };
    // Every session the daemon runs may browse, whoever starts its turns:
    // the browser needs nothing to wake it.
    let browser =
        crate::browser::Browsers::session(services.and_then(|services| services.browsers), &id);
    let model_slot = Arc::new(ModelSlot::default());
    let build = SessionBuild {
        launch: SessionLaunch {
            config_path,
            left_out,
            diagnostics,
            agent,
            prompt_suffix: None,
            host_prompt,
        },
        host: HostCapabilities {
            secret_asks,
            questions,
            surfaces,
            pull_requests,
            browser: browser.clone(),
            peer_sessions,
            children,
            idle_turns,
            subagent_pool,
            environment: environment.clone(),
            mcp_authorization: McpAuthorizationMode::NonInteractive,
            approvals: ApprovalPolicy::Host,
            parent_notices: None,
            session_use,
            // Opening never waits for a slow MCP server, as the in-process
            // TUI's first frame does not. A host's threads bind its task
            // tools when the session is built, so they need its MCP first.
            tool_sources: match children {
                ChildAgents::InProcess => ToolSourceLoad::Deferred,
                ChildAgents::HostThreads => ToolSourceLoad::Inline,
            },
            cache_warming,
            model_requests: Some(Arc::clone(&model_slot) as Arc<dyn rho_sdk::ModelRequestGate>),
        },
        run: RunShape {
            role: SessionRole::Daemon,
            max_steps: None,
            hook_labels: Default::default(),
        },
    };
    let session = SessionOpening {
        build,
        process_config: &config,
        host_mcp,
        cwd,
        added_dirs,
    };
    let owner = match &opening {
        Opening::Fork(parent) => Some(Owner::Forked(rho_sdk::SessionId::from_string(parent.id())?)),
        Opening::Saved(stored) => match stored.forked_from()? {
            Some(parent) => Some(Owner::Forked(rho_sdk::SessionId::from_string(&parent.id)?)),
            None => stored
                .subagent_parent()?
                .map(|parent| rho_sdk::SessionId::from_string(&parent.id).map(Owner::Delegated))
                .transpose()?,
        },
        Opening::New { .. } => None,
    };
    // Opening a session builds a large future; keep it on the heap.
    let runtime = match opening {
        Opening::New { started_by, .. } => {
            Box::pin(SessionRuntime::open_new(
                session,
                id,
                persistence,
                started_by,
            ))
            .await?
        }
        Opening::Fork(parent) => {
            Box::pin(SessionRuntime::open_fork(session, id, &parent, persistence)).await?
        }
        Opening::Saved(stored) => {
            let mut runtime = Box::pin(SessionRuntime::open_saved(session, stored)).await?;
            debug_assert_eq!(
                runtime.session_id(),
                &id,
                "a saved session opens with its file's id"
            );
            if adds_to_saved {
                // The next turn would save it too; an unload before then
                // would lose it.
                if let Err(error) = runtime.save_state() {
                    tracing::warn!(
                        error = format!("{error:#}"),
                        "could not save the setup a reopen added; the session's next turn saves it"
                    );
                }
            }
            runtime
        }
    };
    Ok(OpenedSession {
        engine: Engine::Rho(Box::new(runtime)),
        config,
        global,
        environment,
        // Its file keeps the system prompt, which a later attach may have
        // replaced by the time a reopen reads this.
        setup: SessionSetup {
            system_prompt: None,
            ..requested
        },
        owner,
        held_context: PromptContext::default(),
        browser,
        model_slot,
    })
}

/// The root agent `stored` runs under, bound with `available_tools`: the
/// one it was saved as, refused when its definition changed or is gone, so
/// a reopen never widens a session to another agent's tools (#1661). A
/// session `/agent:` rebound binds the root it was rebound from, with the
/// same checks; the runtime then binds the child again under that root's
/// tools, with the child's own checks. A runtime's session agent is only
/// checked by id.
fn bind_saved_agent(
    cwd: &Path,
    config: &Config,
    stored: &StoredSession,
    available_tools: AgentCapabilities,
    environment: &SessionEnvironment,
) -> anyhow::Result<BoundAgent> {
    let Some(root) = stored.root_agent()? else {
        // A delegated session written before launch identities were saved:
        // nothing names its root, so it runs under the default agent, as it
        // did then.
        return bind_agent(cwd, config, DEFAULT_AGENT_ID, available_tools, environment);
    };
    let agent = bind_agent(cwd, config, &root.id, available_tools, environment)?;
    // A runtime's session agent is rho's own, under an id no file takes:
    // its prompt and tools follow rho's releases, and the agent keeps its
    // conversation itself, so its sessions reopen on the current one.
    if session_agent_runtime(&root.id).is_none() {
        root.validate(agent.definition())?;
    }
    Ok(agent)
}

/// A session asked to run as `agent`, a definition on another runtime than
/// rho's: only that runtime's built-in agent runs a session on it, which
/// `rho/session/new`'s `runtime` picks. Such an agent runs through the
/// `agent` tool.
#[derive(Debug, thiserror::Error)]
#[error(
    "agent '{agent}' runs on {}, which runs a session only as its built-in agent; open the session on that runtime instead",
    runtime.as_str()
)]
struct NotForSessions {
    agent: String,
    runtime: AgentRuntime,
}

/// Agent `id` of `cwd`'s catalog as `environment`'s project trust finds it,
/// its model chosen among those `environment`'s credentials can use, bound as a
/// daemon session's root with `available_tools`.
fn bind_agent(
    cwd: &Path,
    config: &Config,
    id: &str,
    available_tools: AgentCapabilities,
    environment: &SessionEnvironment,
) -> anyhow::Result<BoundAgent> {
    let catalog = AgentCatalog::discover(cwd, environment.project_trust())?;
    let definition = Arc::new(catalog.find(id)?.definition.clone());
    let runtime = definition.runtime.runtime();
    if runtime != AgentRuntime::Rho && session_agent_runtime(id).is_none() {
        return Err(NotForSessions {
            agent: id.to_owned(),
            runtime,
        }
        .into());
    }
    AgentBinder::bind_with_credentials(
        definition,
        AgentInvocation {
            role: AgentRole::DaemonRoot,
            available_tools,
        },
        config,
        /*model_override*/ None,
        environment.credentials().as_ref(),
    )
}

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

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