use config::keys::{PERSONA_KEY, PERSONA_ULTRON};
use regex::Regex;
use serde_json::Value;
use std::path::{Path, PathBuf};
use std::sync::OnceLock;
pub const PERSONALITY_FILE: &str = "personality.md";
pub const MAX_NUDGES: u32 = 5;
pub const NUDGE_TEXT: &str = "Continue: take that next step now. End the turn only when the work is done and verified, or when you need the user; then ask one direct question.";
pub const GUARDRAILS: &str = "Ask the user before an irreversible or outward action (pushing, publishing, deploying, deleting data, sending messages, spending money); in keep-going mode, while the user is away, skip it and list it for the user in the final report instead of asking. Never start a schedule (schedule.every, schedule.at) unless the user asked for one.";
pub fn section_text(personality: &str) -> String {
format!("{personality}\n\n{GUARDRAILS}")
}
pub fn enabled(settings: &serde_json::Map<String, Value>) -> bool {
settings.get(PERSONA_KEY).and_then(Value::as_str) == Some(PERSONA_ULTRON)
}
pub fn personality_path(agent_dir: &Path) -> PathBuf {
agent_dir.join(PERSONALITY_FILE)
}
pub fn read_personality(agent_dir: &Path) -> Result<Option<String>, String> {
let path = personality_path(agent_dir);
match std::fs::read_to_string(&path) {
Ok(text) => {
let text = text.trim();
Ok((!text.is_empty()).then(|| text.to_string()))
}
Err(error) => Err(format!(
"persona: cannot read {}: {error}; the persona is not in the system prompt",
path.display()
)),
}
}
fn announce() -> &'static Regex {
static ANNOUNCE: OnceLock<Regex> = OnceLock::new();
ANNOUNCE.get_or_init(|| {
Regex::new(
r"(?i)\b(next,? I(?:'ll| will)|I(?:'ll| will) (?:now|next|then|start|run|add|fix|write|check)|then I(?:'ll| will)|let me|next step|going to|about to)\b",
)
.expect("the announce pattern compiles")
})
}
pub fn should_nudge(text: &str, tool_calls: usize) -> bool {
if tool_calls == 0 || text.is_empty() {
return false;
}
if crate::keep_going::asks(text) {
return false;
}
announce().is_match(text.trim().rsplit("\n\n").next().unwrap_or(""))
}
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct TurnEnd<'a> {
pub persona: bool,
pub aborted: bool,
pub failed: bool,
pub pending_input: bool,
pub tool_calls: usize,
pub text: &'a str,
pub nudges: u32,
}
pub fn decide(end: &TurnEnd) -> bool {
end.persona
&& !end.aborted
&& !end.failed
&& !end.pending_input
&& end.nudges < MAX_NUDGES
&& should_nudge(end.text, end.tool_calls)
}
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct Chain {
pub nudges: u32,
pub tool_calls: usize,
pub text: String,
}
impl Chain {
pub fn user_input(&mut self) {
self.nudges = 0;
}
pub fn run_started(&mut self) {
self.tool_calls = 0;
self.text.clear();
}
pub fn assistant_message(&mut self, message: &Value) {
let blocks = message["content"].as_array().map(Vec::as_slice).unwrap_or_default();
self.tool_calls += blocks.iter().filter(|b| b["type"] == "toolCall").count();
let text = blocks
.iter()
.filter(|b| b["type"] == "text")
.map(|b| b["text"].as_str().unwrap_or(""))
.collect::<Vec<_>>()
.join("\n");
let text = text.trim();
if !text.is_empty() {
self.text = text.to_string();
}
}
pub fn run_ended(&mut self, persona: bool, aborted: bool, failed: bool, pending_input: bool) -> Option<u32> {
if aborted {
self.nudges = MAX_NUDGES;
}
let due = decide(&TurnEnd {
persona,
aborted,
failed,
pending_input,
tool_calls: self.tool_calls,
text: &self.text,
nudges: self.nudges,
});
due.then(|| {
self.nudges += 1;
self.nudges
})
}
}
pub fn nudge_message(n: u32, timestamp: i64) -> Value {
serde_json::json!({
"role": "custom",
"customType": protocol::custom_types::NUDGE,
"content": NUDGE_TEXT,
"display": true,
"details": {"nudge": n, "max": MAX_NUDGES},
"timestamp": timestamp,
})
}