Soul-driven AI agent with permission-hardened tools, token budgets, and multi-channel access. Runs 24/7 from CLI, Telegram or More.
feat(voice): live Optimus sessions for clients, with remote controls
Salman Qureshi0909b5d1c9bc
diff --git a/plugins/optimus/companion/src/core.rs b/plugins/optimus/companion/src/core.rsindex c55dfeeb..69278557 100644--- a/plugins/optimus/companion/src/core.rs+++ b/plugins/optimus/companion/src/core.rs@@ -123,7 +123,7 @@ pub struct Shared {/// How the talk key reads, e.g. "Control+Option+M" (empty when there's none).pub hotkey_label: Mutex<String>,/// Screen operations in progress, and the (listening, working) state last reported.- working: Mutex<(u32, Option<(bool, bool, bool)>)>,+ working: Mutex<(u32, Option<(bool, bool, 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)>>,}@@ -136,15 +136,15 @@ impl Shared {/// Tell Mercury whether Optimus is listening and/or working (the TUI status bar shows it).pub fn publish_activity(&self) {- let (listening, muted) = match self.session.lock().unwrap().as_ref() {- Some(s) => (true, s.is_muted()),- None => (false, false),+ let (listening, muted, speaking) = match self.session.lock().unwrap().as_ref() {+ Some(s) => (true, s.is_muted(), s.is_speaking()),+ None => (false, false, false),};let mut w = self.working.lock().unwrap();- let now = (listening, w.0 > 0, muted);+ let now = (listening, w.0 > 0, muted, speaking);if w.1 != Some(now) {w.1 = Some(now);- self.out.notify("mercury/channel/activity", json!({ "listening": now.0, "working": now.1, "muted": now.2 }));+ self.out.notify("mercury/channel/activity", json!({ "listening": now.0, "working": now.1, "muted": now.2, "speaking": now.3 }));}}}@@ -352,6 +352,20 @@ fn on_mercury(shared: &Arc<Shared>, msg: &Value) {let p = msg.get("params").cloned().unwrap_or(Value::Null);let call = p.get("callId").and_then(Value::as_str).unwrap_or("").to_string();match method {+ // Mercury Desktop's voice controls (the notch capsule and the status bar).+ "mercury/voice/control" => {+ let action = p.get("action").and_then(Value::as_str).unwrap_or("");+ let live = shared.session.lock().unwrap();+ if let Some(s) = live.as_ref() {+ match action {+ "mute" => s.set_mute(true),+ "unmute" => s.set_mute(false),+ "interrupt" => s.interrupt(),+ "stop" => s.stop(),+ _ => log(format!("voice control: unknown action {action}")),+ }+ }+ }"mercury/call/progress" => {if let Some(a) = p.get("activity").and_then(Value::as_str) {shared.call_activity.lock().unwrap().insert(call, a.chars().take(80).collect());diff --git a/plugins/optimus/companion/src/voice.rs b/plugins/optimus/companion/src/voice.rsindex aa9212cd..c1a04068 100644--- a/plugins/optimus/companion/src/voice.rs+++ b/plugins/optimus/companion/src/voice.rs@@ -32,11 +32,15 @@ pub enum Ctl {Narrate(String),/// The mute key: stop (or start again) listening, without stopping any work.Mute,+ /// Pause from Mercury Desktop: stop what it's saying or doing, keep the session.+ Interrupt,}pub struct SessionCtl {tx: mpsc::UnboundedSender<Ctl>,muted: Arc<std::sync::atomic::AtomicBool>,+ /// Mercury's voice is playing right now (published as activity.speaking).+ speaking: Arc<std::sync::atomic::AtomicBool>,}impl SessionCtl {@@ -52,6 +56,29 @@ impl SessionCtl {pub fn is_muted(&self) -> bool {self.muted.load(std::sync::atomic::Ordering::Relaxed)}+ /// Mute or unmute to a known state (a remote control can't rely on toggling).+ pub fn set_mute(&self, on: bool) {+ if self.is_muted() != on {+ let _ = self.tx.send(Ctl::Mute);+ }+ }+ pub fn interrupt(&self) {+ let _ = self.tx.send(Ctl::Interrupt);+ }+ pub fn is_speaking(&self) -> bool {+ self.speaking.load(std::sync::atomic::Ordering::Relaxed)+ }+}++/// Record whether Mercury's voice is playing, and tell Mercury when it changes.+fn set_speaking(sh: &Arc<Shared>, on: bool) {+ let changed = match sh.session.lock().unwrap().as_ref() {+ Some(s) => s.speaking.swap(on, std::sync::atomic::Ordering::Relaxed) != on,+ None => false,+ };+ if changed {+ sh.publish_activity();+ }}/// The talk key was pressed (or the `listen` tool called).@@ -77,7 +104,7 @@ pub async fn press(sh: Arc<Shared>, from_tool: bool) -> Result<String, String> {if live.is_some() {return Ok(String::new());}- *live = Some(SessionCtl { tx, muted: muted.clone() });+ *live = Some(SessionCtl { tx, muted: muted.clone(), speaking: Arc::new(std::sync::atomic::AtomicBool::new(false)) });}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));@@ -300,6 +327,24 @@ async fn bridge(set_muted(sh, muted, &out, now, &call_id);last_activity = Instant::now();}+ Some(Ctl::Interrupt) => {+ // Like the talk key, except it never ends the session.+ if busy_working(&pending) {+ 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) {+ out.clear();+ link.send(LinkCmd::Cancel);+ responding = false;+ set_speaking(sh, false);+ }+ last_activity = Instant::now();+ }Some(Ctl::Press) if muted.load(std::sync::atomic::Ordering::Relaxed) => {// Muted: the talk key unmutes rather than stopping anything.set_muted(sh, muted, &out, false, &call_id);@@ -421,9 +466,13 @@ async fn bridge(let Some(ev) = ev else { break Err("the voice connection ended".to_string()) };match ev {LinkEvent::Closed(reason) => break Err(reason),- LinkEvent::ResponseStarted => responding = true,+ LinkEvent::ResponseStarted => {+ responding = true;+ set_speaking(sh, true);+ }LinkEvent::ResponseDone => {responding = false;+ set_speaking(sh, false);if !ready_answers.is_empty() { deliver(&link, brain, &mut ready_answers, &mut responding); }else if narration.is_some() { speak_narration(&link, brain, &mut narration, &mut responding); }}diff --git a/src/plugins/channel-bridge.ts b/src/plugins/channel-bridge.tsindex b1613f65..fa633fa4 100644--- a/src/plugins/channel-bridge.ts+++ b/src/plugins/channel-bridge.ts@@ -37,6 +37,7 @@* first answer wins. The plugin accepts a spoken yes only when the owner's own* transcribed words say yes, and a spoken yes never becomes "always".*/+import { voiceFeed } from './voice-feed.js';import { basename } from 'node:path';import { existsSync, readFileSync, statSync } from 'node:fs';import { join } from 'node:path';@@ -249,10 +250,15 @@ export class PluginChannel extends BaseChannel {attach(): void {live.set(this.manifest.id, this);host?.register(this.type, this);+ // Desktop voice (Optimus): clients see the session live and can steer it.+ if (this.desktop) voiceFeed.attach(this.manifest.name, (action) => this.transport.notify?.('mercury/voice/control', { action }));}detach(): void {- if (this.desktop) desktopActivityHook?.(null);+ if (this.desktop) {+ desktopActivityHook?.(null);+ voiceFeed.detach(this.manifest.name);+ }if (live.get(this.manifest.id) === this) live.delete(this.manifest.id);host?.unregister(this.type, this);this.ready = false;@@ -288,6 +294,7 @@ export class PluginChannel extends BaseChannel {return { accept: false, reason: 'voice engine not ready' };}this.callStarted(String(p.callId ?? ''));+ if (this.desktop) voiceFeed.started(String(p.callId ?? ''));return { accept: true, instructions: voiceBriefing() };}case 'mercury/call/briefing':@@ -330,6 +337,7 @@ export class PluginChannel extends BaseChannel {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) : '';if (!callId || !question) throw new Error('callId and question are required');+ if (this.desktop) voiceFeed.asked(callId, question);return { answer: await this.askDuringCall(callId, question) };}default:@@ -389,6 +397,7 @@ export class PluginChannel extends BaseChannel {this.callAsks.delete(target);const answer = ask.chunks.filter((c) => !/^(☿|⚙|⏳|\s*\[)/.test(c.trim())).pop() ?? ask.chunks.pop() ?? '';ask.resolve(spokenPart(answer) || 'Done.');+ if (this.desktop) voiceFeed.answered(spokenPart(answer) || 'Done.');// On the desktop there's no chat to send details to later: deliver them now.const extra = chatPart(answer);if (this.desktop && extra) this.notifyOwner(`🎙 From Optimus:\n${extra}`);@@ -400,6 +409,7 @@ export class PluginChannel extends BaseChannel {private onActivity(params: unknown): void {const p = (params ?? {}) as Record<string, unknown>;desktopActivityHook?.(activityLabel(this.manifest.name, p.listening === true, p.working === true, p.muted === true));+ if (this.desktop) voiceFeed.activity({ listening: p.listening === true, working: p.working === true, muted: p.muted === true, speaking: p.speaking === true });}private onCallEnded(params: unknown): void {@@ -414,6 +424,7 @@ export class PluginChannel extends BaseChannel {}}this.activeCalls.delete(String(p.callId ?? ''));+ if (this.desktop) voiceFeed.ended(String(p.callId ?? ''), String(p.outcome ?? 'ended'));for (const [id, a] of this.callApprovals) if (a.callId === String(p.callId ?? '')) this.resolveCallApproval(id, 'no', 'timeout');const secs = typeof p.durationSec === 'number' ? Math.round(p.durationSec) : 0;// A desktop session happened in front of the owner: only report failures.@@ -709,6 +720,7 @@ export class PluginChannel extends BaseChannel {const call = this.callTarget(channelId);if (!call) return;this.transport.notify?.('mercury/call/progress', { callId: call.slice('call:'.length), activity: describeTool(toolName) });+ if (this.desktop) voiceFeed.doing(describeTool(toolName));}/** `whatsapp:call:<id>` → `call:<id>`; undefined for normal chats. */@@ -778,6 +790,7 @@ export class PluginChannel extends BaseChannel {const timer = setTimeout(() => this.resolveCallApproval(approvalId, 'no', 'timeout'), APPROVAL_TIMEOUT_MS);this.callApprovals.set(approvalId, { callId, prompt, resolve, timer });this.transport.notify?.('mercury/call/approval', { callId, approvalId, prompt: prompt.slice(0, 600) });+ if (this.desktop) voiceFeed.approval(prompt.slice(0, 600));if (this.desktop) return;const chat = this.ownerChatId ? `${this.type}:${this.ownerChatId}` : undefined;void this.send(`🔐 From your call: ${prompt}\n\nSay *yes* on the call, or reply *1* (yes) or *2* (no) here.`, chat).catch(() => {});diff --git a/src/plugins/voice-feed.test.ts b/src/plugins/voice-feed.test.tsnew file mode 100644index 00000000..9d509be8--- /dev/null+++ b/src/plugins/voice-feed.test.ts@@ -0,0 +1,47 @@+import { afterEach, describe, expect, it } from 'vitest';+import { voiceFeed } from './voice-feed.js';++describe('voice feed', () => {+ afterEach(() => voiceFeed.reset());++ it('follows a session: start, question, activity, answer, end', () => {+ const events: string[] = [];+ const off = voiceFeed.subscribe((e) => events.push(e.type === 'turn' ? `turn:${e.turn?.role}` : 'state'));+ voiceFeed.attach('Optimus', () => {});+ voiceFeed.started('desk-1');+ voiceFeed.activity({ listening: true, working: false, muted: false, speaking: false });+ voiceFeed.asked('desk-1', 'what is on my calendar');+ expect(voiceFeed.snapshot().thinking).toBe(true);+ voiceFeed.doing('checking the calendar');+ voiceFeed.answered('Two meetings this afternoon.');+ const s = voiceFeed.snapshot();+ expect(s.active).toBe(true);+ expect(s.thinking).toBe(false);+ expect(s.turns.map((t) => t.role)).toEqual(['owner', 'activity', 'mercury']);+ voiceFeed.ended('desk-1', 'completed');+ expect(voiceFeed.snapshot().active).toBe(false);+ expect(voiceFeed.snapshot().turns).toHaveLength(3);+ expect(events).toContain('turn:owner');+ off();+ });++ it('controls reach the plugin only while a session is live', () => {+ const sent: string[] = [];+ voiceFeed.attach('Optimus', (a) => sent.push(a));+ expect(voiceFeed.control('mute')).toBe(false);+ voiceFeed.started('desk-2');+ expect(voiceFeed.control('mute')).toBe(true);+ expect(voiceFeed.control('stop')).toBe(true);+ expect(sent).toEqual(['mute', 'stop']);+ voiceFeed.detach('Optimus');+ expect(voiceFeed.control('mute')).toBe(false);+ });++ it('the control route accepts only known actions', async () => {+ const { default: routes } = await import('../web/api/voice.js');+ const bad = await routes.request('http://x/api/voice/control', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ action: 'rm' }) });+ expect(bad.status).toBe(400);+ const idle = await routes.request('http://x/api/voice/control', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ action: 'mute' }) });+ expect(idle.status).toBe(409);+ });+});diff --git a/src/plugins/voice-feed.ts b/src/plugins/voice-feed.tsnew file mode 100644index 00000000..d5078081--- /dev/null+++ b/src/plugins/voice-feed.ts@@ -0,0 +1,156 @@+/**+ * Live voice sessions of a desktop plugin (Optimus), for clients that show+ * them: Mercury Desktop's notch capsule, status bar and the live voice chat.+ *+ * The channel bridge feeds it (activity, what the owner asked, what Mercury+ * answered, what it is doing, approvals, the end of the session); the web+ * API reads it and streams changes. Controls go the other way: the bridge+ * registers a sender, and POST /api/voice/control calls it.+ *+ * In-memory only: a voice session is live state. The conversation itself is+ * already kept by the session store like any other turn.+ */++export type VoiceRole = 'owner' | 'mercury' | 'activity' | 'approval' | 'system';++export interface VoiceTurn {+ id: number;+ role: VoiceRole;+ text: string;+ at: number;+}++export interface VoiceState {+ available: boolean;+ plugin: string | null;+ active: boolean;+ callId: string | null;+ startedAt: number | null;+ endedAt: number | null;+ listening: boolean;+ speaking: boolean;+ working: boolean;+ muted: boolean;+ /** A question is being answered (a Mercury turn is running). */+ thinking: boolean;+ activity: string | null;+ outcome: string | null;+ turns: VoiceTurn[];+}++export type VoiceAction = 'mute' | 'unmute' | 'interrupt' | 'stop';+export const VOICE_ACTIONS: readonly VoiceAction[] = ['mute', 'unmute', 'interrupt', 'stop'];++type Listener = (event: { type: 'state' | 'turn'; state: VoiceState; turn?: VoiceTurn }) => void;++const MAX_TURNS = 200;++class VoiceFeed {+ private state: VoiceState = {+ available: false, plugin: null, active: false, callId: null, startedAt: null, endedAt: null,+ listening: false, speaking: false, working: false, muted: false, thinking: false, activity: null, outcome: null, turns: [],+ };+ private seq = 0;+ private listeners = new Set<Listener>();+ private controller: ((action: VoiceAction) => void) | null = null;++ snapshot(): VoiceState {+ return { ...this.state, turns: [...this.state.turns] };+ }++ subscribe(listener: Listener): () => void {+ this.listeners.add(listener);+ return () => this.listeners.delete(listener);+ }++ /** The desktop plugin's bridge: its name, and how to send it a control. */+ attach(plugin: string, controller: (action: VoiceAction) => void): void {+ this.controller = controller;+ this.patch({ available: true, plugin });+ }++ detach(plugin: string): void {+ if (this.state.plugin !== plugin) return;+ this.controller = null;+ this.patch({ available: false, listening: false, speaking: false, working: false, muted: false, thinking: false, active: false });+ }++ control(action: VoiceAction): boolean {+ if (!this.controller || !this.state.active) return false;+ this.controller(action);+ return true;+ }++ started(callId: string): void {+ if (this.state.active && this.state.callId === callId) return;+ this.patch({ active: true, callId, startedAt: Date.now(), endedAt: null, outcome: null, thinking: false, activity: null, turns: [] });+ }++ activity(p: { listening: boolean; working: boolean; muted: boolean; speaking?: boolean }): void {+ const next: Partial<VoiceState> = { listening: p.listening, working: p.working, muted: p.muted, speaking: p.speaking === true };+ // A session the plugin started without a call (e.g. after a restart) still shows.+ if (p.listening && !this.state.active) Object.assign(next, { active: true, startedAt: Date.now(), endedAt: null, turns: [] });+ this.patch(next);+ }++ asked(callId: string, question: string): void {+ this.started(callId);+ this.patch({ thinking: true, activity: null });+ this.push('owner', question);+ }++ doing(activity: string): void {+ if (!this.state.active) return;+ this.patch({ activity });+ this.push('activity', activity);+ }++ answered(answer: string): void {+ if (!this.state.active) return;+ this.patch({ thinking: false, activity: null });+ this.push('mercury', answer);+ }++ approval(prompt: string): void {+ if (!this.state.active) return;+ this.push('approval', prompt);+ }++ ended(callId: string, outcome: string): void {+ if (this.state.callId && callId && this.state.callId !== callId) return;+ this.patch({ active: false, listening: false, speaking: false, thinking: false, activity: null, endedAt: Date.now(), outcome });+ }++ /** Test hook. */+ reset(): void {+ this.controller = null;+ this.seq = 0;+ this.state = { ...this.state, available: false, plugin: null, active: false, callId: null, startedAt: null, endedAt: null, listening: false, speaking: false, working: false, muted: false, thinking: false, activity: null, outcome: null, turns: [] };+ }++ private push(role: VoiceRole, text: string): void {+ const turn: VoiceTurn = { id: ++this.seq, role, text: text.slice(0, 4000), at: Date.now() };+ const turns = [...this.state.turns, turn];+ this.state = { ...this.state, turns: turns.length > MAX_TURNS ? turns.slice(-MAX_TURNS) : turns };+ this.emit({ type: 'turn', state: this.snapshot(), turn });+ }++ private patch(next: Partial<VoiceState>): void {+ const before = JSON.stringify(this.withoutTurns(this.state));+ this.state = { ...this.state, ...next };+ if (JSON.stringify(this.withoutTurns(this.state)) !== before || next.turns) this.emit({ type: 'state', state: this.snapshot() });+ }++ private withoutTurns(s: VoiceState): Omit<VoiceState, 'turns'> {+ const { turns: _turns, ...rest } = s;+ return rest;+ }++ private emit(event: Parameters<Listener>[0]): void {+ for (const l of this.listeners) {+ try { l(event); } catch { /* a listener's bug must not stop the feed */ }+ }+ }+}++export const voiceFeed = new VoiceFeed();diff --git a/src/web/api-contract.ts b/src/web/api-contract.tsindex 3046266f..8bee6b6c 100644--- a/src/web/api-contract.ts+++ b/src/web/api-contract.ts@@ -34,6 +34,7 @@ export const API_FEATURES: readonly string[] = Object.freeze(['brain', // /api/brain/*'code.session', // POST /api/chat/send { programming, cwd } — per-session coding'chat.uploads', // attachments on messages + GET /api/chat/uploads/:month/:file+ 'voice', // /api/voice, /api/voice/events, /api/voice/control (Optimus)]);export interface ApiContractInfo {diff --git a/src/web/api/voice.ts b/src/web/api/voice.tsnew file mode 100644index 00000000..869da307--- /dev/null+++ b/src/web/api/voice.ts@@ -0,0 +1,46 @@+import { Hono } from 'hono';+import { voiceFeed, VOICE_ACTIONS, type VoiceAction } from '../../plugins/voice-feed.js';++/**+ * Live voice (Optimus) for clients:+ * GET /api/voice current session state and transcript+ * GET /api/voice/events SSE: `state` and `turn` events (snapshot first)+ * POST /api/voice/control { action: mute | unmute | interrupt | stop }+ * Owner-authenticated like every /api route.+ */+const voice = new Hono();++voice.get('/api/voice', (c) => c.json(voiceFeed.snapshot()));++voice.get('/api/voice/events', (c) => {+ const stream = new ReadableStream({+ start(controller) {+ const encoder = new TextEncoder();+ const send = (event: string, data: unknown) => {+ try { controller.enqueue(encoder.encode(`event: ${event}\ndata: ${JSON.stringify(data)}\n\n`)); } catch { /* client gone */ }+ };+ send('state', voiceFeed.snapshot());+ const unsubscribe = voiceFeed.subscribe((ev) => {+ if (ev.type === 'turn' && ev.turn) send('turn', ev.turn);+ // Turns travel on their own; state events stay small.+ else send('state', { ...ev.state, turns: undefined });+ });+ const keepalive = setInterval(() => {+ try { controller.enqueue(encoder.encode(': keepalive\n\n')); } catch { clearInterval(keepalive); }+ }, 15000);+ c.req.raw.signal?.addEventListener('abort', () => { clearInterval(keepalive); unsubscribe(); });+ },+ cancel() {},+ });+ return new Response(stream, { headers: { 'Content-Type': 'text/event-stream', 'Cache-Control': 'no-cache', Connection: 'keep-alive' } });+});++voice.post('/api/voice/control', async (c) => {+ const body = await c.req.json<{ action?: unknown }>().catch(() => ({} as { action?: unknown }));+ const action = body.action as VoiceAction;+ if (!VOICE_ACTIONS.includes(action)) return c.json({ error: `action must be one of ${VOICE_ACTIONS.join(', ')}` }, 400);+ if (!voiceFeed.control(action)) return c.json({ error: 'No voice session is running' }, 409);+ return c.json({ ok: true });+});++export default voice;diff --git a/src/web/server.ts b/src/web/server.tsindex 34e9e496..fbcb0969 100644--- a/src/web/server.ts+++ b/src/web/server.ts@@ -24,6 +24,7 @@ import ideRoutes, { setIDEProviders } from './api/workspace-ide.js';import lifecycleRoutes, { setShutdownHandler } from './api/lifecycle.js';import mcpRoutes, { setMcpManager } from './api/mcp.js';import pluginRoutes from './api/plugins.js';+import voiceRoutes from './api/voice.js';import { BoardManager } from '../core/board-manager.js';import { isBetterSqlite3Available } from '../memory/second-brain-db.js';@@ -102,6 +103,7 @@ app.route('/', ideRoutes);app.route('/', lifecycleRoutes);app.route('/', mcpRoutes);app.route('/', pluginRoutes);+app.route('/', voiceRoutes);// ── Legacy static assets (vendor fonts, icons, wasm — still needed by React SPA) ──app.get('/vendor/*', (c) => {