Soul-driven AI agent with permission-hardened tools, token budgets, and multi-channel access. Runs 24/7 from CLI, Telegram or More.
feat(optimus): "stop" really stops, and a soft tick while Mercury works (0.4.1)
Salman Qureshi7f2fe821ddec
diff --git a/plugins/optimus/README.md b/plugins/optimus/README.mdindex 1ca3d89f..2637322d 100644--- a/plugins/optimus/README.md+++ b/plugins/optimus/README.md@@ -24,7 +24,10 @@ Change any of it later in `/plugins optimus`.## Talking to it- **Chat:** ask Mercury in any chat (TUI, dashboard, WhatsApp, Telegram): "look at my screen", "open Safari and search for…".-- **Listening:** press the talk key (you hear a rising chime), talk, and Mercury answers out loud while it works on your screen. Press the key while it's speaking to interrupt; press it when it's quiet, or say goodbye, to stop (falling chime). Links and details go to your Mercury chat. Approvals are asked out loud.+- **Listening:** press the talk key (you hear a rising chime), talk, and Mercury answers out loud while it works on your screen, saying each step as it happens. A soft tick means it's still working.+- **The talk key:** while Optimus is working it's the **stop button** (everything halts, you keep talking); while Mercury is speaking it interrupts; when all is quiet it ends the session (falling chime).+- **Saying "stop"** ("cancel", "ruko", "bas") halts every action and the task at once; **"bye"** does the same and ends the session. Silence for 60 seconds ends it too.+- Links and details go to your Mercury chat. Approvals are asked out loud.- With speakers, the mic is muted while Mercury talks so it doesn't hear itself. With headphones, turn on "I use headphones" in `/plugins optimus` → 🎙 Voice to interrupt just by talking.- macOS asks once for the **Microphone** for Optimus.diff --git a/plugins/optimus/companion/Cargo.lock b/plugins/optimus/companion/Cargo.lockindex 5dd5c514..31d54d75 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.0"+version = "0.4.1"dependencies = ["base64 0.22.1","core-foundation",diff --git a/plugins/optimus/companion/Cargo.toml b/plugins/optimus/companion/Cargo.tomlindex 320269d4..c44a69a9 100644--- a/plugins/optimus/companion/Cargo.toml+++ b/plugins/optimus/companion/Cargo.toml@@ -1,6 +1,6 @@[package]name = "mercury-optimus"-version = "0.4.0"+version = "0.4.1"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/audio.rs b/plugins/optimus/companion/src/audio.rsindex 3f43c4b3..6494e396 100644--- a/plugins/optimus/companion/src/audio.rs+++ b/plugins/optimus/companion/src/audio.rs@@ -66,11 +66,28 @@ impl Output {}}+ /// The "still working" tick: two very soft, short clicks, well below speech level.+ pub fn tick(&self) {+ let mut q = self.queue.lock().unwrap();+ for (f, gap) in [(1500.0f32, 0.07f32), (1150.0, 0.0)] {+ let n = (self.rate as f32 * 0.016) as usize;+ for i in 0..n {+ let t = i as f32 / self.rate as f32;+ let env = (1.0 - i as f32 / n as f32).powi(3);+ q.push_back((2.0 * std::f32::consts::PI * f * t).sin() * 0.03 * env);+ }+ for _ in 0..(self.rate as f32 * gap) as usize {+ q.push_back(0.0);+ }+ }+ }+fn next(&self) -> f32 {let s = self.queue.lock().unwrap().pop_front();match s {Some(v) => {- if v.abs() > 0.004 {+ // Only real sound (speech, chimes) counts: the quiet thinking tick doesn't mute the mic.+ if v.abs() > 0.06 {self.last_sound.store(self.start.elapsed().as_millis() as u64, Ordering::Relaxed);}vdiff --git a/plugins/optimus/companion/src/core.rs b/plugins/optimus/companion/src/core.rsindex 39b68cd1..40125aa7 100644--- a/plugins/optimus/companion/src/core.rs+++ b/plugins/optimus/companion/src/core.rs@@ -32,6 +32,31 @@ fn error_sound() {let _ = std::process::Command::new("afplay").arg("/System/Library/Sounds/Basso.aiff").spawn();}+/// "Stop" from the owner: until this time (ms since the epoch) no screen action+/// runs, and any in progress aborts at its next step.+static HALT_UNTIL_MS: AtomicU64 = AtomicU64::new(0);++fn now_ms() -> u64 {+ std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map(|d| d.as_millis() as u64).unwrap_or(0)+}++/// Stop every screen action now, and refuse new ones for `secs` (while Mercury cancels the task).+pub fn halt(secs: u64) {+ HALT_UNTIL_MS.store(now_ms() + secs * 1000, Ordering::Relaxed);+ crate::overlay::done();+}++pub fn halted() -> bool {+ now_ms() < HALT_UNTIL_MS.load(Ordering::Relaxed)+}++/// A new request from the owner lifts an earlier stop.+pub fn clear_halt() {+ HALT_UNTIL_MS.store(0, Ordering::Relaxed);+}++pub const STOPPED: &str = "Stopped: the owner said stop. Don't continue this task or try again unless they ask.";+pub fn settings() -> Value {std::env::var("MERCURY_PLUGIN_SETTINGS").ok().and_then(|s| serde_json::from_str(&s).ok()).unwrap_or(json!({}))}@@ -102,6 +127,11 @@ pub struct Shared {}impl Shared {+ /// A screen action is running right now.+ pub fn is_working(&self) -> bool {+ self.working.lock().unwrap().0 > 0+ }+/// Tell Mercury whether Optimus is listening and/or working (the TUI status bar shows it).pub fn publish_activity(&self) {let listening = self.session.lock().unwrap().is_some();@@ -155,6 +185,10 @@ pub fn run(inbox: std::sync::mpsc::Receiver<Value>, send: impl Fn(Value) + Send}}let on_screen = matches!(name.as_str(), "look" | "act" | "open" | "windows");+ if on_screen && name != "look" && halted() {+ shared.out.op_result(id, Err(STOPPED.into()));+ continue;+ }if on_screen {shared.working.lock().unwrap().0 += 1;shared.publish_activity();diff --git a/plugins/optimus/companion/src/motion.rs b/plugins/optimus/companion/src/motion.rsindex 267d834f..39d115fa 100644--- a/plugins/optimus/companion/src/motion.rs+++ b/plugins/optimus/companion/src/motion.rs@@ -88,6 +88,10 @@ pub fn glide(e: &mut Enigo, to: (i32, i32), last: &mut Option<(i32, i32)>) -> Relet x = u * u * from.0 as f64 + 2.0 * u * s * ctrl.0 + s * s * to.0 as f64;let y = u * u * from.1 as f64 + 2.0 * u * s * ctrl.1 + s * s * to.1 as f64;let p = (x.round() as i32, y.round() as i32);+ if crate::core::halted() {+ *last = None;+ return Err(crate::core::STOPPED.into());+ }if p != prev {// Something other than us moved it since the last step: the owner took over.if let Ok(now) = e.location() {@@ -118,6 +122,9 @@ pub fn type_text(e: &mut Enigo, text: &str, last: &Option<(i32, i32)>) -> Resultlet fast = pace() == Pace::Fast;let mut n = 0usize;for c in text.chars() {+ if crate::core::halted() {+ return Err(format!("typed {n} characters, then: {}", crate::core::STOPPED));+ }if n % 12 == 0 {if let (Some((lx, ly)), Ok(now)) = (*last, e.location()) {if (now.0 - lx).abs() > TAKEOVER_PX || (now.1 - ly).abs() > TAKEOVER_PX {diff --git a/plugins/optimus/companion/src/ops.rs b/plugins/optimus/companion/src/ops.rsindex d2eb1167..77242998 100644--- a/plugins/optimus/companion/src/ops.rs+++ b/plugins/optimus/companion/src/ops.rs@@ -212,6 +212,10 @@ impl Ops {let mut stopped: Option<String> = None;for (i, a) in actions.iter().enumerate() {+ if crate::core::halted() {+ stopped = Some(format!("Stopped before action {}: {}", i + 1, crate::core::STOPPED));+ break;+ }// The user moved the mouse since our last move: they're taking over.if let Some((lx, ly)) = last_set {if let Some((cx, cy)) = self.cursor() {diff --git a/plugins/optimus/companion/src/voice.rs b/plugins/optimus/companion/src/voice.rsindex e234d6d0..7220568a 100644--- a/plugins/optimus/companion/src/voice.rs+++ b/plugins/optimus/companion/src/voice.rs@@ -69,6 +69,7 @@ pub async fn press(sh: Arc<Shared>, from_tool: bool) -> Result<String, String> {}*live = Some(SessionCtl { tx });}+ crate::core::clear_halt();let call_id = format!("desk-{}", std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map(|d| d.as_millis()).unwrap_or(0));let problem = links::not_ready(&settings());let decision = sh@@ -211,6 +212,9 @@ async fn bridge(let silence = vec![0i16; FRAME];// Live narration: the newest line waits while the voice is speaking; older ones are dropped.let mut narration: Option<String> = None;+ let thinking_sound = settings().get("thinkingSound").and_then(Value::as_bool).unwrap_or(true);+ let mut tick = tokio::time::interval(Duration::from_millis(1100));+ tick.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Skip);let mut last_narrated = Instant::now() - Duration::from_secs(60);// Silence ends the session by itself, so an open mic never streams (and bills) for nothing.@@ -241,11 +245,33 @@ async fn bridge(});};+ // "Stop": the screen actions and the Mercury task this session started end now.+ let stop_all = |pending: &Arc<std::sync::Mutex<HashMap<String, (Instant, Instant, u32)>>>| {+ crate::core::halt(8);+ pending.lock().unwrap().clear();+ let sh2 = sh.clone();+ let call = call_id.to_string();+ tokio::spawn(async move {+ let _ = sh2.out.request("mercury/call/stop", json!({ "callId": call }), Duration::from_secs(5)).await;+ });+ log(format!("{call_id}: stopped by the owner"));+ };+ let busy_working = |pending: &Arc<std::sync::Mutex<HashMap<String, (Instant, Instant, u32)>>>| !pending.lock().unwrap().is_empty() || sh.is_working();+let result = loop {tokio::select! {_ = &mut deadline => break Ok(()),+ _ = tick.tick() => {+ // Soft "still working" tick while Mercury searches or acts and nobody is talking.+ if thinking_sound && !pending.lock().unwrap().is_empty() && !responding && !out.busy() && last_narrated.elapsed() > Duration::from_secs(2) {+ out.tick();+ }+ }c = ctl.recv() => match c {- None | Some(Ctl::Stop) => break Ok(()),+ None | Some(Ctl::Stop) => {+ if busy_working(&pending) { stop_all(&pending); }+ break Ok(());+ }Some(Ctl::Narrate(line)) => {last_narrated = Instant::now();narration = Some(line);@@ -254,7 +280,16 @@ async fn bridge(}}Some(Ctl::Press) => {- if responding || out.recently_audible(300) {+ if busy_working(&pending) {+ // While it's working, the key is the stop button: everything halts, the session stays.+ stop_all(&pending);+ narration = None;+ ready_answers.clear();+ out.clear();+ link.send(LinkCmd::Cancel);+ say_stopped(&link, brain);+ responding = true;+ } else if responding || out.recently_audible(300) {// Mercury is talking: the key interrupts.out.clear();link.send(LinkCmd::Cancel);@@ -271,7 +306,7 @@ async fn bridge(link.send(LinkCmd::Audio(if muted { silence.clone() } else { frame }));}Some(a) = answer_rx.recv() => {- if a.1.starts_with("(superseded") { continue; }+ if a.1.starts_with("(superseded") || a.1.starts_with("(stopped") { continue; }narration = None; // the result supersedes anything still unsaidready_answers.push_back(a);if !responding { deliver(&link, brain, &mut ready_answers, &mut responding); }@@ -378,6 +413,17 @@ async fn bridge(transcript.push(json!({ "role": "owner", "text": t.clone() }));user_said.push((Instant::now(), t.clone()));if user_said.len() > 20 { user_said.remove(0); }+ if is_stop(&t) && verifying.is_none() && awaiting.is_none() {+ // "Stop" / "cancel" / "ruko": halt everything at once.+ stop_all(&pending);+ narration = None;+ ready_answers.clear();+ out.clear();+ link.send(LinkCmd::Cancel);+ say_stopped(&link, brain);+ responding = true;+ continue;+ }if let Some((fc, id, asked_at, _)) = verifying.clone() {if let Some(v) = spoken_verdict(&user_said, asked_at) {verifying = None;@@ -398,6 +444,7 @@ async fn bridge(}}if is_goodbye(&t) {+ if busy_working(&pending) { stop_all(&pending); }link.send(LinkCmd::Say("Okay, bye for now!".into()));tokio::time::sleep(Duration::from_millis(2500)).await;break Ok(());@@ -409,6 +456,7 @@ async fn bridge(}LinkEvent::ToolCall { id, name, args } => {if name == "end_conversation" || name == "end_call" {+ if busy_working(&pending) { stop_all(&pending); }for _ in 0..50 {if !out.busy() { break; }tokio::time::sleep(Duration::from_millis(100)).await;@@ -453,6 +501,23 @@ async fn bridge(result}+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())),+ Brain::Mercury => link.send(LinkCmd::Say("Stopped.".into())),+ }+}++/// A short "stop!" / "cancel" / "ruko" / "bas": halt everything.+fn is_stop(t: &str) -> bool {+ let t = format!(" {} ", t.to_lowercase().replace(|c: char| !c.is_alphanumeric() && !c.is_whitespace() && (c as u32) < 128, " "));+ t.split_whitespace().count() <= 4+ && [" stop ", " cancel ", " halt ", " abort ", " enough ", " never mind ", " nevermind ", " ruko ", " ruk jao ", " ruk ", " bas ", " band karo ", "रुको", "रुक जाओ", "बस", "رکو", "بس"]+ .iter()+ .any(|w| t.contains(w))+ && !t.contains(" stop listening ")+}+fn is_goodbye(t: &str) -> bool {let t = format!(" {} ", t.to_lowercase().trim_matches(|c: char| !c.is_alphanumeric() && !c.is_whitespace()));let short = t.split_whitespace().count() <= 4;@@ -543,6 +608,15 @@ mod tests {assert_eq!(spoken_verdict(&[(asked - Duration::from_secs(5), "yes".into())], asked), None);}+ #[test]+ fn stop_words() {+ assert!(is_stop("Stop!"));+ assert!(is_stop("cancel that"));+ assert!(is_stop("ruko"));+ assert!(!is_stop("stop listening"), "that's a goodbye, handled separately");+ assert!(!is_stop("can you stop by the store on your way home later"));+ }+#[test]fn goodbyes() {assert!(is_goodbye("Okay, bye!"));diff --git a/plugins/optimus/mercury-plugin.template.json b/plugins/optimus/mercury-plugin.template.jsonindex 7cf92318..95f7dc5a 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.0",+ "version": "0.4.1","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",@@ -197,6 +197,19 @@]}},+ "thinkingSound": {+ "type": "boolean",+ "default": true,+ "label": "Soft tick while Mercury works",+ "description": "A very quiet tick about once a second while Mercury searches or works on your screen and nobody is talking, so you know it's still going.",+ "group": "voice",+ "when": {+ "mode": [+ "voice",+ "both"+ ]+ }+ },"idleStopSeconds": {"type": "number","default": 60,diff --git a/src/core/agent.ts b/src/core/agent.tsindex 7a56b81c..dd263354 100644--- a/src/core/agent.ts+++ b/src/core/agent.ts@@ -4556,6 +4556,27 @@ RULES:* next start does not auto-resume killed tasks. Crash recovery is* unaffected — this is only invoked on intentional exits.*/+ /**+ * Stop only the work started from one place (e.g. a desktop voice session,+ * "desktop:call:<id>"): the running turn if it's theirs, and anything+ * queued for it. Other chats keep going. Returns whether anything stopped.+ */+ stopWorkFor(channelPrefix: string, reason = 'Stopped by the owner.'): boolean {+ const before = this.messageQueue.length;+ this.messageQueue = this.messageQueue.filter((i) => !i.message.channelId.startsWith(channelPrefix));+ let stopped = this.messageQueue.length !== before;+ if (this.currentMessage?.channelId.startsWith(channelPrefix) && this.currentAbort && !this.currentAbort.signal.aborted) {+ this.currentAbortReason = 'stopped';+ this.currentAbort.abort();+ if (this.currentWorkKey) {+ try { this.workLedger.markCancelled(this.currentWorkKey, reason); } catch { /* entry may not exist */ }+ }+ stopped = true;+ }+ if (stopped) logger.info({ channelPrefix }, 'Work stopped for one channel');+ return stopped;+ }+cancelActiveWork(reason = 'Cancelled by the user.'): number {try {return this.workLedger.cancelActive(reason);diff --git a/src/index.ts b/src/index.tsindex ddbe08f2..9fa719f7 100644--- a/src/index.ts+++ b/src/index.ts@@ -54,7 +54,7 @@ import { buildConversationHistoryPayload, CloudSessionSynchronizer, SessionReposimport { UserMemoryStore } from './memory/user-memory.js';import { BotManager } from './bots/bot-manager.js';import { getPluginManager, peekPluginManager, setProviderLookup } from './plugins/manager.js';-import { setCallLearning, setChannelHost, setDesktopActivityHook, setVoiceBriefing } from './plugins/channel-bridge.js';+import { setCallLearning, setChannelHost, setDesktopActivityHook, setVoiceBriefing, setWorkStopper } from './plugins/channel-bridge.js';import { registerPluginsCli } from './cli/plugins-cli.js';import { SECOND_BRAIN_UNAVAILABLE_MESSAGE } from './memory/second-brain-db.js';import { isSqliteAvailable } from './utils/sqlite-driver.js';@@ -2694,6 +2694,7 @@ async function runAgent(isDaemon: boolean = false): Promise<void> {// Calls know what chats know (identity, about, the owner's profile) and learn like chats do.setVoiceBriefing(() => agent.voiceBriefing());setCallLearning((ownerSaid, mercurySaid) => agent.learnFromConversation(ownerSaid, mercurySaid));+ setWorkStopper((prefix) => agent.stopWorkFor(prefix, 'Stopped by the owner on a voice call.'));setDesktopActivityHook((label) => {const cli = channels.get('cli');if (cli instanceof CLIChannel) cli.setDesktopActivity(label);diff --git a/src/plugins/channel-bridge.ts b/src/plugins/channel-bridge.tsindex 42af903f..7933c96c 100644--- a/src/plugins/channel-bridge.ts+++ b/src/plugins/channel-bridge.ts@@ -308,6 +308,22 @@ export class PluginChannel extends BaseChannel {const ok = this.resolveCallApproval(approvalId, p.approved === true ? 'yes' : 'no', 'voice');return { ok, reason: ok ? undefined : 'that approval is no longer open (answered in the chat, or timed out)' };}+ case 'mercury/call/stop': {+ // The owner said stop (or goodbye) on the call: end the work it started, now.+ const callId = String(p.callId ?? '').replace(/[^\w.-]/g, '').slice(0, 80);+ if (!callId) throw new Error('callId is required');+ const target = `call:${callId}`;+ const stopped = workStopper?.(`${this.type}:${target}`) ?? false;+ const ask = this.callAsks.get(target);+ if (ask) {+ clearTimeout(ask.timer);+ this.callAsks.delete(target);+ ask.resolve('(stopped by the owner)');+ }+ this.overflow.delete(target);+ for (const [id, a] of this.callApprovals) if (a.callId === callId) this.resolveCallApproval(id, 'no', 'timeout');+ return { stopped };+ }case 'mercury/call/ask': {const callId = typeof p.callId === 'string' ? p.callId.replace(/[^\w.-]/g, '').slice(0, 80) : '';const question = typeof p.question === 'string' ? p.question.trim().slice(0, 4000) : '';@@ -806,6 +822,12 @@ export function setVoiceBriefing(fn: (() => string) | null): void {}/** After a call: let Mercury learn from it like any other conversation. */+let workStopper: ((channelPrefix: string) => boolean) | null = null;+/** How a call's "stop" ends the Mercury work it started (agent.stopWorkFor). */+export function setWorkStopper(fn: ((channelPrefix: string) => boolean) | null): void {+ workStopper = fn;+}+let desktopActivityHook: ((label: string | null) => void) | null = null;/** Where desktop activity is shown (the TUI status bar). */export function setDesktopActivityHook(fn: ((label: string | null) => void) | null): void {diff --git a/src/plugins/channel.test.ts b/src/plugins/channel.test.tsindex b469b5ae..70b3cfa1 100644--- a/src/plugins/channel.test.ts+++ b/src/plugins/channel.test.ts@@ -7,7 +7,7 @@ import type { Channel } from '../channels/base.js';import type { ChannelMessage } from '../types/channel.js';import { PluginManager, setProviderLookup } from './manager.js';import { PluginChannel } from './channel-bridge.js';-import { activityLabel, getPluginChannel, setCallLearning, setChannelHost, setDesktopActivityHook, setVoiceBriefing, splitMessage, spokenPart, toWhatsAppText, voiceBriefing } from './channel-bridge.js';+import { activityLabel, getPluginChannel, setCallLearning, setChannelHost, setDesktopActivityHook, setVoiceBriefing, setWorkStopper, splitMessage, spokenPart, toWhatsAppText, voiceBriefing } from './channel-bridge.js';import { getPluginTools, resetToolBridge } from './tool-bridge.js';import { pluginDataDir } from './store.js';import { manifestSchema } from './types.js';@@ -560,6 +560,26 @@ describe('plugin channels (plugin API 1.1)', () => {expect(activityLabel('Optimus', false, true)).toBe('🖱 Optimus working');});+ it('"stop" on the call ends the work it started, and its pending approvals', async () => {+ const stoppedFor: string[] = [];+ setWorkStopper((prefix) => { stoppedFor.push(prefix); return true; });+ try {+ const ch = await installDesktop();+ await callsim('mercury/call/ask', { callId: 's1', question: 'Clean my junk mail' });+ await waitFor(() => received.length === 1);+ const approval = ch.askPermission('Delete 40 emails', 'desktop:call:s1');+ await callsim('mercury/call/stop', { callId: 's1' });+ await waitFor(() => lines('replies.jsonl').length === 2);+ const r = lines('replies.jsonl');+ expect(r.find((x) => 'answer' in (x.result ?? {}))?.result.answer).toBe('(stopped by the owner)');+ expect(r.find((x) => 'stopped' in (x.result ?? {}))?.result.stopped).toBe(true);+ expect(stoppedFor).toEqual(['desktop:call:s1']);+ expect(await approval).toBe('no');+ } finally {+ setWorkStopper(null);+ }+ });+it('approvals are asked out loud only', async () => {const ch = await installDesktop();const answer = ch.askPermission('Submit the job application', 'desktop:call:d3');