Skip to main content

resources/
keep_going.rs

1//! The per-session persona toggle and keep-going mode (Rust-only, no TypeScript reference).
2//!
3//! - The session's own toggle (`on`, `off`, `auto`: follow the settings' `persona`) overrides the global setting.
4//! - A user prompt that asks the agent to keep working unattended ([`trigger`]: "keep going", "don't stop until you
5//!   finish", "I'm going to sleep", ...) turns the persona on for the session and starts keep-going mode.
6//! - Keep-going mode ([`after_run`]): after a run that did work (an `rlm` call), the host continues it with the
7//!   keep-going nudge, whatever the run's last paragraph says and with no 5-nudge cap; a run that ends with a question
8//!   is told that the user is away. It ends when a run makes no `rlm` call (that run is the final report), on user
9//!   input or an abort, when the user turns it off, or at the ceiling ([`Limits`]: 100 continues or 8 hours), where a
10//!   last nudge asks for the final report.
11//!
12//! The state is one session value (`ultron.module/persona`, [`SessionPersona::to_json`]), so a resumed session (a
13//! restarted durable instance, a crashed worker) keeps the toggle, the mode and its counters.
14
15use regex::Regex;
16use serde_json::{Value, json};
17use std::sync::OnceLock;
18
19/// The session value's key in `ultron.module`.
20pub const STATE_KEY: &str = "persona";
21/// Continues allowed in one keep-going stretch.
22pub const MAX_CONTINUES: u32 = 100;
23/// How long one keep-going stretch may run.
24pub const MAX_DURATION_MS: i64 = 8 * 60 * 60 * 1000;
25/// Overrides of the ceiling (tests, and a user who wants another one): a count and milliseconds.
26pub const ENV_MAX_CONTINUES: &str = "ULTRON_KEEPGOING_MAX_CONTINUES";
27pub const ENV_MAX_MS: &str = "ULTRON_KEEPGOING_MAX_MS";
28
29/// What the keep-going nudge says after a run that did work.
30pub const KEEP_GOING_TEXT: &str = "Keep going: the user is away and asked you to work until the task is done. Take the next step now. Skip irreversible or outward actions (pushing, publishing, deploying, deleting data, sending messages, spending money) and start schedules only for explicit user-requested watches or loops (without authorizing any other outward action); otherwise list them for the user in your final report instead of asking. When the work is done and verified, write the final report and make no further rlm call.";
31/// The keep-going nudge after a run that ended with a question to the user.
32pub const KEEP_GOING_ASKED_TEXT: &str = "The user is away and cannot answer your question. Decide yourself: take the safest reversible option, record the decision and the alternative in your final report, and continue. Skip irreversible or outward actions (pushing, publishing, deploying, deleting data, sending messages, spending money) and start schedules only for explicit user-requested watches or loops (without authorizing any other outward action); otherwise list them for the user in your final report instead of asking. When the work is done and verified, write the final report and make no further rlm call.";
33/// The last nudge at the ceiling.
34pub const FINAL_TEXT: &str = "Keep-going limit reached: stop working now and write the final report: what was done, what was verified, the decisions you made with their alternatives, and the irreversible or outward actions left for the user. Make no further rlm call.";
35/// What the model is told when a prompt starts keep-going mode (`ultron claude`'s UserPromptSubmit context).
36pub const START_TEXT: &str = "Keep-going mode is on: the user is away. Work until the task is done and verified without waiting for answers; decide open questions yourself and record each decision and its alternative for the final report. Skip irreversible or outward actions (pushing, publishing, deploying, deleting data, sending messages, spending money) and start schedules only for explicit user-requested watches or loops (without authorizing any other outward action); otherwise list them for the user in the final report instead of asking.";
37
38/// The session's own persona choice.
39#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
40pub enum Toggle {
41    /// Follow the settings' `persona`.
42    #[default]
43    Auto,
44    On,
45    Off,
46}
47
48impl Toggle {
49    pub fn name(self) -> &'static str {
50        match self {
51            Toggle::Auto => "auto",
52            Toggle::On => "on",
53            Toggle::Off => "off",
54        }
55    }
56}
57
58/// One keep-going stretch.
59#[derive(Clone, Debug, PartialEq, Eq)]
60pub struct KeepGoing {
61    /// When it started (ms since the epoch).
62    pub started_at: i64,
63    /// Keep-going nudges sent.
64    pub continues: u32,
65    /// The phrase that started it (or `/keepgoing on`).
66    pub reason: String,
67    /// The run in progress made an `rlm` call (kept so a run resumed after a restart still counts its work).
68    pub worked: bool,
69    /// `ultron claude`: the tool calls Claude Code's transcript held at the last decision (a run did work when the
70    /// count grew); `None` before the first.
71    pub tool_calls_seen: Option<u64>,
72}
73
74/// The session's persona state.
75#[derive(Clone, Debug, Default, PartialEq, Eq)]
76pub struct SessionPersona {
77    pub toggle: Toggle,
78    pub keep_going: Option<KeepGoing>,
79}
80
81impl SessionPersona {
82    /// The session value; anything unreadable is the default (auto, no keep-going).
83    pub fn from_json(value: Option<&Value>) -> SessionPersona {
84        let Some(value) = value.filter(|v| v.is_object()) else {
85            return SessionPersona::default();
86        };
87        let toggle = match value["persona"].as_str() {
88            Some("on") => Toggle::On,
89            Some("off") => Toggle::Off,
90            _ => Toggle::Auto,
91        };
92        let keep_going = value["keepGoing"].as_object().map(|k| KeepGoing {
93            started_at: k.get("startedAt").and_then(Value::as_i64).unwrap_or(0),
94            continues: k
95                .get("continues")
96                .and_then(Value::as_u64)
97                .map_or(0, |n| u32::try_from(n).unwrap_or(u32::MAX)),
98            reason: k.get("reason").and_then(Value::as_str).unwrap_or_default().to_string(),
99            worked: k.get("worked") == Some(&Value::Bool(true)),
100            tool_calls_seen: k.get("toolCallsSeen").and_then(Value::as_u64),
101        });
102        SessionPersona { toggle, keep_going }
103    }
104
105    pub fn to_json(&self) -> Value {
106        json!({
107            "version": 1,
108            "persona": self.toggle.name(),
109            "keepGoing": self.keep_going.as_ref().map(|k| json!({
110                "startedAt": k.started_at,
111                "continues": k.continues,
112                "reason": k.reason,
113                "worked": k.worked,
114                "toolCallsSeen": k.tool_calls_seen,
115            })),
116        })
117    }
118
119    /// Whether the persona is on for this session, given the settings' `persona` (`global`).
120    pub fn effective(&self, global: bool) -> bool {
121        match self.toggle {
122            Toggle::On => true,
123            Toggle::Off => false,
124            Toggle::Auto => global,
125        }
126    }
127
128    /// The session's prompt-mode override: `None` follows the settings.
129    pub fn prompt_override(&self) -> Option<bool> {
130        match self.toggle {
131            Toggle::On => Some(true),
132            Toggle::Off => Some(false),
133            Toggle::Auto => None,
134        }
135    }
136
137    /// A user's input (a prompt, a queued message) at `now`: its keep-going phrase turns the persona on and starts
138    /// keep-going mode; any other input ends a stretch in progress. The one-line notice for the user, if any.
139    pub fn user_input(&mut self, text: &str, now: i64) -> Option<String> {
140        if let Some(phrase) = trigger(text) {
141            self.toggle = Toggle::On;
142            let notice = format!("keep-going on: \"{phrase}\" (/keepgoing off ends it)");
143            self.keep_going = Some(KeepGoing {
144                started_at: now,
145                continues: 0,
146                reason: phrase,
147                worked: false,
148                tool_calls_seen: None,
149            });
150            return Some(notice);
151        }
152        self.keep_going
153            .take()
154            .map(|_| "keep-going off: you sent input".to_string())
155    }
156
157    /// The run made an `rlm` call; `true` when the stored state changed.
158    pub fn worked(&mut self) -> bool {
159        match &mut self.keep_going {
160            Some(k) if !k.worked => {
161                k.worked = true;
162                true
163            }
164            _ => false,
165        }
166    }
167
168    /// The status line `/persona` and `/keepgoing` answer with.
169    pub fn status(&self, global: bool, limits: Limits) -> String {
170        let persona = match self.toggle {
171            Toggle::Auto => format!(
172                "Persona for this session follows the settings ({})",
173                if global { "on" } else { "off" }
174            ),
175            Toggle::On => "Persona is on for this session".to_string(),
176            Toggle::Off => "Persona is off for this session".to_string(),
177        };
178        let keep_going = match &self.keep_going {
179            Some(k) => format!(
180                "keep-going on ({}/{} continues, \"{}\")",
181                k.continues, limits.max_continues, k.reason
182            ),
183            None => "keep-going off".to_string(),
184        };
185        format!("{persona}; {keep_going}")
186    }
187
188    /// `/persona on|off|auto` and `/keepgoing on|off` (`command`: `persona` or `keepgoing`; empty `args` reports).
189    /// Turning the persona off ends keep-going too. Errors are the usage text.
190    pub fn command(
191        &mut self,
192        command: &str,
193        args: &str,
194        now: i64,
195        global: bool,
196        limits: Limits,
197    ) -> Result<String, String> {
198        let arg = args.trim().to_lowercase();
199        match (command, arg.as_str()) {
200            ("persona", "") | ("keepgoing", "") => {}
201            ("persona", "on") => self.toggle = Toggle::On,
202            ("persona", "off") => {
203                self.toggle = Toggle::Off;
204                self.keep_going = None;
205            }
206            ("persona", "auto") => self.toggle = Toggle::Auto,
207            ("keepgoing", "on") => {
208                self.toggle = Toggle::On;
209                if self.keep_going.is_none() {
210                    self.keep_going = Some(KeepGoing {
211                        started_at: now,
212                        continues: 0,
213                        reason: "/keepgoing on".into(),
214                        worked: false,
215                        tool_calls_seen: None,
216                    });
217                }
218            }
219            ("keepgoing", "off") => self.keep_going = None,
220            ("persona", _) => return Err("Usage: /persona on|off|auto (this session)".into()),
221            _ => return Err("Usage: /keepgoing on|off".into()),
222        }
223        Ok(self.status(global, limits))
224    }
225}
226
227/// `/persona <args>` or `/keepgoing <args>` as a whole prompt (with or without the slash): `(command, args)`.
228pub fn toggle_command(prompt: &str) -> Option<(&'static str, String)> {
229    let text = prompt.trim();
230    let text = text.strip_prefix('/').unwrap_or(text);
231    let (head, rest) = text.split_once(char::is_whitespace).unwrap_or((text, ""));
232    let command = match head.to_lowercase().as_str() {
233        "persona" => "persona",
234        "keepgoing" | "keep-going" => "keepgoing",
235        _ => return None,
236    };
237    let args = rest.trim().to_lowercase();
238    let known = match command {
239        "persona" => matches!(args.as_str(), "on" | "off" | "auto" | ""),
240        _ => matches!(args.as_str(), "on" | "off" | ""),
241    };
242    // Without the slash only an explicit argument makes it a command ("persona" alone is a word).
243    (known && (prompt.trim().starts_with('/') || !args.is_empty())).then_some((command, args))
244}
245
246/// The keep-going ceiling.
247#[derive(Clone, Copy, Debug, PartialEq, Eq)]
248pub struct Limits {
249    pub max_continues: u32,
250    pub max_ms: i64,
251}
252
253impl Default for Limits {
254    fn default() -> Self {
255        Limits {
256            max_continues: MAX_CONTINUES,
257            max_ms: MAX_DURATION_MS,
258        }
259    }
260}
261
262impl Limits {
263    /// The ceiling with [`ENV_MAX_CONTINUES`] / [`ENV_MAX_MS`] over the defaults (unparsable values are ignored).
264    pub fn from_env(var: &dyn Fn(&str) -> Option<String>) -> Limits {
265        let defaults = Limits::default();
266        Limits {
267            max_continues: var(ENV_MAX_CONTINUES)
268                .and_then(|v| v.trim().parse().ok())
269                .unwrap_or(defaults.max_continues),
270            max_ms: var(ENV_MAX_MS)
271                .and_then(|v| v.trim().parse().ok())
272                .unwrap_or(defaults.max_ms),
273        }
274    }
275}
276
277/// How a root run ended, for [`after_run`].
278#[derive(Clone, Debug, Default, PartialEq, Eq)]
279pub struct RunEnd<'a> {
280    pub aborted: bool,
281    pub failed: bool,
282    /// A user message is queued, or other input waits for the lane.
283    pub pending_input: bool,
284    /// `rlm` calls the run made.
285    pub tool_calls: usize,
286    pub text: &'a str,
287}
288
289/// What follows a run in keep-going mode.
290#[derive(Clone, Debug, PartialEq, Eq)]
291pub enum Next {
292    /// Not in keep-going mode: the persona's own nudge rule decides.
293    Persona,
294    /// Nothing (the mode ended, or input waits).
295    Stop,
296    /// Continue with keep-going nudge `n`; `asked`: the run ended with a question.
297    Continue { n: u32, asked: bool },
298    /// The ceiling: the last nudge, asking for the final report (the mode has ended).
299    Final { n: u32 },
300}
301
302/// The keep-going decision after a root run at `now`. Changes `state` (counters, the end of the mode).
303pub fn after_run(state: &mut SessionPersona, end: &RunEnd, now: i64, limits: Limits) -> Next {
304    let Some(stretch) = state.keep_going.as_mut() else {
305        return Next::Persona;
306    };
307    if end.aborted || end.failed {
308        state.keep_going = None;
309        return Next::Stop;
310    }
311    if end.pending_input {
312        // The waiting input runs next; a user's message ends the mode when it arrives.
313        return Next::Stop;
314    }
315    if end.tool_calls == 0 && !stretch.worked {
316        // A run that only reported: the final report.
317        state.keep_going = None;
318        return Next::Stop;
319    }
320    if stretch.continues >= limits.max_continues || now.saturating_sub(stretch.started_at) >= limits.max_ms {
321        let n = stretch.continues + 1;
322        state.keep_going = None;
323        return Next::Final { n };
324    }
325    stretch.continues += 1;
326    stretch.worked = false;
327    Next::Continue {
328        n: stretch.continues,
329        asked: asks(end.text),
330    }
331}
332
333pub fn asks(text: &str) -> bool {
334    text.trim()
335        .rsplit("\n\n")
336        .next()
337        .unwrap_or("")
338        .trim_end()
339        .ends_with('?')
340}
341
342pub fn nudge_text(next: &Next) -> Option<&'static str> {
343    match next {
344        Next::Continue { asked: false, .. } => Some(KEEP_GOING_TEXT),
345        Next::Continue { asked: true, .. } => Some(KEEP_GOING_ASKED_TEXT),
346        Next::Final { .. } => Some(FINAL_TEXT),
347        Next::Persona | Next::Stop => None,
348    }
349}
350
351/// A keep-going nudge as a transcript message (the persona nudge's custom type, `details.keepGoing`).
352pub fn nudge_message(next: &Next, limits: Limits, timestamp: i64) -> Option<Value> {
353    let text = nudge_text(next)?;
354    let (n, last) = match next {
355        Next::Continue { n, .. } => (*n, false),
356        Next::Final { n } => (*n, true),
357        _ => return None,
358    };
359    Some(json!({
360        "role": "custom",
361        "customType": protocol::custom_types::NUDGE,
362        "content": text,
363        "display": true,
364        "details": {"nudge": n, "max": limits.max_continues, "keepGoing": true, "final": last},
365        "timestamp": timestamp,
366    }))
367}
368
369fn patterns() -> &'static [Regex; 5] {
370    static PATTERNS: OnceLock<[Regex; 5]> = OnceLock::new();
371    PATTERNS.get_or_init(|| {
372        [
373            // "don't stop", "do not stop", "don't ever stop": what follows is checked by `stop_tail`.
374            Regex::new(r"\b(?:don'?t|do not)(?: ever)? stop\b").expect("pattern"),
375            // "keep going", "keep on going".
376            Regex::new(r"\bkeep (?:on )?going\b").expect("pattern"),
377            // "continue until you're done", "keep working till it's finished", "work until done".
378            Regex::new(
379                r"\b(?:continue|carry on|go on|keep working|work|keep at it) (?:until|till|til|'til|untill) (?:(?:you(?:'re| are)?|it(?:'s| is)|everything(?:'s| is)|the (?:work|task|job)s? (?:is|are)) )?(?:all )?(?:done|finished|complete|completed|finish|finishing|through)\b",
380            )
381            .expect("pattern"),
382            // "work through the night", "work overnight".
383            Regex::new(r"\bwork (?:through the night|all night|overnight)\b").expect("pattern"),
384            // The user says they will be away: "I'm going to sleep", "im gonna sleep", "I'll be away".
385            Regex::new(
386                r"\bi(?:'m| am|m) (?:going to|gonna|off to|about to|heading to) (?:go to )?(?:sleep|bed)\b|\bi(?:'m| am|m) (?:going|heading) to bed\b|\bi(?:'ll| will|ll) be (?:away|afk|offline|asleep|gone|out)\b|\bi(?:'m| am|m) (?:away|afk|stepping away|heading out|logging off)\b",
387            )
388            .expect("pattern"),
389        ]
390    })
391}
392
393/// Words that may come before an instruction in its clause and still leave it addressed to the agent ("please
394/// keep going", "ok, just keep going", "can you work through the night").
395const ADDRESS_WORDS: [&str; 30] = [
396    "please",
397    "pls",
398    "plz",
399    "just",
400    "and",
401    "so",
402    "then",
403    "ok",
404    "okay",
405    "now",
406    "also",
407    "but",
408    "simply",
409    "you",
410    "can",
411    "could",
412    "should",
413    "must",
414    "will",
415    "to",
416    "alright",
417    "yes",
418    "yeah",
419    "great",
420    "good",
421    "thanks",
422    "hey",
423    "ultron",
424    "really",
425    "seriously",
426];
427
428/// What may follow "don't stop" for it to mean "don't stop working" (not "don't stop the server").
429const STOP_TAIL_WORDS: [&str; 16] = [
430    "until", "till", "til", "'til", "untill", "unless", "working", "now", "at", "even", "no", "for", "and", "or",
431    "yet", "there",
432];
433
434/// Whether the words before the match in its clause leave it addressed to the agent: after the clause's last
435/// `and` / `then` (an instruction joined to another, "fix it and keep going"), only [`ADDRESS_WORDS`] may come
436/// first, so "the loop should keep going" or "why do you keep going back" are not instructions.
437fn addressed(prefix: &str) -> bool {
438    let prefix = prefix.trim();
439    let prefix = [
440        "i want you to",
441        "i need you to",
442        "i'd like you to",
443        "i would like you to",
444    ]
445    .iter()
446    .find_map(|lead| prefix.strip_suffix(lead).map(str::trim))
447    .unwrap_or(prefix);
448    let words: Vec<&str> = prefix
449        .split_whitespace()
450        .map(|word| word.trim_matches(|c: char| !c.is_alphanumeric() && c != '\''))
451        .collect();
452    let start = words
453        .iter()
454        .rposition(|word| matches!(*word, "and" | "then"))
455        .map_or(0, |index| index + 1);
456    words[start..].iter().all(|word| ADDRESS_WORDS.contains(word))
457}
458
459fn stop_tail(rest: &str) -> bool {
460    match rest.split_whitespace().next() {
461        None => true,
462        Some(word) => STOP_TAIL_WORDS.contains(&word),
463    }
464}
465
466/// The keep-going phrase a user prompt contains, addressed to the agent (lowercased, as written), if any.
467pub fn trigger(prompt: &str) -> Option<String> {
468    let text = prompt.to_lowercase().replace(['\u{2019}', '\u{2018}', '`'], "'");
469    for clause in text.split(['.', '!', '?', ';', ':', ',', '\n', '(', ')', '"']) {
470        let clause = clause.split_whitespace().collect::<Vec<_>>().join(" ");
471        for (index, pattern) in patterns().iter().enumerate() {
472            let Some(found) = pattern.find(&clause) else { continue };
473            let (before, rest) = (&clause[..found.start()], &clause[found.end()..]);
474            let ok = match index {
475                0 => addressed(before) && stop_tail(rest),
476                // The user's own away message is about them, not an instruction.
477                4 => true,
478                _ => addressed(before),
479            };
480            if ok {
481                let phrase = match index {
482                    0 => format!("{}{}", found.as_str(), rest).trim().to_string(),
483                    _ => found.as_str().to_string(),
484                };
485                return Some(phrase);
486            }
487        }
488    }
489    None
490}