Skip to main content

byob_types/
routine.rs

1//! Routines: saved instructions byob carries out by itself, on a schedule or by hand ("Every
2//! morning, search the web for a deal on a new loom"). Each run is a chat; a run that finds
3//! something calls `report`, and the user hears about it.
4//!
5//! The engine keeps routines in `<config>/routines.json` and each one's runs in
6//! `<data>/routine-runs/<id>.json`; clients get them over the protocol (cap `routines`).
7//! Everything here is untrusted when it arrives (a client's save, a model's tool call, a hand
8//! edit): [`Routine::validated`] trims and refuses what doesn't fit. Whether a schedule's rule
9//! makes sense is the engine's check (it reads rules with `byob-when`).
10
11use serde::{Deserialize, Serialize};
12use serde_json::Value;
13
14use crate::config::Approvals;
15
16/// Most routines one byob keeps.
17pub const MAX_ROUTINES: usize = 200;
18/// Longest routine name (characters).
19pub const MAX_NAME_CHARS: usize = 80;
20/// Longest instructions (bytes).
21pub const MAX_INSTRUCTIONS_BYTES: usize = 8 * 1024;
22/// Longest routine id.
23pub const MAX_ID_CHARS: usize = 64;
24/// Most triggers on one routine.
25pub const MAX_TRIGGERS: usize = 8;
26/// Most per-tool grants on one routine.
27pub const MAX_GRANTS: usize = 64;
28/// Most report channels on one routine.
29pub const MAX_CHANNELS: usize = 8;
30/// Most runs kept (with their chats) per routine.
31pub const MAX_KEEP: u32 = 200;
32/// Runs kept when a routine doesn't say.
33pub const DEFAULT_KEEP: u32 = 30;
34/// Most run records kept per routine (older runs beyond `keep` keep only their report).
35pub const MAX_RUN_RECORDS: usize = 200;
36/// Longest report title as kept (characters): a notification's headline.
37pub const MAX_REPORT_TITLE_CHARS: usize = 80;
38/// Longest report body as kept (characters): a few lines; details stay in the run's chat.
39pub const MAX_REPORT_BODY_CHARS: usize = 2000;
40/// Longest report body (bytes).
41pub const MAX_REPORT_BODY_BYTES: usize = 8 * 1024;
42/// Longest text field of a trigger (a rule, a time, a zone, a plugin or trigger id).
43pub const MAX_TRIGGER_TEXT: usize = 500;
44/// Largest plugin trigger `params` (JSON bytes).
45pub const MAX_TRIGGER_PARAMS_BYTES: usize = 8 * 1024;
46/// The built-in channel: a desktop notification.
47pub const CHANNEL_DESKTOP: &str = "desktop";
48
49fn yes() -> bool {
50    true
51}
52
53fn read_only() -> Approvals {
54    Approvals::ReadOnly
55}
56
57fn default_keep() -> u32 {
58    DEFAULT_KEEP
59}
60
61fn desktop() -> Vec<String> {
62    vec![CHANNEL_DESKTOP.to_owned()]
63}
64
65/// A saved routine.
66#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
67pub struct Routine {
68    /// `[a-z0-9-]`, made by the engine for new routines.
69    #[serde(default)]
70    pub id: String,
71    pub name: String,
72    /// What a run is asked to do (the prompt).
73    pub instructions: String,
74    #[serde(default = "yes")]
75    pub enabled: bool,
76    /// What starts it besides Run now.
77    #[serde(default)]
78    pub when: Vec<Trigger>,
79    /// The project (workspace id) its runs work in; `None`: a folder of its own.
80    #[serde(default, skip_serializing_if = "Option::is_none")]
81    pub project: Option<String>,
82    /// The model profile its runs use; `None`: the default model.
83    #[serde(default, skip_serializing_if = "Option::is_none")]
84    pub model: Option<String>,
85    /// What its runs may do without asking (default Read only).
86    #[serde(default = "read_only")]
87    pub allowed: Approvals,
88    /// Tools its runs may call without asking beyond `allowed` ("Always for this routine").
89    #[serde(default, skip_serializing_if = "Vec::is_empty")]
90    pub grants: Vec<String>,
91    /// When a run tells the user.
92    #[serde(default)]
93    pub tell: Tell,
94    /// Where reports go (`desktop`, or a plugin's `plugin:channel`).
95    #[serde(default = "desktop")]
96    pub channels: Vec<String>,
97    /// What happens to runs missed while byob wasn't running.
98    #[serde(default)]
99    pub missed: Missed,
100    /// How many runs (with their chats) to keep.
101    #[serde(default = "default_keep")]
102    pub keep: u32,
103    /// Milliseconds since the epoch; set by the engine.
104    #[serde(default)]
105    pub created_at: i64,
106}
107
108impl Default for Routine {
109    fn default() -> Self {
110        Self {
111            id: String::new(),
112            name: String::new(),
113            instructions: String::new(),
114            enabled: true,
115            when: Vec::new(),
116            project: None,
117            model: None,
118            allowed: Approvals::ReadOnly,
119            grants: Vec::new(),
120            tell: Tell::default(),
121            channels: desktop(),
122            missed: Missed::default(),
123            keep: DEFAULT_KEEP,
124            created_at: 0,
125        }
126    }
127}
128
129/// What starts a routine.
130#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
131#[serde(tag = "type", rename_all = "snake_case")]
132pub enum Trigger {
133    /// A schedule: `rule` an RRULE (`FREQ=DAILY`, `FREQ=WEEKLY;BYDAY=MO,WE`,
134    /// `FREQ=HOURLY;INTERVAL=2`), `at` a 24-hour `HH:MM`, `zone` an IANA zone (none: the
135    /// user's), `start` the first day `YYYY-MM-DD`.
136    Schedule {
137        rule: String,
138        #[serde(default)]
139        at: String,
140        #[serde(default, skip_serializing_if = "Option::is_none")]
141        zone: Option<String>,
142        #[serde(default, skip_serializing_if = "Option::is_none")]
143        start: Option<String>,
144    },
145    /// A plugin's trigger (`trigger` of plugin `plugin`, with its `params`).
146    Plugin {
147        plugin: String,
148        trigger: String,
149        #[serde(default)]
150        params: Value,
151    },
152    /// A trigger a newer byob wrote: kept out of the way, never fires.
153    #[serde(other)]
154    Unknown,
155}
156
157/// When a run tells the user.
158#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
159#[serde(rename_all = "snake_case")]
160pub enum Tell {
161    /// Only runs that call `report`.
162    #[default]
163    Found,
164    /// Every run (a quiet one says it found nothing).
165    Always,
166    /// Never: reports are only kept.
167    Never,
168}
169
170/// Runs missed while byob wasn't running (or the computer slept).
171#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
172#[serde(rename_all = "snake_case")]
173pub enum Missed {
174    /// Made up once, never once per missed slot.
175    #[default]
176    Once,
177    /// Not made up.
178    Skip,
179}
180
181/// `[a-z0-9-]`, 1 to [`MAX_ID_CHARS`].
182pub fn id_ok(id: &str) -> bool {
183    (1..=MAX_ID_CHARS).contains(&id.len()) && id.bytes().all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b == b'-')
184}
185
186/// A new id from a name: `loom-deals`, `loom-deals-2` when taken.
187pub fn new_id(name: &str, taken: impl Fn(&str) -> bool) -> String {
188    let mut slug = String::new();
189    for c in name.chars().flat_map(char::to_lowercase) {
190        if c.is_ascii_alphanumeric() {
191            slug.push(c);
192        } else if !slug.ends_with('-') && !slug.is_empty() {
193            slug.push('-');
194        }
195        if slug.len() >= 40 {
196            break;
197        }
198    }
199    let slug = slug.trim_matches('-');
200    let base = if slug.is_empty() { "routine" } else { slug };
201    if !taken(base) {
202        return base.to_owned();
203    }
204    (2..10_000u32).map(|n| format!("{base}-{n}")).find(|id| !taken(id)).unwrap_or_else(|| format!("{base}-{}", name.len()))
205}
206
207fn long(s: &str, max: usize) -> bool {
208    s.chars().count() > max
209}
210
211impl Routine {
212    /// Check an untrusted routine: trims text, refuses what doesn't fit. The id may be empty
213    /// (a new routine: the engine makes one); otherwise it must be [`id_ok`].
214    pub fn validated(mut self) -> Result<Self, String> {
215        self.id = self.id.trim().to_owned();
216        self.name = self.name.trim().to_owned();
217        self.instructions = self.instructions.trim().to_owned();
218        if !self.id.is_empty() && !id_ok(&self.id) {
219            return Err(format!("{:?} isn't a routine id", self.id.chars().take(80).collect::<String>()));
220        }
221        if self.name.is_empty() {
222            return Err("a routine needs a name".into());
223        }
224        if long(&self.name, MAX_NAME_CHARS) {
225            return Err(format!("routine names are limited to {MAX_NAME_CHARS} characters"));
226        }
227        if self.instructions.is_empty() {
228            return Err("a routine needs instructions (what each run should do)".into());
229        }
230        if self.instructions.len() > MAX_INSTRUCTIONS_BYTES {
231            return Err(format!("a routine's instructions are limited to {} KB", MAX_INSTRUCTIONS_BYTES / 1024));
232        }
233        if self.when.len() > MAX_TRIGGERS {
234            return Err(format!("a routine has at most {MAX_TRIGGERS} triggers"));
235        }
236        for t in &mut self.when {
237            match t {
238                Trigger::Schedule { rule, at, zone, start } => {
239                    *rule = rule.trim().to_owned();
240                    *at = at.trim().to_owned();
241                    for s in [&mut *zone, &mut *start] {
242                        if let Some(v) = s {
243                            *v = v.trim().to_owned();
244                        }
245                        if s.as_deref().is_some_and(str::is_empty) {
246                            *s = None;
247                        }
248                    }
249                    let texts = [Some(rule.as_str()), Some(at.as_str()), zone.as_deref(), start.as_deref()];
250                    if texts.into_iter().flatten().any(|s| long(s, MAX_TRIGGER_TEXT)) {
251                        return Err("a schedule's text is too long".into());
252                    }
253                }
254                Trigger::Plugin { plugin, trigger, params } => {
255                    if !crate::config::plugin_id_ok(plugin) {
256                        return Err(format!("{:?} isn't a plugin id", plugin.chars().take(60).collect::<String>()));
257                    }
258                    if trigger.is_empty() || long(trigger, MAX_TRIGGER_TEXT) {
259                        return Err("bad plugin trigger".into());
260                    }
261                    if serde_json::to_string(params).map_or(usize::MAX, |s| s.len()) > MAX_TRIGGER_PARAMS_BYTES {
262                        return Err("a trigger's settings are too large".into());
263                    }
264                }
265                Trigger::Unknown => {}
266            }
267        }
268        for o in [&mut self.project, &mut self.model] {
269            if let Some(v) = o {
270                *v = v.trim().to_owned();
271            }
272            if o.as_deref().is_some_and(str::is_empty) {
273                *o = None;
274            }
275            if o.as_deref().is_some_and(|v| long(v, 200)) {
276                return Err("bad project or model id".into());
277            }
278        }
279        self.grants.retain(|g| !g.trim().is_empty());
280        self.grants.sort();
281        self.grants.dedup();
282        if self.grants.len() > MAX_GRANTS || self.grants.iter().any(|g| long(g, 200)) {
283            return Err(format!("a routine has at most {MAX_GRANTS} tool grants"));
284        }
285        self.channels.retain(|c| !c.trim().is_empty());
286        self.channels.dedup();
287        if self.channels.len() > MAX_CHANNELS || self.channels.iter().any(|c| long(c, 200)) {
288            return Err(format!("a routine has at most {MAX_CHANNELS} channels"));
289        }
290        if self.keep == 0 || self.keep > MAX_KEEP {
291            return Err(format!("a routine keeps between 1 and {MAX_KEEP} runs"));
292        }
293        Ok(self)
294    }
295
296    /// Its schedules (rule, at, zone, start).
297    pub fn schedules(&self) -> impl Iterator<Item = (&str, &str, Option<&str>, Option<&str>)> {
298        self.when.iter().filter_map(|t| match t {
299            Trigger::Schedule { rule, at, zone, start } => Some((rule.as_str(), at.as_str(), zone.as_deref(), start.as_deref())),
300            _ => None,
301        })
302    }
303}
304
305/// How a run went.
306#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
307#[serde(rename_all = "snake_case")]
308pub enum RunStatus {
309    /// Due, waiting for a free run slot (at most a few routine runs at once).
310    Queued,
311    /// Working.
312    #[default]
313    Running,
314    /// Stopped at a call it isn't allowed to make: waiting for a person.
315    Waiting,
316    /// Finished and reported something.
317    Reported,
318    /// Finished with nothing to report.
319    Quiet,
320    /// Ended with an error.
321    Failed,
322    /// Stopped by a person (or by byob quitting).
323    Stopped,
324    /// Due while the previous run was still going: not started.
325    Skipped,
326    /// A status a newer byob wrote.
327    #[serde(other)]
328    Unknown,
329}
330
331impl RunStatus {
332    /// Still going (or about to).
333    pub fn active(self) -> bool {
334        matches!(self, Self::Queued | Self::Running | Self::Waiting)
335    }
336
337    /// In words: `Nothing new`, `Waiting for you`.
338    pub fn label(self) -> &'static str {
339        match self {
340            Self::Queued => "Waiting to start",
341            Self::Running => "Running",
342            Self::Waiting => "Waiting for you",
343            Self::Reported => "Reported",
344            Self::Quiet => "Nothing new",
345            Self::Failed => "Failed",
346            Self::Stopped => "Stopped",
347            Self::Skipped => "Skipped (the last run was still going)",
348            Self::Unknown => "Unknown",
349        }
350    }
351}
352
353/// What started a run.
354#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
355#[serde(rename_all = "snake_case")]
356pub enum RunCause {
357    /// Its schedule.
358    #[default]
359    Schedule,
360    /// Run now (a person or the model's `run_routine`).
361    Manual,
362    /// A plugin's trigger.
363    Plugin,
364    #[serde(other)]
365    Unknown,
366}
367
368/// What a run reported (`report { title, body }`).
369#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
370pub struct Report {
371    pub title: String,
372    #[serde(default)]
373    pub body: String,
374}
375
376impl Report {
377    /// Trimmed and cut to size (a model wrote it): the title to one line of at most
378    /// [`MAX_REPORT_TITLE_CHARS`], cut at a word with "…"; the body to
379    /// [`MAX_REPORT_BODY_CHARS`].
380    pub fn clean(title: &str, body: &str) -> Self {
381        let title = title.split_whitespace().collect::<Vec<_>>().join(" ");
382        let title = if title.chars().count() <= MAX_REPORT_TITLE_CHARS {
383            title
384        } else {
385            let cut: String = title.chars().take(MAX_REPORT_TITLE_CHARS - 1).collect();
386            // At the last space, unless that leaves too little.
387            let at = cut.rfind(' ').filter(|i| *i >= MAX_REPORT_TITLE_CHARS / 2).unwrap_or(cut.len());
388            format!("{}…", cut[..at].trim_end_matches([' ', ',', ';', ':', '.', '-']))
389        };
390        let body = body.trim();
391        let body = if body.chars().count() <= MAX_REPORT_BODY_CHARS {
392            body.to_owned()
393        } else {
394            format!("{}…", body.chars().take(MAX_REPORT_BODY_CHARS - 1).collect::<String>().trim_end())
395        };
396        Self { title, body }
397    }
398}
399
400/// One run of a routine.
401#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
402pub struct RunRecord {
403    /// Its chat; `None` once pruned (beyond `keep`) or for a run that never started.
404    #[serde(default, skip_serializing_if = "Option::is_none")]
405    pub chat: Option<String>,
406    /// Milliseconds since the epoch.
407    #[serde(default)]
408    pub started: i64,
409    #[serde(default, skip_serializing_if = "Option::is_none")]
410    pub finished: Option<i64>,
411    #[serde(default)]
412    pub status: RunStatus,
413    #[serde(default)]
414    pub cause: RunCause,
415    /// The scheduled time it stood for (ms), for scheduled runs.
416    #[serde(default, skip_serializing_if = "Option::is_none")]
417    pub slot: Option<i64>,
418    #[serde(default, skip_serializing_if = "Option::is_none")]
419    pub report: Option<Report>,
420    /// Why it failed.
421    #[serde(default, skip_serializing_if = "Option::is_none")]
422    pub error: Option<String>,
423    /// Tokens the run used (prompt + completion), once finished.
424    #[serde(default, skip_serializing_if = "is_zero")]
425    pub tokens: u64,
426}
427
428fn is_zero(n: &u64) -> bool {
429    *n == 0
430}
431
432#[cfg(test)]
433mod tests {
434    use super::*;
435
436    fn loom() -> Routine {
437        Routine {
438            name: " Loom deals ".into(),
439            instructions: "Search the web for deals on a new floor loom.".into(),
440            when: vec![Trigger::Schedule { rule: "FREQ=DAILY".into(), at: "08:00".into(), zone: Some(" ".into()), start: None }],
441            ..Routine::default()
442        }
443    }
444
445    #[test]
446    fn validates_and_trims() {
447        let r = loom().validated().unwrap();
448        assert_eq!(r.name, "Loom deals");
449        assert_eq!(r.allowed, Approvals::ReadOnly, "runs are read only unless said otherwise");
450        assert!(matches!(&r.when[0], Trigger::Schedule { zone: None, .. }), "a blank zone is the user's");
451        assert!(Routine { name: String::new(), ..loom() }.validated().is_err());
452        assert!(Routine { instructions: "x".repeat(MAX_INSTRUCTIONS_BYTES + 1), ..loom() }.validated().is_err());
453        assert!(Routine { keep: 0, ..loom() }.validated().is_err());
454        assert!(Routine { id: "../etc".into(), ..loom() }.validated().is_err());
455        assert!(Routine { when: vec![Trigger::Unknown; MAX_TRIGGERS + 1], ..loom() }.validated().is_err());
456    }
457
458    #[test]
459    fn reads_what_older_and_newer_builds_write() {
460        // the least a hand edit can say
461        let r: Routine = serde_json::from_str(r#"{"name":"A","instructions":"B"}"#).unwrap();
462        assert!(r.enabled);
463        assert_eq!((r.keep, r.allowed, r.tell, r.missed), (DEFAULT_KEEP, Approvals::ReadOnly, Tell::Found, Missed::Once));
464        assert_eq!(r.channels, [CHANNEL_DESKTOP]);
465        // a newer trigger kind and run status don't make it unreadable
466        let r: Routine = serde_json::from_str(r#"{"name":"A","instructions":"B","when":[{"type":"geofence","lat":1}]}"#).unwrap();
467        assert_eq!(r.when, [Trigger::Unknown]);
468        let run: RunRecord = serde_json::from_str(r#"{"status":"teleported","started":5}"#).unwrap();
469        assert_eq!((run.status, run.started), (RunStatus::Unknown, 5));
470    }
471
472    #[test]
473    fn ids_and_reports() {
474        assert_eq!(new_id("Loom deals!", |_| false), "loom-deals");
475        assert_eq!(new_id("Loom deals", |id| id == "loom-deals"), "loom-deals-2");
476        assert_eq!(new_id("???", |_| false), "routine");
477        assert!(id_ok("loom-deals-2") && !id_ok("") && !id_ok("Loom"));
478        let r = Report::clean(&"t".repeat(500), &"é".repeat(MAX_REPORT_BODY_BYTES));
479        assert_eq!(r.title.chars().count(), MAX_REPORT_TITLE_CHARS);
480        assert!(r.body.chars().count() == MAX_REPORT_BODY_CHARS && r.body.ends_with('…'));
481        // A long title is cut at a word.
482        let r = Report::clean("Schacht Cricket bundle $487 (reg. $569.99); Flip bundles from $629 (reg. $711.99) at Schacht", "");
483        assert_eq!(r.title, "Schacht Cricket bundle $487 (reg. $569.99); Flip bundles from $629 (reg…");
484        assert!(r.title.chars().count() <= MAX_REPORT_TITLE_CHARS);
485        assert_eq!(Report::clean(" Short\n title ", " b ").title, "Short title");
486    }
487}