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
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
//! What a session job's turns owe the session that started them: whether
//! a turn owes its starter the notice of its end, what it reported, what a
//! session that reports to its starter owes it between turns, and the ends
//! and stops no starter took yet (see `sessions/peer_wake.rs`).
//!
//! Notices live in the starter's memory until its turn takes them, so the
//! record keeps what was told until the notice is delivered
//! ([`JobRegistry::delivered`]): a daemon restart before then tells it
//! again as the starter loads.

use std::collections::HashMap;

use serde::{Deserialize, Serialize};

use crate::app::peer_sessions::Stop;

use super::{persist, JobRegistry};
use crate::app::daemon_host::jobs::{
    JobId, JobRecord, JobState, JobStore, JobSubject, TurnEnd, TurnRecord,
};

/// What a session that reports to its starter owes it between turns, as
/// its job keeps it ([`JobRecord::word`]).
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub(in crate::app::daemon_host) struct OwedWord {
    /// The session it reports to.
    pub(in crate::app::daemon_host) starter: rho_sdk::SessionId,
    #[serde(flatten)]
    pub(in crate::app::daemon_host) word: Word,
}

/// Where a session that reports to its starter stands with it.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(tag = "word", rename_all = "snake_case")]
pub(in crate::app::daemon_host) enum Word {
    /// It owes a report: its starter asked for work it has not reported
    /// on.
    Working,
    /// Its last turn answered with `answer` and no report; something may
    /// still wake it to report.
    Unreported { answer: String },
    /// It stopped without a report: it settled with nothing left to wake
    /// it, its last turn having answered with `answer`, or a daemon's end
    /// stopped it, with `answer` absent. Its starter was told, or is told
    /// as it loads, and hears no more of it once that notice is delivered.
    Stopped { answer: Option<String> },
}

/// What a turn's end does to the word its session owes its starter (see
/// [`JobRegistry::end_turn`]).
#[derive(Clone, Debug, PartialEq, Eq)]
pub(in crate::app::daemon_host) enum WordChange {
    /// Nothing: the session does not report to its starter, or the turn
    /// did not answer.
    Keep,
    /// The turn answered with a report: the session owes nothing more.
    Reported,
    /// The turn answered with `answer` and no report: a session that owes
    /// a report now owes it with that answer.
    Answered { answer: String },
    /// The turn ended without answering, as one that failed, and its end is
    /// told: that notice, which the turn's record keeps until it is
    /// delivered, is the word the session owed, so it owes nothing more
    /// until its starter prompts it again.
    Told,
}

impl WordChange {
    /// Applies the change to `record`'s word.
    pub(super) fn apply(self, record: &mut JobRecord) {
        match self {
            Self::Keep => {}
            Self::Reported => record.word = None,
            Self::Answered { answer } => {
                if let Some(owed) = &mut record.word {
                    owed.word = Word::Unreported { answer };
                }
            }
            Self::Told => record.word = None,
        }
    }
}

/// A notice that was delivered: its starter's turn took it (see
/// [`JobRegistry::delivered`]).
#[derive(Clone, Debug, PartialEq, Eq)]
pub(in crate::app::daemon_host) enum Delivered {
    /// The notice of turn `turn`'s end.
    End {
        turn: rho_protocol::TurnId,
        starter: rho_sdk::SessionId,
    },
    /// The notice that the session stopped without a report.
    Stopped { starter: rho_sdk::SessionId },
}

/// A session that stopped without a report, its starter to be told (see
/// [`JobRegistry::stop_words`]).
pub(in crate::app::daemon_host) struct StoppedWord {
    pub(in crate::app::daemon_host) job: JobId,
    pub(in crate::app::daemon_host) session: rho_sdk::SessionId,
    pub(in crate::app::daemon_host) title: Option<String>,
    /// How it stopped: while waiting on the answer to a question it asked
    /// without waiting (see `sessions/self_questions.rs`), or else after
    /// its last turn's answer, or before any.
    pub(in crate::app::daemon_host) stop: Stop,
}

/// A session that reports to its starter, as its job last recorded (see
/// [`JobRegistry::reporters`]).
#[derive(Clone, Debug, PartialEq, Eq)]
pub(in crate::app::daemon_host) struct Reporter {
    pub(in crate::app::daemon_host) starter: rho_sdk::SessionId,
    pub(in crate::app::daemon_host) session: rho_sdk::SessionId,
    pub(in crate::app::daemon_host) title: Option<String>,
}

impl JobRegistry {
    /// Records that job `id`'s session, as it just opened, reports to
    /// `starter`, or to nobody.
    pub(in crate::app::daemon_host) fn set_reports_to(
        &self,
        id: &JobId,
        starter: Option<&rho_sdk::SessionId>,
    ) {
        let mut jobs = self.lock();
        let Some(record) = jobs.get_mut(id) else {
            return;
        };
        if record.reports_to.as_ref() != starter {
            record.reports_to = starter.cloned();
            persist(&self.store, record);
        }
    }

    /// Every session that reports to its starter and whose last turn
    /// completed, as the latest job of its turns recorded them. One whose
    /// last turn ended otherwise was told so.
    pub(in crate::app::daemon_host) fn reporters(&self) -> Vec<Reporter> {
        let jobs = self.lock();
        let mut latest: HashMap<&rho_sdk::SessionId, &JobRecord> = HashMap::new();
        for record in jobs.values() {
            let JobSubject::Session { session } = &record.subject else {
                continue;
            };
            let later = latest
                .get(session)
                .is_none_or(|last| (last.created_at, &last.id) < (record.created_at, &record.id));
            if later {
                latest.insert(session, record);
            }
        }
        latest
            .into_iter()
            .filter(|(_, record)| matches!(record.state, JobState::Ended(TurnEnd::Completed)))
            .filter_map(|(session, record)| {
                Some(Reporter {
                    starter: record.reports_to.clone()?,
                    session: session.clone(),
                    title: record.title.clone(),
                })
            })
            .collect()
    }

    /// Records that job `id`'s turn `turn` owes session `starter` the notice
    /// of its end, as the `sessions` call that started it asked (see
    /// `sessions/peer_wake.rs`). Does nothing once another turn started.
    pub(in crate::app::daemon_host) fn owe_starter(
        &self,
        id: &JobId,
        turn: &rho_protocol::TurnId,
        starter: &rho_sdk::SessionId,
    ) {
        let mut jobs = self.lock();
        if let Some(record) = jobs.get_mut(id) {
            let current = record.turn.as_mut();
            if let Some(turn) = current.filter(|current| current.id == *turn) {
                turn.starter = Some(starter.clone());
                persist(&self.store, record);
            }
        }
    }

    /// Records that job `id`'s session, which reports to `starter`, owes it
    /// a report: `starter` just asked it for work.
    pub(in crate::app::daemon_host) fn owe_word(&self, id: &JobId, starter: &rho_sdk::SessionId) {
        let mut jobs = self.lock();
        if let Some(record) = jobs.get_mut(id) {
            record.word = Some(OwedWord {
                starter: starter.clone(),
                word: Word::Working,
            });
            persist(&self.store, record);
        }
    }

    /// What job `id`'s session owes the session it reports to, if anything.
    pub(in crate::app::daemon_host) fn word_of(&self, id: &JobId) -> Option<OwedWord> {
        self.lock().get(id)?.word.clone()
    }

    /// Job `id`'s session, which reports to its starter, settled with
    /// nothing left to wake it: should its last turn have answered without
    /// a report, it stopped without one. Returns the starter and that
    /// answer, the stop recorded. Never once a turn started: a turn's start
    /// puts the word back to working under this lock (see
    /// [`JobRegistry::start_turn`]), so a stop is never told after it.
    pub(in crate::app::daemon_host) fn stop_unreported(
        &self,
        id: &JobId,
    ) -> Option<(rho_sdk::SessionId, String)> {
        let mut jobs = self.lock();
        let record = jobs.get_mut(id)?;
        let owed = record.word.as_mut()?;
        let Word::Unreported { answer } = &owed.word else {
            return None;
        };
        let answer = answer.clone();
        owed.word = Word::Stopped {
            answer: Some(answer.clone()),
        };
        let starter = owed.starter.clone();
        persist(&self.store, record);
        Some((starter, answer))
    }

    /// Job `id`'s session, which reports to `starter`, is not working on
    /// what it owes `starter`, as a starter that just loaded finds it: it
    /// is not loaded, as after a daemon's end, or settled. Records the
    /// stop and returns it, unless the session owes `starter` nothing or a
    /// turn of it is under way.
    pub(in crate::app::daemon_host) fn stop_word(
        &self,
        id: &JobId,
        starter: &rho_sdk::SessionId,
    ) -> Option<StoppedWord> {
        stop(&self.store, self.lock().get_mut(id)?, starter)
    }

    /// [`Self::stop_word`] for every session that owes `starter` word,
    /// but those `skip` names, as one this daemon has loaded.
    pub(in crate::app::daemon_host) fn stop_words(
        &self,
        starter: &rho_sdk::SessionId,
        skip: impl Fn(&rho_sdk::SessionId) -> bool,
    ) -> Vec<StoppedWord> {
        let mut jobs = self.lock();
        jobs.values_mut()
            .filter(|record| {
                record
                    .subject
                    .session()
                    .is_none_or(|session| !skip(session))
            })
            .filter_map(|record| stop(&self.store, record, starter))
            .collect()
    }

    /// Job `id`'s notice `delivered` reached its starter: the record no
    /// longer keeps it to tell again. Does nothing once a later turn or
    /// word replaced what the notice told.
    pub(in crate::app::daemon_host) fn delivered(&self, id: &JobId, delivered: &Delivered) {
        let mut jobs = self.lock();
        let Some(record) = jobs.get_mut(id) else {
            return;
        };
        let changed = match delivered {
            Delivered::End { turn, starter } => record
                .turn
                .as_mut()
                .filter(|ended| ended.id == *turn && ended.starter.as_ref() == Some(starter))
                .map(|ended| ended.starter = None)
                .is_some(),
            Delivered::Stopped { starter } => {
                let stopped = record.word.as_ref().is_some_and(|owed| {
                    owed.starter == *starter && matches!(owed.word, Word::Stopped { .. })
                });
                if stopped {
                    record.word = None;
                }
                stopped
            }
        };
        if changed {
            persist(&self.store, record);
        }
    }

    /// The session job `id`'s last turn tells of its end, if one does.
    pub(in crate::app::daemon_host) fn starter_of(&self, id: &JobId) -> Option<rho_sdk::SessionId> {
        self.lock().get(id)?.turn.as_ref()?.starter.clone()
    }

    /// What job `id`'s last turn owes `starter`, whose call started it or
    /// the interrupted turn it continues. Call under the job's session's
    /// turn lock, which the turn ends under.
    pub(in crate::app::daemon_host) fn owing(
        &self,
        id: &JobId,
        starter: &rho_sdk::SessionId,
    ) -> Owing {
        let jobs = self.lock();
        let Some(record) = jobs.get(id) else {
            return Owing::Nothing;
        };
        let owes = record
            .turn
            .as_ref()
            .is_some_and(|turn| turn.starter.as_ref() == Some(starter));
        if !owes {
            return Owing::Nothing;
        }
        if record.state.in_progress() {
            return Owing::Running;
        }
        match untold(id, record, starter) {
            Some(untold) => Owing::Ended(untold),
            None => Owing::Nothing,
        }
    }

    /// Job `id`'s last turn's end, which `starter` has yet to take, if it
    /// ended so: see [`Self::untold_ends`].
    pub(in crate::app::daemon_host) fn untold_end(
        &self,
        id: &JobId,
        starter: &rho_sdk::SessionId,
    ) -> Option<UntoldEnd> {
        untold(id, self.lock().get(id)?, starter)
    }

    /// The ended last turns that `starter` started, or that continue one it
    /// started, which `starter` has yet to take: a daemon's end interrupted
    /// them, they ended while `starter` was not loaded to hear, or their
    /// notice was not delivered before `starter` unloaded or the daemon
    /// ended. Leaves out the sessions `skip` names, as one whose turn will
    /// continue and tell of its own end. Each stays recorded until its
    /// notice is [`Self::delivered`].
    pub(in crate::app::daemon_host) fn untold_ends(
        &self,
        starter: &rho_sdk::SessionId,
        skip: impl Fn(&rho_sdk::SessionId) -> bool,
    ) -> Vec<UntoldEnd> {
        let jobs = self.lock();
        jobs.iter()
            .filter(|(_, record)| {
                record
                    .subject
                    .session()
                    .is_none_or(|session| !skip(session))
            })
            .filter_map(|(id, record)| untold(id, record, starter))
            .collect()
    }
}

/// What a session job's turn that ended still owes the session that
/// started it, as [`JobRegistry::end_turn`] records with the end.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(in crate::app::daemon_host) enum StarterNotice {
    /// Nothing: the turn tells nothing of itself.
    Nothing,
    /// The notice of its end, if the turn owes one, with what it reported,
    /// kept until the notice is delivered.
    Owed {
        report: Option<crate::app::starter_report::ReportKind>,
    },
}

impl StarterNotice {
    /// Records what `turn`, which just ended, still owes its starter.
    pub(super) fn record(self, turn: &mut TurnRecord) {
        match self {
            Self::Nothing => turn.starter = None,
            Self::Owed { report } => turn.report = report,
        }
    }
}

/// What a session job's last turn owes the session that started it (see
/// [`JobRegistry::owing`]).
pub(in crate::app::daemon_host) enum Owing {
    Nothing,
    /// The turn runs, and tells of its end as it ends.
    Running,
    /// The turn ended, and `starter` has yet to take its end.
    Ended(UntoldEnd),
}

/// Job `id`'s last turn's end, `record`'s, if `starter` has yet to take
/// it.
fn untold(id: &JobId, record: &JobRecord, starter: &rho_sdk::SessionId) -> Option<UntoldEnd> {
    let JobSubject::Session { session } = &record.subject else {
        return None;
    };
    let (JobState::Ended(end), Some(turn)) = (&record.state, record.turn.as_ref()) else {
        return None;
    };
    if turn.starter.as_ref() != Some(starter) {
        return None;
    }
    Some(UntoldEnd {
        job: id.clone(),
        turn: turn.id.clone(),
        session: session.clone(),
        title: record.title.clone(),
        end: end.clone(),
        outcome: record.outcome.clone(),
        report: turn.report,
    })
}

/// Records that `record`'s session, which reports to `starter`, stopped
/// without a report (see [`JobRegistry::stop_word`]).
fn stop(
    store: &JobStore,
    record: &mut JobRecord,
    starter: &rho_sdk::SessionId,
) -> Option<StoppedWord> {
    let JobSubject::Session { session } = &record.subject else {
        return None;
    };
    // A turn under way, as one a reopen just started, works on it.
    if record.state.in_progress() {
        return None;
    }
    let owed = record
        .word
        .as_mut()
        .filter(|owed| owed.starter == *starter)?;
    let answer = match &owed.word {
        Word::Working => None,
        Word::Unreported { answer } => Some(answer.clone()),
        Word::Stopped { answer } => answer.clone(),
    };
    // Each load of the starter tells a stop again until it is delivered,
    // which writes it once.
    let first = !matches!(owed.word, Word::Stopped { .. });
    owed.word = Word::Stopped {
        answer: answer.clone(),
    };
    let stop = match (super::questions::waits_on(record), answer) {
        (Some(ask), _) => Stop::Asking { ask },
        (None, Some(answer)) => Stop::Unreported { answer },
        (None, None) => Stop::Interrupted,
    };
    let stopped = StoppedWord {
        job: record.id.clone(),
        session: session.clone(),
        title: record.title.clone(),
        stop,
    };
    if first {
        persist(store, record);
    }
    Some(stopped)
}

/// A session's ended turn whose starter has yet to take its end (see
/// [`JobRegistry::untold_ends`]).
pub(in crate::app::daemon_host) struct UntoldEnd {
    pub(in crate::app::daemon_host) job: JobId,
    pub(in crate::app::daemon_host) turn: rho_protocol::TurnId,
    pub(in crate::app::daemon_host) session: rho_sdk::SessionId,
    pub(in crate::app::daemon_host) title: Option<String>,
    pub(in crate::app::daemon_host) end: TurnEnd,
    pub(in crate::app::daemon_host) outcome: Option<rho_protocol::TurnOutcome>,
    /// What the turn reported, for a session that reports to its starter.
    pub(in crate::app::daemon_host) report: Option<crate::app::starter_report::ReportKind>,
}

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