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): 'when' alternatives; provider requirements that depend on settings

Salman Qureshi5f39189e5a97
diff --git a/src/plugins/dialog.ts b/src/plugins/dialog.ts
index c8f21170..97184159 100644
--- a/src/plugins/dialog.ts
+++ b/src/plugins/dialog.ts
@@ -12,7 +12,7 @@
* button tap all work.
*/
import type { PluginService } from './service.js';
-import type { PluginListItem } from './types.js';
+import { whenMatches, type PluginListItem } from './types.js';
export interface DialogOption {
label: string;
@@ -355,11 +355,7 @@ 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);
- });
+ return whenMatches(s.when, Object.fromEntries(all.map((x) => [x.key, x.value])));
}
/** Plain-text rendering (WhatsApp, terminal, any chat without buttons). */
diff --git a/src/plugins/manager.ts b/src/plugins/manager.ts
index cc0ce776..f88db355 100644
--- a/src/plugins/manager.ts
+++ b/src/plugins/manager.ts
@@ -35,7 +35,7 @@ import { OutOfProcessRuntime } from './runtime/out-of-process.js';
import { PluginChannel, type ChannelStatus } from './channel-bridge.js';
import { transcribeAudio } from './transcribe.js';
import type { PluginRuntime } from './runtime/types.js';
-import { providerSecretNames, type CatalogEntry, type DisabledCode, type PluginListItem, type PluginManifest, type PluginProviderId, type PluginsState } from './types.js';
+import { providerSecretNames, whenMatches, type WhenCondition, 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;
@@ -774,7 +774,10 @@ export function providerCredentials(manifest: PluginManifest): Record<string, st
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]>) {
+ const values = resolvedSettings(manifest);
+ for (const [id, spec] of Object.entries(manifest.permissions.providers ?? {}) as Array<[PluginProviderId, string | { unlocks: string; when?: WhenCondition | WhenCondition[] }]>) {
+ const unlocks = typeof spec === 'string' ? spec : spec.unlocks;
+ if (typeof spec !== 'string' && !whenMatches(spec.when, values)) continue;
if (creds[providerSecretNames(id).apiKey]) continue;
out.push({
key: `provider:${id}`,
diff --git a/src/plugins/types.ts b/src/plugins/types.ts
index 8188dae9..0b8f8576 100644
--- a/src/plugins/types.ts
+++ b/src/plugins/types.ts
@@ -86,6 +86,8 @@ const commandDecl = z.object({
const settingKey = z.string().regex(/^[a-zA-Z][a-zA-Z0-9_]{0,40}$/);
+const whenCondition = z.record(settingKey, z.union([z.string(), z.boolean(), z.array(z.string())]));
+
const settingField = z.object({
/**
* 'secret': an API key the owner pastes once. Stored in Mercury's key store
@@ -108,8 +110,11 @@ const settingField = z.object({
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(),
+ /**
+ * Only relevant when other settings have these values, e.g.
+ * { "voiceEngine": ["elevenlabs"] }. A list of conditions means any of them.
+ */
+ when: z.union([whenCondition, z.array(whenCondition).min(1).max(8)]).optional(),
}).strict();
@@ -182,7 +187,11 @@ export const manifestSchema = z.object({
* 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(),
+ providers: z.record(z.enum(PLUGIN_PROVIDER_IDS), z.union([
+ z.string().min(1).max(200),
+ /** Needed only when settings match, e.g. { unlocks: "Voice calls", when: { voiceEngine: "openai" } }. */
+ z.object({ unlocks: z.string().min(1).max(200), when: z.union([whenCondition, z.array(whenCondition).min(1).max(8)]).optional() }).strict(),
+ ])).optional(),
}).strict().default({ network: [], secrets: [] }),
settings: z.object({
/** Bump when a field is renamed, removed or changes meaning, and add a migration. */
@@ -207,8 +216,10 @@ export const manifestSchema = z.object({
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 cond of [f.when ?? []].flat()) {
+ for (const dep of Object.keys(cond)) {
+ 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 ?? {})) {
@@ -241,6 +252,14 @@ export const manifestSchema = z.object({
});
export type PluginManifest = z.infer<typeof manifestSchema>;
+export type WhenCondition = Record<string, string | boolean | string[]>;
+
+/** Does a `when` condition (or any of a list) match these setting values? */
+export function whenMatches(when: WhenCondition | WhenCondition[] | undefined, values: Record<string, unknown>): boolean {
+ if (!when) return true;
+ return [when].flat().some((cond) => Object.entries(cond).every(([key, want]) =>
+ Array.isArray(want) ? want.includes(String(values[key])) : String(values[key]) === String(want)));
+}
export type PluginToolDecl = PluginManifest['contributes']['tools'][number];
// ── state ────────────────────────────────────────────────────────────────
@@ -319,7 +338,7 @@ export interface PluginListItem {
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[]>;
+ when?: WhenCondition | WhenCondition[];
/** 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.ts
index f9babee7..6442b493 100644
--- a/ui/src/lib/api.ts
+++ b/ui/src/lib/api.ts
@@ -276,7 +276,7 @@ export interface PluginSetting {
options?: string[];
value: unknown;
label?: string;
- when?: Record<string, string | boolean | string[]>;
+ when?: Record<string, string | boolean | string[]> | Array<Record<string, string | boolean | string[]>>;
isSet?: boolean;
setup?: boolean;
required?: boolean;
diff --git a/ui/src/pages/Plugins.tsx b/ui/src/pages/Plugins.tsx
index 0233769f..14d94845 100644
--- a/ui/src/pages/Plugins.tsx
+++ b/ui/src/pages/Plugins.tsx
@@ -691,8 +691,8 @@ function ChannelPanel({ id, enabled }: { id: string; enabled: boolean }) {
/** 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);
- });
+ const values = Object.fromEntries(all.map((x) => [x.key, x.value]));
+ const conds = Array.isArray(s.when) ? s.when : [s.when];
+ return conds.some((cond) => Object.entries(cond).every(([key, want]) =>
+ Array.isArray(want) ? want.includes(String(values[key])) : String(values[key]) === String(want)));
}