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): optional secrets; tell the owner once what a missing key turns off

Salman Qureshi6816b2c2f081
diff --git a/src/plugins/commands.ts b/src/plugins/commands.ts
index 430d8d92..f424e91f 100644
--- a/src/plugins/commands.ts
+++ b/src/plugins/commands.ts
@@ -81,6 +81,7 @@ 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`);
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 660fb2e0..b816a226 100644
--- a/src/plugins/lifecycle.test.ts
+++ b/src/plugins/lifecycle.test.ts
@@ -145,3 +145,41 @@ describe('web API', () => {
expect((await pluginRoutes.request('/api/plugins/install', post({ source: 'http://insecure.example/p.tgz' }), loopback)).status).toBe(400);
});
});
+
+describe('optional secrets', () => {
+ it('tells the owner once per version when an optional secret is missing', async () => {
+ const { SECRET_NOTICE_DELAY } = await import('./manager.js');
+ const saved = SECRET_NOTICE_DELAY.ms;
+ SECRET_NOTICE_DELAY.ms = 20;
+ const prev = process.env.FIXTURE_VOICE_KEY;
+ delete process.env.FIXTURE_VOICE_KEY;
+ const notices: string[] = [];
+ const m = new PluginManager({ safeMode: false, notify: (n) => { notices.push(n); } });
+ try {
+ const manifest = { permissions: { network: [], secrets: ['FIXTURE_VOICE_KEY'], optionalSecrets: { FIXTURE_VOICE_KEY: 'Voice calls' } } };
+ 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' }]);
+ // Restarting the same version doesn't repeat it.
+ await m.disable('voicey');
+ await m.enable('voicey');
+ await new Promise((r) => setTimeout(r, 80));
+ expect(notices).toHaveLength(1);
+ // With the key set, nothing is missing.
+ process.env.FIXTURE_VOICE_KEY = 'k';
+ expect((await m.info('voicey'))?.missingOptionalSecrets).toEqual([]);
+ } finally {
+ await m.shutdown();
+ SECRET_NOTICE_DELAY.ms = saved;
+ if (prev === undefined) delete process.env.FIXTURE_VOICE_KEY; else process.env.FIXTURE_VOICE_KEY = prev;
+ }
+ });
+
+ it('an optional secret must also be declared in permissions.secrets', () => {
+ const base = JSON.parse(readFileSync(join(inProcessPlugin(src, { id: 'bad-secret' }), 'mercury-plugin.json'), 'utf8'));
+ const bad = { ...base, permissions: { network: [], secrets: [], optionalSecrets: { OPENAI_API_KEY: 'Voice calls' } } };
+ expect(manifestSchema.safeParse(bad).success).toBe(false);
+ });
+});
diff --git a/src/plugins/manager.ts b/src/plugins/manager.ts
index 43fb6c10..87f11439 100644
--- a/src/plugins/manager.ts
+++ b/src/plugins/manager.ts
@@ -38,6 +38,8 @@ import type { CatalogEntry, DisabledCode, PluginListItem, PluginManifest, Plugin
export const CIRCUIT_BREAKER_FAILURES = 5;
export const BOOT_HEALTHY_AFTER_MS = 60_000;
+/** How long after start the missing-secret notice is sent (mutable for tests). */
+export const SECRET_NOTICE_DELAY = { ms: 15_000 };
const BOOT_GUARD_WINDOW_MS = 24 * 60 * 60 * 1000;
interface Running {
@@ -276,6 +278,7 @@ export class PluginManager {
this.running.set(id, { runtime, manifest, version, startedAt: Date.now(), consecutiveFailures: 0, channel });
this.lastErrors.delete(id);
logger.info({ plugin: id, version, kind: manifest.kind }, 'Plugin started');
+ this.noticeMissingSecrets(id, manifest);
} finally {
this.starting.delete(id);
}
@@ -298,6 +301,35 @@ export class PluginManager {
}
}
+ /**
+ * Tell the owner, once per plugin version, about optional secrets that
+ * aren't set (e.g. "Voice calls need OPENAI_API_KEY"). Delayed a little
+ * so it lands after channels have connected at startup.
+ */
+ private noticeMissingSecrets(id: string, manifest: PluginManifest): void {
+ const missing = missingOptionalSecrets(manifest);
+ if (!missing.length) return;
+ const entry = readState().plugins[id];
+ const fresh = missing.filter((m) => entry?.secretNotices?.[m.name] !== 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.`,
+ ].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;
+ }).catch(() => {});
+ }, SECRET_NOTICE_DELAY.ms);
+ timer.unref?.();
+ }
+
// ── health ───────────────────────────────────────────────────────────
private recordSuccess(id: string): void {
@@ -568,6 +600,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,
lastError: run?.lastError ?? this.lastErrors.get(id),
incompatibleReason: instIncompat ?? catIncompat ?? undefined,
};
@@ -636,3 +669,10 @@ export function peekPluginManager(): PluginManager | null {
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 }));
+}
diff --git a/src/plugins/types.ts b/src/plugins/types.ts
index da879428..ad5c8152 100644
--- a/src/plugins/types.ts
+++ b/src/plugins/types.ts
@@ -138,6 +138,12 @@ export const manifestSchema = z.object({
network: z.array(z.string().min(1).max(253)).max(32).default([]),
/** Secret names from ~/.mercury/.env the plugin may read. Nothing else is visible to it. */
secrets: z.array(z.string().regex(SECRET_NAME_RE)).max(16).default([]),
+ /**
+ * Secrets the plugin works without, and what they unlock, e.g.
+ * { "OPENAI_API_KEY": "Voice calls" }. A missing one is reported to the
+ * 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(),
}).strict().default({ network: [], secrets: [] }),
settings: z.object({
/** Bump when a field is renamed, removed or changes meaning, and add a migration. */
@@ -159,6 +165,9 @@ export const manifestSchema = z.object({
if (m.kind === 'out-of-process' && m.contributes.commands.length > 0) {
ctx.addIssue({ code: 'custom', path: ['contributes', 'commands'], message: 'slash commands are only supported for in-process plugins in plugin API 1.0' });
}
+ for (const name of Object.keys(m.permissions.optionalSecrets ?? {})) {
+ if (!m.permissions.secrets.includes(name)) ctx.addIssue({ code: 'custom', path: ['permissions', 'optionalSecrets'], message: `${name} must also be listed in permissions.secrets` });
+ }
if (m.contributes.channel && m.kind !== 'out-of-process') {
ctx.addIssue({ code: 'custom', path: ['contributes', 'channel'], message: 'only out-of-process plugins can provide a channel' });
}
@@ -210,6 +219,8 @@ 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. */
+ secretNotices?: Record<string, string>;
}
export interface PluginsState {
@@ -241,6 +252,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 }>;
/** 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'];