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): plugins use Mercury's own providers; one place to set a key

Salman Qureshic083d174bf6c
diff --git a/src/index.ts b/src/index.ts
index 06b277a0..f2806f14 100644
--- a/src/index.ts
+++ b/src/index.ts
@@ -53,7 +53,7 @@ import { ShortTermMemory, LongTermMemory, EpisodicMemory, migrateLegacyMemory }
import { buildConversationHistoryPayload, CloudSessionSynchronizer, SessionRepository } from './sessions/index.js';
import { UserMemoryStore } from './memory/user-memory.js';
import { BotManager } from './bots/bot-manager.js';
-import { getPluginManager, peekPluginManager } from './plugins/manager.js';
+import { getPluginManager, peekPluginManager, setProviderLookup } from './plugins/manager.js';
import { setChannelHost } from './plugins/channel-bridge.js';
import { registerPluginsCli } from './cli/plugins-cli.js';
import { SECOND_BRAIN_UNAVAILABLE_MESSAGE } from './memory/second-brain-db.js';
@@ -2678,6 +2678,9 @@ async function runAgent(isDaemon: boolean = false): Promise<void> {
register: (type, channel) => channels.register(type, channel),
unregister: (type, channel) => channels.unregister(type, channel),
});
+ // 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]);
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/commands.ts b/src/plugins/commands.ts
index f424e91f..3a41e72a 100644
--- a/src/plugins/commands.ts
+++ b/src/plugins/commands.ts
@@ -81,7 +81,9 @@ function describe(i: PluginListItem): string {
const p = i.permissions;
lines.push(`Network: ${p?.network.length ? p.network.join(', ') : 'none'}`);
lines.push(`Secrets it can read: ${p?.secrets.length ? p.secrets.join(', ') : 'none'}`);
- for (const m of i.missingOptionalSecrets ?? []) lines.push(`⚠️ ${m.unlocks} is off: add ${m.name} to ~/.mercury/.env`);
+ for (const m of i.missing ?? []) lines.push(`⚠️ ${m.unlocks} is off: needs ${m.needs}. ${m.fix}`);
+ const providers = Object.keys(i.permissions?.providers ?? {});
+ if (providers.length) lines.push(`Uses your Mercury providers: ${providers.join(', ')}`);
if (i.lastError && i.status !== 'enabled') lines.push(`Last error: ${i.lastError}`);
return lines.join('\n');
}
diff --git a/src/plugins/lifecycle.test.ts b/src/plugins/lifecycle.test.ts
index b816a226..599d580a 100644
--- a/src/plugins/lifecycle.test.ts
+++ b/src/plugins/lifecycle.test.ts
@@ -160,8 +160,8 @@ describe('optional secrets', () => {
await m.install(inProcessPlugin(src, { id: 'voicey', manifest }));
await new Promise((r) => setTimeout(r, 80));
expect(notices).toHaveLength(1);
- expect(notices[0]).toMatch(/Voice calls: needs FIXTURE_VOICE_KEY/);
- expect((await m.info('voicey'))?.missingOptionalSecrets).toEqual([{ name: 'FIXTURE_VOICE_KEY', unlocks: 'Voice calls' }]);
+ expect(notices[0]).toMatch(/Voice calls needs FIXTURE_VOICE_KEY/);
+ expect((await m.info('voicey'))?.missing).toMatchObject([{ key: 'secret:FIXTURE_VOICE_KEY', unlocks: 'Voice calls' }]);
// Restarting the same version doesn't repeat it.
await m.disable('voicey');
await m.enable('voicey');
@@ -169,7 +169,7 @@ describe('optional secrets', () => {
expect(notices).toHaveLength(1);
// With the key set, nothing is missing.
process.env.FIXTURE_VOICE_KEY = 'k';
- expect((await m.info('voicey'))?.missingOptionalSecrets).toEqual([]);
+ expect((await m.info('voicey'))?.missing).toEqual([]);
} finally {
await m.shutdown();
SECRET_NOTICE_DELAY.ms = saved;
@@ -183,3 +183,44 @@ describe('optional secrets', () => {
expect(manifestSchema.safeParse(bad).success).toBe(false);
});
});
+
+describe('Mercury providers for plugins', () => {
+ const code = `export async function activate(ctx) {
+ ctx.tools.register({ name: 'echo', inputSchema: { type: 'object' }, execute: async () => JSON.stringify({ key: ctx.secrets.get('MERCURY_PROVIDER_OPENAI_API_KEY') ?? null, url: ctx.secrets.get('MERCURY_PROVIDER_OPENAI_BASE_URL') ?? null, raw: ctx.secrets.get('OPENAI_API_KEY') ?? null }) });
+}`;
+ const manifest = { permissions: { network: [], secrets: [], providers: { openai: 'Voice calls' } } };
+
+ async function callEcho(): Promise<{ key: string | null; url: string | null; raw: string | null }> {
+ const t = listLiveTools().find((x) => x.pluginId === 'prov' && x.name === 'echo')!;
+ return JSON.parse(String(await t.invoke({}, new AbortController().signal)));
+ }
+
+ it('uses the key from Mercury\'s OpenAI provider; no plugin-specific setup', async () => {
+ const { setProviderLookup } = await import('./manager.js');
+ setProviderLookup((id) => (id === 'openai' ? { apiKey: 'sk-from-providers', baseUrl: 'https://api.openai.com/v1' } : undefined));
+ try {
+ await mgr.install(inProcessPlugin(src, { id: 'prov', code, manifest }));
+ const got = await callEcho();
+ expect(got.key).toBe('sk-from-providers');
+ expect(got.url).toMatch(/^https:\/\//);
+ expect(got.raw).toBeNull(); // only the provider names, never arbitrary env
+ expect((await mgr.info('prov'))?.missing).toEqual([]);
+ } finally {
+ setProviderLookup(() => undefined);
+ }
+ });
+
+ it('without an OpenAI provider: runs, and says to add one in Providers (not .env)', async () => {
+ const { setProviderLookup } = await import('./manager.js');
+ setProviderLookup(() => undefined);
+ {
+ await mgr.install(inProcessPlugin(src, { id: 'prov', code, manifest }));
+ expect((await callEcho()).key).toBeNull();
+ const missing = (await mgr.info('prov'))?.missing ?? [];
+ expect(missing).toHaveLength(1);
+ expect(missing[0]).toMatchObject({ key: 'provider:openai', unlocks: 'Voice calls', needs: 'an OpenAI provider' });
+ expect(missing[0].fix).toMatch(/Providers/);
+ expect(missing[0].fix).not.toMatch(/\.env/);
+ }
+ });
+});
diff --git a/src/plugins/manager.ts b/src/plugins/manager.ts
index 87f11439..9943f6a2 100644
--- a/src/plugins/manager.ts
+++ b/src/plugins/manager.ts
@@ -34,7 +34,8 @@ import { InProcessRuntime, inProcessLogger } from './runtime/in-process.js';
import { OutOfProcessRuntime } from './runtime/out-of-process.js';
import { PluginChannel, type ChannelStatus } from './channel-bridge.js';
import type { PluginRuntime } from './runtime/types.js';
-import type { CatalogEntry, DisabledCode, PluginListItem, PluginManifest, PluginsState } from './types.js';
+import { providerSecretNames, type CatalogEntry, type DisabledCode, type PluginListItem, type PluginManifest, type PluginProviderId, type PluginsState } from './types.js';
+import { loadConfig } from '../utils/config.js';
export const CIRCUIT_BREAKER_FAILURES = 5;
export const BOOT_HEALTHY_AFTER_MS = 60_000;
@@ -257,7 +258,7 @@ export class PluginManager {
mercuryVersion: mercuryVersion(),
dataDir: pluginDataDir(id),
settings: resolvedSettings(manifest),
- secrets: Object.fromEntries(manifest.permissions.secrets.map((k) => [k, process.env[k]])),
+ secrets: { ...Object.fromEntries(manifest.permissions.secrets.map((k) => [k, process.env[k]])), ...providerCredentials(manifest) },
log: inProcessLogger(id),
onError: (message: string) => this.recordFailure(id, message),
onFatal: (code: 'crashed' | 'activation', message: string) => {
@@ -307,24 +308,22 @@ export class PluginManager {
* so it lands after channels have connected at startup.
*/
private noticeMissingSecrets(id: string, manifest: PluginManifest): void {
- const missing = missingOptionalSecrets(manifest);
+ const missing = missingRequirements(manifest);
if (!missing.length) return;
const entry = readState().plugins[id];
- const fresh = missing.filter((m) => entry?.secretNotices?.[m.name] !== manifest.version);
+ const fresh = missing.filter((m) => entry?.secretNotices?.[m.key] !== manifest.version);
if (!fresh.length) return;
const timer = setTimeout(() => {
if (!this.running.has(id)) return;
- const lines = fresh.map((m) => `• ${m.unlocks}: needs ${m.name}`);
void this.notifyFn([
- `🧩 ${manifest.name} is running. Some features are off until you add a key:`,
- ...lines,
- `Add it to ~/.mercury/.env (or set up that provider with \`mercury doctor\`), then restart Mercury.`,
+ `🧩 ${manifest.name} is running, but some features are off:`,
+ ...fresh.map((m) => `• ${m.unlocks} needs ${m.needs}. ${m.fix}`),
].join('\n'));
void updateState((s) => {
const e = s.plugins[id];
if (!e) return;
e.secretNotices = { ...(e.secretNotices ?? {}) };
- for (const m of fresh) e.secretNotices[m.name] = manifest.version;
+ for (const m of fresh) e.secretNotices[m.key] = manifest.version;
}).catch(() => {});
}, SECRET_NOTICE_DELAY.ms);
timer.unref?.();
@@ -600,7 +599,7 @@ export class PluginManager {
: undefined,
permissions: manifest?.permissions ?? (cat ? { network: cat.permissions.network, secrets: cat.permissions.secrets } : undefined),
disabled: inst?.disabled,
- missingOptionalSecrets: manifest ? missingOptionalSecrets(manifest) : undefined,
+ missing: manifest ? missingRequirements(manifest) : undefined,
lastError: run?.lastError ?? this.lastErrors.get(id),
incompatibleReason: instIncompat ?? catIncompat ?? undefined,
};
@@ -670,9 +669,56 @@ export function resetPluginManager(): void {
instance = null;
}
-/** Optional secrets this plugin declares that aren't set in the environment. */
-export function missingOptionalSecrets(manifest: PluginManifest): Array<{ name: string; unlocks: string }> {
- return Object.entries(manifest.permissions.optionalSecrets ?? {})
- .filter(([name]) => !process.env[name])
- .map(([name, unlocks]) => ({ name, unlocks }));
+const PROVIDER_LABEL: Record<PluginProviderId, string> = { openai: 'OpenAI' };
+
+type ProviderLookup = (id: PluginProviderId) => { apiKey?: string; baseUrl?: string } | undefined;
+
+let providerLookup: ProviderLookup = (id) => {
+ try {
+ return (loadConfig().providers as unknown as Record<string, { apiKey?: string; baseUrl?: string }>)[id];
+ } catch {
+ return undefined;
+ }
+};
+
+/**
+ * Where provider credentials come from. The runtime points this at its live
+ * config, the same one its own model calls use; tests point it at a fake.
+ */
+export function setProviderLookup(fn: ProviderLookup): void {
+ providerLookup = fn;
+}
+
+/** Credentials for the Mercury providers a plugin declared, from Mercury's own provider settings. */
+export function providerCredentials(manifest: PluginManifest): Record<string, string> {
+ const out: Record<string, string> = {};
+ const declared = Object.keys(manifest.permissions.providers ?? {}) as PluginProviderId[];
+ for (const id of declared) {
+ const p = providerLookup(id);
+ if (!p?.apiKey) continue;
+ const names = providerSecretNames(id);
+ out[names.apiKey] = p.apiKey;
+ if (p.baseUrl) out[names.baseUrl] = p.baseUrl;
+ }
+ return out;
+}
+
+/** Optional providers and secrets this plugin declares that aren't set up. */
+export function missingRequirements(manifest: PluginManifest): Array<{ key: string; unlocks: string; needs: string; fix: string }> {
+ const creds = providerCredentials(manifest);
+ const out: Array<{ key: string; unlocks: string; needs: string; fix: string }> = [];
+ for (const [id, unlocks] of Object.entries(manifest.permissions.providers ?? {}) as Array<[PluginProviderId, string]>) {
+ if (creds[providerSecretNames(id).apiKey]) continue;
+ out.push({
+ key: `provider:${id}`,
+ unlocks,
+ needs: `an ${PROVIDER_LABEL[id]} provider`,
+ fix: `Add your ${PROVIDER_LABEL[id]} key once in the dashboard (Providers) or with \`mercury doctor\`; Mercury uses it for everything.`,
+ });
+ }
+ for (const [name, unlocks] of Object.entries(manifest.permissions.optionalSecrets ?? {})) {
+ if (process.env[name]) continue;
+ out.push({ key: `secret:${name}`, unlocks, needs: name, fix: `Add ${name} to ~/.mercury/.env and restart Mercury.` });
+ }
+ return out;
}
diff --git a/src/plugins/runtime/in-process.ts b/src/plugins/runtime/in-process.ts
index 0fd92242..d5e1a412 100644
--- a/src/plugins/runtime/in-process.ts
+++ b/src/plugins/runtime/in-process.ts
@@ -17,7 +17,7 @@ import { pathToFileURL } from 'node:url';
import { resolve } from 'node:path';
import { assertFetchableTarget, MAX_REDIRECTS } from '../../utils/ssrf.js';
import { logger } from '../../utils/logger.js';
-import { PLUGIN_API_VERSION, type PluginManifest } from '../types.js';
+import { PLUGIN_API_VERSION, providerSecretNames, type PluginManifest, type PluginProviderId } from '../types.js';
import type { Disposable, PluginCommandDefinition, PluginContext, PluginModule, PluginToolDefinition } from '../sdk.js';
import { publishCommand, publishTool, unpublishPlugin } from '../tool-bridge.js';
import type { PluginRuntime, RuntimeDeps } from './types.js';
@@ -145,7 +145,10 @@ export class InProcessRuntime implements PluginRuntime {
const m = this.manifest;
const declaredTools = new Map(m.contributes.tools.map((t) => [t.name, t]));
const declaredCommands = new Map(m.contributes.commands.map((c) => [c.name, c]));
- const declaredSecrets = new Set(m.permissions.secrets);
+ const declaredSecrets = new Set([
+ ...m.permissions.secrets,
+ ...(Object.keys(m.permissions.providers ?? {}) as PluginProviderId[]).flatMap((p) => Object.values(providerSecretNames(p))),
+ ]);
const signal = this.ac.signal;
const self = this;
diff --git a/src/plugins/types.ts b/src/plugins/types.ts
index ad5c8152..c78a6ce9 100644
--- a/src/plugins/types.ts
+++ b/src/plugins/types.ts
@@ -41,6 +41,16 @@ export const RESERVED_COMMANDS: ReadonlySet<string> = new Set([
'usage', 'cost', 'doctor', 'settings', 'config', 'login', 'logout', 'upgrade', 'version', 'about',
]);
+/** Mercury providers a plugin can ask to use (Plugin API 1.1). */
+export const PLUGIN_PROVIDER_IDS = ['openai'] as const;
+export type PluginProviderId = (typeof PLUGIN_PROVIDER_IDS)[number];
+
+/** Env names a plugin gets for a provider it declared. */
+export function providerSecretNames(id: PluginProviderId): { apiKey: string; baseUrl: string } {
+ const up = id.toUpperCase();
+ return { apiKey: `MERCURY_PROVIDER_${up}_API_KEY`, baseUrl: `MERCURY_PROVIDER_${up}_BASE_URL` };
+}
+
/** Channel types a plugin may provide (Plugin API 1.1). */
export const PLUGIN_CHANNEL_TYPES = ['whatsapp'] as const;
export type PluginChannelType = (typeof PLUGIN_CHANNEL_TYPES)[number];
@@ -144,6 +154,15 @@ export const manifestSchema = z.object({
* owner once per plugin version, and shown in /plugins info.
*/
optionalSecrets: z.record(z.string().regex(SECRET_NAME_RE), z.string().min(1).max(200)).optional(),
+ /**
+ * Mercury AI providers the plugin may use, and what each unlocks, e.g.
+ * { "openai": "Voice calls" }. The credentials come from Mercury's own
+ * provider settings (dashboard → Providers, or `mercury doctor`), so the
+ * owner sets a key once for everything. The plugin receives them as
+ * MERCURY_PROVIDER_<ID>_API_KEY and MERCURY_PROVIDER_<ID>_BASE_URL.
+ * All optional: the plugin runs without them, minus that feature.
+ */
+ providers: z.record(z.enum(PLUGIN_PROVIDER_IDS), z.string().min(1).max(200)).optional(),
}).strict().default({ network: [], secrets: [] }),
settings: z.object({
/** Bump when a field is renamed, removed or changes meaning, and add a migration. */
@@ -219,7 +238,7 @@ export interface PluginStateEntry {
installedAt: string;
updatedAt: string;
disabled?: { code: DisabledCode; message: string; at: string };
- /** Optional secrets the owner was already told are missing, at this version. */
+ /** Missing optional requirements the owner was already told about, at this version. */
secretNotices?: Record<string, string>;
}
@@ -252,8 +271,8 @@ export interface PluginListItem {
verified: boolean;
tools: string[];
commands: string[];
- /** Optional secrets that aren't set, with what each would unlock. */
- missingOptionalSecrets?: Array<{ name: string; unlocks: string }>;
+ /** Optional providers or secrets that aren't set up: what's off, what it needs, how to fix it. */
+ missing?: Array<{ key: string; unlocks: string; needs: string; fix: string }>;
/** Plugin API 1.1: the chat channel this plugin provides, and its live state. */
channel?: { type: string; state?: string; detail?: string; account?: string };
permissions?: PluginManifest['permissions'];