rho-coding-agent 3.13.0

A fast Rust agent harness with a small footprint and opinionated defaults
Documentation
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
//! Identity on the session header line: which agent definition a session
//! belongs to, whether `/agent:` rebound it as a delegated child of which
//! root, and the host that created it.

use std::{
    fs,
    io::{BufRead, BufReader, Write},
    path::Path,
};

use rho_sdk::SessionSnapshot;
use serde::{Deserialize, Serialize};

use crate::agent::{AgentDefinition, PromptPolicy};

use super::{
    index,
    layout::{set_private_file_permissions, timestamp},
    persistence::{session_root, SessionEntry, SessionStore, SESSION_VERSION},
    tree::{NodeId, SessionNode, SessionNodeKind, StoredStateTransition},
    Session, SessionEngine, SessionOrigin, SessionTarget,
};

/// How the session's agent was bound. Absent from the header means `Root`:
/// the process launch agent. `Delegated` marks a session rebound with
/// `/agent:<name>`, by ACP or the daemon, whose reload must restore the
/// child's tool boundary even when the child shares the launch agent's id.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub(crate) enum SessionAgentRole {
    #[default]
    Root,
    Delegated,
}

impl SessionAgentRole {
    pub(super) fn is_root(&self) -> bool {
        matches!(self, Self::Root)
    }
}

/// An agent definition a session header names: its id, the fingerprint of
/// the definition the session was created or rebound under, and that
/// definition's instructions, which the session keeps. A session that
/// starts from a reopened one, as a fork, saves the fingerprint of what it
/// runs, the current definition with the kept instructions, which no file
/// may have; only a workflow node's reopen compares it.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub(crate) struct SavedAgent {
    pub(crate) id: String,
    pub(crate) fingerprint: String,
    /// `None` in a file written before instructions were kept, or for an
    /// agent an external runtime runs.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub(crate) prompt: Option<PromptPolicy>,
}

impl SavedAgent {
    /// An identity that keeps no instructions: an agent an external runtime
    /// runs, which keeps its own.
    pub(crate) fn named(id: &str, fingerprint: &str) -> Self {
        Self {
            id: id.to_owned(),
            fingerprint: fingerprint.to_owned(),
            prompt: None,
        }
    }

    /// Refuses to resume as `definition` unless it is this agent: a session
    /// never reopens as another agent, with that agent's tools (#1661).
    pub(crate) fn validate(&self, definition: &AgentDefinition) -> anyhow::Result<()> {
        let selected_id = definition.id.as_str();
        anyhow::ensure!(
            self.id == selected_id,
            "cannot resume session created by agent '{}' as selected agent '{selected_id}'",
            self.id
        );
        Ok(())
    }
}

/// The root agent a session reopens under, as its header names it.
#[derive(Clone, Debug, PartialEq, Eq)]
pub(crate) enum SavedRoot {
    /// The session's own agent, whose instructions its prompt renders.
    Own(SavedAgent),
    /// The root a session `/agent:` rebound was rebound from, which only
    /// caps its child's tools; the child's instructions are the session's.
    LaunchedFrom(SavedAgent),
}

impl SavedRoot {
    pub(crate) fn agent(&self) -> &SavedAgent {
        match self {
            Self::Own(agent) | Self::LaunchedFrom(agent) => agent,
        }
    }
}

/// The agent identity the session file at `path` stores, which a resume as
/// `selected`, when named, needs.
fn saved_identity(path: &Path, selected: Option<&str>) -> anyhow::Result<SavedAgent> {
    match read_agent_identity(path)? {
        Some(saved) => Ok(saved),
        None => match selected {
            Some(selected) => anyhow::bail!(
                "cannot resume this session as agent '{selected}': the session has no stored agent definition identity"
            ),
            None => anyhow::bail!("the session has no stored agent definition identity"),
        },
    }
}

/// Whether a launch that named `definition` may resume the session at
/// `path`: the session was saved as that agent.
fn validate_launch(path: &Path, definition: &AgentDefinition) -> anyhow::Result<()> {
    saved_identity(path, Some(definition.id.as_str()))?.validate(definition)
}

fn read_header(path: &Path) -> anyhow::Result<SessionEntry> {
    let file = fs::File::open(path)?;
    let line = BufReader::new(file)
        .lines()
        .next()
        .transpose()?
        .ok_or_else(|| anyhow::anyhow!("session file is empty"))?;
    Ok(serde_json::from_str(&line)?)
}

pub(super) fn read_agent_identity(path: &Path) -> anyhow::Result<Option<SavedAgent>> {
    match read_header(path)? {
        SessionEntry::Session {
            agent_id: Some(id),
            agent_fingerprint: Some(fingerprint),
            agent_prompt: prompt,
            ..
        } => Ok(Some(SavedAgent {
            id,
            fingerprint,
            prompt,
        })),
        SessionEntry::Session { .. } => Ok(None),
        _ => anyhow::bail!("session file does not start with session metadata"),
    }
}

/// The root agent the session reopens under: its own agent, or the root a
/// session `/agent:` rebound was rebound from. `None` for a delegated
/// session written before launch identities were saved; an error for a root
/// session whose header names no agent.
pub(super) fn read_root_agent(path: &Path) -> anyhow::Result<Option<SavedRoot>> {
    match read_header(path)? {
        SessionEntry::Session {
            agent_role: SessionAgentRole::Delegated,
            launch_agent,
            ..
        } => Ok(launch_agent.map(SavedRoot::LaunchedFrom)),
        SessionEntry::Session {
            agent_role: SessionAgentRole::Root,
            agent_id: Some(id),
            agent_fingerprint: Some(fingerprint),
            agent_prompt: prompt,
            ..
        } => Ok(Some(SavedRoot::Own(SavedAgent {
            id,
            fingerprint,
            prompt,
        }))),
        SessionEntry::Session { .. } => {
            anyhow::bail!("the session has no saved agent to reopen it as")
        }
        _ => anyhow::bail!("session file does not start with session metadata"),
    }
}

/// The host that created the session, or `None` for a file written before
/// origins were recorded.
pub(super) fn read_origin(path: &Path) -> anyhow::Result<Option<SessionOrigin>> {
    match read_header(path)? {
        SessionEntry::Session { origin, .. } => Ok(origin),
        _ => anyhow::bail!("session file does not start with session metadata"),
    }
}

/// What runs the session's turns, or `None` for Rho's own loop.
pub(super) fn read_engine(path: &Path) -> anyhow::Result<Option<SessionEngine>> {
    match read_header(path)? {
        SessionEntry::Session { engine, .. } => Ok(engine),
        _ => anyhow::bail!("session file does not start with session metadata"),
    }
}

/// The session that started this one through session control, by id, as
/// its header records it; `None` for one nothing started that way.
pub(super) fn read_started_by(path: &Path) -> anyhow::Result<Option<String>> {
    match read_header(path)? {
        SessionEntry::Session { started_by, .. } => Ok(started_by),
        _ => anyhow::bail!("session file does not start with session metadata"),
    }
}

/// The session a fork forks, or `None` for a session that is not a fork.
pub(super) fn read_forked_from(path: &Path) -> anyhow::Result<Option<SessionTarget>> {
    match read_header(path)? {
        SessionEntry::Session {
            origin: Some(SessionOrigin::Fork),
            parent_session,
            ..
        } => Ok(parent_session),
        SessionEntry::Session { .. } => Ok(None),
        _ => anyhow::bail!("session file does not start with session metadata"),
    }
}

/// The session that started a subagent's session, as its header records it,
/// the parent a delete cascades over. `None` for a session of any other
/// origin, and for a subagent whose parent had no file when it started.
pub(super) fn read_subagent_parent(path: &Path) -> anyhow::Result<Option<SessionTarget>> {
    match read_header(path)? {
        SessionEntry::Session {
            origin: Some(SessionOrigin::Subagent),
            parent_session,
            ..
        } => Ok(parent_session),
        SessionEntry::Session { .. } => Ok(None),
        _ => anyhow::bail!("session file does not start with session metadata"),
    }
}

/// The agent id of a session rebound as a delegated child, or `None` for a
/// root session.
pub(super) fn read_delegated_agent_id(path: &Path) -> anyhow::Result<Option<String>> {
    match read_header(path)? {
        SessionEntry::Session {
            agent_role: SessionAgentRole::Root,
            ..
        } => Ok(None),
        SessionEntry::Session {
            agent_role: SessionAgentRole::Delegated,
            agent_id: Some(id),
            ..
        } => Ok(Some(id)),
        SessionEntry::Session {
            agent_role: SessionAgentRole::Delegated,
            agent_id: None,
            ..
        } => anyhow::bail!("delegated session header has no agent id"),
        _ => anyhow::bail!("session file does not start with session metadata"),
    }
}

impl Session {
    pub(crate) fn stored_agent_identity(&self) -> anyhow::Result<Option<SavedAgent>> {
        read_agent_identity(&self.path)
    }

    /// The root agent the session reopens under: its own agent, or the
    /// root `/agent:` rebound it from. `None` for a delegated session
    /// written before launch identities were saved; an error for a root
    /// session whose header names no agent.
    pub(crate) fn root_agent(&self) -> anyhow::Result<Option<SavedRoot>> {
        read_root_agent(&self.path)
    }

    /// Rebinds the session to a delegated child agent, only before any
    /// history has been persisted. An initial snapshot is committed atomically
    /// with the identity so reload cannot observe half of the child binding.
    pub(crate) fn rebind_fresh_delegated_agent(
        &self,
        agent: &SavedAgent,
        initial_snapshot: Option<&SessionSnapshot>,
    ) -> anyhow::Result<()> {
        self.rewrite_fresh_delegated_identity(agent, initial_snapshot)
    }

    /// The child agent id when the session was rebound as a delegated agent.
    pub(crate) fn delegated_agent_id(&self) -> anyhow::Result<Option<String>> {
        read_delegated_agent_id(&self.path)
    }

    /// The child agent the session was rebound as, with the fingerprint and
    /// instructions of the definition it was bound under; `None` for a root
    /// session.
    pub(crate) fn delegated_agent(&self) -> anyhow::Result<Option<SavedAgent>> {
        match read_delegated_agent_id(&self.path)? {
            Some(_) => saved_identity(&self.path, None).map(Some),
            None => Ok(None),
        }
    }

    /// Whether a launch that named `definition` may resume session
    /// `target`: it was saved as that agent. Read without opening the
    /// session, which another process may hold.
    pub(crate) fn validate_launch_agent_of(
        target: &SessionTarget,
        definition: &AgentDefinition,
    ) -> anyhow::Result<()> {
        let resolved =
            SessionStore::new(&session_root()?, &target.cwd).resolve_in_workspace(&target.id)?;
        validate_launch(&resolved.path, definition)
    }

    pub(super) fn rewrite_fresh_delegated_identity(
        &self,
        agent: &SavedAgent,
        initial_snapshot: Option<&SessionSnapshot>,
    ) -> anyhow::Result<()> {
        if let Some(snapshot) = initial_snapshot {
            anyhow::ensure!(
                snapshot.session_id().as_str() == self.id,
                "snapshot session id '{}' does not match store id '{}'",
                snapshot.session_id(),
                self.id,
            );
        }
        let mut cursor = self
            .write_lock
            .lock()
            .unwrap_or_else(|poisoned| poisoned.into_inner());
        let contents = fs::read_to_string(&self.path)?;
        let mut lines = contents.lines();
        let header = lines
            .next()
            .ok_or_else(|| anyhow::anyhow!("session file is empty"))?;
        if lines.next().is_some() {
            anyhow::bail!("cannot rebind agent: the session already has history");
        }
        let mut entry: SessionEntry = serde_json::from_str(header)?;
        let SessionEntry::Session {
            version,
            agent_id: stored_id,
            agent_fingerprint,
            agent_prompt,
            agent_role,
            launch_agent,
            ..
        } = &mut entry
        else {
            anyhow::bail!("session file does not start with session metadata");
        };
        // The root's identity moves aside, so a reload can bind the root
        // again and cap the child at its tools. A header already delegated
        // keeps the launch identity it has.
        if agent_role.is_root() {
            let prompt = agent_prompt.take();
            *launch_agent =
                stored_id
                    .take()
                    .zip(agent_fingerprint.take())
                    .map(|(id, fingerprint)| SavedAgent {
                        id,
                        fingerprint,
                        prompt,
                    });
        }
        *stored_id = Some(agent.id.clone());
        *agent_fingerprint = Some(agent.fingerprint.clone());
        *agent_prompt = agent.prompt.clone();
        *agent_role = SessionAgentRole::Delegated;
        if initial_snapshot.is_some() {
            // A header-only file has no history to migrate, so its new root
            // snapshot can use the current format.
            *version = SESSION_VERSION;
        }

        let parent = self
            .path
            .parent()
            .ok_or_else(|| anyhow::anyhow!("session file has no parent directory"))?;
        let mut temporary = tempfile::NamedTempFile::new_in(parent)?;
        set_private_file_permissions(temporary.as_file())?;
        serde_json::to_writer(&mut temporary, &entry)?;
        temporary.write_all(b"\n")?;
        if let Some(snapshot) = initial_snapshot {
            let state = SessionEntry::Node {
                node: SessionNode {
                    id: NodeId::new(),
                    parent_id: None,
                    timestamp: timestamp(),
                    kind: SessionNodeKind::Commit,
                    compaction_facts: None,
                    transition: StoredStateTransition::Snapshot {
                        snapshot: Box::new(snapshot.clone()),
                    },
                    display_messages: Vec::new(),
                    display_keys: Default::default(),
                    display_subagents: Default::default(),
                    display_origins: Default::default(),
                    turn_end: None,
                },
            };
            serde_json::to_writer(&mut temporary, &state)?;
            temporary.write_all(b"\n")?;
        }
        temporary.as_file().sync_all()?;
        temporary.persist(&self.path)?;
        cursor.valid_len = None;
        cursor.invalidate_tree();
        // The index records the agent the session now runs as, with its
        // transcript stats. Refresh them best-effort, like every other
        // persistence operation.
        let _ = index::sync_session_file(&self.session_root, &self.cwd, &self.path);
        Ok(())
    }
}

#[cfg(test)]
#[path = "agent_identity_tests.rs"]
mod tests;