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.

feat(plugins): desktop channel type for voice sessions on the owner's computer

Salman Qureshi6fc72dd7b9af
diff --git a/src/core/work-ledger.ts b/src/core/work-ledger.ts
index 4eb7282d..192e6dd5 100644
--- a/src/core/work-ledger.ts
+++ b/src/core/work-ledger.ts
@@ -8,7 +8,7 @@ import { logger } from '../utils/logger.js';
const channelMessageSchema = z.object({
id: z.string(),
channelId: z.string(),
- channelType: z.enum(['cli', 'telegram', 'web', 'internal', 'signal', 'discord', 'slack', 'whatsapp']),
+ channelType: z.enum(['cli', 'telegram', 'web', 'internal', 'signal', 'discord', 'slack', 'whatsapp', 'desktop']),
senderId: z.string(),
senderName: z.string().optional(),
content: z.string(),
diff --git a/src/plugins/channel-bridge.ts b/src/plugins/channel-bridge.ts
index a61d1571..f363ab28 100644
--- a/src/plugins/channel-bridge.ts
+++ b/src/plugins/channel-bridge.ts
@@ -159,6 +159,9 @@ interface IncomingParams {
timestamp?: unknown;
}
+/** 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).]';
+
export class PluginChannel extends BaseChannel {
readonly type: ChannelType;
private status: ChannelStatus = { state: 'starting', at: Date.now() };
@@ -211,6 +214,15 @@ export class PluginChannel extends BaseChannel {
/** Phone chats: no per-step messages or "Working…" heartbeats; keep "typing…" alive instead. */
readonly quietProgress = true;
+ /**
+ * A desktop channel (plugin API 1.2, e.g. Optimus): voice sessions on the
+ * owner's own computer. Whoever sits at it is the owner; there is no chat
+ * of its own, so anything for "the chat" goes to Mercury's usual channel.
+ */
+ private get desktop(): boolean {
+ return this.type === 'desktop';
+ }
+
get pluginId(): string {
return this.manifest.id;
@@ -319,7 +331,9 @@ export class PluginChannel extends BaseChannel {
}
this.callAsks.delete(target);
this.overflow.add(target);
- resolve('Mercury is still working on that. It will send the answer to WhatsApp when it\'s done.');
+ resolve(this.desktop
+ ? 'Mercury is still working on that. It will send the answer to your Mercury chat when it\'s done.'
+ : 'Mercury is still working on that. It will send the answer to WhatsApp when it\'s done.');
};
const timer = setTimeout(giveUp, 90_000);
this.callAsks.set(target, { chunks: [], resolve, timer });
@@ -331,9 +345,9 @@ export class PluginChannel extends BaseChannel {
id: `call-${callId}-${Date.now()}`,
channelId: `${this.type}:${target}`,
channelType: this.type,
- senderId: digits(owner),
+ senderId: this.desktop ? 'local' : digits(owner),
senderRole: 'admin',
- content: `[Voice call: the owner asked this out loud. Use your tools to get the real answer: web_search for news and anything current, fetch_url, memory, skills. Then answer in one to three short spoken sentences, with no markdown, lists, links or code. Go ahead and do what they ask, including saving files or running things: if an action needs approval, Mercury asks the owner on the call and in the chat, and continues once they say yes. Don't ask them to confirm by message yourself. Links, lists, prices, addresses and other details worth keeping: never read them out. If they asked for them, send them with whatsapp__send_to_chat and say you've sent them to the chat. If you found something useful they didn't ask to receive, end your answer by offering to send it ("Want me to send the links to your chat?") and only send once they say yes. Whenever your answer involves links or details, add them after a final line "For the chat:" (that part isn't spoken, and lets you send them later without searching again).]${sentNote}\n${question}`,
+ content: this.desktop ? `${DESKTOP_VOICE_NOTE}\n${question}` : `[Voice call: the owner asked this out loud. Use your tools to get the real answer: web_search for news and anything current, fetch_url, memory, skills. Then answer in one to three short spoken sentences, with no markdown, lists, links or code. Go ahead and do what they ask, including saving files or running things: if an action needs approval, Mercury asks the owner on the call and in the chat, and continues once they say yes. Don't ask them to confirm by message yourself. Links, lists, prices, addresses and other details worth keeping: never read them out. If they asked for them, send them with whatsapp__send_to_chat and say you've sent them to the chat. If you found something useful they didn't ask to receive, end your answer by offering to send it ("Want me to send the links to your chat?") and only send once they say yes. Whenever your answer involves links or details, add them after a final line "For the chat:" (that part isn't spoken, and lets you send them later without searching again).]${sentNote}\n${question}`,
timestamp: Date.now(),
metadata: { pluginId: this.manifest.id, voiceCall: true, callId, attachments: files.slice(-4), channelAccess: this.accessFor('admin'), channelGuidance: this.guidance('admin', false, true) },
});
@@ -349,6 +363,9 @@ 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.');
+ // 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}`);
}
this.overflow.delete(target);
}
@@ -367,6 +384,12 @@ export class PluginChannel extends BaseChannel {
this.activeCalls.delete(String(p.callId ?? ''));
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.
+ if (this.desktop) {
+ const outcome = String(p.outcome ?? '');
+ if (outcome.startsWith('failed')) this.notifyOwner(`🎙 Optimus couldn't start listening: ${outcome.replace(/^failed:?\s*/, '') || 'unknown error'}.`);
+ return;
+ }
const dur = secs >= 60 ? `${Math.floor(secs / 60)}m ${secs % 60}s` : `${secs}s`;
const outcome = String(p.outcome ?? '');
const reason = typeof p.reason === 'string' ? p.reason.slice(0, 300) : '';
@@ -419,6 +442,7 @@ export class PluginChannel extends BaseChannel {
/** Who may talk to Mercury here: 'admin' for the owner, 'member' for listed members, null otherwise. */
roleOf(sender: string): 'admin' | 'member' | null {
+ if (this.desktop) return sender === 'local' ? 'admin' : null;
const s = this.settings();
const d = digits(sender);
if (!d) return null;
@@ -559,6 +583,7 @@ export class PluginChannel extends BaseChannel {
/** The owner's level (chosen during setup; General until they pick Extended). */
ownerAccess(): 'general' | 'extended' {
+ if (this.desktop) return 'extended';
return String(this.settings().access ?? 'general') === 'extended' ? 'extended' : 'general';
}
@@ -572,6 +597,14 @@ export class PluginChannel extends BaseChannel {
/** Told to the model every turn: where it is, who it's talking to, what it may do, how to write. */
guidance(role: 'admin' | 'member', isGroup: boolean, voiceCall = false): string {
const name = this.manifest.name;
+ if (this.desktop) {
+ return [
+ `## 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 anything that submits, sends, pays, deletes or installs. Say briefly what you're doing as you go.`,
+ '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');
+ }
const who = role === 'admin' ? 'the owner (the person you work for)' : 'an approved member, not the owner';
const where = voiceCall ? `a ${name} voice call` : `${name}${isGroup ? ', in a group chat' : ''}, a phone chat app`;
const lines = [
@@ -606,6 +639,7 @@ export class PluginChannel extends BaseChannel {
/** Notifications with no chat go to the owner's own chat. */
private defaultTarget(): string | undefined {
+ if (this.desktop) return 'local';
const owner = digits(String(this.settings().owner ?? ''));
return owner ? `${owner}@s.whatsapp.net` : undefined;
}
@@ -622,6 +656,10 @@ export class PluginChannel extends BaseChannel {
// The call question timed out but the turn kept going: deliver in chat.
return this.send(`📞 From your call:\n${content}`);
}
+ if (this.desktop) {
+ this.notifyOwner(content);
+ return;
+ }
const chatId = this.chatOf(targetId);
for (const chunk of splitMessage(toWhatsAppText(content))) {
await this.transport.request('mercury/channel/send', { chatId, text: chunk }, SEND_TIMEOUT_MS);
@@ -706,6 +744,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) 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(() => {});
});
@@ -783,6 +822,12 @@ function rawSoulBriefing(): string {
* The part of a call answer to speak: everything before a "For the chat:"
* section (links and details kept in the call's history for send_to_chat).
*/
+/** The "For the chat:" part of a call answer (links and details), if any. */
+export function chatPart(answer: string): string {
+ const m = /(^|\n)\s*\**\s*for the chat\s*:?\**\s*:?/i.exec(answer);
+ return m ? answer.slice(m.index + m[0].length).trim() : '';
+}
+
export function spokenPart(answer: string): string {
const cut = answer.search(/(^|\n)\s*\**\s*for the chat\s*:?\**\s*:?/i);
return (cut >= 0 ? answer.slice(0, cut) : answer).trim();
diff --git a/src/plugins/channel.test.ts b/src/plugins/channel.test.ts
index 80ecddc9..c782c91e 100644
--- a/src/plugins/channel.test.ts
+++ b/src/plugins/channel.test.ts
@@ -490,4 +490,66 @@ describe('plugin channels (plugin API 1.1)', () => {
expect(learned[0]).toMatch(/morning calls[\s\S]*\| Got it, mornings/);
});
});
+ describe('desktop channel (plugin API 1.2, Optimus)', () => {
+ const dataFile = (name: string) => join(pluginDataDir('optimus'), name);
+ const lines = (name: string) => {
+ const f = dataFile(name);
+ return existsSync(f) ? readFileSync(f, 'utf8').split('\n').filter((l) => l.trim().endsWith('}')).map((l) => JSON.parse(l)) : [];
+ };
+ const callsim = async (method: string, params: Record<string, unknown>) => {
+ const t = getPluginTools(new PermissionManager())['optimus__callsim'] as Tool & { execute: (a: unknown, o: unknown) => Promise<unknown> };
+ await t.execute({ method, params }, { toolCallId: 't', messages: [] });
+ await sleep(40);
+ };
+ async function installDesktop(): Promise<PluginChannel> {
+ const dir = channelPlugin(src, 'optimus', { name: 'Optimus' });
+ const manifestPath = join(dir, 'mercury-plugin.json');
+ const m = JSON.parse(readFileSync(manifestPath, 'utf8'));
+ m.contributes.channel = { type: 'desktop' };
+ writeFileSync(manifestPath, JSON.stringify(m));
+ await mgr.install(dir);
+ await waitFor(() => !!getPluginChannel('optimus') && registered.length === 1);
+ expect(registered[0].type).toBe('desktop');
+ return getPluginChannel('optimus')!;
+ }
+
+ it('only the person at the computer is the owner', async () => {
+ const ch = await installDesktop();
+ expect(ch.roleOf('local')).toBe('admin');
+ expect(ch.roleOf('15550002')).toBeNull();
+ expect(ch.accessFor('admin')).toBe('extended');
+ await callsim('mercury/call/incoming', { callId: 'd0', from: 'local', voiceReady: true });
+ await callsim('mercury/call/incoming', { callId: 'd1', from: 'someone', voiceReady: true });
+ await waitFor(() => lines('replies.jsonl').length === 2);
+ expect(lines('replies.jsonl').map((r) => r.result.accept)).toEqual([true, false]);
+ });
+
+ it('a spoken question runs a desktop turn; details go to the usual Mercury chat', async () => {
+ const ch = await installDesktop();
+ await callsim('mercury/call/ask', { callId: 'd2', question: 'Find me flights to Dubai' });
+ await waitFor(() => received.length === 1);
+ const msg = received[0];
+ expect(msg.channelId).toBe('desktop:call:d2');
+ expect(msg.senderId).toBe('local');
+ expect(msg.content).toMatch(/own computer[\s\S]*Optimus tools[\s\S]*Find me flights to Dubai/);
+ expect(msg.metadata?.channelGuidance).toMatch(/optimus__look/);
+ await ch.send('The cheapest is Emirates at 420 dollars.\n\nFor the chat:\n- Emirates: https://a.example', msg.channelId);
+ ch.endTask(msg.channelId);
+ await waitFor(() => lines('replies.jsonl').length === 1);
+ expect(lines('replies.jsonl')[0].result.answer).toBe('The cheapest is Emirates at 420 dollars.');
+ expect(notices.some((n) => /From Optimus[\s\S]*https:\/\/a\.example/.test(n))).toBe(true);
+ expect(lines('out.jsonl').filter((m) => m.method === 'mercury/channel/send')).toEqual([]);
+ });
+
+ it('approvals are asked out loud only', async () => {
+ const ch = await installDesktop();
+ const answer = ch.askPermission('Submit the job application', 'desktop:call:d3');
+ await waitFor(() => lines('approvals.jsonl').length === 1);
+ const { approvalId } = lines('approvals.jsonl')[0];
+ await callsim('mercury/call/approve', { callId: 'd3', approvalId, approved: true });
+ expect(await answer).toBe('yes');
+ expect(notices.filter((n) => /From your call/.test(n))).toEqual([]);
+ expect(lines('out.jsonl').filter((m) => m.method === 'mercury/channel/send')).toEqual([]);
+ });
+ });
});
diff --git a/src/plugins/types.ts b/src/plugins/types.ts
index 9aa8de64..ff3b8b3f 100644
--- a/src/plugins/types.ts
+++ b/src/plugins/types.ts
@@ -52,7 +52,7 @@ export function providerSecretNames(id: PluginProviderId): { apiKey: string; bas
}
/** Channel types a plugin may provide (Plugin API 1.1). */
-export const PLUGIN_CHANNEL_TYPES = ['whatsapp'] as const;
+export const PLUGIN_CHANNEL_TYPES = ['whatsapp', 'desktop'] as const;
export type PluginChannelType = (typeof PLUGIN_CHANNEL_TYPES)[number];
export const SECRET_NAME_RE = /^[A-Z][A-Z0-9_]{1,63}$/;
diff --git a/src/sessions/repository.ts b/src/sessions/repository.ts
index 5974265d..0c60c3e9 100644
--- a/src/sessions/repository.ts
+++ b/src/sessions/repository.ts
@@ -8,7 +8,7 @@ import type { AppendSessionMessageInput, CreateSessionInput, Session, SessionBin
const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
const ID_PREFIX_RE = /^[0-9a-f]{4,32}$/i;
const ALIAS_RE = /^[a-z0-9]+(?:-[a-z0-9]+)*$/i;
-const CHANNEL_TYPES: ChannelType[] = ['cli', 'telegram', 'web', 'internal', 'signal', 'discord', 'slack', 'whatsapp'];
+const CHANNEL_TYPES: ChannelType[] = ['cli', 'telegram', 'web', 'internal', 'signal', 'discord', 'slack', 'whatsapp', 'desktop'];
const TITLE_SOURCES: Session['titleSource'][] = ['fallback', 'generated', 'user'];
const SESSION_STATUSES: Session['status'][] = ['active', 'archived', 'deleted'];
const MESSAGE_ROLES: SessionMessage['role'][] = ['user', 'assistant', 'system', 'tool'];
@@ -600,7 +600,7 @@ export class SessionRepository {
private legacyChannelType(id: string): ChannelType {
const prefix = id.split(':', 1)[0];
- return ['cli', 'telegram', 'web', 'internal', 'signal', 'discord', 'slack', 'whatsapp'].includes(prefix) ? prefix as ChannelType : 'internal';
+ return ['cli', 'telegram', 'web', 'internal', 'signal', 'discord', 'slack', 'whatsapp', 'desktop'].includes(prefix) ? prefix as ChannelType : 'internal';
}
private assertUuid(id: string): void {
diff --git a/src/types/channel.ts b/src/types/channel.ts
index 5593ed80..c12861a4 100644
--- a/src/types/channel.ts
+++ b/src/types/channel.ts
@@ -16,7 +16,7 @@ export interface TelegramPendingRequest {
pairingCode?: string;
}
-export type ChannelType = 'cli' | 'telegram' | 'web' | 'internal' | 'signal' | 'discord' | 'slack' | 'whatsapp';
+export type ChannelType = 'cli' | 'telegram' | 'web' | 'internal' | 'signal' | 'discord' | 'slack' | 'whatsapp' | 'desktop';
export interface ChannelMessage {
id: string;