Soul-driven AI agent with permission-hardened tools, token budgets, and multi-channel access. Runs 24/7 from CLI, Telegram or More.
feat(plugins): API-key settings and conditional settings
Salman Qureshi7050b68a4f1e
diff --git a/src/plugins/dialog.ts b/src/plugins/dialog.tsindex 1612de92..c8f21170 100644--- a/src/plugins/dialog.ts+++ b/src/plugins/dialog.ts@@ -27,6 +27,8 @@ export interface DialogPrompt {}interface Step {+ /** False to skip this step (a setting that doesn't apply to the current choices). */+ applies?(): Promise<boolean>;prompt(): Promise<DialogPrompt>;/** Handle an answer. Return a message to show before the next prompt, if any. */answer(input: string, option: DialogOption | undefined): Promise<StepOutcome>;@@ -75,6 +77,7 @@ export class PluginDialog {/** The prompt to show now, or null when the dialog has finished. */async current(): Promise<DialogPrompt | null> {+ while (this.steps[0]?.applies && !(await this.steps[0].applies())) this.steps.shift();const step = this.steps[0];if (!step) return null;this.lastPrompt = await step.prompt();@@ -126,10 +129,20 @@ export class PluginDialog {private settingStep(s: Setting, ctx: { index?: number; total?: number; setup?: boolean } = {}): Step {const title = s.label ?? s.key;const counter = ctx.index ? ` (${ctx.index}/${ctx.total})` : '';- const current = s.value === undefined || s.value === '' ? 'not set' : String(s.optionLabels?.[String(s.value)] ?? s.value);- const keep = ctx.setup && !s.required && s.value !== undefined && s.value !== '' ? [{ label: `Keep: ${current}`, value: '__keep' }] : [];+ const current = s.type === 'secret' ? (s.isSet ? 'set ✓' : 'not set') : s.value === undefined || s.value === '' ? 'not set' : String(s.optionLabels?.[String(s.value)] ?? s.value);+ const hasValue = s.type === 'secret' ? !!s.isSet : s.value !== undefined && s.value !== '';+ const keep = ctx.setup && hasValue ? [{ label: `Keep: ${current}`, value: '__keep' }] : [];return {+ applies: async () => settingApplies(s, (await this.svc.info(this.pluginId))?.settings ?? []),prompt: async () => {+ if (s.type === 'secret') {+ const head = `${ctx.setup ? `⚙️ ${this.title}${counter}\n` : ''}*${title}*${s.description ? `\n${s.description}` : ''}`;+ return {+ text: `${head}\nNow: ${current}`,+ freeText: 'Paste the key here. It\'s stored with Mercury\'s keys (never shown again), and only this plugin can use it. You can delete your message afterwards.',+ options: keep.length ? keep : (s.required ? undefined : [{ label: 'Skip', value: '__keep' }]),+ };+ }const head = `${ctx.setup ? `⚙️ ${this.title}${counter}\n` : ''}*${title}*${s.description ? `\n${s.description}` : ''}`;if (s.type === 'enum') {return { text: `${head}\nNow: ${current}`, options: (s.options ?? []).map((o) => ({ label: s.optionLabels?.[o] ?? o, value: o })) };@@ -142,6 +155,11 @@ export class PluginDialog {},answer: async (input, option) => {if (option?.value === '__keep') return { kind: 'next' };+ if (s.type === 'secret') {+ if (!input || input.length < 8) return { kind: 'retry', message: 'Paste the whole key, or reply "skip".' };+ await this.svc.setSetting(this.pluginId, s.key, input.trim());+ return { kind: 'next', message: `✅ ${title} saved.` };+ }let value: string;if (s.type === 'enum' || s.type === 'boolean') {if (!option) return { kind: 'retry', message: 'Reply with one of the numbers.' };@@ -219,8 +237,8 @@ export class PluginDialog {const status = i.installedVersion ? (i.enabled ? (i.status === 'enabled' ? 'on' : i.status) : 'off') : 'not installed';lines.push('', `Status: ${status}`);if (i.channel) lines.push(`Account: ${i.channel.state === 'connected' ? `linked${i.channel.account ? ` as +${i.channel.account}` : ''}` : (i.channel.state ?? 'not linked')}`);- for (const s of (i.settings ?? []).filter((x) => x.setup || x.label)) {- const v = s.value === undefined || s.value === '' ? 'not set' : s.type === 'boolean' ? (s.value ? 'yes' : 'no') : String(s.optionLabels?.[String(s.value)]?.split(':')[0] ?? s.value);+ for (const s of (i.settings ?? []).filter((x) => (x.setup || x.label) && settingApplies(x, i.settings ?? []))) {+ const v = s.type === 'secret' ? (s.isSet ? 'set ✓' : 'not set') : s.value === undefined || s.value === '' ? 'not set' : s.type === 'boolean' ? (s.value ? 'yes' : 'no') : String(s.optionLabels?.[String(s.value)]?.split(':')[0] ?? s.value);lines.push(`${s.label ?? s.key}: ${v}`);}for (const m of i.missing ?? []) lines.push(`⚠️ ${m.unlocks} is off: needs ${m.needs}.`);@@ -290,7 +308,7 @@ export class PluginDialog {}private pickSettingStep(i: PluginListItem): Step {- const settings = i.settings ?? [];+ const settings = (i.settings ?? []).filter((x) => settingApplies(x, i.settings ?? []));return {prompt: async () => ({text: '*Which setting?*',@@ -335,6 +353,15 @@ export class PluginDialog {}}+/** Does a setting apply, given the current values of the settings it depends on (`when`)? */+export function settingApplies(s: Setting, all: Setting[]): boolean {+ if (!s.when) return true;+ return Object.entries(s.when).every(([key, want]) => {+ const v = all.find((x) => x.key === key)?.value;+ return Array.isArray(want) ? want.includes(String(v)) : String(v) === String(want);+ });+}+/** Plain-text rendering (WhatsApp, terminal, any chat without buttons). */export function renderPrompt(p: DialogPrompt, buttons: boolean): string {const lines = [p.text];diff --git a/src/plugins/lifecycle.test.ts b/src/plugins/lifecycle.test.tsindex 599d580a..4151c472 100644--- a/src/plugins/lifecycle.test.ts+++ b/src/plugins/lifecycle.test.ts@@ -224,3 +224,59 @@ describe('Mercury providers for plugins', () => {}});});++describe('secret settings (API keys a plugin asks for)', () => {+ const manifest = {+ permissions: { network: [], secrets: ['FIXTURE_VOICE_KEY'] },+ settings: { version: 1, fields: {+ engine: { type: 'enum', options: ['openai', 'other'], default: 'openai', setup: true },+ otherKey: { type: 'secret', secret: 'FIXTURE_VOICE_KEY', label: 'Other key', setup: true, when: { engine: 'other' } },+ } },+ };+ const code = `export async function activate(ctx) {+ ctx.tools.register({ name: 'echo', inputSchema: { type: 'object' }, execute: async () => String(ctx.secrets.get('FIXTURE_VOICE_KEY') ?? 'none') });+}`;++ it('are kept in the key store, never in settings, shown only as set, and reach the plugin', async () => {+ const prev = process.env.FIXTURE_VOICE_KEY;+ delete process.env.FIXTURE_VOICE_KEY;+ try {+ await mgr.install(inProcessPlugin(src, { id: 'keyed', code, manifest }));+ await mgr.setSetting('keyed', 'otherKey', 'sk-test-1234567890');+ const settingsFile = existsSync(pluginSettingsPath('keyed')) ? readFileSync(pluginSettingsPath('keyed'), 'utf8') : '';+ expect(settingsFile).not.toContain('sk-test');+ const { readPluginKeys } = await import('./store.js');+ expect(readPluginKeys().FIXTURE_VOICE_KEY).toBe('sk-test-1234567890');+ const s = (await mgr.info('keyed'))?.settings?.find((x) => x.key === 'otherKey');+ expect(s).toMatchObject({ type: 'secret', isSet: true, value: undefined });+ const t = listLiveTools().find((x) => x.pluginId === 'keyed')!;+ expect(await t.invoke({}, new AbortController().signal)).toBe('sk-test-1234567890'); // restarted with the key+ await mgr.setSetting('keyed', 'otherKey', '');+ expect((await mgr.info('keyed'))?.settings?.find((x) => x.key === 'otherKey')?.isSet).toBe(false);+ await expect(mgr.setSetting('keyed', 'otherKey', 'short')).rejects.toThrow(/API key/);+ } finally {+ if (prev !== undefined) process.env.FIXTURE_VOICE_KEY = prev;+ }+ });++ it('a secret setting must name a declared secret; "when" must refer to a real setting', () => {+ const base = JSON.parse(readFileSync(join(inProcessPlugin(src, { id: 'bad-keys' }), 'mercury-plugin.json'), 'utf8'));+ expect(manifestSchema.safeParse({ ...base, settings: { version: 1, fields: { k: { type: 'secret', secret: 'UNDECLARED_KEY' } } } }).success).toBe(false);+ expect(manifestSchema.safeParse({ ...base, settings: { version: 1, fields: { k: { type: 'secret' } } } }).success).toBe(false);+ expect(manifestSchema.safeParse({ ...base, settings: { version: 1, fields: { a: { type: 'string', when: { nope: 'x' } } } } }).success).toBe(false);+ });++ it('setup skips settings that do not apply to the choices made so far', async () => {+ const { PluginDialog, renderPrompt } = await import('./dialog.js');+ const { localService } = await import('./service.js');+ await mgr.install(inProcessPlugin(src, { id: 'keyed', code, manifest }));+ const d = (await PluginDialog.setup(localService(mgr), 'keyed'))!;+ expect(renderPrompt((await d.current())!, false)).toMatch(/engine/);+ await d.answer('1'); // openai: the "Other key" question doesn't apply+ expect(renderPrompt((await d.current())!, false)).toMatch(/is set up/);+ const d2 = (await PluginDialog.setup(localService(mgr), 'keyed'))!;+ await d2.current();+ await d2.answer('2'); // other: now it asks for the key+ expect(renderPrompt((await d2.current())!, false)).toMatch(/Other key[\s\S]*Paste the key here/);+ });+});diff --git a/src/plugins/manager.ts b/src/plugins/manager.tsindex 4dbaba3d..cc0ce776 100644--- a/src/plugins/manager.ts+++ b/src/plugins/manager.ts@@ -27,7 +27,7 @@ import {type InstallResult,} from './installer.js';import {- incompatibility, mercuryVersion, pluginDataDir, pluginDir, pluginVersionDir, readState, resolvedSettings, updateState, writeSettings, migrateSettings,+ incompatibility, mercuryVersion, pluginDataDir, pluginDir, pluginVersionDir, readState, resolvedSettings, updateState, writeSettings, migrateSettings, secretValue, setPluginKey,} from './store.js';import { setToolOutcomeSink, unpublishPlugin, listLiveTools, listPluginCommands } from './tool-bridge.js';import { InProcessRuntime, inProcessLogger } from './runtime/in-process.js';@@ -291,7 +291,7 @@ export class PluginManager {mercuryVersion: mercuryVersion(),dataDir: pluginDataDir(id),settings: resolvedSettings(manifest),- secrets: { ...Object.fromEntries(manifest.permissions.secrets.map((k) => [k, process.env[k]])), ...providerCredentials(manifest) },+ secrets: { ...Object.fromEntries(manifest.permissions.secrets.map((k) => [k, secretValue(k)])), ...providerCredentials(manifest) },log: inProcessLogger(id),onError: (message: string) => this.recordFailure(id, message),onFatal: (code: 'crashed' | 'activation', message: string) => {@@ -511,6 +511,18 @@ export class PluginManager {const manifest = installedManifest(id, entry.version);const field = manifest?.settings?.fields?.[key];if (!manifest || !field) throw new Error(`"${id}" has no setting called "${key}".`);+ if (field.type === 'secret') {+ // Keys go to Mercury's key store, never the plugin's settings file; the+ // plugin gets them at start, so restart it if it's running.+ const v = typeof value === 'string' ? value.trim() : '';+ if (v && v.length < 8) throw new Error('That doesn\'t look like an API key.');+ setPluginKey(field.secret!, v || null);+ if (this.running.has(id)) {+ await this.stopRuntime(id);+ await this.reconcile();+ }+ return;+ }const coerced = coerceSetting(field.type, field.options, value, field.format);const values = { ...resolvedSettings(manifest), [key]: coerced };writeSettings(id, values, manifest.settings?.version ?? 1);@@ -600,8 +612,10 @@ export class PluginManager {if (manifest && Object.keys(fields).length) {const values = resolvedSettings(manifest);item.settings = Object.entries(fields).map(([key, f]) => ({- key, type: f.type, description: f.description, options: f.options, value: values[key],- label: f.label, setup: f.setup, required: f.required, optionLabels: f.optionLabels, format: f.format,+ key, type: f.type, description: f.description, options: f.options,+ value: f.type === 'secret' ? undefined : values[key],+ isSet: f.type === 'secret' ? !!secretValue(f.secret!) : undefined,+ label: f.label, setup: f.setup, required: f.required, optionLabels: f.optionLabels, format: f.format, when: f.when,}));}return item;@@ -722,7 +736,7 @@ export function resetPluginManager(): void {instance = null;}-const PROVIDER_LABEL: Record<PluginProviderId, string> = { openai: 'OpenAI' };+const PROVIDER_LABEL: Record<PluginProviderId, string> = { openai: 'OpenAI', grok: 'xAI Grok' };type ProviderLookup = (id: PluginProviderId) => { apiKey?: string; baseUrl?: string } | undefined;diff --git a/src/plugins/store.ts b/src/plugins/store.tsindex da6fe11e..728d54ba 100644--- a/src/plugins/store.ts+++ b/src/plugins/store.ts@@ -311,6 +311,7 @@ export function resolvedSettings(manifest: PluginManifest): Record<string, unknoconst saved = !file ? {} : file.settingsVersion < target ? migrateSettingValues(manifest, file.values, file.settingsVersion) : file.settingsVersion > target ? {} : file.values;const out: Record<string, unknown> = {};for (const [key, field] of Object.entries(fields)) {+ if (field.type === 'secret') continue; // keys live in the key store, not settingsconst v = saved[key];let value: unknown = field.default;if (field.type === 'boolean' && typeof v === 'boolean') value = v;@@ -326,3 +327,35 @@ export function writeSettings(id: string, values: Record<string, unknown>, settimkdirSync(pluginDir(id), { recursive: true });writeJsonAtomic(pluginSettingsPath(id), { settingsVersion, values });}++// ── key store ─────────────────────────────────────────────────────────────++/**+ * API keys plugin settings ask for (type "secret"), e.g. an ElevenLabs key+ * for WhatsApp voice. One owner-only file for every plugin; each plugin only+ * ever receives the names it declares in permissions.secrets.+ */+export function pluginKeysPath(): string {+ return join(getMercuryHome(), 'plugin-keys.json');+}++export function readPluginKeys(): Record<string, string> {+ try {+ const raw = JSON.parse(readFileSync(pluginKeysPath(), 'utf8')) as Record<string, unknown>;+ return Object.fromEntries(Object.entries(raw).filter((e): e is [string, string] => typeof e[1] === 'string' && e[1].length > 0));+ } catch {+ return {};+ }+}++export function setPluginKey(name: string, value: string | null): void {+ const keys = readPluginKeys();+ if (value) keys[name] = value;+ else delete keys[name];+ writeJsonAtomic(pluginKeysPath(), keys);+}++/** A declared secret: Mercury's environment first (~/.mercury/.env), then the key store. */+export function secretValue(name: string): string | undefined {+ return process.env[name] || readPluginKeys()[name] || undefined;+}diff --git a/src/plugins/types.ts b/src/plugins/types.tsindex 25129929..8188dae9 100644--- a/src/plugins/types.ts+++ b/src/plugins/types.ts@@ -42,7 +42,7 @@ export const RESERVED_COMMANDS: ReadonlySet<string> = new Set([]);/** Mercury providers a plugin can ask to use (Plugin API 1.1). */-export const PLUGIN_PROVIDER_IDS = ['openai'] as const;+export const PLUGIN_PROVIDER_IDS = ['openai', 'grok'] as const;export type PluginProviderId = (typeof PLUGIN_PROVIDER_IDS)[number];/** Env names a plugin gets for a provider it declared. */@@ -84,8 +84,15 @@ const commandDecl = z.object({description: z.string().min(1).max(200),}).strict();+const settingKey = z.string().regex(/^[a-zA-Z][a-zA-Z0-9_]{0,40}$/);+const settingField = z.object({- type: z.enum(['string', 'number', 'boolean', 'enum']),+ /**+ * 'secret': an API key the owner pastes once. Stored in Mercury's key store+ * (never in the plugin's settings file), shown only as "set", and passed to+ * the plugin as the env var named by `secret`.+ */+ type: z.enum(['string', 'number', 'boolean', 'enum', 'secret']),description: z.string().max(300).default(''),default: z.union([z.string(), z.number(), z.boolean()]).optional(),options: z.array(z.string()).max(50).optional(),@@ -99,9 +106,12 @@ const settingField = z.object({optionLabels: z.record(z.string(), z.string().max(160)).optional(),/** Input format for string settings, validated and normalised on save. */format: z.enum(['text', 'phone']).default('text'),+ /** For type 'secret': the env var name the plugin receives it as (must be in permissions.secrets). */+ secret: z.string().regex(SECRET_NAME_RE).optional(),+ /** Only relevant when other settings have these values, e.g. { "voiceEngine": ["elevenlabs"] }. */+ when: z.record(settingKey, z.union([z.string(), z.boolean(), z.array(z.string())])).optional(),}).strict();-const settingKey = z.string().regex(/^[a-zA-Z][a-zA-Z0-9_]{0,40}$/);const settingsMigration = z.object({/** The settings version this step produces. */@@ -194,6 +204,13 @@ 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 [key, f] of Object.entries(m.settings?.fields ?? {})) {+ if (f.type === 'secret' && !f.secret) ctx.addIssue({ code: 'custom', path: ['settings', 'fields', key], message: 'secret settings need "secret": the env var name' });+ if (f.secret && !m.permissions.secrets.includes(f.secret)) ctx.addIssue({ code: 'custom', path: ['settings', 'fields', key], message: `${f.secret} must also be listed in permissions.secrets` });+ for (const dep of Object.keys(f.when ?? {})) {+ if (!m.settings?.fields[dep]) ctx.addIssue({ code: 'custom', path: ['settings', 'fields', key, 'when'], message: `"when" refers to unknown setting ${dep}` });+ }+ }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` });}@@ -292,7 +309,7 @@ export interface PluginListItem {/** Only in `info`: the settings the plugin declares, with current values. */settings?: Array<{key: string;- type: 'string' | 'number' | 'boolean' | 'enum';+ type: 'string' | 'number' | 'boolean' | 'enum' | 'secret';description: string;options?: string[];value: unknown;@@ -301,6 +318,10 @@ export interface PluginListItem {required?: boolean;optionLabels?: Record<string, string>;format?: 'text' | 'phone';+ /** Only relevant when these other settings match (the menu and setup hide it otherwise). */+ when?: Record<string, string | boolean | string[]>;+ /** Secret settings: whether a value is stored (the value itself is never shown). */+ isSet?: boolean;}>;}diff --git a/ui/src/lib/api.ts b/ui/src/lib/api.tsindex 3738e362..f9babee7 100644--- a/ui/src/lib/api.ts+++ b/ui/src/lib/api.ts@@ -271,11 +271,13 @@ export type PluginStatus = "available" | "installed" | "enabled" | "disabled" |export interface PluginSetting {key: string;- type: "string" | "number" | "boolean" | "enum";+ type: "string" | "number" | "boolean" | "enum" | "secret";description: string;options?: string[];value: unknown;label?: string;+ when?: Record<string, string | boolean | string[]>;+ isSet?: boolean;setup?: boolean;required?: boolean;optionLabels?: Record<string, string>;diff --git a/ui/src/pages/Plugins.tsx b/ui/src/pages/Plugins.tsxindex 65310f09..0233769f 100644--- a/ui/src/pages/Plugins.tsx+++ b/ui/src/pages/Plugins.tsx@@ -432,21 +432,28 @@ function PermissionList({ p }: { p: PluginItem }) {}function SettingField({ s, disabled, onSave }: { s: PluginSetting; disabled: boolean; onSave: (v: unknown) => void }) {- const [draft, setDraft] = useState(s.value === undefined ? "" : String(s.value));- useEffect(() => setDraft(s.value === undefined ? "" : String(s.value)), [s.value]);+ const [draft, setDraft] = useState(s.value === undefined || s.type === "secret" ? "" : String(s.value));+ useEffect(() => setDraft(s.value === undefined || s.type === "secret" ? "" : String(s.value)), [s.value, s.type]);return (<div className="space-y-1"><div className="flex items-center justify-between gap-3"><label className="text-sm font-medium text-foreground" htmlFor={`setting-${s.key}`}>{s.label ?? s.key}- {s.required && (s.value === undefined || s.value === "") && <span className="ml-2 text-xs text-amber-500">needed</span>}+ {s.required && (s.type === "secret" ? !s.isSet : s.value === undefined || s.value === "") && <span className="ml-2 text-xs text-amber-500">needed</span>}+ {s.type === "secret" && s.isSet && <span className="ml-2 text-xs text-emerald-500">set ✓</span>}</label>{s.type === "boolean" && (<Switch id={`setting-${s.key}`} checked={s.value === true} disabled={disabled} onCheckedChange={(v) => onSave(v)} />)}</div>{s.description && <p className="text-xs text-muted-foreground">{s.description}</p>}- {s.type === "enum" ? (+ {s.type === "secret" ? (+ <form className="flex gap-2" onSubmit={(e) => { e.preventDefault(); if (draft.trim()) { onSave(draft.trim()); setDraft(""); } }}>+ <Input id={`setting-${s.key}`} value={draft} onChange={(e) => setDraft(e.target.value)} type="password" autoComplete="off" placeholder={s.isSet ? "Saved ✓ (paste to replace)" : "Paste API key"} disabled={disabled} className="h-8 text-sm" />+ <Button size="sm" variant="outline" type="submit" disabled={disabled || !draft.trim()}>Save</Button>+ {s.isSet && <Button size="sm" variant="ghost" type="button" disabled={disabled} onClick={() => onSave("")}>Remove</Button>}+ </form>+ ) : s.type === "enum" ? (<selectid={`setting-${s.key}`}className="h-9 w-full rounded-md border border-input bg-background px-2 text-sm"@@ -502,7 +509,7 @@ function PluginDetails({ p, busy, safeMode, onAct, onInstall, onClose }: {{p.settings && p.settings.length > 0 && (<div className="space-y-3 rounded-lg border border-border p-3"><p className="text-xs font-medium uppercase tracking-wide text-muted-foreground">Settings</p>- {[...p.settings].sort((a, b) => Number(!!b.setup) - Number(!!a.setup)).map((setting) => (+ {[...p.settings].filter((x) => settingApplies(x, p.settings ?? [])).sort((a, b) => Number(!!b.setup) - Number(!!a.setup)).map((setting) => (<SettingFieldkey={setting.key}s={setting}@@ -680,3 +687,12 @@ function ChannelPanel({ id, enabled }: { id: string; enabled: boolean }) {</div>);}++/** Hide settings that only apply to other choices (manifest `when`). */+function settingApplies(s: PluginSetting, all: PluginSetting[]): boolean {+ if (!s.when) return true;+ return Object.entries(s.when).every(([key, want]) => {+ const v = all.find((x) => x.key === key)?.value;+ return Array.isArray(want) ? want.includes(String(v)) : String(v) === String(want);+ });+}