Soul-driven AI agent with permission-hardened tools, token budgets, and multi-channel access. Runs 24/7 from CLI, Telegram or More.
Add provider model selection during setup
M Shehzenf12e6faa7c9e
diff --git a/src/index.ts b/src/index.tsindex 436a39ed..9e168b16 100644--- a/src/index.ts+++ b/src/index.ts@@ -25,6 +25,8 @@ import { startBackground, stopDaemon, showLogs, getDaemonStatus, restartDaemon,import { installService, uninstallService, showServiceStatus, isServiceInstalled } from './cli/service.js';import { runWithWatchdog } from './cli/watchdog.js';import { setGitHubToken } from './utils/github.js';+import { selectWithArrowKeys } from './utils/arrow-select.js';+import { ProviderModelFetchError, fetchProviderModelCatalog } from './utils/provider-models.js';const __dirname = dirname(fileURLToPath(import.meta.url));const pkgVersion = JSON.parse(readFileSync(join(__dirname, '..', 'package.json'), 'utf8')).version;@@ -246,6 +248,133 @@ function validateModelName(value: string): string | null {return null;}+async function chooseProviderModel(+ providerLabel: string,+ recommendedModel: string,+ models: string[],+): Promise<string> {+ const selection = await selectWithArrowKeys(+ `${providerLabel} Models`,+ [+ {+ value: '__default__',+ label: `Use provider default (${recommendedModel})`,+ },+ ...models.map((model) => ({+ value: model,+ label: model,+ })),+ {+ value: '__custom__',+ label: 'Enter a custom model name',+ },+ ],+ );++ if (!selection || selection === '__default__') {+ return recommendedModel;+ }++ if (selection !== '__custom__') {+ return selection;+ }++ while (true) {+ const customModel = await ask(chalk.white(` ${providerLabel} model [Enter or "none" for ${recommendedModel}]: `));+ if (!customModel || customModel.toLowerCase() === 'none') {+ return recommendedModel;+ }++ const error = validateModelName(customModel);+ if (!error) {+ return customModel;+ }++ console.log(chalk.red(` ${error}`));+ }+}++async function promptApiKeyWithModelSelection(+ config: MercuryConfig,+ provider: ProviderName,+ providerLabel: string,+ prompt: string,+ isReconfig: boolean,+): Promise<{ apiKey?: string; model?: string; skipped: boolean }> {+ const existingConfig = config.providers[provider];++ while (true) {+ const value = await ask(prompt);+ if (!value) {+ if (isReconfig && existingConfig.apiKey) {+ return {+ apiKey: existingConfig.apiKey,+ model: existingConfig.model,+ skipped: true,+ };+ }++ return { skipped: true };+ }++ const formatError = validateApiKey(provider, value);+ if (formatError) {+ console.log(chalk.red(` ${formatError}`));+ continue;+ }++ console.log(chalk.dim(` Validating ${providerLabel} and fetching models...`));+ try {+ const catalog = await fetchProviderModelCatalog(provider, {+ ...existingConfig,+ apiKey: value,+ });+ const model = await chooseProviderModel(+ providerLabel,+ catalog.recommendedModel,+ catalog.models,+ );+ return { apiKey: value, model, skipped: false };+ } catch (error) {+ const message = error instanceof ProviderModelFetchError+ ? error.message+ : `Mercury could not fetch models for ${providerLabel}. Please re-enter the key.`;+ console.log(chalk.red(` ${message}`));+ }+ }+}++async function promptOllamaLocalModelSelection(config: MercuryConfig): Promise<{ baseUrl?: string; model?: string; skipped: boolean }> {+ const existingConfig = config.providers.ollamaLocal;++ while (true) {+ const baseUrl = (await promptValidatedValue(+ chalk.white(` Ollama Local base URL [${existingConfig.baseUrl}]: `),+ validateBaseUrl,+ existingConfig.baseUrl,+ ))!;++ console.log(chalk.dim(' Fetching Ollama Local models...'));+ try {+ const catalog = await fetchProviderModelCatalog('ollamaLocal', {+ ...existingConfig,+ baseUrl,+ });+ const model = await chooseProviderModel(+ 'Ollama Local',+ catalog.recommendedModel,+ catalog.models,+ );+ return { baseUrl, model, skipped: false };+ } catch (error) {+ const message = error instanceof ProviderModelFetchError+ ? error.message+ : 'Mercury could not fetch Ollama Local models. Please check the base URL and try again.';+ console.log(chalk.red(` ${message}`));+ }+ }+}+async function promptValidatedValue(prompt: string,validator: (value: string) => string | null,@@ -343,14 +472,16 @@ async function configure(existingConfig?: MercuryConfig): Promise<void> {for (const provider of selectedProviders) {if (provider === 'deepseek') {const mask = isReconfig && config.providers.deepseek.apiKey ? ` [${maskKey(config.providers.deepseek.apiKey)}]` : '';- const key = await promptValidatedValue(+ const result = await promptApiKeyWithModelSelection(+ config,+ 'deepseek',+ 'DeepSeek',chalk.white(` DeepSeek API key${mask}${isReconfig ? '' : ' (Enter to skip)'}: `),- (value) => validateApiKey('deepseek', value),- isReconfig ? config.providers.deepseek.apiKey : undefined,- { allowSkip: true },+ isReconfig,);- if (key) {- config.providers.deepseek.apiKey = key;+ if (!result.skipped && result.apiKey && result.model) {+ config.providers.deepseek.apiKey = result.apiKey;+ config.providers.deepseek.model = result.model;config.providers.deepseek.enabled = true;}continue;@@ -358,14 +489,16 @@ async function configure(existingConfig?: MercuryConfig): Promise<void> {if (provider === 'openai') {const mask = isReconfig && config.providers.openai.apiKey ? ` [${maskKey(config.providers.openai.apiKey)}]` : '';- const key = await promptValidatedValue(+ const result = await promptApiKeyWithModelSelection(+ config,+ 'openai',+ 'OpenAI',chalk.white(` OpenAI API key${mask}${isReconfig ? '' : ' (Enter to skip)'}: `),- (value) => validateApiKey('openai', value),- isReconfig ? config.providers.openai.apiKey : undefined,- { allowSkip: true },+ isReconfig,);- if (key) {- config.providers.openai.apiKey = key;+ if (!result.skipped && result.apiKey && result.model) {+ config.providers.openai.apiKey = result.apiKey;+ config.providers.openai.model = result.model;config.providers.openai.enabled = true;}continue;@@ -373,14 +506,16 @@ async function configure(existingConfig?: MercuryConfig): Promise<void> {if (provider === 'anthropic') {const mask = isReconfig && config.providers.anthropic.apiKey ? ` [${maskKey(config.providers.anthropic.apiKey)}]` : '';- const key = await promptValidatedValue(+ const result = await promptApiKeyWithModelSelection(+ config,+ 'anthropic',+ 'Anthropic',chalk.white(` Anthropic API key${mask}${isReconfig ? '' : ' (Enter to skip)'}: `),- (value) => validateApiKey('anthropic', value),- isReconfig ? config.providers.anthropic.apiKey : undefined,- { allowSkip: true },+ isReconfig,);- if (key) {- config.providers.anthropic.apiKey = key;+ if (!result.skipped && result.apiKey && result.model) {+ config.providers.anthropic.apiKey = result.apiKey;+ config.providers.anthropic.model = result.model;config.providers.anthropic.enabled = true;}continue;@@ -388,14 +523,16 @@ async function configure(existingConfig?: MercuryConfig): Promise<void> {if (provider === 'grok') {const mask = isReconfig && config.providers.grok.apiKey ? ` [${maskKey(config.providers.grok.apiKey)}]` : '';- const key = await promptValidatedValue(+ const result = await promptApiKeyWithModelSelection(+ config,+ 'grok',+ 'Grok',chalk.white(` Grok API key${mask}${isReconfig ? '' : ' (Enter to skip)'}: `),- (value) => validateApiKey('grok', value),- isReconfig ? config.providers.grok.apiKey : undefined,- { allowSkip: true },+ isReconfig,);- if (key) {- config.providers.grok.apiKey = key;+ if (!result.skipped && result.apiKey && result.model) {+ config.providers.grok.apiKey = result.apiKey;+ config.providers.grok.model = result.model;config.providers.grok.enabled = true;}continue;@@ -403,33 +540,28 @@ async function configure(existingConfig?: MercuryConfig): Promise<void> {if (provider === 'ollamaCloud') {const mask = isReconfig && config.providers.ollamaCloud.apiKey ? ` [${maskKey(config.providers.ollamaCloud.apiKey)}]` : '';- const key = await promptValidatedValue(+ const result = await promptApiKeyWithModelSelection(+ config,+ 'ollamaCloud',+ 'Ollama Cloud',chalk.white(` Ollama Cloud API key${mask}${isReconfig ? '' : ' (Enter to skip)'}: `),- (value) => validateApiKey('ollamaCloud', value),- isReconfig ? config.providers.ollamaCloud.apiKey : undefined,- { allowSkip: true },+ isReconfig,);- if (key) {- config.providers.ollamaCloud.apiKey = key;+ if (!result.skipped && result.apiKey && result.model) {+ config.providers.ollamaCloud.apiKey = result.apiKey;+ config.providers.ollamaCloud.model = result.model;config.providers.ollamaCloud.enabled = true;}continue;}if (provider === 'ollamaLocal') {- config.providers.ollamaLocal.baseUrl = (await promptValidatedValue(- chalk.white(` Ollama Local base URL [${config.providers.ollamaLocal.baseUrl}]: `),- validateBaseUrl,- config.providers.ollamaLocal.baseUrl,- ))!;-- config.providers.ollamaLocal.model = (await promptValidatedValue(- chalk.white(` Ollama Local model [${config.providers.ollamaLocal.model}]: `),- validateModelName,- config.providers.ollamaLocal.model,- ))!;-- config.providers.ollamaLocal.enabled = true;+ const result = await promptOllamaLocalModelSelection(config);+ if (!result.skipped && result.baseUrl && result.model) {+ config.providers.ollamaLocal.baseUrl = result.baseUrl;+ config.providers.ollamaLocal.model = result.model;+ config.providers.ollamaLocal.enabled = true;+ }}}@@ -607,8 +739,14 @@ async function runAgent(isDaemon: boolean = false): Promise<void> {}const available = providers.listAvailable();+ const providerLabels = available.map((provider) => getProviderLabel(provider as ProviderName));+ const providerModels = available.map((provider) => {+ const key = provider as ProviderName;+ return `${getProviderLabel(key)}: ${config.providers[key].model}`;+ });if (!isDaemon) {- console.log(chalk.dim(` Providers: ${available.join(', ')}`));+ console.log(chalk.dim(` Providers: ${providerLabels.join(', ')}`));+ console.log(chalk.dim(` Models: ${providerModels.join(' | ')}`));} else {logger.info({ providers: available }, 'Providers loaded');}@@ -692,10 +830,6 @@ async function runAgent(isDaemon: boolean = false): Promise<void> {const toolNames = capabilities.getToolNames();if (!isDaemon) {- console.log(chalk.dim(` Channels: ${activeCh.join(', ')}`));- console.log(chalk.dim(` Tools: ${toolNames.join(', ')}`));- console.log(chalk.dim(` Permissions: ${getMercuryHome()}/permissions.yaml`));- console.log(chalk.dim(` Schedules: ${getMercuryHome()}/schedules.yaml`));if (config.identity.creator) {console.log(chalk.dim(` Creator: ${config.identity.creator}`));}diff --git a/src/utils/arrow-select.ts b/src/utils/arrow-select.tsnew file mode 100644index 00000000..b55a5304--- /dev/null+++ b/src/utils/arrow-select.ts@@ -0,0 +1,89 @@+import readline from 'node:readline';+import chalk from 'chalk';++export interface ArrowSelectOption {+ value: string;+ label: string;+}++export async function selectWithArrowKeys(+ title: string,+ options: ArrowSelectOption[],+): Promise<string> {+ if (!process.stdin.isTTY || !process.stdout.isTTY || options.length === 0) {+ return options[0]?.value ?? '';+ }++ readline.emitKeypressEvents(process.stdin);++ const stdin = process.stdin;+ const stdout = process.stdout;+ const canUseRawMode = typeof stdin.setRawMode === 'function';+ let activeIndex = 0;+ let renderedLineCount = 0;++ const render = () => {+ if (renderedLineCount > 0) {+ readline.moveCursor(stdout, 0, -renderedLineCount);+ readline.clearScreenDown(stdout);+ }++ const lines = [+ chalk.bold.white(` ${title}`),+ chalk.dim(' Use the arrow keys, then press Enter.'),+ '',+ ...options.map((option, index) => {+ const marker = index === activeIndex ? chalk.cyan('>') : ' ';+ const text = index === activeIndex ? chalk.white(option.label) : chalk.dim(option.label);+ return ` ${marker} ${text}`;+ }),+ '',+ ];++ stdout.write(lines.join('\n'));+ renderedLineCount = lines.length;+ };++ return await new Promise<string>((resolve) => {+ const cleanup = () => {+ stdin.off('keypress', onKeypress);+ if (canUseRawMode) {+ stdin.setRawMode(false);+ }+ };++ const onKeypress = (_input: string, key: readline.Key) => {+ if (key.ctrl && key.name === 'c') {+ cleanup();+ process.kill(process.pid, 'SIGINT');+ return;+ }++ if (key.name === 'up') {+ activeIndex = (activeIndex - 1 + options.length) % options.length;+ render();+ return;+ }++ if (key.name === 'down') {+ activeIndex = (activeIndex + 1) % options.length;+ render();+ return;+ }++ if (key.name === 'return') {+ const selected = options[activeIndex]?.value ?? '';+ cleanup();+ stdout.write('\n');+ resolve(selected);+ }+ };++ if (canUseRawMode) {+ stdin.setRawMode(true);+ }+ stdin.resume();+ stdin.on('keypress', onKeypress);+ render();+ });+}diff --git a/src/utils/provider-models.test.ts b/src/utils/provider-models.test.tsnew file mode 100644index 00000000..2bc6d788--- /dev/null+++ b/src/utils/provider-models.test.ts@@ -0,0 +1,45 @@+import { describe, expect, it } from 'vitest';+import { buildModelCatalog } from './provider-models.js';++describe('buildModelCatalog', () => {+ it('prefers the provider recommended OpenAI model when available', () => {+ const catalog = buildModelCatalog('openai', [+ 'gpt-4.1',+ 'gpt-5-mini',+ 'gpt-5.2',+ 'gpt-image-1',+ ]);++ expect(catalog.recommendedModel).toBe('gpt-5.2');+ expect(catalog.models).toContain('gpt-5-mini');+ expect(catalog.models).toContain('gpt-4.1');+ expect(catalog.models).not.toContain('gpt-5.2');+ });++ it('falls back to the current Ollama Local model when no preferred default is installed', () => {+ const catalog = buildModelCatalog(+ 'ollamaLocal',+ ['qwen3:14b', 'llama3.2:latest'],+ 'llama3.2:latest',+ );++ expect(catalog.recommendedModel).toBe('llama3.2:latest');+ });++ it('limits the list of displayed models', () => {+ const catalog = buildModelCatalog('anthropic', [+ 'claude-sonnet-4-20250514',+ 'claude-opus-4-20250514',+ 'claude-3-7-sonnet-latest',+ 'claude-3-5-sonnet-latest',+ 'claude-3-5-haiku-latest',+ 'claude-test-a',+ 'claude-test-b',+ 'claude-test-c',+ 'claude-test-d',+ ]);++ expect(catalog.models).toHaveLength(7);+ expect(catalog.models).not.toContain('claude-sonnet-4-20250514');+ });+});diff --git a/src/utils/provider-models.ts b/src/utils/provider-models.tsnew file mode 100644index 00000000..30b3eb0b--- /dev/null+++ b/src/utils/provider-models.ts@@ -0,0 +1,301 @@+import type { ProviderConfig, ProviderName } from './config.js';++export interface ProviderModelCatalog {+ models: string[];+ recommendedModel: string;+}++const MAX_MODEL_OPTIONS = 7;++const OPENAI_PREFERRED_MODELS = [+ 'gpt-5.2',+ 'gpt-5.2-chat-latest',+ 'gpt-5.2-pro',+ 'gpt-5-mini',+ 'gpt-5-nano',+ 'gpt-4.1',+ 'gpt-4.1-mini',+ 'gpt-oss-120b',+ 'gpt-oss-20b',+] as const;++const ANTHROPIC_PREFERRED_MODELS = [+ 'claude-sonnet-4-20250514',+ 'claude-opus-4-20250514',+ 'claude-3-7-sonnet-latest',+ 'claude-3-5-sonnet-latest',+ 'claude-3-5-haiku-latest',+] as const;++const DEEPSEEK_PREFERRED_MODELS = [+ 'deepseek-chat',+ 'deepseek-reasoner',+] as const;++const GROK_PREFERRED_MODELS = [+ 'grok-4',+ 'grok-4-latest',+ 'grok-4.20',+ 'grok-3',+ 'grok-3-latest',+] as const;++const OLLAMA_CLOUD_PREFERRED_MODELS = [+ 'gpt-oss:120b',+ 'gpt-oss:120b-cloud',+ 'gpt-oss:20b',+] as const;++const OLLAMA_LOCAL_PREFERRED_MODELS = [+ 'gpt-oss:20b',+ 'gpt-oss:120b',+] as const;++export class ProviderModelFetchError extends Error {+ constructor(message: string) {+ super(message);+ this.name = 'ProviderModelFetchError';+ }+}++interface OpenAIModelResponse {+ data?: Array<{ id?: string }>;+}++interface AnthropicModelResponse {+ data?: Array<{ id?: string }>;+}++interface XAIModelResponse {+ data?: Array<{+ id?: string;+ input_modalities?: string[];+ output_modalities?: string[];+ }>;+}++interface OllamaTagsResponse {+ models?: Array<{ name?: string; model?: string }>;+}++function trimTrailingSlash(value: string): string {+ return value.replace(/\/+$/, '');+}++async function fetchJson<T>(url: string, init: RequestInit, invalidMessage: string): Promise<T> {+ let response: Response;+ try {+ response = await fetch(url, {+ ...init,+ signal: AbortSignal.timeout(10_000),+ });+ } catch {+ throw new ProviderModelFetchError(invalidMessage);+ }++ if (!response.ok) {+ throw new ProviderModelFetchError(invalidMessage);+ }++ try {+ return await response.json() as T;+ } catch {+ throw new ProviderModelFetchError('Mercury could not read the model list returned by this provider.');+ }+}++function uniq(values: string[]): string[] {+ return [...new Set(values.filter(Boolean))];+}++function prioritizeModels(models: string[], preferred: readonly string[]): string[] {+ const preferredSet = new Set(preferred);+ const preferredMatches = preferred.filter((model) => models.includes(model));+ const others = models+ .filter((model) => !preferredSet.has(model))+ .sort((a, b) => a.localeCompare(b));++ return [...preferredMatches, ...others];+}++function limitModels(models: string[]): string[] {+ return models.slice(0, MAX_MODEL_OPTIONS);+}++function isOpenAIChatModel(id: string): boolean {+ const lower = id.toLowerCase();+ if (+ lower.includes('image')+ || lower.includes('audio')+ || lower.includes('tts')+ || lower.includes('transcribe')+ || lower.includes('embedding')+ || lower.includes('moderation')+ || lower.includes('realtime')+ || lower.includes('whisper')+ || lower.includes('search')+ || lower.includes('computer')+ ) {+ return false;+ }++ return lower.startsWith('gpt-') || /^o\d/.test(lower);+}++function chooseRecommendedModel(+ provider: ProviderName,+ models: string[],+ currentModel?: string,+): string {+ const preferredByProvider: Record<ProviderName, readonly string[]> = {+ deepseek: DEEPSEEK_PREFERRED_MODELS,+ openai: OPENAI_PREFERRED_MODELS,+ anthropic: ANTHROPIC_PREFERRED_MODELS,+ grok: GROK_PREFERRED_MODELS,+ ollamaCloud: OLLAMA_CLOUD_PREFERRED_MODELS,+ ollamaLocal: OLLAMA_LOCAL_PREFERRED_MODELS,+ };++ for (const candidate of preferredByProvider[provider]) {+ if (models.includes(candidate)) {+ return candidate;+ }+ }++ if (currentModel && models.includes(currentModel)) {+ return currentModel;+ }++ return models[0];+}++export function buildModelCatalog(+ provider: ProviderName,+ models: string[],+ currentModel?: string,+): ProviderModelCatalog {+ const filtered = uniq(models);+ if (filtered.length === 0) {+ throw new ProviderModelFetchError('Mercury could not find any supported chat models for this provider.');+ }++ const recommendedModel = chooseRecommendedModel(provider, filtered, currentModel);+ const preferredByProvider: Record<ProviderName, readonly string[]> = {+ deepseek: DEEPSEEK_PREFERRED_MODELS,+ openai: OPENAI_PREFERRED_MODELS,+ anthropic: ANTHROPIC_PREFERRED_MODELS,+ grok: GROK_PREFERRED_MODELS,+ ollamaCloud: OLLAMA_CLOUD_PREFERRED_MODELS,+ ollamaLocal: OLLAMA_LOCAL_PREFERRED_MODELS,+ };++ const withoutRecommended = filtered.filter((model) => model !== recommendedModel);+ const prioritized = prioritizeModels(withoutRecommended, preferredByProvider[provider]);++ return {+ recommendedModel,+ models: limitModels(prioritized),+ };+}++async function fetchOpenAICompatModels(provider: ProviderName, config: ProviderConfig): Promise<ProviderModelCatalog> {+ const data = await fetchJson<OpenAIModelResponse>(+ `${trimTrailingSlash(config.baseUrl)}/models`,+ {+ headers: {+ Authorization: `Bearer ${config.apiKey}`,+ },+ },+ `Mercury could not fetch models for this ${provider === 'grok' ? 'Grok' : provider === 'deepseek' ? 'DeepSeek' : 'OpenAI'} key. Please re-enter it.`,+ );++ const ids = (data.data ?? [])+ .map((model) => model.id?.trim() ?? '')+ .filter((id) => {+ if (provider === 'deepseek') {+ return id.startsWith('deepseek-');+ }+ return isOpenAIChatModel(id);+ });++ return buildModelCatalog(provider, ids, config.model);+}++async function fetchAnthropicModels(config: ProviderConfig): Promise<ProviderModelCatalog> {+ const data = await fetchJson<AnthropicModelResponse>(+ 'https://api.anthropic.com/v1/models',+ {+ headers: {+ 'x-api-key': config.apiKey,+ 'anthropic-version': '2023-06-01',+ },+ },+ 'Mercury could not fetch models for this Anthropic key. Please re-enter it.',+ );++ const ids = (data.data ?? [])+ .map((model) => model.id?.trim() ?? '')+ .filter((id) => id.startsWith('claude-'));++ return buildModelCatalog('anthropic', ids, config.model);+}++async function fetchGrokModels(config: ProviderConfig): Promise<ProviderModelCatalog> {+ const data = await fetchJson<XAIModelResponse>(+ `${trimTrailingSlash(config.baseUrl)}/language-models`,+ {+ headers: {+ Authorization: `Bearer ${config.apiKey}`,+ },+ },+ 'Mercury could not fetch models for this Grok key. Please re-enter it.',+ );++ const ids = (data.data ?? [])+ .filter((model) => model.output_modalities?.includes('text') || model.output_modalities == null)+ .map((model) => model.id?.trim() ?? '')+ .filter((id) => id.startsWith('grok-'));++ return buildModelCatalog('grok', ids, config.model);+}++async function fetchOllamaModels(provider: ProviderName, config: ProviderConfig): Promise<ProviderModelCatalog> {+ const headers = config.apiKey+ ? { Authorization: `Bearer ${config.apiKey}` }+ : undefined;++ const data = await fetchJson<OllamaTagsResponse>(+ `${trimTrailingSlash(config.baseUrl)}/tags`,+ {+ headers,+ },+ provider === 'ollamaCloud'+ ? 'Mercury could not fetch models for this Ollama Cloud key. Please re-enter it.'+ : 'Mercury could not fetch models from this Ollama Local server. Please check the base URL and try again.',+ );++ const ids = (data.models ?? [])+ .map((model) => model.model?.trim() || model.name?.trim() || '')+ .filter(Boolean);++ return buildModelCatalog(provider, ids, config.model);+}++export async function fetchProviderModelCatalog(+ provider: ProviderName,+ config: ProviderConfig,+): Promise<ProviderModelCatalog> {+ if (provider === 'anthropic') {+ return fetchAnthropicModels(config);+ }++ if (provider === 'grok') {+ return fetchGrokModels(config);+ }++ if (provider === 'ollamaCloud' || provider === 'ollamaLocal') {+ return fetchOllamaModels(provider, config);+ }++ return fetchOpenAICompatModels(provider, config);+}