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
//! Sessions whose turns another engine than Rho's own loop runs: an agent
//! on an external runtime over ACP, which keeps its own conversation. That
//! is a subagent or workflow agent node's one run, or a daemon session the
//! agent runs turn by turn. The file records each prompt and final reply,
//! for listings, search and reading, and its header names the artifacts,
//! whose attach journal holds what the agent showed, for clients that
//! replay it.
//!
//! The file records the run's agent, which no Rho runtime runs: a build
//! that predates the engine exports the file but refuses to open it, to
//! continue or to read it, as it cannot bind its agent; a subagent's it
//! also refuses to continue for its origin, as only its parent does.
use std::path::{Component, Path, PathBuf};
use rho_sdk::{
model::{Message, ModelIdentity},
CompactionState, Revision, SessionId, SessionSnapshot,
};
use serde::{Deserialize, Serialize};
use super::{
agent_identity, resolve_saved, session_root, unix_timestamp_secs, Session, SessionProvenance,
SessionStore,
};
/// What runs a session's turns, as its header records it. A header with
/// none is a session of Rho's own loop.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(tag = "kind", rename_all = "snake_case")]
pub(crate) enum SessionEngine {
/// A subagent or workflow agent node run on an external agent runtime
/// over ACP, in `permission_mode`. What it showed is the attach journal
/// among the run's `artifacts`, whose status names the runtime. Nothing
/// continues, forks or resumes it.
///
/// A later Rho must not change these fields: a header whose `acp`
/// engine does not read does not read at all.
Acp {
artifacts: RunArtifacts,
permission_mode: rho_protocol::PermissionMode,
},
/// A daemon session whose turns an agent on an external runtime runs
/// over ACP, in `permission_mode`, one agent process per turn: each
/// turn after the first resumes the agent's own session, which the
/// status among the session's `artifacts` names. Its attach journal
/// holds every turn, each from its prompt. Nothing forks it.
///
/// A later Rho must not change these fields, as for [`Self::Acp`].
AcpSession {
artifacts: RunArtifacts,
permission_mode: rho_protocol::PermissionMode,
},
/// An engine a later Rho records that this one does not know.
#[serde(other)]
Unknown,
}
/// The directory of a run's artifacts, its status and attach journal, as a
/// path under the rho home, which holds every run's: a subagent run's under
/// `subagents` or its parent session's folder, a workflow node attempt's
/// under `workflows`. Only plain components, so it never leaves the home.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(try_from = "PathBuf", into = "PathBuf")]
pub(crate) struct RunArtifacts(PathBuf);
impl RunArtifacts {
/// The artifacts in `directory`, which must be under `rho_home`.
pub(crate) fn of(directory: &Path, rho_home: &Path) -> anyhow::Result<Self> {
let relative = directory.strip_prefix(rho_home).map_err(|_| {
anyhow::anyhow!(
"the run's artifacts at {} are outside the rho home {}",
directory.display(),
rho_home.display()
)
})?;
Self::try_from(relative.to_path_buf())
}
/// The artifacts' directory under `rho_home`.
pub(crate) fn directory(&self, rho_home: &Path) -> PathBuf {
rho_home.join(&self.0)
}
}
impl TryFrom<PathBuf> for RunArtifacts {
type Error = anyhow::Error;
fn try_from(path: PathBuf) -> anyhow::Result<Self> {
let plain = path
.components()
.all(|component| matches!(component, Component::Normal(_)));
anyhow::ensure!(
plain && path.components().next().is_some(),
"{} is not a path under the rho home",
path.display()
);
Ok(Self(path))
}
}
impl From<RunArtifacts> for PathBuf {
fn from(artifacts: RunArtifacts) -> Self {
artifacts.0
}
}
impl Session {
/// Creates the file of session `id` in `cwd`'s workspace, which came
/// from `provenance` as agent `agent` (its id and fingerprint) and runs
/// on `engine`.
pub(crate) fn create_on_engine(
cwd: &Path,
id: &str,
agent: (&str, &str),
provenance: SessionProvenance,
engine: &SessionEngine,
) -> anyhow::Result<Self> {
Self::create_on_engine_in_root(&session_root()?, cwd, id, agent, provenance, engine)
}
fn create_on_engine_in_root(
session_root: &Path,
cwd: &Path,
id: &str,
agent: (&str, &str),
provenance: SessionProvenance,
engine: &SessionEngine,
) -> anyhow::Result<Self> {
let created_at = unix_timestamp_secs();
let path = SessionStore::new(session_root, cwd).create_path(id, created_at)?;
let session = Self::from_parts(session_root, cwd, id.to_owned(), path)?;
session.append_session_metadata(
id.to_owned(),
created_at,
Some(&super::SavedAgent::named(agent.0, agent.1)),
provenance,
Some(engine),
)?;
Ok(session)
}
/// Creates the file of session `id` in `cwd`'s workspace, which came
/// from `provenance` and whose turns agent `agent` (its id and
/// fingerprint), on an external runtime, runs in `permission_mode`
/// ([`SessionEngine::AcpSession`]). Its artifacts are in the session's
/// own folder, which its delete removes; returns their directory too.
pub(crate) fn create_on_agent(
cwd: &Path,
id: &str,
agent: (&str, &str),
provenance: SessionProvenance,
permission_mode: rho_protocol::PermissionMode,
) -> anyhow::Result<(Self, PathBuf)> {
let rho_home = crate::paths::rho_dir()?;
let session_root = super::layout::session_root_in(&rho_home);
let created_at = unix_timestamp_secs();
let path = SessionStore::new(&session_root, cwd).create_path(id, created_at)?;
let artifacts = path.with_file_name(super::layout::SESSION_AGENT_DIR_NAME);
let engine = SessionEngine::AcpSession {
artifacts: RunArtifacts::of(&artifacts, &rho_home)?,
permission_mode,
};
let session = Self::from_parts(&session_root, cwd, id.to_owned(), path)?;
session.append_session_metadata(
id.to_owned(),
created_at,
Some(&super::SavedAgent::named(agent.0, agent.1)),
provenance,
Some(&engine),
)?;
Ok((session, artifacts))
}
/// Saves `history`, the conversation of a session another engine runs
/// on `model`, whose last rows, `shown`, it adds. `history` only ever
/// grows, so its length orders the saves.
pub(crate) fn save_engine_history(
&self,
history: &[Message],
shown: &[Message],
model: ModelIdentity,
) -> anyhow::Result<()> {
self.save_snapshot(&self.engine_snapshot(history, model)?, shown)
}
/// What runs the turns of the session saved under exactly `id` in
/// `cwd`'s workspace, read without opening it, which another process may
/// hold: `None` for Rho's own loop; an error when nothing is saved
/// under `id` there.
pub(crate) fn engine_by_id(cwd: &Path, id: &str) -> anyhow::Result<Option<SessionEngine>> {
agent_identity::read_engine(&resolve_saved(cwd, id)?.path)
}
/// What runs this session's turns: `None` for Rho's own loop.
pub(crate) fn engine(&self) -> anyhow::Result<Option<SessionEngine>> {
agent_identity::read_engine(&self.path)
}
/// The session that started this one through session control, by id;
/// `None` for one a person or an agent outside any session opened.
pub(crate) fn started_by(&self) -> anyhow::Result<Option<String>> {
agent_identity::read_started_by(&self.path)
}
/// Saves `prompt` as the first message of a session another engine
/// runs on `model`, as the run starts.
pub(crate) fn save_engine_prompt(
&self,
prompt: &str,
model: ModelIdentity,
) -> anyhow::Result<()> {
let history = vec![Message::user_text(prompt)];
self.save_snapshot(&self.engine_snapshot(&history, model)?, &history)
}
/// Saves the `reply` a run another engine ran on `model` gave to
/// `prompt`, once it ended. `prompt_row` says whether
/// [`Self::save_engine_prompt`] saved the prompt's row; when it did not,
/// the prompt's row is saved here, before the reply's, so the session
/// never shows a reply without its prompt.
pub(crate) fn save_engine_reply(
&self,
prompt: &str,
reply: &str,
model: ModelIdentity,
prompt_row: PromptRow,
) -> anyhow::Result<()> {
let history = vec![Message::user_text(prompt), Message::assistant_text(reply)];
let shown = match prompt_row {
PromptRow::Saved => &history[1..],
PromptRow::Unsaved => &history[..],
};
self.save_snapshot(&self.engine_snapshot(&history, model)?, shown)
}
fn engine_snapshot(
&self,
history: &[Message],
model: ModelIdentity,
) -> anyhow::Result<SessionSnapshot> {
Ok(SessionSnapshot::new(
SessionId::from_string(self.id.clone())?,
// Each save must advance the revision, or the file does not
// reopen: each saves one more message, so its count does.
Revision::from_u64(history.len() as u64),
history.to_vec(),
model,
CompactionState::default(),
))
}
}
/// Whether an engine session's prompt row was saved as its run started.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum PromptRow {
Saved,
Unsaved,
}
#[cfg(test)]
#[path = "engine_tests.rs"]
mod tests;