Skip to content

Soul-driven AI agent with permission-hardened tools, token budgets, and multi-channel access. Runs 24/7 from CLI, Telegram or More.

fix(optimus): no more "done" when it wasn't (0.4.3)

Salman Qureshi3a81f4195f5d
diff --git a/plugins/optimus/companion/Cargo.lock b/plugins/optimus/companion/Cargo.lock
index 31d54d75..c590c693 100644
--- a/plugins/optimus/companion/Cargo.lock
+++ b/plugins/optimus/companion/Cargo.lock
@@ -1280,7 +1280,7 @@ dependencies = [
[[package]]
name = "mercury-optimus"
-version = "0.4.1"
+version = "0.4.3"
dependencies = [
"base64 0.22.1",
"core-foundation",
diff --git a/plugins/optimus/companion/Cargo.toml b/plugins/optimus/companion/Cargo.toml
index 99ec2186..a7b93c09 100644
--- a/plugins/optimus/companion/Cargo.toml
+++ b/plugins/optimus/companion/Cargo.toml
@@ -1,6 +1,6 @@
[package]
name = "mercury-optimus"
-version = "0.4.2"
+version = "0.4.3"
edition = "2024"
rust-version = "1.94"
description = "Optimus: full computer control for Mercury (screen, mouse, keyboard, apps, voice)"
diff --git a/plugins/optimus/companion/src/core.rs b/plugins/optimus/companion/src/core.rs
index 40125aa7..a779c578 100644
--- a/plugins/optimus/companion/src/core.rs
+++ b/plugins/optimus/companion/src/core.rs
@@ -124,6 +124,8 @@ pub struct Shared {
pub hotkey_label: Mutex<String>,
/// Screen operations in progress, and the (listening, working) state last reported.
working: Mutex<(u32, Option<(bool, bool)>)>,
+ /// Steps that failed or were stopped, with when: a voice answer is checked against them.
+ pub failures: Mutex<Vec<(std::time::Instant, String)>>,
}
impl Shared {
@@ -157,6 +159,7 @@ pub fn run(inbox: std::sync::mpsc::Receiver<Value>, send: impl Fn(Value) + Send
session: Mutex::new(None),
hotkey_label: Mutex::new(String::new()),
working: Mutex::new((0, None)),
+ failures: Mutex::new(Vec::new()),
});
shared.publish_activity();
@@ -195,6 +198,18 @@ pub fn run(inbox: std::sync::mpsc::Receiver<Value>, send: impl Fn(Value) + Send
}
rt.spawn_blocking(move || {
let r = sh.ops.lock().unwrap_or_else(|e| e.into_inner()).run(&name, &args);
+ // Remember what didn't work, so nobody can say it did.
+ let failed = match &r {
+ Err(e) => Some(e.clone()),
+ Ok(v) => v.get("text").and_then(Value::as_str).filter(|t| t.starts_with("FAILED")).map(str::to_string),
+ };
+ if let Some(f) = failed {
+ let mut list = sh.failures.lock().unwrap();
+ list.push((std::time::Instant::now(), format!("{name}: {}", f.chars().take(160).collect::<String>())));
+ if list.len() > 50 {
+ list.remove(0);
+ }
+ }
sh.out.op_result(id, r);
if on_screen {
{
diff --git a/plugins/optimus/companion/src/main.rs b/plugins/optimus/companion/src/main.rs
index 468f644c..309b7004 100644
--- a/plugins/optimus/companion/src/main.rs
+++ b/plugins/optimus/companion/src/main.rs
@@ -200,7 +200,7 @@ fn action_schema() -> Value {
const TOOL_DESCRIPTIONS: [(&str, &str); 7] = [
("look", "See the screen: a screenshot of the display the mouse is on (or `display` N), with the active window. Use `zoom` [x0,y0,x1,y1] for a closer look at part of the last screenshot (coordinates stay in the full screenshot)."),
- ("act", "Use the mouse and keyboard like a person: click, type, paste, press keys, scroll, drag, draw freehand. Returns a fresh screenshot. Pass `actions` as a list. To write text (posts, emails, articles) click the box, then use type: it types key by key like a person, so it works in every editor (up to 3,000 characters per type action; longer text in parts). Use paste only if typing fails. Only for ordinary, reversible steps. Anything that submits, sends, posts, pays, buys, deletes, installs or changes settings must go through act_consequential instead. Never type passwords, card numbers or 2FA codes: ask the owner to do that part."),
+ ("act", "Use the mouse and keyboard like a person: click, type, paste, press keys, scroll, drag, draw freehand. Returns a fresh screenshot. Pass `actions` as a list. To write text (posts, emails, articles) click the box, then use type: it types key by key like a person, so it works in every editor (up to 3,000 characters per type action; longer text in parts). Use paste only if typing fails. \"Sent\" means the input was sent, not that it worked: check the returned screenshot, and before telling the owner a task is done, look and confirm the result. FAILED means nothing (or not everything) happened. Only for ordinary, reversible steps. Anything that submits, sends, posts, pays, buys, deletes, installs or changes settings must go through act_consequential instead. Never type passwords, card numbers or 2FA codes: ask the owner to do that part."),
("act_consequential", "Same as act, for the step that commits something: submit a form, send a message or email, post, pay or buy, delete, install, change a setting. The owner approves it first, so say what it will do."),
("open", "Open an app by name (\"Chrome\", \"Notes\", \"Freeform\"), a URL, or a file/folder path. Faster and more reliable than clicking through menus. If the app isn't installed, the reply lists what is. For drawing use Freeform (Mac), Paint (Windows) or a web canvas like https://excalidraw.com."),
("windows", "List open windows (app and title), front first."),
@@ -247,7 +247,10 @@ fn call_tool(shell: &Arc<Shell>, name: &str, args: &Value) -> Value {
}
json!({ "content": content })
}
- Err(e) => json!({ "content": [{ "type": "text", "text": e }], "isError": true }),
+ Err(e) => {
+ let text = if e.starts_with("FAILED") || e.starts_with("Stopped") || e.starts_with("Optimus is off") { e } else { format!("FAILED: {e}") };
+ json!({ "content": [{ "type": "text", "text": text }], "isError": true })
+ }
}
}
diff --git a/plugins/optimus/companion/src/ops.rs b/plugins/optimus/companion/src/ops.rs
index 77242998..a08d3d3d 100644
--- a/plugins/optimus/companion/src/ops.rs
+++ b/plugins/optimus/companion/src/ops.rs
@@ -199,7 +199,11 @@ impl Ops {
// ── Acting ─────────────────────────────────────────────────────────
fn act(&mut self, args: &Value) -> OpResult {
- let actions = actions_of(args)?;
+ let actions = actions_of(args).map_err(|e| {
+ let raw = args.to_string();
+ crate::core::log(format!("act: couldn't read the steps ({e}): {}", raw.chars().take(600).collect::<String>()));
+ format!("FAILED: nothing was done. {e}")
+ })?;
let actions = &actions;
if actions.is_empty() {
return Err("no actions given".into());
@@ -242,11 +246,12 @@ impl Ops {
crate::overlay::done();
// Let the screen settle, then show what happened (unless asked not to).
let mut out = json!({});
- let mut text = if done.is_empty() { "Nothing was done.".to_string() } else { format!("Done: {}.", done.join("; ")) };
+ // "Sent", not "done": an input reaching the screen doesn't mean it had the intended effect.
+ let mut text = if done.is_empty() { "Nothing was sent.".to_string() } else { format!("Sent: {}.", done.join("; ")) };
if let Some(s) = &stopped {
- text.push(' ');
- text.push_str(s);
+ text = format!("FAILED: {s} {text}");
}
+ text.push_str(" This only means the input was sent: check the screenshot below to see whether it actually worked before saying so.");
if args.get("screenshot").and_then(Value::as_bool) != Some(false) {
std::thread::sleep(Duration::from_millis(args.get("settle_ms").and_then(Value::as_u64).unwrap_or(500).min(5000)));
match self.look(&json!({})) {
@@ -613,20 +618,38 @@ fn find_mac_app(name: &str) -> Result<String, String> {
))
}
-/// The action list, however the model sent it: a list, a JSON string of
-/// one, a single action, or the action's fields at the top level.
-fn actions_of(args: &Value) -> Result<Vec<Value>, String> {
- let raw = match args.get("actions") {
- Some(Value::String(s)) => serde_json::from_str::<Value>(s).map_err(|_| "actions must be a list of {\"type\": …} steps".to_string())?,
- Some(v) => v.clone(),
+/// The action list, however the model sent it: a list; that list as a JSON
+/// string (even twice-encoded, or with single quotes); one action; an object
+/// of numbered actions; or one action's fields at the top level. Also under
+/// "steps" or "action".
+pub fn actions_of(args: &Value) -> Result<Vec<Value>, String> {
+ const HOW: &str = "actions must be a list of steps, e.g. [{\"type\": \"click\", \"x\": 100, \"y\": 200}]";
+ let raw = match args.get("actions").or_else(|| args.get("steps")).or_else(|| args.get("action")) {
+ Some(v) => decode(v.clone()).ok_or(HOW)?,
None if args.get("type").is_some() => args.clone(),
- None => return Err("actions must be a list of {\"type\": …} steps".into()),
+ None => return Err(HOW.into()),
};
let list = match raw {
Value::Array(a) => a,
- Value::Object(_) => vec![raw],
- _ => return Err("actions must be a list of {\"type\": …} steps".into()),
+ Value::Object(ref o) if o.contains_key("type") => vec![raw],
+ // {"0": {...}, "1": {...}} or {"actions": [...]} one level down.
+ Value::Object(o) => {
+ if let Some(inner) = o.get("actions").cloned().and_then(decode) {
+ return actions_of(&serde_json::json!({ "actions": inner }));
+ }
+ let mut items: Vec<(usize, Value)> = o.into_iter().filter_map(|(k, v)| Some((k.parse::<usize>().ok()?, v))).collect();
+ if items.is_empty() {
+ return Err(HOW.into());
+ }
+ items.sort_by_key(|(k, _)| *k);
+ items.into_iter().map(|(_, v)| v).collect()
+ }
+ _ => return Err(HOW.into()),
};
+ let list: Vec<Value> = list.into_iter().filter_map(decode).collect();
+ if list.iter().any(|a| !a.is_object()) {
+ return Err(HOW.into());
+ }
// Numbers sent as strings ("x": "120") are fine too.
Ok(list
.into_iter()
@@ -646,6 +669,21 @@ fn actions_of(args: &Value) -> Result<Vec<Value>, String> {
.collect())
}
+/// A value that may be JSON text (possibly encoded more than once, or with
+/// single quotes): decoded until it's an array or object.
+fn decode(v: Value) -> Option<Value> {
+ let mut v = v;
+ for _ in 0..4 {
+ let Value::String(s) = &v else { return Some(v) };
+ let t = s.trim();
+ let t = t.strip_prefix("```json").or_else(|| t.strip_prefix("```")).unwrap_or(t).trim_end_matches("```").trim();
+ v = serde_json::from_str::<Value>(t)
+ .or_else(|_| serde_json::from_str::<Value>(&t.replace('\'', "\"")))
+ .ok()?;
+ }
+ (!v.is_string()).then_some(v)
+}
+
/// [[x, y], …] or [{"x": …, "y": …}, …]
fn points_of(v: &Value) -> Option<Vec<(f64, f64)>> {
v.as_array()?
@@ -816,6 +854,14 @@ mod action_input_tests {
assert_eq!(actions_of(&json!({ "type": "key", "keys": "enter" })).unwrap().len(), 1);
assert!(actions_of(&json!({})).is_err());
assert!(actions_of(&json!({ "actions": "not json" })).is_err());
+ // Twice-encoded, single quotes, numbered objects, code fences, other keys.
+ let twice = serde_json::to_string(&serde_json::to_string(&json!([{ "type": "click", "x": 1, "y": 2 }])).unwrap()).unwrap();
+ assert_eq!(actions_of(&json!({ "actions": serde_json::from_str::<Value>(&twice).unwrap() })).unwrap().len(), 1);
+ assert_eq!(actions_of(&json!({ "actions": "[{'type': 'key', 'keys': 'enter'}]" })).unwrap().len(), 1);
+ assert_eq!(actions_of(&json!({ "actions": { "1": { "type": "key", "keys": "b" }, "0": { "type": "key", "keys": "a" } } })).unwrap()[0]["keys"], json!("a"));
+ assert_eq!(actions_of(&json!({ "actions": "```json\n[{\"type\":\"key\",\"keys\":\"enter\"}]\n```" })).unwrap().len(), 1);
+ assert_eq!(actions_of(&json!({ "steps": [{ "type": "key", "keys": "enter" }] })).unwrap().len(), 1);
+ assert_eq!(actions_of(&json!({ "actions": ["{\"type\":\"key\",\"keys\":\"enter\"}"] })).unwrap().len(), 1);
}
#[test]
diff --git a/plugins/optimus/companion/src/voice.rs b/plugins/optimus/companion/src/voice.rs
index f3919d5b..39b2466b 100644
--- a/plugins/optimus/companion/src/voice.rs
+++ b/plugins/optimus/companion/src/voice.rs
@@ -125,6 +125,7 @@ fn instructions_for(instructions: &str) -> String {
When ask_mercury returns, say what was done or found, briefly and in the past tense. \
Some actions need the user's approval. When you get an approval request, ask the user plainly whether to go ahead, wait for their answer, \
then call answer_approval. Never answer an approval yourself: only the user's own words count. \
+ Only say something is done when ask_mercury's answer says so; if it says something failed, couldn't be checked or was stopped, tell the user plainly. Never fill in a result yourself. \
Links, lists and details go to the user's Mercury chat automatically; just say you've sent them. \
When the user says goodbye or is done, say a short goodbye and call end_conversation.";
if instructions.is_empty() { base.to_string() } else { format!("{base}\n\n{instructions}") }
@@ -201,7 +202,7 @@ async fn bridge(
let mut mic = std::mem::replace(&mut audio.mic, mpsc::unbounded_channel().1);
let pending: Arc<std::sync::Mutex<HashMap<String, (Instant, Instant, u32)>>> = Arc::new(std::sync::Mutex::new(HashMap::new()));
let mut responding = false;
- let (answer_tx, mut answer_rx) = mpsc::unbounded_channel::<(String, String)>();
+ let (answer_tx, mut answer_rx) = mpsc::unbounded_channel::<(String, String, Instant)>();
let mut ready_answers: VecDeque<(String, String)> = VecDeque::new();
let mut awaiting: Option<(String, Instant)> = None;
let mut user_said: Vec<(Instant, String)> = Vec::new();
@@ -242,7 +243,7 @@ async fn bridge(
.and_then(|v| v.get("answer").and_then(Value::as_str).map(str::to_string))
.unwrap_or_else(|| "Mercury didn't answer in time. It will send the answer to the chat.".into());
pending2.lock().unwrap().remove(&id);
- let _ = tx2.send((id, answer));
+ let _ = tx2.send((id, answer, now));
});
};
@@ -312,7 +313,9 @@ async fn bridge(
Some(a) = answer_rx.recv() => {
if a.1.starts_with("(superseded") || a.1.starts_with("(stopped") { continue; }
narration = None; // the result supersedes anything still unsaid
- ready_answers.push_back(a);
+ // Hold the answer against what actually happened on the screen.
+ let failed: Vec<String> = sh.failures.lock().unwrap().iter().filter(|(at, _)| *at >= a.2).map(|(_, f)| f.clone()).collect();
+ ready_answers.push_back((a.0, honest(brain, a.1, &failed)));
if !responding { deliver(&link, brain, &mut ready_answers, &mut responding); }
}
_ = status_tick.tick() => {
@@ -505,6 +508,25 @@ async fn bridge(
result
}
+/// Mercury's answer, with the steps that failed during it made impossible to miss.
+fn honest(brain: Brain, answer: String, failed: &[String]) -> String {
+ if failed.is_empty() {
+ return answer;
+ }
+ match brain {
+ Brain::Voice => format!(
+ "{answer}\n[Optimus log for this request, not part of Mercury's answer: {} step(s) failed or were stopped ({}). Unless the answer above says Mercury checked the result on the screen, don't tell the user it's done: say what didn't work and offer to try again.]",
+ failed.len(),
+ failed.join("; ")
+ ),
+ Brain::Mercury => {
+ let a = answer.to_lowercase();
+ let admits = ["fail", "couldn", "could not", "didn", "did not", "not able", "unable", "wasn't", "stopped"].iter().any(|w| a.contains(w));
+ if admits { answer } else { format!("Heads up, some steps didn't work. {answer}") }
+ }
+ }
+}
+
fn say_stopped(link: &Link, brain: Brain) {
match brain {
Brain::Voice => link.send(LinkCmd::Instruct("[The user stopped everything, not said by the user] All of Mercury's actions have been stopped. Say only: 'Stopped.' Then wait.".into())),
@@ -556,7 +578,7 @@ fn speak_narration(link: &Link, brain: Brain, pending: &mut Option<String>, resp
if let Some(line) = pending.take() {
match brain {
Brain::Voice => link.send(LinkCmd::Instruct(format!(
- "[Live update, not said by the user] Mercury is doing this on the screen right now: {line}. Say it in a few words, present tense, and nothing else."
+ "[Live update, not said by the user] Mercury is doing this on the screen right now: {line}. It is in progress, not finished. Say it in a few words, present tense, and nothing else; never say the task is done because of an update."
))),
Brain::Mercury => link.send(LinkCmd::Say(line)),
}
@@ -612,6 +634,14 @@ mod tests {
assert_eq!(spoken_verdict(&[(asked - Duration::from_secs(5), "yes".into())], asked), None);
}
+ #[test]
+ fn failed_steps_are_never_hidden() {
+ assert_eq!(honest(Brain::Voice, "Done.".into(), &[]), "Done.");
+ assert!(honest(Brain::Voice, "I've posted it.".into(), &["act: FAILED".into()]).contains("don't tell the user it's done"));
+ assert!(honest(Brain::Mercury, "I've posted it.".into(), &["act: FAILED".into()]).starts_with("Heads up"));
+ assert_eq!(honest(Brain::Mercury, "The click failed.".into(), &["act: FAILED".into()]), "The click failed.");
+ }
+
#[test]
fn stop_words() {
assert!(is_stop("Stop!"));
diff --git a/plugins/optimus/mercury-plugin.template.json b/plugins/optimus/mercury-plugin.template.json
index 3a68e531..f0988ba1 100644
--- a/plugins/optimus/mercury-plugin.template.json
+++ b/plugins/optimus/mercury-plugin.template.json
@@ -2,7 +2,7 @@
"manifestVersion": 1,
"id": "optimus",
"name": "Optimus",
- "version": "0.4.2",
+ "version": "0.4.3",
"description": "Mercury uses your computer like a person: sees the screen, moves the mouse, types and opens apps, by chat or out loud with a talk key. macOS, Windows and Linux. Asks before anything that submits, sends, pays or deletes.",
"kind": "out-of-process",
"author": "Cosmic Stack",
@@ -32,7 +32,7 @@
},
{
"name": "act",
- "description": "Use the mouse and keyboard like a person: click, type, paste, press keys, scroll, drag, draw freehand. Returns a fresh screenshot. Pass `actions` as a list. To write text (posts, emails, articles) click the box, then use type: it types key by key like a person, so it works in every editor (up to 3,000 characters per type action; longer text in parts). Use paste only if typing fails. Only for ordinary, reversible steps. Anything that submits, sends, posts, pays, buys, deletes, installs or changes settings must go through act_consequential instead. Never type passwords, card numbers or 2FA codes: ask the owner to do that part.",
+ "description": "Use the mouse and keyboard like a person: click, type, paste, press keys, scroll, drag, draw freehand. Returns a fresh screenshot. Pass `actions` as a list. To write text (posts, emails, articles) click the box, then use type: it types key by key like a person, so it works in every editor (up to 3,000 characters per type action; longer text in parts). Use paste only if typing fails. \"Sent\" means the input was sent, not that it worked: check the returned screenshot, and before telling the owner a task is done, look and confirm the result. FAILED means nothing (or not everything) happened. Only for ordinary, reversible steps. Anything that submits, sends, posts, pays, buys, deletes, installs or changes settings must go through act_consequential instead. Never type passwords, card numbers or 2FA codes: ask the owner to do that part.",
"readOnly": true,
"timeoutMs": 300000
},
diff --git a/src/plugins/channel-bridge.ts b/src/plugins/channel-bridge.ts
index 7933c96c..19321451 100644
--- a/src/plugins/channel-bridge.ts
+++ b/src/plugins/channel-bridge.ts
@@ -160,7 +160,7 @@ interface IncomingParams {
}
/** Put in front of a question asked out loud in a desktop voice session. */
-const DESKTOP_VOICE_NOTE = '[Voice, on the owner\'s own computer: they asked this out loud. Use your tools to get the real answer: web_search for anything current, fetch_url, memory, skills, and the Optimus tools to see and use their screen. Then answer in one to three short spoken sentences, with no markdown, lists, links or code. Go ahead and do what they ask: if an action needs approval, Mercury asks them out loud and continues once they say yes. Links, lists and other details worth keeping: don\'t read them out; put them after a final line "For the chat:" (that part isn\'t spoken; it goes to their Mercury chat).]';
+const DESKTOP_VOICE_NOTE = '[Voice, on the owner\'s own computer: they asked this out loud. Use your tools to get the real answer: web_search for anything current, fetch_url, memory, skills, and the Optimus tools to see and use their screen. Then answer in one to three short spoken sentences, with no markdown, lists, links or code. Only say something is done if you checked it on the screen; if a step failed or you could not confirm it, say so. Go ahead and do what they ask: if an action needs approval, Mercury asks them out loud and continues once they say yes. Links, lists and other details worth keeping: don\'t read them out; put them after a final line "For the chat:" (that part isn\'t spoken; it goes to their Mercury chat).]';
export class PluginChannel extends BaseChannel {
readonly type: ChannelType;
@@ -632,6 +632,7 @@ export class PluginChannel extends BaseChannel {
`## Channel: ${name} (voice, on the owner's computer)`,
'You\'re talking with the owner, out loud, at their own computer. Your answer is spoken: one to three short sentences, no markdown, lists, links or code.',
`To see their screen use ${this.manifest.id}__look; to do things on it use ${this.manifest.id}__open and ${this.manifest.id}__act, and ${this.manifest.id}__act_consequential for the step that submits, sends, posts, pays, deletes or installs (e.g. the final Post or Send button). Give every open/act call a short \`say\` ("Opening Gmail", "Typing your post"): it is spoken the moment it happens, so the owner hears each step live. Look after each step and check it worked before the next. To write text, click the box and use a type action (it types like a person); paste only if typing fails.`,
+ 'Never say a task is done unless you saw it done: before answering, take a fresh look and check the exact result (the post is published, the emails are gone, the file is saved), and say what you saw. If any step came back FAILED, was stopped, or you could not confirm the result, say that plainly and offer to try again. A step reply that says "Sent" only means the input reached the screen.',
'Access: Extended. Use your tools, skills, files and memory as you would anywhere else. Approvals are asked out loud and answered by voice.',
].join('\n');
}