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
//! Opens the daemon session an interactive launch follows (#1667), from the
//! launch's CLI flags. A new session opens with its first prompt, so until
//! then the TUI shows the options this launch's config and agent give it.
//!
//! The daemon reads config for the session's workspace itself, so the
//! flags that override this process's settings (`--provider`, `--model`,
//! `--auth`, `--reasoning`, `--permission-mode`) are sent as changes to the
//! session once it is open, and one the daemon refuses fails the launch.
//! `--config` names a file the daemon does not read, so it is refused rather
//! than ignored. `--no-tools`, `--no-system-prompt`, `--no-subagents`, and
//! `--no-save` leave the same parts out of the daemon session.
use std::path::Path;
use crate::{added_dirs::AddedDirs, cli::Cli, config::Config, tui};
use super::{super::agent_binding::BoundAgent, StartupSession};
/// Resumes the session `startup` names in the daemon, which starts when
/// none runs, and attaches to it, or connects for a new one its first
/// prompt opens. `config` is this launch's, with the
/// CLI's overrides applied, and `bound` the agent it bound: `--agent`'s, or
/// the default.
pub(super) async fn open(
cli: &Cli,
config: &Config,
bound: &BoundAgent,
startup: &StartupSession<'_>,
cwd: &Path,
added_dirs: &AddedDirs,
) -> anyhow::Result<tui::DaemonSession> {
use rho_protocol::{
ChildThreads, IdleWake, ModelRef, SessionChange, SessionPart, SessionSetup, SignIn,
};
use crate::{
app::{session_options::reasoning_to_wire, LaunchFlag, SettingOrigins},
session::Session,
tui::LaunchChange,
};
let Cli {
provider,
model,
config: config_path,
auth,
no_system_prompt,
no_tools,
no_subagents,
agent,
reasoning,
permission_mode,
add_dirs: _,
// Startup already wrote the overrides to the config the daemon reads.
save: _,
no_save,
resume: _,
continue_latest: _,
// The TUI submits it from the composer, which sends it to the
// session like any prompt.
prompt: _,
// Where the TUI draws; the session never sees it.
minimal: _,
// `None`: interactive launches have no subcommand.
command: _,
} = cli;
if config_path.is_some() {
// The daemon's sessions share the config in its Rho home.
anyhow::bail!(
"--config is not supported in a daemon session: the daemon reads the config in its Rho home; set RHO_HOME to run on another"
);
}
// A model first, since it decides which reasoning levels it may take.
let mut changes = Vec::new();
let launch_model = || ModelRef {
provider: config.provider.clone(),
model: config.model.clone(),
};
match (provider.is_some() || model.is_some(), auth) {
(true, _) => changes.push(LaunchChange::Change(SessionChange::Model {
model: launch_model(),
auth: auth.is_some().then(|| config.auth.clone()),
setup: true,
})),
// The flag may name another provider's profile, which the launch's
// config then holds.
(false, Some(_)) => changes.push(LaunchChange::Auth {
auth: config.auth.clone(),
on: launch_model(),
}),
(false, None) => {}
}
if reasoning.is_some() {
changes.push(LaunchChange::Change(SessionChange::Reasoning {
level: reasoning_to_wire(config.reasoning),
}));
}
if permission_mode.is_some() {
changes.push(LaunchChange::Change(SessionChange::PermissionMode {
mode: config.permission_mode.into(),
}));
}
let without = [
(SessionPart::Tools, *no_tools),
(SessionPart::SystemPrompt, *no_system_prompt),
(SessionPart::Subagents, *no_subagents),
(SessionPart::Saving, *no_save),
]
.into_iter()
.filter_map(|(part, left_out)| left_out.then_some(part))
.collect();
// Startup read it a moment ago; it loads unless edited since.
let config_file = std::sync::Arc::new(crate::app::read_config_file()?);
let launch = tui::DaemonLaunch {
cwd: cwd.to_path_buf(),
agent: agent.clone(),
setup: SessionSetup {
additional_directories: added_dirs.as_slice().to_vec(),
mcp_servers: Vec::new(),
without,
child_threads: ChildThreads::Daemon,
// The TUI follows the session, so it shows the turn the daemon
// starts when a workflow or background process finishes.
idle_wake: IdleWake::Turn,
// A session without a login opens signed out, and the TUI
// offers /login.
sign_in: SignIn::Later,
// The TUI draws A2UI surfaces, so its sessions have the `ui`
// tool. It attaches with this setup too, which counts it among
// the clients a waiting `ui` call can be answered in.
surfaces: rho_protocol::Surfaces::Drawn,
system_prompt: None,
},
config: std::sync::Arc::new(config.clone()),
definition: std::sync::Arc::new(bound.definition().clone()),
flags: SettingOrigins::of_launch_flags(
[
match (provider.is_some() || model.is_some(), auth.is_some()) {
(true, _) => Some(LaunchFlag::Model),
(false, true) => Some(LaunchFlag::Auth),
(false, false) => None,
},
reasoning.is_some().then_some(LaunchFlag::Reasoning),
permission_mode
.is_some()
.then_some(LaunchFlag::PermissionMode),
]
.into_iter()
.flatten(),
std::sync::Arc::clone(&config_file),
),
config_file,
};
// The picker opens over a new session, which opens only if prompted,
// and switches to its choice, which runs as it was saved: a flag for
// the session has nothing to apply to yet.
if matches!(startup, StartupSession::Picker) && !changes.is_empty() {
anyhow::bail!(
"--provider, --model, --auth, --reasoning, and --permission-mode need a session id with --resume"
);
}
// A session the daemon still has loaded keeps the setup it opened
// with, so it would go on saving while this TUI treated it as unsaved,
// and cancel its turn on quit.
if *no_save && matches!(startup, StartupSession::ById(_) | StartupSession::Latest(_)) {
anyhow::bail!(
"--no-save cannot be combined with --resume or --continue: a resumed session keeps saving"
);
}
let id = match startup {
// The flags are this launch's config, which the draft is built
// from; chosen, the first prompt opens the session with them over
// the config the daemon reads then, and `/new` carries them on.
StartupSession::Fresh | StartupSession::Picker => {
let mut options = new_options(&launch, bound).await;
options.set_launch_flags(launch.flags.clone());
return tui::DaemonSession::draft(launch, options).await;
}
// Resolve the id, but never take the writer lease from the daemon
// that may still be running this session's turn.
StartupSession::ById(prefix) => {
resumed(Session::resolve_target(cwd, prefix)?, agent, bound)?
}
StartupSession::Latest(target) => resumed(target.clone(), agent, bound)?,
};
tui::DaemonSession::open(launch, id, tui::InitialSettings::Required(changes)).await
}
/// The options a new session of `launch` starts with, as its config and
/// `bound`, its agent, give them: the commands it lists before its MCP
/// servers connect, as the daemon's would.
async fn new_options(
launch: &tui::DaemonLaunch,
bound: &BoundAgent,
) -> crate::app::session_options::DraftOptions {
use crate::app::{
daemon_host::DAEMON_COMMANDS,
session_commands::CommandFiles,
session_options::{available_auths, drafted_commands, DraftOptions},
};
let home = crate::paths::home_dir();
let files = CommandFiles {
cwd: &launch.cwd,
home: home.as_deref(),
project_trust: crate::workspace::ProjectTrusts::of_this_process(),
config: &launch.config,
};
let commands = drafted_commands(&files, bound.rho_capabilities(), DAEMON_COMMANDS);
DraftOptions::new(
(*launch.config).clone(),
available_auths(std::sync::Arc::new(
crate::credential_store::AppCredentialStore,
))
.await,
commands,
launch.setup.additional_directories.clone(),
)
}
/// Resuming `session`. It runs as the agent it was saved as, so `--agent`
/// may only name that one, unchanged since.
fn resumed(
session: crate::session::SessionTarget,
agent: &Option<String>,
bound: &BoundAgent,
) -> anyhow::Result<rho_protocol::SessionId> {
if agent.is_some() {
crate::session::Session::validate_agent_definition_identity_of(
&session,
bound.definition(),
)?;
}
Ok(rho_protocol::SessionId::new(session.id))
}