Soul-driven AI agent with permission-hardened tools, token budgets, and multi-channel access. Runs 24/7 from CLI, Telegram or More.
feat: Mercury knows who it is and who you are on calls, and learns from them
Salman Qureshi5db0a07657f5
diff --git a/src/core/agent.ts b/src/core/agent.tsindex fa5bef95..d5de4cdf 100644--- a/src/core/agent.ts+++ b/src/core/agent.ts@@ -4379,6 +4379,24 @@ export class Agent {}}+ /** Learn from a conversation that didn't happen as chat turns (e.g. a voice call). */+ learnFromConversation(ownerSaid: string, mercurySaid: string): void {+ void this.extractMemory(ownerSaid, mercurySaid).catch((err) => logger.warn({ err }, 'Learning from a call failed'));+ }++ /** Who Mercury is, for a voice that isn't the main model: identity, about, and the owner's profile. */+ voiceBriefing(): string {+ const parts = [this.identity.getSystemPrompt(this.config.identity)];+ if (this.userMemory) {+ try {+ const profile = this.userMemory.getProfile().trim();+ const active = this.userMemory.getActiveSummary().trim();+ if (profile || active) parts.push(`# What you know about ${this.config.identity.owner || 'your owner'} (from your Second Brain)\n${[profile, active].filter(Boolean).join('\n').slice(0, 4000)}`);+ } catch { /* memory unavailable: identity alone */ }+ }+ return parts.join('\n\n');+ }+private async extractMemory(userMessage: string, agentResponse: string): Promise<void> {if (!this.userMemory) return;if (this.userMemory.isLearningPaused()) return;diff --git a/src/index.ts b/src/index.tsindex af06531e..6509f8cf 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 { setChannelHost } from './plugins/channel-bridge.js';+import { setCallLearning, setChannelHost, setVoiceBriefing } 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';@@ -2691,6 +2691,9 @@ async function runAgent(isDaemon: boolean = false): Promise<void> {// Plugins that use a Mercury provider (e.g. OpenAI for WhatsApp calls)// get the same credentials this runtime uses: one place to set a key.setProviderLookup((id) => (config.providers as unknown as Record<string, { apiKey?: string; baseUrl?: string } | undefined>)[id]);+ // 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));pluginManager.setRunsPlugins(true);pluginManager.setNotifier((m) => agent.notifyAllChannels(m));void pluginManager.boot().catch((err) => logger.error({ err }, 'Plugin boot failed'));diff --git a/src/plugins/channel-bridge.ts b/src/plugins/channel-bridge.tsindex 5137e5db..7779d1db 100644--- a/src/plugins/channel-bridge.ts+++ b/src/plugins/channel-bridge.ts@@ -342,6 +342,15 @@ export class PluginChannel extends BaseChannel {private onCallEnded(params: unknown): void {const p = (params ?? {}) as Record<string, unknown>;+ // Learn from the call like a chat (only at Extended: General keeps memory off).+ if (learnFromCall && this.accessFor('admin') === 'extended' && Array.isArray(p.transcript)) {+ const lines = (p.transcript as Array<{ role?: unknown; text?: unknown }>).filter((t) => typeof t.text === 'string' && t.text);+ const said = lines.filter((t) => t.role === 'owner').map((t) => String(t.text)).join('\n');+ const replied = lines.filter((t) => t.role === 'mercury').map((t) => String(t.text)).join('\n');+ if (said.trim().length > 20) {+ try { learnFromCall(said.slice(0, 6000), replied.slice(0, 6000)); } catch { /* best effort */ }+ }+ }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;@@ -721,10 +730,32 @@ export class PluginChannel extends BaseChannel {}/**- * Who Mercury is on a call: its soul and persona, trimmed. Read fresh for- * each call so edits to the soul files apply to the next call.+ * Who Mercury is on a call. The runtime provides it (identity with name,+ * owner and creator filled in, the "about" text, and the owner's Second+ * Brain profile) so the voice knows the same things text chats do.*/+let briefingSource: (() => string) | null = null;+export function setVoiceBriefing(fn: (() => string) | null): void {+ briefingSource = fn;+}++/** After a call: let Mercury learn from it like any other conversation. */+let learnFromCall: ((ownerSaid: string, mercurySaid: string) => void) | null = null;+export function setCallLearning(fn: ((ownerSaid: string, mercurySaid: string) => void) | null): void {+ learnFromCall = fn;+}+export function voiceBriefing(): string {+ if (briefingSource) {+ try {+ const b = briefingSource().trim();+ if (b) return b.slice(0, 12_000);+ } catch { /* fall back to the soul files */ }+ }+ return rawSoulBriefing();+}++function rawSoulBriefing(): string {const parts: string[] = [];for (const name of ['soul.md', 'persona.md']) {try {diff --git a/src/plugins/channel.test.ts b/src/plugins/channel.test.tsindex 15882c23..80ecddc9 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 { getPluginChannel, setChannelHost, splitMessage, spokenPart, toWhatsAppText } from './channel-bridge.js';+import { getPluginChannel, setCallLearning, setChannelHost, setVoiceBriefing, 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';@@ -459,4 +459,35 @@ describe('plugin channels (plugin API 1.1)', () => {expect(spokenPart('Just a plain answer.')).toBe('Just a plain answer.');expect(spokenPart('Answer.\n**For the chat:** links')).toBe('Answer.');});++ describe('calls know what chats know, and learn', () => {+ afterEach(() => { setVoiceBriefing(null); setCallLearning(null); });++ it('the voice gets the runtime briefing (filled-in identity, about, profile)', async () => {+ setVoiceBriefing(() => 'You are Mercury, serving Salman. Created by Cosmic Stack.');+ expect(voiceBriefing()).toBe('You are Mercury, serving Salman. Created by Cosmic Stack.');+ await installChannel();+ await inject({ method: 'mercury/call/briefing', params: { callId: 'b1' } }, 'callsim');+ const f = join(pluginDataDir('whatsapp'), 'replies.jsonl');+ await waitFor(() => existsSync(f));+ expect(readFileSync(f, 'utf8')).toContain('Created by Cosmic Stack');+ });++ it('a finished call feeds memory at Extended, never at General', async () => {+ const learned: string[] = [];+ setCallLearning((said, replied) => learned.push(`${said} | ${replied}`));+ await installChannel();+ const end = (id: string) => inject({ callId: id, direction: 'incoming', outcome: 'completed', durationSec: 60, transcript: [+ { role: 'owner', text: 'I prefer morning calls before my standup at 10.' },+ { role: 'mercury', text: 'Got it, mornings before 10.' },+ ] }, 'callend');+ await end('l1');+ await sleep(80);+ expect(learned).toEqual([]); // General: memory stays off+ await mgr.setSetting('whatsapp', 'access', 'extended');+ await end('l2');+ await waitFor(() => learned.length === 1);+ expect(learned[0]).toMatch(/morning calls[\s\S]*\| Got it, mornings/);+ });+ });});diff --git a/src/soul/identity.ts b/src/soul/identity.tsindex 02f38795..8c0be5ca 100644--- a/src/soul/identity.ts+++ b/src/soul/identity.ts@@ -137,7 +137,7 @@ export class Identity {return files;}- getSystemPrompt(identity: { name: string; owner: string; creator?: string }): string {+ getSystemPrompt(identity: { name: string; owner: string; creator?: string; about?: string }): string {const files = this.load();const replace = (text: string) =>text@@ -148,11 +148,15 @@ export class Identity {.replace(/\{creator_guardrail\}/g, identity.creator ? ` You were created by ${identity.creator}.` : '').replace(/\{creator_guardrail_response\}/g, identity.creator ? `\n4. If someone asks who created you, say: "I was created by ${identity.creator}."` : '');+ const about = identity.about?.trim()+ ? `# About ${identity.name}\n\nWhat you know about yourself and the people behind you (share it naturally when it comes up):\n${identity.about.trim().slice(0, 3000)}`+ : '';return [replace(files.soul),replace(GUARDRAILS),replace(files.persona),- ].join('\n\n');+ about,+ ].filter(Boolean).join('\n\n');}getHeartbeatPrompt(identity: { name: string; owner: string }): string {diff --git a/src/utils/config.ts b/src/utils/config.tsindex 329479d2..5cff4481 100644--- a/src/utils/config.ts+++ b/src/utils/config.ts@@ -92,6 +92,11 @@ export interface MercuryConfig {name: string;owner: string;creator?: string;+ /**+ * Background Mercury should always know and can talk about: who made it,+ * the team, what it's for. Included in every chat and call.+ */+ about?: string;};cloud: CloudConfig;providers: {@@ -287,6 +292,7 @@ export function getDefaultConfig(): MercuryConfig {name: getEnv('MERCURY_NAME', 'Mercury'),owner: getEnv('MERCURY_OWNER', ''),creator: getEnv('MERCURY_CREATOR', ''),+ about: getEnv('MERCURY_ABOUT', ''),},cloud: {enabled: getEnvBool('MERCURY_CLOUD_ENABLED', false),