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
//! A session's setup as the daemon opens it with: the opening request's
//! [`SessionSetup`] on top of what a reopened session's file keeps,
//! checked and converted once (#1661).
//!
//! The session owns its added directories and the parts it leaves out but
//! questions: its file keeps them, and a reopen adds the request's to the
//! saved ones, so a later client can narrow a session further but never
//! widen it, and a reopen never drops a saved directory that still exists.
//! That holds across daemon reopens only: the TUI keeps an existing record
//! but does not record its own `--no-*` flags, until it becomes a daemon
//! client (#1667).
//! A new session opened without saving has no file, so none of this is kept
//! and no request can reopen it. A fork starts from what the file of the
//! session it forks keeps, so it has the same tools, and adds to it as a
//! new session does.
//! The session owns the system prompt a client gave it too: its file keeps
//! the last one a request brought, a reopen that brings none keeps it, one
//! that brings another replaces it, and a fork starts with it.
//! The opening client owns its MCP servers, whose `env` and `headers` may
//! hold secrets, whether it shows questions and draws surfaces, and whether
//! its own threads run the session's children, which goes with the MCP server they go
//! through: a reopen takes them from its own request alone, so a prompt,
//! which brings no setup, reopens a session without them.
use std::path::Path;
use rho_protocol::{
ChildThreads, ErrorCode, IdleWake, RpcError, SessionPart, SessionSetup, Surfaces,
SystemPromptMode,
};
use super::open_failed;
use crate::{
added_dirs::{session_added_dirs, AddedDirs},
app::{
host_mcp::host_mcp_config,
session_runtime::{saved_host_prompt, ChildAgents, IdleTurns, LeftOut, QuestionSupport},
},
prompt::{HostPrompt, HostPromptMode},
session::{Session as StoredSession, SessionPersistence},
tools::{mcp::config::McpConfig, ui::SurfaceHost},
};
/// What a session opens with.
pub(super) struct Setup {
/// The parts it leaves out: those its file keeps, and the request's.
pub(super) left_out: LeftOut,
/// Its client's system prompt: the request's, else the one its file
/// keeps.
pub(super) host_prompt: Option<HostPrompt>,
/// Whether its client shows questions.
pub(super) questions: QuestionSupport,
/// Its A2UI surfaces, when the request says its client draws them.
pub(super) surfaces: Option<SurfaceHost>,
/// Who runs its children: the host's threads when the request says so.
pub(super) children: ChildAgents,
/// Whether the daemon starts a turn when its background work finishes
/// idle: when the request says so.
pub(super) idle_turns: IdleTurns,
/// The directories it adds: those its file keeps that still exist, and
/// the request's.
pub(super) added_dirs: AddedDirs,
/// The opening client's MCP servers.
pub(super) host_mcp: McpConfig,
/// Whether it has a file: not when the request leaves saving out.
pub(super) persistence: SessionPersistence,
/// Whether the request adds to what the session's file keeps, or
/// replaces its system prompt, so a
/// reopen saves at once rather than lose it to an unload before the
/// next turn saves.
pub(super) adds_to_saved: bool,
}
/// The saved session a setup builds on, if any.
#[derive(Clone, Copy)]
pub(super) enum Base<'a> {
/// None: a new session.
New,
/// The session the request reopens, whose file it adds to.
Reopened(&'a StoredSession),
/// The session a new fork starts from: the fork leaves out the parts
/// and adds the directories it does, so it has the same tools.
Forked(&'a StoredSession),
}
impl<'a> Base<'a> {
fn file(self) -> Option<&'a StoredSession> {
match self {
Self::New => None,
Self::Reopened(stored) | Self::Forked(stored) => Some(stored),
}
}
}
impl Setup {
/// The setup of the session in workspace `cwd` that `requested` opens,
/// on top of what `base`'s file keeps. A directory the session cannot
/// grant and a part this daemon does not know are invalid params; a
/// workspace or saved record that cannot be read fails the open.
pub(super) fn resolve(
requested: &SessionSetup,
cwd: &Path,
base: Base<'_>,
) -> Result<Self, RpcError> {
let root = std::fs::canonicalize(cwd).map_err(|error| {
open_failed(anyhow::anyhow!(
"could not resolve the workspace {}: {error}",
cwd.display()
))
})?;
let (saved_left_out, saved_dirs, saved_prompt) = match base.file() {
Some(stored) => {
let restored = AddedDirs::from_storage(stored, &root);
for dir in &restored.missing {
tracing::warn!(
session = stored.id(),
dir = %dir.display(),
"could not restore added directory: not found"
);
}
(
LeftOut::saved(stored).map_err(open_failed)?,
restored.dirs,
saved_host_prompt(stored).map_err(open_failed)?,
)
}
None => (LeftOut::default(), AddedDirs::default(), None),
};
let mut asked = LeftOut::default();
let mut questions = QuestionSupport::Available;
let mut persistence = SessionPersistence::Saved;
for part in &requested.without {
match part {
SessionPart::Tools => asked.tools = true,
SessionPart::SystemPrompt => asked.system_prompt = true,
SessionPart::Subagents => asked.subagents = true,
SessionPart::Questions => questions = QuestionSupport::Unavailable,
SessionPart::Saving if matches!(base, Base::Reopened(_)) => {
return Err(invalid(
"a saved session cannot be reopened without saving; open a new one",
))
}
SessionPart::Saving => persistence = SessionPersistence::Ephemeral,
// `SessionPart` is `#[non_exhaustive]`, so the arm is
// required: a part from a later protocol minor that this
// daemon does not know fails here as invalid params.
_ => return Err(invalid("unknown session part")),
}
}
let asked_dirs = session_added_dirs(&requested.additional_directories, &root)
.map_err(|rejected| invalid(rejected.to_string()))?;
let children = match requested.child_threads {
ChildThreads::Daemon => ChildAgents::InProcess,
ChildThreads::Host => ChildAgents::HostThreads,
};
let surfaces = match requested.surfaces {
Surfaces::Unsupported => None,
Surfaces::Drawn => Some(SurfaceHost::default()),
};
let idle_turns = match requested.idle_wake {
IdleWake::Never => IdleTurns::Never,
IdleWake::Turn => IdleTurns::Host,
};
let left_out = saved_left_out.union(asked);
let added_dirs = saved_dirs.union(&root, &asked_dirs);
let host_prompt = match &requested.system_prompt {
Some(asked) => Some(host_prompt(asked)?),
None => saved_prompt.clone(),
};
Ok(Self {
adds_to_saved: matches!(base, Base::Reopened(_))
&& (left_out != saved_left_out
|| added_dirs != saved_dirs
|| host_prompt != saved_prompt),
left_out,
host_prompt,
questions,
surfaces,
children,
idle_turns,
added_dirs,
persistence,
host_mcp: host_mcp_config(&requested.mcp_servers),
})
}
}
/// The session's form of a client's system prompt. An empty one, or one in
/// a mode this daemon does not know, is invalid params.
pub(super) fn host_prompt(asked: &rho_protocol::SystemPrompt) -> Result<HostPrompt, RpcError> {
if asked.text.trim().is_empty() {
return Err(invalid("a system prompt needs text"));
}
let mode = match asked.mode {
SystemPromptMode::Append => HostPromptMode::Append,
SystemPromptMode::Override => HostPromptMode::Override,
// `SystemPromptMode` is `#[non_exhaustive]`: a mode from a later
// protocol minor that this daemon does not know fails here.
_ => return Err(invalid("unknown system prompt mode")),
};
Ok(HostPrompt {
mode,
text: asked.text.clone(),
})
}
fn invalid(message: impl Into<String>) -> RpcError {
RpcError::new(ErrorCode::InvalidParams, message)
}