rig_memory/saved.rs
1//! A saved agent's values read without the host that saved them: the keys
2//! rig saves an agent's model and title and the session's current agent
3//! under, typed reads of any saved value, and which agent of a session is
4//! its main one.
5
6use std::collections::BTreeMap;
7
8use serde::de::DeserializeOwned;
9use serde_json::Value;
10
11use crate::{SavedAgent, Session};
12
13/// The key an agent's model is saved under: a string, `vendor/model`.
14pub const MODEL: &str = "rig::model";
15
16/// The key an agent's title is saved under, such as a subagent's task: a
17/// string.
18pub const TITLE: &str = "rig::title";
19
20/// The key the session's current agent is saved under, the agent the user
21/// talks to when none is named: a string, the agent's id. One of the
22/// session's own values.
23pub const CURRENT: &str = "rig::current_agent";
24
25impl SavedAgent {
26 /// Its saved value under `key`, such as a plugin's `goals.goal`, read
27 /// as a `T`: `None` when it has none, an error when the value is not a
28 /// `T`.
29 pub fn value<T: DeserializeOwned>(&self, key: &str) -> Option<Result<T, serde_json::Error>> {
30 value(&self.saved, key)
31 }
32
33 /// Its model, `vendor/model`, when one was saved ([`MODEL`]).
34 pub fn model(&self) -> Option<String> {
35 self.value(MODEL)?.ok()
36 }
37
38 /// Its title, when one was saved ([`TITLE`]).
39 pub fn title(&self) -> Option<String> {
40 self.value(TITLE)?.ok()
41 }
42}
43
44/// The value of `key` in `state`, parsed.
45fn value<T: DeserializeOwned>(
46 state: &BTreeMap<String, Value>,
47 key: &str,
48) -> Option<Result<T, serde_json::Error>> {
49 state.get(key).map(rig_core::json_utils::from_value)
50}
51
52impl Session {
53 /// The session's own saved value under `key` (the [`SESSION`](crate::SESSION)
54 /// log's), read as a `T`: `None` when it has none, an error when the
55 /// value is not a `T`.
56 pub fn value<T: DeserializeOwned>(&self, key: &str) -> Option<Result<T, serde_json::Error>> {
57 value(&self.saved, key)
58 }
59
60 /// The main agent: of the agents nothing spawned and not retired, the
61 /// one [`CURRENT`] names, else the first by id.
62 pub fn main_agent(&self) -> Option<&SavedAgent> {
63 let top = (self.agents.iter()).filter(|agent| agent.parent.is_none() && !agent.retired);
64 let current = self.value::<String>(CURRENT).and_then(Result::ok);
65 let named = top
66 .clone()
67 .find(|agent| Some(&agent.id) == current.as_ref());
68 named.or_else(|| top.min_by_key(|agent| &agent.id))
69 }
70}
71
72#[cfg(test)]
73mod tests;