1use regex::Regex;
16use serde_json::{Value, json};
17use std::sync::OnceLock;
18
19pub const STATE_KEY: &str = "persona";
21pub const MAX_CONTINUES: u32 = 100;
23pub const MAX_DURATION_MS: i64 = 8 * 60 * 60 * 1000;
25pub const ENV_MAX_CONTINUES: &str = "ULTRON_KEEPGOING_MAX_CONTINUES";
27pub const ENV_MAX_MS: &str = "ULTRON_KEEPGOING_MAX_MS";
28
29pub 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.";
31pub 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.";
33pub 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.";
35pub 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#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
40pub enum Toggle {
41 #[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#[derive(Clone, Debug, PartialEq, Eq)]
60pub struct KeepGoing {
61 pub started_at: i64,
63 pub continues: u32,
65 pub reason: String,
67 pub worked: bool,
69 pub tool_calls_seen: Option<u64>,
72}
73
74#[derive(Clone, Debug, Default, PartialEq, Eq)]
76pub struct SessionPersona {
77 pub toggle: Toggle,
78 pub keep_going: Option<KeepGoing>,
79}
80
81impl SessionPersona {
82 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 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 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 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 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 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 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
227pub 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 (known && (prompt.trim().starts_with('/') || !args.is_empty())).then_some((command, args))
244}
245
246#[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 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#[derive(Clone, Debug, Default, PartialEq, Eq)]
279pub struct RunEnd<'a> {
280 pub aborted: bool,
281 pub failed: bool,
282 pub pending_input: bool,
284 pub tool_calls: usize,
286 pub text: &'a str,
287}
288
289#[derive(Clone, Debug, PartialEq, Eq)]
291pub enum Next {
292 Persona,
294 Stop,
296 Continue { n: u32, asked: bool },
298 Final { n: u32 },
300}
301
302pub 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 return Next::Stop;
314 }
315 if end.tool_calls == 0 && !stretch.worked {
316 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
351pub 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 Regex::new(r"\b(?:don'?t|do not)(?: ever)? stop\b").expect("pattern"),
375 Regex::new(r"\bkeep (?:on )?going\b").expect("pattern"),
377 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 Regex::new(r"\bwork (?:through the night|all night|overnight)\b").expect("pattern"),
384 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
393const 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
428const 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
434fn 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
466pub 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 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}