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
//! Permission mode changes for one session: swaps the mode by rebuilding the
//! SDK runtime around the live conversation, the same way the interactive
//! host does. Other changes that need a new runtime rebuild through here
//! too, around the live conversation or another point of the session's tree.
use std::path::PathBuf;
use rho_providers::credentials::CredentialStore;
use rho_sdk::{SessionOptions, SessionSnapshot, SystemPrompt};
use super::{
ensure_auto_classifier_model, model_scoped_config, RunShape, SessionRuntime, SettingChangeError,
};
use crate::{
app::{
conversation_switch::replace_system_prompt,
policy::AppPolicy,
runtime_builder::{build_runtime_with_max_steps, RuntimeBuildOptions},
sdk_config::WorkspaceOptions,
session_assembly::ApprovalInputs,
},
compaction::CompactionConfig,
config::Config,
permission::{PermissionMode, SessionWriteLog},
};
/// Permission state one session owns. Starts from the process config's
/// mode; a host's mode change applies to this session only.
pub(crate) struct SessionPermission {
pub(crate) mode: PermissionMode,
/// Write grants the current policy remembers.
pub(crate) writes: SessionWriteLog,
/// Primary workspace root the session's tools resolve against.
pub(crate) workspace_root: PathBuf,
}
/// What a permission-mode change does when the session already runs the mode.
#[derive(Clone, Copy)]
pub(crate) enum SameMode {
/// Nothing.
Keep,
/// Auto rebuilds, reading the classifier model again.
RebuildAuto,
}
/// A move of a session's permission mode, checked but not yet applied: the
/// config the mode runs under and the write grants its policy keeps. Rho's
/// own sessions and the tools a daemon session serves an agent on another
/// runtime (`daemon_host/sessions/acp_tools.rs`) move through it, wire the
/// mode's approvals and policy from it, and take it
/// ([`SessionPermission::take`]) only once that succeeded, so a failed
/// move leaves the session as it was.
pub(crate) struct ModeMove {
pub(crate) mode: PermissionMode,
/// The session's config in `mode`.
pub(crate) config: Config,
pub(crate) writes: SessionWriteLog,
}
impl ModeMove {
/// A session's first mode, `mode` under `config`, with no write grants
/// yet; [`SettingChangeError::Unsupported`] for a mode `config` cannot
/// run: auto without a classifier model.
pub(crate) fn first(
mode: PermissionMode,
config: &Config,
credentials: &dyn CredentialStore,
) -> Result<Self, SettingChangeError> {
Ok(Self {
mode,
config: config_in_mode(config, mode, credentials)?,
writes: SessionWriteLog::default(),
})
}
/// The permission state of a session whose tools resolve against
/// `workspace_root`, in this mode.
pub(crate) fn into_permission(self, workspace_root: PathBuf) -> SessionPermission {
SessionPermission {
mode: self.mode,
writes: self.writes,
workspace_root,
}
}
}
impl SessionPermission {
/// Checks a move to `mode` under `config`, the session's config
/// whatever mode it names: `None` when the session runs `mode` and
/// `same` keeps it, [`SettingChangeError::Unsupported`] for a mode
/// `config` cannot run (auto without a classifier model). Write grants
/// carry across as [`SessionWriteLog::carried_across`] says.
pub(crate) fn move_to(
&self,
mode: PermissionMode,
config: &Config,
credentials: &dyn CredentialStore,
same: SameMode,
) -> Result<Option<ModeMove>, SettingChangeError> {
let rebuild_same = match same {
SameMode::Keep => false,
SameMode::RebuildAuto => mode == PermissionMode::Auto,
};
if self.mode == mode && !rebuild_same {
return Ok(None);
}
Ok(Some(ModeMove {
mode,
config: config_in_mode(config, mode, credentials)?,
writes: self.writes.clone().carried_across(self.mode, mode),
}))
}
/// Takes `moved`, once the session's approvals and policy run its mode.
pub(crate) fn take(&mut self, moved: ModeMove) {
self.mode = moved.mode;
self.writes = moved.writes;
}
}
/// `config` in `mode`, or [`SettingChangeError::Unsupported`] when it
/// cannot run `mode`: auto without a classifier model.
fn config_in_mode(
config: &Config,
mode: PermissionMode,
credentials: &dyn CredentialStore,
) -> Result<Config, SettingChangeError> {
let mut config = config.clone();
config.permission_mode = mode;
ensure_auto_classifier_model(&config, credentials)
.map_err(|error| SettingChangeError::Unsupported(error.to_string()))?;
Ok(config)
}
impl SessionRuntime {
/// Applies `mode` to later prompts. The host holds the runtime between
/// prompts, so none is in flight. On error the session keeps its old
/// mode: a mode this session's config cannot run, such as auto without
/// a classifier model, is [`SettingChangeError::Unsupported`].
pub(crate) async fn set_permission_mode(
&mut self,
mode: PermissionMode,
process_config: &Config,
) -> Result<(), SettingChangeError> {
self.change_permission_mode(mode, process_config, SameMode::Keep)
.await
}
/// [`Self::set_permission_mode`] as a client asks for it: Auto set again
/// on a session that runs it rebuilds, so a classifier model picked
/// since takes effect.
pub(crate) async fn reapply_permission_mode(
&mut self,
mode: PermissionMode,
process_config: &Config,
) -> Result<(), SettingChangeError> {
self.change_permission_mode(mode, process_config, SameMode::RebuildAuto)
.await
}
async fn change_permission_mode(
&mut self,
mode: PermissionMode,
process_config: &Config,
same: SameMode,
) -> Result<(), SettingChangeError> {
let config = model_scoped_config(&self.current_model(), process_config);
let credentials = self.build.host.environment.credentials();
let Some(moved) = self
.permission
.move_to(mode, &config, credentials.as_ref(), same)?
else {
return Ok(());
};
// `exit_plan_mode` is offered only in plan mode; the rebuilt runtime
// must see the tool list of the mode it serves.
self.built.tools.set_plan_exit_registered(mode);
if let Err(error) = self
.rebuild_runtime(&moved.config, mode, moved.writes.clone())
.await
{
self.built
.tools
.set_plan_exit_registered(self.permission.mode);
return Err(error);
}
if let Some(manager) = self.built.tools.subagents() {
manager.update_permission_mode(mode);
}
self.permission.take(moved);
Ok(())
}
/// `process_config` scoped to the session's model, in `mode`, or
/// [`SettingChangeError::Unsupported`] when that config cannot run
/// `mode`: auto without a classifier model.
pub(super) fn config_for_mode(
&self,
mode: PermissionMode,
process_config: &Config,
) -> Result<Config, SettingChangeError> {
let config = model_scoped_config(&self.current_model(), process_config);
let credentials = self.build.host.environment.credentials();
config_in_mode(&config, mode, credentials.as_ref())
}
/// Rebuilds the SDK runtime around the live conversation and the tool
/// set as it stands, with `mode`'s policy and approvals over `writes`
/// whatever mode `config` names, keeping the session's run shape. The
/// live runtime is replaced only once the new one holds the session, so
/// on error the session keeps its runtime. Callers that change the tool
/// list keep the system prompt and tell the model with an appended notice instead.
pub(super) async fn rebuild_runtime(
&mut self,
config: &Config,
mode: PermissionMode,
writes: SessionWriteLog,
) -> Result<(), SettingChangeError> {
self.rebuild_around(config, mode, writes, /*moved_to*/ None)
.await
}
/// [`Self::rebuild_runtime`], around `conversation`, another point of
/// the session's saved tree, in place of the live one. The conversation
/// runs under the system prompt the session has now, which a node saved
/// before a model switch does not hold, and the checklist and loaded
/// tools are the ones it had there.
pub(super) async fn rebuild_runtime_onto(
&mut self,
config: &Config,
mode: PermissionMode,
writes: SessionWriteLog,
conversation: SessionSnapshot,
) -> Result<(), SettingChangeError> {
self.rebuild_around(config, mode, writes, Some(conversation))
.await
}
/// Rebuilds around `moved_to`, or the live conversation when `None`.
async fn rebuild_around(
&mut self,
config: &Config,
mode: PermissionMode,
writes: SessionWriteLog,
moved_to: Option<SessionSnapshot>,
) -> Result<(), SettingChangeError> {
// Approvals follow the session's mode, which a caller's config,
// built from the process config, may not carry.
let mut config = config.clone();
config.permission_mode = mode;
let config = &config;
let approval = self.build.host.approvals.wire(ApprovalInputs {
config: config.clone(),
workspace_root: self.permission.workspace_root.clone(),
usage_recording: self.built.runtime.usage_recording(),
session_writes: writes.clone(),
credentials: self.build.host.environment.credentials(),
});
let workspace = WorkspaceOptions {
root: self.permission.workspace_root.clone(),
}
.build_workspace(&self.added_dirs)
.map_err(|error| SettingChangeError::Apply(error.into()))?;
// The whole run shape, as when the session opened: a rebuild keeps
// its step limit, attribution and hook labels.
let RunShape {
role,
max_steps,
hook_labels,
} = &self.build.run;
let runtime = build_runtime_with_max_steps(
RuntimeBuildOptions {
provider: std::sync::Arc::clone(&self.built.provider),
tools: &self.built.tools,
workspace,
workspace_policy: AppPolicy::for_mode(
mode,
writes,
self.build.host.environment.current().path(),
),
approval_session: approval.session,
system_prompt: self.built.prompt.system.clone(),
reasoning: self.built.session.reasoning_level(),
service_tier: self.built.session.service_tier(),
compaction: CompactionConfig::from(config),
context_window: self.configured_context_window(),
usage_purpose: role.usage_purpose(),
usage_parent_session_id: role.parent().cloned(),
usage_recording: self.built.runtime.usage_recording(),
hook_host_labels: hook_labels.clone(),
hooks: self.built.hooks.as_ref(),
diagnostics: self.built.diagnostics.clone(),
recall: self.built.tools.recall_store(),
model_requests: self.build.host.model_requests.clone(),
},
*max_steps,
)
.map_err(|error| SettingChangeError::Apply(error.into()))?;
let conversation = moved_to
.clone()
.unwrap_or_else(|| self.built.session.snapshot());
let rebound = runtime
.rebind_session(SessionOptions::from_snapshot(conversation))
.await
.and_then(|session| {
// Before the swap, so a failure leaves the live session.
// The live conversation has the prompt already, and a
// session without one has none to restore.
if let (Some(_), SystemPrompt::Custom(text)) =
(&moved_to, &self.built.prompt.system)
{
replace_system_prompt(&session, text)?;
}
Ok(session)
});
let session = match rebound {
Ok(session) => session,
Err(error) => {
runtime.shutdown();
return Err(SettingChangeError::Apply(error.into()));
}
};
if moved_to.is_some() {
let moved = session.snapshot();
self.built.tools.todo_state().restore(&moved);
self.built.tools.code_mode().restore(&moved);
}
let previous = std::mem::replace(&mut self.built.runtime, runtime);
self.built.session = session;
self.built.approval_receiver = approval.receiver;
if let Some(advisor) = self.built.tools.advisor() {
advisor.bind_session(self.built.session.clone());
}
previous.shutdown();
Ok(())
}
}
#[cfg(test)]
#[path = "mode_tests.rs"]
mod tests;