Skip to main content

resources/
persona.rs

1//! The Ultron persona (`"persona": "ultron"` in settings.json): `<agent dir>/personality.md` as a section of the
2//! system prompt, and the auto-nudge that continues a root turn which ended by announcing its next step instead of
3//! taking it. Rust-only (no TypeScript reference); the nudge rule and text are those of the user's Claude Code hook
4//! (ultron-persona.py), recorded in fixtures/persona-nudge.json.
5
6use 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";
13/// Nudges allowed since the user last sent input.
14pub 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
17/// The host's rules that close the persona section, whatever personality.md says: outward or irreversible actions
18/// wait for the user (in keep-going mode they are skipped and listed), and schedules start only when asked.
19pub 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
21/// The persona section's text: the persona's own text, then [`GUARDRAILS`].
22pub fn section_text(personality: &str) -> String {
23    format!("{personality}\n\n{GUARDRAILS}")
24}
25
26/// Whether the settings' `persona` is `ultron` (any other value, or none, is off).
27pub 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
35/// The persona's text for the system prompt: `Ok(None)` for an empty file, `Err(warning)` when it cannot be read.
36pub 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
60/// The hook's `should_nudge`: the turn made a tool call and its final text's last paragraph (split on blank lines)
61/// announces a next step instead of asking a question.
62pub 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/// How a root turn ended, for [`decide`].
73#[derive(Clone, Debug, Default, PartialEq, Eq)]
74pub struct TurnEnd<'a> {
75    pub persona: bool,
76    /// The user (or a client) aborted the run.
77    pub aborted: bool,
78    pub failed: bool,
79    /// A user message is queued, or other input waits for the lane.
80    pub pending_input: bool,
81    /// Tool (`rlm`) calls the turn made.
82    pub tool_calls: usize,
83    pub text: &'a str,
84    /// Nudges since the user last sent input.
85    pub nudges: u32,
86}
87
88/// Whether the host sends a nudge after this turn.
89pub 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/// The nudge chain since the user's last input: how many ran, and what the current run did.
99#[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    /// The user sent input: the count starts over.
108    pub fn user_input(&mut self) {
109        self.nudges = 0;
110    }
111
112    /// A run starts: its own calls and text.
113    pub fn run_started(&mut self) {
114        self.tool_calls = 0;
115        self.text.clear();
116    }
117
118    /// An assistant message ended (a transcript message as stored): its tool calls count, and its text, when it has
119    /// any, is the turn's final text so far.
120    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    /// The run ended: the nudge number to send (1-based), if one is due. An abort ends the chain until the user's
136    /// next input.
137    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
157/// The nudge as a transcript message: a displayed custom message the model reads as a user message.
158pub 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}