rho-coding-agent 3.12.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
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
//! The daemon's job registry: every unit of agent work the daemon knows,
//! with its state, where it runs, and the session it writes.
//!
//! A job is the turns of a session the daemon hosts (see `sessions/`), a
//! workflow run one of those sessions drives, or a subagent run, whose
//! parent is the job of the session or workflow run that started it (see
//! `subagents.rs`).
//! A job's state moves only through the events in `state.rs`, and every
//! transition rewrites the job's durable record (see `store.rs`), so a
//! daemon that restarts lists the jobs its predecessor ran and marks the
//! ones it left unfinished as interrupted.
//!
//! A record is deleted with a session the daemon discards having saved
//! nothing (see `sessions/unload.rs`), since no request could reopen it,
//! and once an ended subagent or workflow run falls beyond the newest
//! `retention::ENDED_RUNS_KEPT`. Session jobs otherwise stay.

use std::path::PathBuf;

use serde::{Deserialize, Serialize};

use super::sessions::KeyDigest;
use crate::{app::subagent_pool::RunStarter, caller_context::CallerContext, workflow::RunId};

mod registry;
mod retention;
mod state;
mod store;

#[cfg(test)]
pub(super) use registry::Word;
pub(super) use registry::{
    AnswerRefused, Delivered, JobRegistry, Moved, OwedWord, Owing, RegisterError, SessionJob,
    StartTurnError, StarterNotice, TransitionError, UntoldEnd, WordChange,
};
pub(super) use registry::{HeldBy, QuestionState, SavedQuestion};
pub(super) use state::{JobEvent, JobState, TurnEnd};
pub(super) use store::JobStore;

/// One job's identity: a UUID v4, as a string on the wire and as the name
/// of its record file. Only [`JobId::generate`] and [`JobId::parse`] make
/// one, so every id names a safe file.
#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
#[serde(try_from = "String", into = "String")]
pub(super) struct JobId(String);

/// A string that is not a job id.
#[derive(Clone, Copy, Debug, PartialEq, Eq, thiserror::Error)]
#[error("not a job id")]
pub(super) struct InvalidJobId;

impl JobId {
    /// A new, random id.
    pub(super) fn generate() -> Self {
        Self(uuid::Uuid::new_v4().hyphenated().to_string())
    }

    /// The id `value` names, in its canonical (lowercase, hyphenated) form.
    pub(super) fn parse(value: &str) -> Result<Self, InvalidJobId> {
        uuid::Uuid::parse_str(value)
            .map(|uuid| Self(uuid.hyphenated().to_string()))
            .map_err(|_| InvalidJobId)
    }

    pub(super) fn as_str(&self) -> &str {
        &self.0
    }
}

impl std::fmt::Display for JobId {
    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        formatter.write_str(&self.0)
    }
}

impl TryFrom<String> for JobId {
    type Error = InvalidJobId;

    fn try_from(value: String) -> Result<Self, Self::Error> {
        Self::parse(&value)
    }
}

impl From<JobId> for String {
    fn from(id: JobId) -> Self {
        id.0
    }
}

/// What a job runs, and what that run is known by. A record holds it
/// flattened: `kind` names the variant beside its fields.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(tag = "kind", rename_all = "snake_case")]
pub(super) enum JobSubject {
    /// The turns of a session the daemon hosts, prompted one by one.
    Session { session: rho_sdk::SessionId },
    /// One subagent run, started by the session or workflow job that is its
    /// parent. `session` is the session it shows its events under: the Rho
    /// session a Rho run writes, or the one a run on Claude Code or
    /// Antigravity is recorded under, whose file holds its prompt and reply;
    /// `None` for such a run in a record an earlier daemon wrote.
    /// `run` is the run's id, which names its artifact directory; `None`
    /// in a record written before jobs kept it. `worktree` is the git
    /// worktree the run works in, for a run the `agent` tool started with
    /// `worktree: true`. A session job's worktree, which the daemon owns,
    /// prunes and restores, is the record's own; the daemon cleans up a
    /// run's as one no session owns. Stored as `run_worktree`: the subject
    /// is flattened into the record, whose `worktree` key would take it.
    /// `started_by` says whether Rho started the run or the agent runtime
    /// of its parent's session did; a record that lacks it is Rho's.
    Subagent {
        #[serde(default, skip_serializing_if = "Option::is_none")]
        session: Option<rho_sdk::SessionId>,
        #[serde(default, skip_serializing_if = "Option::is_none")]
        run: Option<String>,
        #[serde(
            default,
            rename = "run_worktree",
            skip_serializing_if = "Option::is_none"
        )]
        worktree: Option<rho_protocol::SessionWorktree>,
        #[serde(default, skip_serializing_if = "RunStarter::is_rho")]
        started_by: RunStarter,
    },
    /// One drive of workflow run `workflow_run`, started by the session job
    /// that is its parent. The run's agent nodes are its subagent jobs.
    Workflow { workflow_run: RunId },
}

impl JobSubject {
    /// The session the job writes or is recorded under: a session job's,
    /// or a subagent run's. `None` for any other job.
    pub(super) fn session(&self) -> Option<&rho_sdk::SessionId> {
        match self {
            Self::Session { session }
            | Self::Subagent {
                session: Some(session),
                ..
            } => Some(session),
            Self::Subagent { session: None, .. } | Self::Workflow { .. } => None,
        }
    }
}

/// How a session job's turns get under way.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub(super) enum Admission {
    /// At once, as a person's session's do.
    #[default]
    Immediate,
    /// Once they have a slot in the daemon-wide agent budget, which
    /// subagent runs share, as the turns of a session another session
    /// started do (#1714).
    SharedBudget,
}

/// What the daemon knows about one job, as its record file holds it.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub(super) struct JobRecord {
    pub(super) id: JobId,
    #[serde(flatten)]
    pub(super) subject: JobSubject,
    pub(super) state: JobState,
    /// The workspace the job runs in, canonicalized.
    pub(super) workspace: PathBuf,
    /// The job that started this one, such as a subagent run's parent; `None`
    /// for a job a client started.
    pub(super) parent: Option<JobId>,
    /// What a session job's turn under way, or its last, may do through
    /// session control, as the request that started it said (#1780), held
    /// to `grant_limit`; before the first turn, what the session opened
    /// with. The session's `RHO_SESSION_*` variables are written from it.
    /// Other jobs keep [`CallerContext::ROOT`].
    #[serde(default = "root_grant", skip_serializing_if = "CallerContext::is_root")]
    pub(super) grant: CallerContext,
    /// The most `grant` may ever be, for a session that opened under a
    /// limit, as one an agent starts through session control does (#1796):
    /// the grant it opened with, which is no more than a session its
    /// parent's turn starts may have. Set once, when the session opens.
    /// `None` for a session that opened without a limit, as a person's
    /// does, which each prompt grants anew, and for other jobs.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub(super) grant_limit: Option<CallerContext>,
    /// How a session job's turns get under way; subagent and workflow jobs
    /// keep [`Admission::Immediate`], their runs taking capacity as
    /// `subagents.rs` says.
    #[serde(default, skip_serializing_if = "Admission::is_immediate")]
    pub(super) admission: Admission,
    /// Unix time, in seconds, when the job was created.
    pub(super) created_at: u64,
    /// Unix time, in seconds, of the job's last transition.
    pub(super) updated_at: u64,
    /// How the job's last turn ended, as the session's clients were told,
    /// so a later daemon that reopens the session tells them again (#1661).
    /// `None` while no turn has ended, for a turn the daemon's stop or death
    /// interrupted, and for jobs other than a session's.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub(super) outcome: Option<rho_protocol::TurnOutcome>,
    /// A session job's turn under way, or its last one, which `state` and
    /// `outcome` are of. `None` before the job's first turn and for jobs
    /// other than a session's. Kept in the record so a later daemon names
    /// the turn by the same id and still answers a prompt sent again with
    /// its key (#1777).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub(super) turn: Option<TurnRecord>,
    /// The git worktree a session job's session works in, which the daemon
    /// added when the session opened (#1673); `workspace` is in it. `None`
    /// for a session in its own workspace and for other jobs.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub(super) worktree: Option<rho_protocol::SessionWorktree>,
    /// The commit `worktree` had checked out when the daemon's cleanup
    /// removed it, which a reopen or read adds it back at. `None` while it
    /// is on disk, and for one a person removed: the daemon never adds that
    /// back.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub(super) worktree_removed_at: Option<String>,
    /// Whether the daemon's restart in place interrupted this session job's
    /// last turn, one that [`TurnRecord::continues_after_restart`], which
    /// the restarted daemon then continues (see
    /// `sessions/restart_resume.rs`). Only that interruption sets it; the
    /// job's next transition clears it, and so does every daemon start,
    /// which takes it (see [`JobRegistry::take_restart_interrupted`]).
    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
    pub(super) resume_after_restart: bool,
    /// The agent the job runs as now, and what runs it: a subagent run's as
    /// it started, a session job's as its session last opened or an
    /// `/agent:` rebind moved it. `None` for a workflow's drive, and in a
    /// record an earlier daemon wrote until its session reopens.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub(super) agent: Option<JobAgent>,
    /// What the job shows as: a subagent run's title, once its status
    /// names it, and until then, from the moment the run queues, its
    /// task's placeholder (`title::placeholder`), which stays if the run
    /// is never titled; and a session job's session title, as it last
    /// opened, was titled or renamed, and until it is titled, from the
    /// moment its first prompt queues, that prompt's placeholder, which
    /// stays if it never is. `None` until a session's first prompt, for a
    /// run or session whose prompt has no placeholder, for a workflow's
    /// drive, and in a record an earlier daemon wrote: for good for a
    /// subagent run's, and until it reopens titled or is renamed for a
    /// session job's.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub(super) title: Option<String>,
    /// What a session that reports to its starter owes it between turns,
    /// kept here so a starter that loads later, after a daemon restart
    /// too, hears of it (see `sessions/peer_wake.rs`). `None` while it owes
    /// nothing, and for other sessions and jobs.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub(super) word: Option<OwedWord>,
    /// The questions a session that reports to its starter asked without
    /// waiting whose answers no turn took yet, oldest first (see
    /// `sessions/self_questions.rs`). Empty for other sessions and jobs.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub(super) questions: Vec<SavedQuestion>,
    /// Whether the record has a file. Never read from one: a record a file
    /// holds is kept.
    #[serde(skip)]
    pub(super) keeping: Keeping,
}

/// An agent a job runs as, by id, and what runs its turns.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub(super) struct JobAgent {
    pub(super) id: String,
    /// Read leniently: a runtime a later daemon recorded reads as unknown.
    pub(super) engine: rho_protocol::AgentRuntime,
}

/// Where a job's record lives.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub(super) enum Keeping {
    /// In the store, so later daemons know the job.
    #[default]
    Stored,
    /// In this daemon's memory alone, as the job of a session opened
    /// without saving is, and the jobs it starts: a turn's outcome holds
    /// its answer, which must not reach disk.
    MemoryOnly,
}

/// One turn of a session job, as its record keeps it.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub(super) struct TurnRecord {
    pub(super) id: rho_protocol::TurnId,
    /// The digest of the key the prompt that started the turn named, if it
    /// named one; never the key.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub(super) key_digest: Option<KeyDigest>,
    /// Whether the turn began, as its prompt's request was answered (see
    /// `sessions::turn::PromptStart`). A turn that did not begin ran
    /// nothing, so a prompt sent again with its key starts a turn.
    #[serde(default)]
    pub(super) began: bool,
    /// The user message the turn inserted, as it began, if it inserted one
    /// the daemon knew then, which a prompt sent again answers with.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub(super) message: Option<rho_protocol::MessageId>,
    /// Whether a restart in place that interrupts the turn has the
    /// restarted daemon continue it (see `sessions/restart_resume.rs`):
    /// only a turn with no time limit, of a session whose client takes the
    /// turns the daemon starts (`idle_wake: turn`). The turn that continues
    /// it is one the daemon starts, with no limit, so it must not run a
    /// turn its client would not have, nor outlive the limit of a turn
    /// that had one, such as `rho run --detach --timeout`'s.
    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
    pub(super) continues_after_restart: bool,
    /// The session whose `sessions` call started the turn, at any depth,
    /// or the interrupted turn this one continues, while the turn owes it
    /// the notice of its end (see `sessions/peer_wake.rs`). Cleared once a
    /// turn of the starter took that notice ([`JobRegistry::delivered`]).
    /// The notice lives in the daemon's memory until then, so a turn whose
    /// notice was not delivered, as one the daemon's end interrupted, tells
    /// a starter that loads later, in this daemon or a later one (see
    /// [`JobRegistry::untold_ends`]).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub(super) starter: Option<rho_sdk::SessionId>,
    /// What the turn reported to the session that started its session, for
    /// a session that reports to its starter, so a starter told of the end
    /// after a restart reads it as the report it was.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub(super) report: Option<crate::app::starter_report::ReportKind>,
}

impl TurnRecord {
    /// A turn about to start, under a new id, for a prompt that named the
    /// key `key_digest` is of, which no restart continues.
    pub(super) fn starting(key_digest: Option<KeyDigest>) -> Self {
        Self {
            id: rho_protocol::TurnId::new(uuid::Uuid::new_v4().hyphenated().to_string()),
            key_digest,
            began: false,
            message: None,
            continues_after_restart: false,
            starter: None,
            report: None,
        }
    }
}

impl JobRecord {
    /// A new job `id` for the turns of `session` in `workspace`, before its
    /// first turn.
    pub(super) fn new_session(id: JobId, workspace: PathBuf, session: rho_sdk::SessionId) -> Self {
        Self::new(
            id,
            JobSubject::Session { session },
            JobState::Idle,
            workspace,
            None,
        )
    }

    /// A new job for subagent run `run` that job `parent` started in
    /// `workspace`, waiting for capacity.
    pub(super) fn new_subagent(
        parent: JobId,
        workspace: PathBuf,
        session: Option<rho_sdk::SessionId>,
        run: String,
        worktree: Option<rho_protocol::SessionWorktree>,
    ) -> Self {
        Self::new(
            JobId::generate(),
            JobSubject::Subagent {
                session,
                run: Some(run),
                worktree,
                started_by: RunStarter::Rho,
            },
            JobState::Queued,
            workspace,
            Some(parent),
        )
    }

    /// A new job for run `run` of a child that the agent runtime of job
    /// `parent`'s session started on its own in `workspace`, recorded under
    /// `session`. It takes no capacity of its own (its parent's turn holds
    /// it), so it is queued only until its run's first status.
    pub(super) fn new_runtime_child(
        parent: JobId,
        workspace: PathBuf,
        session: Option<rho_sdk::SessionId>,
        run: String,
    ) -> Self {
        Self::new(
            JobId::generate(),
            JobSubject::Subagent {
                session,
                run: Some(run),
                worktree: None,
                started_by: RunStarter::Runtime,
            },
            JobState::Queued,
            workspace,
            Some(parent),
        )
    }

    /// A new job for a drive of workflow run `run` that job `parent`
    /// started in `workspace`, running from the start: its agent nodes wait
    /// for capacity, the drive does not.
    pub(super) fn new_workflow(parent: JobId, workspace: PathBuf, run: RunId) -> Self {
        Self::new(
            JobId::generate(),
            JobSubject::Workflow { workflow_run: run },
            JobState::Running,
            workspace,
            Some(parent),
        )
    }

    /// The grant a request that asks for `asked` gets on this job: `asked`
    /// held to the job's limit, if it has one. Every grant the record takes
    /// after it opens goes through here.
    pub(super) fn held(&self, asked: CallerContext) -> CallerContext {
        match &self.grant_limit {
            Some(limit) => asked.within(limit),
            None => asked,
        }
    }

    fn new(
        id: JobId,
        subject: JobSubject,
        state: JobState,
        workspace: PathBuf,
        parent: Option<JobId>,
    ) -> Self {
        let now = unix_now();
        Self {
            id,
            subject,
            state,
            workspace,
            parent,
            grant: CallerContext::ROOT,
            grant_limit: None,
            admission: Admission::Immediate,
            created_at: now,
            updated_at: now,
            outcome: None,
            turn: None,
            worktree: None,
            worktree_removed_at: None,
            resume_after_restart: false,
            agent: None,
            title: None,
            word: None,
            questions: Vec::new(),
            keeping: Keeping::Stored,
        }
    }
}

/// The grant of a record that names none.
fn root_grant() -> CallerContext {
    CallerContext::ROOT
}

impl Admission {
    fn is_immediate(&self) -> bool {
        *self == Self::Immediate
    }
}

/// The current Unix time in seconds; 0 on a clock set before 1970.
pub(super) fn unix_now() -> u64 {
    std::time::SystemTime::now()
        .duration_since(std::time::UNIX_EPOCH)
        .map_or(0, |since_epoch| since_epoch.as_secs())
}