1use config::keys::{PERSONA_KEY, PERSONA_ULTRON};
7use regex::Regex;
8use serde_json::Value;
9use std::path::{Path, PathBuf};
10use std::sync::OnceLock;
11
12pub const PERSONALITY_FILE: &str = "personality.md";
13pub const MAX_NUDGES: u32 = 5;
15pub 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.";
16
17pub 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.";
20
21pub fn section_text(personality: &str) -> String {
23 format!("{personality}\n\n{GUARDRAILS}")
24}
25
26pub fn enabled(settings: &serde_json::Map<String, Value>) -> bool {
28 settings.get(PERSONA_KEY).and_then(Value::as_str) == Some(PERSONA_ULTRON)
29}
30
31pub fn personality_path(agent_dir: &Path) -> PathBuf {
32 agent_dir.join(PERSONALITY_FILE)
33}
34
35pub fn read_personality(agent_dir: &Path) -> Result<Option<String>, String> {
37 let path = personality_path(agent_dir);
38 match std::fs::read_to_string(&path) {
39 Ok(text) => {
40 let text = text.trim();
41 Ok((!text.is_empty()).then(|| text.to_string()))
42 }
43 Err(error) => Err(format!(
44 "persona: cannot read {}: {error}; the persona is not in the system prompt",
45 path.display()
46 )),
47 }
48}
49
50fn announce() -> &'static Regex {
51 static ANNOUNCE: OnceLock<Regex> = OnceLock::new();
52 ANNOUNCE.get_or_init(|| {
53 Regex::new(
54 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",
55 )
56 .expect("the announce pattern compiles")
57 })
58}
59
60pub fn should_nudge(text: &str, tool_calls: usize) -> bool {
63 if tool_calls == 0 || text.is_empty() {
64 return false;
65 }
66 if crate::keep_going::asks(text) {
67 return false;
68 }
69 announce().is_match(text.trim().rsplit("\n\n").next().unwrap_or(""))
70}
71
72#[derive(Clone, Debug, Default, PartialEq, Eq)]
74pub struct TurnEnd<'a> {
75 pub persona: bool,
76 pub aborted: bool,
78 pub failed: bool,
79 pub pending_input: bool,
81 pub tool_calls: usize,
83 pub text: &'a str,
84 pub nudges: u32,
86}
87
88pub fn decide(end: &TurnEnd) -> bool {
90 end.persona
91 && !end.aborted
92 && !end.failed
93 && !end.pending_input
94 && end.nudges < MAX_NUDGES
95 && should_nudge(end.text, end.tool_calls)
96}
97
98#[derive(Clone, Debug, Default, PartialEq, Eq)]
100pub struct Chain {
101 pub nudges: u32,
102 pub tool_calls: usize,
103 pub text: String,
104}
105
106impl Chain {
107 pub fn user_input(&mut self) {
109 self.nudges = 0;
110 }
111
112 pub fn run_started(&mut self) {
114 self.tool_calls = 0;
115 self.text.clear();
116 }
117
118 pub fn assistant_message(&mut self, message: &Value) {
121 let blocks = message["content"].as_array().map(Vec::as_slice).unwrap_or_default();
122 self.tool_calls += blocks.iter().filter(|b| b["type"] == "toolCall").count();
123 let text = blocks
124 .iter()
125 .filter(|b| b["type"] == "text")
126 .map(|b| b["text"].as_str().unwrap_or(""))
127 .collect::<Vec<_>>()
128 .join("\n");
129 let text = text.trim();
130 if !text.is_empty() {
131 self.text = text.to_string();
132 }
133 }
134
135 pub fn run_ended(&mut self, persona: bool, aborted: bool, failed: bool, pending_input: bool) -> Option<u32> {
138 if aborted {
139 self.nudges = MAX_NUDGES;
140 }
141 let due = decide(&TurnEnd {
142 persona,
143 aborted,
144 failed,
145 pending_input,
146 tool_calls: self.tool_calls,
147 text: &self.text,
148 nudges: self.nudges,
149 });
150 due.then(|| {
151 self.nudges += 1;
152 self.nudges
153 })
154 }
155}
156
157pub fn nudge_message(n: u32, timestamp: i64) -> Value {
159 serde_json::json!({
160 "role": "custom",
161 "customType": protocol::custom_types::NUDGE,
162 "content": NUDGE_TEXT,
163 "display": true,
164 "details": {"nudge": n, "max": MAX_NUDGES},
165 "timestamp": timestamp,
166 })
167}