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
//! Opening a new session for `rho/session/new`, in its workspace or in a
//! worktree added for it, and registering the job of its turns.
//!
//! A session opened under a `parent` takes what a person chose for the
//! sessions its choosing session starts (see `configure.rs`): its runtime,
//! unless the `new` names its own runtime, agent or model, and its
//! permission mode and model, before anything else can reach it, kept as
//! its own settings, and a copy of the choice itself, kept as its own, in
//! its folder on another runtime than rho's, so the sessions it starts take
//! it too. The choosing session is the nearest session a person or session
//! control opened: the parent itself, or, for a subagent's or workflow
//! node's session, the session whose turn runs that, found as the grant of
//! a session it starts is, through the job writing it or, once that run
//! ended, the latest run that wrote it. A parent this daemon has no job
//! record of, such as a subagent whose job was never recorded or one an
//! in-process rho runs, is found through its file instead: a subagent's
//! session records the session that started it, with that session's
//! workspace, followed up to the first session that is no subagent's. Its
//! choice is read before the session opens, for the runtime and model it
//! opens on, and again just before it applies: from its feed while it is
//! loaded, as it is while its turn runs, else from its file, or its folder
//! for a session an agent runs. A runtime the choice decided that changed
//! between the two reads fails the `new` rather than run the session on one
//! nobody chose now. A choice that cannot be read or taken, or a recorded
//! owner whose file cannot be read, fails the `new` rather than open the
//! session on the config's, which may be looser.
//!
//! One gap remains, reached only when this daemon has no job record of the
//! parent: a parent whose file records no owner to follow, a workflow
//! node's session or a subagent of a session that had saved nothing yet,
//! is its own choosing session, and chose nothing, so the session takes
//! the config's. So does a session started without a parent, or under one
//! nothing is saved under, as any new session does.
use anyhow::Context as _;
use rho_protocol::{
self as wire, ErrorCode, RpcError, SessionNewParams, SessionNewQuery, SessionNewResponse,
};
use rho_sdk::SessionId;
use super::{
acp_turns,
configure::{set_up_new_session, set_up_started_agent_session, NewModel},
engine::Engine,
grant,
open::{config_for_new, open_session, OpenWith, Opening, OpensOn, Workspace},
options, reopen,
reopen::FirstTurn,
started_agent::{OwnModel, StartRequest},
store::store_blocking,
worktree, Admission, JobId, JobRecord, Keeping, SessionJob, SessionJobRecord, Sessions,
};
use crate::{
app::daemon_host::{runtimes, wire::session_to_wire},
session::{Session as StoredSession, SessionTarget},
};
/// The agent a new session on `runtime` runs as, given the `agent` its
/// client named: on rho's loop that agent, which may not be another
/// runtime's session agent; on another runtime its session agent, which
/// `agent` may name. No `runtime` leaves `agent` to say.
fn runtime_agent(
runtime: Option<wire::AgentRuntime>,
agent: Option<String>,
) -> Result<Option<String>, RpcError> {
let invalid = |message: String| RpcError::new(ErrorCode::InvalidParams, message);
let Some(runtime) = runtime else {
return Ok(agent);
};
let runtime = crate::agent::AgentRuntime::try_from(runtime).map_err(|_| {
invalid("the session's runtime is one this daemon does not know".to_owned())
})?;
let named = agent
.as_deref()
.and_then(crate::agent::session_agent_runtime);
match (runtime.session_agent(), agent, named) {
(None, Some(agent), Some(named)) => Err(invalid(format!(
"agent '{agent}' runs only sessions on {named}"
))),
(None, agent, _) => Ok(agent),
(Some(session_agent), Some(agent), _) if agent != session_agent => Err(invalid(format!(
"a session on {runtime} runs as its built-in agent '{session_agent}', not '{agent}'"
))),
(Some(session_agent), _, _) => Ok(Some(session_agent.to_owned())),
}
}
/// What decides a new session's runtime.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum RuntimeFrom {
/// Its `new`: the runtime, agent, or model of rho's it names, or, with
/// no choice that applies, rho's loop.
Request,
/// The choice of its choosing session: another runtime, or `None` for
/// rho's loop.
Choice(Option<wire::AgentRuntime>),
}
/// The session whose choice applies to the sessions a parent starts, as
/// [`Sessions::choosing_session`] finds it.
#[derive(Clone, Debug, PartialEq, Eq)]
struct Choosing {
id: SessionId,
/// The workspace its file is in, when the walk of saved files found it
/// there, so its choice is read there and not from another workspace's
/// session of the same id. `None` for one found through this daemon's
/// jobs, or one nothing is saved under, whose file is found by id.
saved_in: Option<std::path::PathBuf>,
}
impl Sessions {
/// Opens a new session in `cwd`, or in a worktree added for it, as
/// `agent` on `runtime`, with the client's `setup`, and registers the
/// job of its turns.
pub(in crate::app::daemon_host) async fn open_new(
&self,
query: SessionNewQuery,
) -> Result<SessionNewResponse, RpcError> {
let SessionNewQuery {
params:
SessionNewParams {
cwd,
environment,
agent,
setup,
parent,
grant,
worktree,
},
runtime,
..
} = query;
self.refuse_when_stopping()?;
let workspace = Workspace::parse("cwd", &cwd)?;
// Resolved before the session opens, so a malformed parent, or
// one whose choosing session is lost, opens nothing.
let parent = parent.as_ref().map(reopen::parse_session).transpose()?;
let parent_job = parent.as_ref().and_then(|parent| self.job_writing(parent));
let choosing = match &parent {
Some(parent) => Some(self.choosing_session(parent, parent_job.as_ref()).await?),
None => None,
};
// Read for the runtime and model the session opens on; what it
// takes once it opened is read again (below).
let chosen = match &choosing {
Some(choosing) => Some(self.chosen_by(choosing).await?),
None => None,
};
let names_runtime = runtime.is_some() || agent.is_some() || setup.model.is_some();
let runtime_from = match &chosen {
Some(chosen) if !names_runtime => RuntimeFrom::Choice(chosen.runtime),
_ => RuntimeFrom::Request,
};
let chosen_runtime = match runtime_from {
RuntimeFrom::Choice(runtime) => runtime,
RuntimeFrom::Request => None,
};
let agent = runtime_agent(runtime.or(chosen_runtime), agent)?;
// The session job whose turn runs the parent: the parent's own, or,
// when a subagent run or workflow node writes the parent, that of
// the session that started it. The new session opens with no more
// than that turn could give, and its file records that session as
// the one that started it, which a client can list, as it cannot a
// run's own session. A parent no job of this daemon writes records
// none.
let starter = parent_job
.as_ref()
.and_then(|job| self.jobs.runs_under(job));
let opening = grant::opening(
grant::asked(grant, &environment)?,
starter.as_ref().map(|starter| &starter.grant),
);
let with = OpenWith::under(opening, &environment, setup)?;
// Refused now, as `rho/runtime/list` tells the client it would be,
// whether `runtime` or `agent` chose the runtime, rather than by
// the session's first turn, which may wait for a slot first; and
// before a worktree is added for it. A runtime the starting session
// chose fails the same way, naming the choice, rather than open the
// session on rho's loop.
let engine = crate::agent::session_engine(agent.as_deref());
if let Some(reason) = runtimes::unavailable(engine, &with.environment) {
let message = match (chosen_runtime, &choosing) {
(Some(_), Some(choosing)) => format!(
"could not open the session on {} chosen for the sessions {} starts: {reason}",
engine.display_name(),
choosing.id
),
_ => format!("could not open session: {reason}"),
};
return Err(RpcError::new(ErrorCode::SessionOpenFailed, message));
}
// What the agent it names takes from its starter, for a session
// another starts on rho's loop, refused when its starter's choice of
// runtime may not run it: read before a worktree is added, so a
// refusal adds none.
let own_model = match (&runtime, &with.setup.model) {
(_, Some(_)) => OwnModel::Named,
(Some(_), None) => OwnModel::OnNamedRuntime,
(None, None) => OwnModel::Undecided,
};
let started_agent = match (engine, &choosing) {
(crate::agent::AgentRuntime::Rho, Some(choosing)) => {
let request = StartRequest {
workspace: workspace.path(),
agent: agent.as_deref(),
trust: with.environment.project_trusts(),
choosing: &choosing.id,
own_model,
};
let chosen_runtime = chosen.as_ref().and_then(|chosen| chosen.runtime);
self.started_agent(request, chosen_runtime).await?
}
_ => None,
};
let global = config_for_new(&self.settings).await?;
// Added last, once the request is otherwise sound, since a failed
// open leaves it behind.
let (workspace, worktree) = match worktree {
false => (workspace, None),
true => {
let start = crate::worktree::Start::of(&global);
let (workspace, added) =
worktree::add_for_session(&self.worktrees, &workspace, start).await?;
(workspace, Some(added))
}
};
// The model its starter runs on, for an agent that opens on it.
let starters = started_agent
.as_ref()
.and_then(|started| started.starters.clone());
// A model the client names, else its starter's for an agent that
// opens on it, else the one the starting session chose for rho's
// loop, which the session switches to once it opens all the same
// (below). An agent on another runtime takes its chosen model once
// it opened.
let opens_on = match (engine, &with.setup.model, starters, chosen) {
(crate::agent::AgentRuntime::Rho, Some(asked), ..) => {
Some(OpensOn::Asked(asked.clone()))
}
(crate::agent::AgentRuntime::Rho, None, Some(starters), _) => {
Some(OpensOn::Starters(starters))
}
(crate::agent::AgentRuntime::Rho, None, None, Some(chosen))
if chosen.runtime.is_none() =>
{
chosen.model.map(OpensOn::Chosen)
}
_ => None,
};
let new_model = match (&with.setup.model, &opens_on) {
(Some(asked), _) => NewModel::Asked(asked),
(None, Some(OpensOn::Starters(_))) => NewModel::Starters,
(None, Some(OpensOn::Asked(_) | OpensOn::Chosen(_)) | None) => NewModel::Chosen,
};
// Named again once it opened, should the choice refuse it then.
let opened_agent = agent.clone();
let job = JobId::generate();
let mut opened = open_session(
Opening::New {
workspace,
agent,
started_by: starter.map(|starter| starter.session),
model: opens_on,
},
&with,
&self.subagents,
self.run_services(),
&self.settings,
global,
&job,
)
.await
.map_err(|error| worktree::kept(error, worktree.as_ref()))?;
// Read now, so a change a person made while the session opened
// counts, and applied before it is added, so no prompt finds it on
// the config's.
let started = match &choosing {
Some(choosing) => self
.chosen_by(choosing)
.await
.map(|chosen| Some((&choosing.id, chosen))),
None => Ok(None),
};
// A runtime the choice decided that changed meanwhile fails the
// open rather than run the session on one nobody chose now; so does
// a choice of another runtime made meanwhile for an agent that runs
// only on rho's loop.
let started = match (&started_agent, started) {
(Some(started_agent), Ok(Some((choosing, now)))) => started_agent
.refused_under(opened_agent.as_deref(), choosing, now.runtime)
.map(|()| Some((choosing, now))),
(_, started) => started,
};
let started = match (runtime_from, started) {
(RuntimeFrom::Choice(decided), Ok(Some((choosing, now)))) if now.runtime != decided => {
Err(RpcError::new(
ErrorCode::SessionOpenFailed,
format!(
"could not open the session: the runtime chosen for the sessions {choosing} starts changed while it opened; start it again"
),
))
}
(_, started) => started,
};
let set_up = match (started, &mut opened.engine) {
(Err(error), _) => Err(error),
(Ok(started), Engine::Rho(runtime)) => {
set_up_new_session(runtime, &opened.config, started, new_model).await
}
(Ok(Some((choosing, chosen))), Engine::Acp(turns)) => {
set_up_started_agent_session(turns, engine, choosing, chosen)
}
(Ok(None), Engine::Acp(_)) => Ok(()),
};
if let Err(error) = set_up {
// Never added, so nothing else holds the runtime.
opened.engine.discard_new().await;
return Err(worktree::kept(error, worktree.as_ref()));
}
let session = opened.engine.session_id().clone();
let record = JobRecord {
// A session started from one no daemon job writes still shares
// the budget, with no parent to show.
admission: match parent {
Some(_) => Admission::SharedBudget,
None => Admission::Immediate,
},
parent: parent_job,
keeping: match opened.engine.persistence() {
crate::session::SessionPersistence::Saved => Keeping::Stored,
crate::session::SessionPersistence::Ephemeral => Keeping::MemoryOnly,
},
// A session that opens under a limit keeps it: no later
// prompt widens it (#1796).
grant_limit: (!with.grant.is_root()).then(|| with.grant.clone()),
grant: with.grant,
worktree: worktree.clone(),
..JobRecord::new_session(
job.clone(),
opened.engine.workspace_root().to_path_buf(),
session.clone(),
)
};
let added = self
.add(
SessionJobRecord::Register(record),
opened,
FirstTurn::Daemon,
)
.await
.map_err(|error| worktree::kept(error, worktree.as_ref()))?;
tracing::info!(%session, %job, "opened session");
Ok(SessionNewResponse {
session: session_to_wire(session),
options: added.feed.options(),
worktree,
})
}
/// The job writing `session`, a new session's parent (#1714): the one
/// under way, as the turn of a session that starts another is, else the
/// latest job of its turns. `None` for a session no job of this daemon
/// writes, such as one an in-process rho runs.
fn job_writing(&self, session: &SessionId) -> Option<JobId> {
match self.jobs.session_job(session) {
SessionJob::Busy(job) => Some(job),
SessionJob::Last(record) => Some(record.id),
SessionJob::New => None,
}
}
/// The session whose choice applies to a session `parent` starts, when
/// `writer` is the job writing `parent`: the nearest session job's at
/// or above `writer`, as a session `parent` starts takes that one's
/// grant, so a subagent or workflow node of a session starts sessions
/// under that session's choice. When no job of this daemon writes
/// `parent`, the same of the latest run that wrote it and has ended
/// (`JobRegistry::last_run_writing`); when no job of this daemon ever
/// wrote it, the session that owns it as its file records it (see
/// [`owning_session`]). A run whose session job is gone is
/// `SessionOpenFailed`: the choice that applies cannot be found.
async fn choosing_session(
&self,
parent: &SessionId,
writer: Option<&JobId>,
) -> Result<Choosing, RpcError> {
let Some(writer) = writer
.cloned()
.or_else(|| self.jobs.last_run_writing(parent))
else {
let parent = parent.clone();
return store_blocking(FIND_OWNER, move || owning_session(parent)).await;
};
let under = self.jobs.runs_under(&writer).ok_or_else(|| {
RpcError::new(
ErrorCode::SessionOpenFailed,
format!(
"could not find the session whose turn runs job {writer}, which writes or wrote {parent}, so not what it chose for the sessions it starts"
),
)
})?;
Ok(Choosing {
id: under.session,
saved_in: None,
})
}
/// What `choosing` chose for the sessions it starts, as it is now: from
/// its feed while it is loaded, as it is while its turn or that of one
/// of its subagents runs, else from its file, or, for a session an agent
/// runs, its folder, in the workspace the walk found it in, if it did.
/// A session nothing is saved under chose
/// nothing. A choice its file keeps but this rho cannot read is a mode
/// this rho does not know, which the new session refuses to open in: it
/// may be stricter than the config.
async fn chosen_by(
&self,
choosing: &Choosing,
) -> Result<wire::StartedSessionDefaults, RpcError> {
let loaded = self.loaded().get(&choosing.id).cloned();
if let Some(session) = loaded {
return Ok(session.feed.started_session_defaults());
}
let Choosing { id, saved_in } = choosing.clone();
let saved = store_blocking(READ_CHOICE, move || {
let cwd = match saved_in {
Some(cwd) => cwd,
None => match StoredSession::workspace_of(id.as_str())? {
Some(cwd) => cwd,
None => return Ok(None),
},
};
acp_turns::started::saved_by_id(&cwd, id.as_str()).map(Some)
})
.await?;
Ok(saved
.as_ref()
.map(options::started_session_defaults)
.unwrap_or_default())
}
}
/// What a failed read of a starting session's choice could not do.
const READ_CHOICE: &str =
"read what the session that starts this one chose for the sessions it starts";
/// What a failed walk of [`owning_session`] could not do.
const FIND_OWNER: &str = "find the session that owns the subagent that starts this one";
/// The session whose choice applies to a session `parent` starts when no
/// job of this daemon ever wrote `parent`: `parent` itself, unless its file
/// records it as a subagent's session, whose parent the file names, with
/// its workspace (the one a delete cascades over), followed up to the first
/// session that is no subagent's. That one a person or session control
/// opened. A parent nothing is saved under, or whose file records no owner
/// (a workflow node's session, a subagent of a session that had saved
/// nothing yet), is its own. An owner a file names but that cannot be read
/// fails, so the `new` fails rather than open the session on the config's.
/// Blocking.
fn owning_session(parent: SessionId) -> anyhow::Result<Choosing> {
let Some(cwd) = StoredSession::workspace_of(parent.as_str())? else {
return Ok(Choosing {
id: parent,
saved_in: None,
});
};
let mut session = SessionTarget::new(parent.as_str(), cwd);
let mut seen = std::collections::HashSet::new();
loop {
let Some(owner) = StoredSession::subagent_parent_by_id(&session.cwd, &session.id)
.with_context(|| format!("could not read which session owns {}", session.id))?
else {
return Ok(Choosing {
id: SessionId::from_string(session.id)?,
saved_in: Some(session.cwd),
});
};
anyhow::ensure!(
seen.insert(session.id.clone()),
"the subagent sessions above {} name each other as their parent",
session.id
);
session = owner;
}
}
#[cfg(test)]
#[path = "new_tests.rs"]
mod tests;