Soul-driven AI agent with permission-hardened tools, token budgets, and multi-channel access. Runs 24/7 from CLI, Telegram or More.
50/50 RevShare Integration: Mercury & AIML API (#117)
Hugo1ffd2ef01939
diff --git a/.env.example b/.env.exampleindex 6f71e194..10607578 100644--- a/.env.example+++ b/.env.example@@ -33,6 +33,11 @@ ATLASCLOUD_API_KEY=ATLASCLOUD_BASE_URL=https://api.atlascloud.ai/v1ATLASCLOUD_MODEL=qwen/qwen3.5-flash+# AI/ML API (OpenAI-compatible API)+AIMLAPI_API_KEY=+AIMLAPI_BASE_URL=https://api.aimlapi.com/v1+AIMLAPI_MODEL=anthropic/claude-sonnet-4.6+# Ollama Cloud (API key required for ollama.com/v1)OLLAMA_CLOUD_API_KEY=OLLAMA_CLOUD_BASE_URL=https://ollama.com/v1@@ -60,7 +65,7 @@ MIMO_TOKEN_PLAN_BASE_URL=https://token-plan-cn.xiaomimimo.com/v1MIMO_TOKEN_PLAN_MODEL=mimo-v2.5-proMIMO_TOKEN_PLAN_ENABLED=false-# Default provider: deepseek | openai | anthropic | grok | atlascloud | ollamaCloud | ollamaLocal | openaiCompat | mimo | mimoTokenPlan+# Default provider: deepseek | openai | anthropic | grok | atlascloud | aimlapi | ollamaCloud | ollamaLocal | openaiCompat | mimo | mimoTokenPlanDEFAULT_PROVIDER=deepseek# ── Telegram ──diff --git a/src/index.ts b/src/index.tsindex 6a22245e..52ff2262 100644--- a/src/index.ts+++ b/src/index.ts@@ -147,6 +147,7 @@ function maskKey(key: string): string {}const PROVIDER_OPTIONS: Array<{ key: ProviderName; label: string }> = [+ { key: 'aimlapi', label: 'AI/ML API (recommended — 350+ models on one key)' },{ key: 'mercuryCloud', label: 'Mercury Cloud (hosted — no API keys needed)' },{ key: 'deepseek', label: 'DeepSeek' },{ key: 'openai', label: 'OpenAI' },@@ -1204,6 +1205,23 @@ async function configure(existingConfig?: MercuryConfig): Promise<void> {}for (const provider of selectedProviders) {+ if (provider === 'aimlapi') {+ const mask = isReconfig && config.providers.aimlapi.apiKey ? ` [${maskKey(config.providers.aimlapi.apiKey)}]` : '';+ const result = await promptApiKeyWithModelSelection(+ config,+ 'aimlapi',+ 'AI/ML API',+ chalk.white(` AI/ML API key${mask}${isReconfig ? '' : ' (Enter to skip)'}: `),+ isReconfig,+ );+ if (!result.skipped && result.apiKey && result.model) {+ config.providers.aimlapi.apiKey = result.apiKey;+ config.providers.aimlapi.model = result.model;+ config.providers.aimlapi.enabled = true;+ }+ continue;+ }+if (provider === 'deepseek') {const mask = isReconfig && config.providers.deepseek.apiKey ? ` [${maskKey(config.providers.deepseek.apiKey)}]` : '';const result = await promptApiKeyWithModelSelection(diff --git a/src/providers/aimlapi-attribution.test.ts b/src/providers/aimlapi-attribution.test.tsnew file mode 100644index 00000000..b0a7d9f7--- /dev/null+++ b/src/providers/aimlapi-attribution.test.ts@@ -0,0 +1,51 @@+import { describe, it, expect } from 'vitest';+import { aimlapiHeaders, isAimlapiBaseUrl, AIMLAPI_BASE_URL } from './aimlapi-attribution.js';++describe('AI/ML API attribution', () => {+ it('sends the four headers for the default base URL', () => {+ const headers = aimlapiHeaders(AIMLAPI_BASE_URL);+ expect(headers).toEqual({+ 'X-AIMLAPI-Partner-ID': expect.stringMatching(/^part_[A-Za-z0-9]{1,64}$/),+ 'X-AIMLAPI-Source': 'agent/mercury-agent',+ 'HTTP-Referer': 'https://github.com/cosmicstack-labs/mercury-agent',+ 'X-Title': 'Mercury Agent',+ });+ });++ it('keeps sending them when the user trims or extends the path', () => {+ for (const url of [+ 'https://api.aimlapi.com',+ 'https://api.aimlapi.com/',+ 'https://api.aimlapi.com/v1/',+ 'https://API.AIMLAPI.COM/v1',+ ]) {+ expect(aimlapiHeaders(url), url).toBeDefined();+ }+ });++ it('sends nothing to a lookalike host', () => {+ // The reason this is a test and not a comment: AI/ML API serves a request+ // with someone else's partner id normally, so leaking one is silent.+ for (const url of [+ 'https://api.aimlapi.com.example.test/v1',+ 'https://not-api.aimlapi.com/v1',+ 'https://example.test/?next=https://api.aimlapi.com/v1',+ 'https://example.test/api.aimlapi.com/v1',+ ]) {+ expect(aimlapiHeaders(url), url).toBeUndefined();+ expect(isAimlapiBaseUrl(url), url).toBe(false);+ }+ });++ it('sends nothing to the other providers this class serves', () => {+ for (const url of [+ 'https://api.openai.com/v1',+ 'https://api.deepseek.com/v1',+ 'http://localhost:11434/v1',+ '',+ 'not a url',+ ]) {+ expect(aimlapiHeaders(url), url).toBeUndefined();+ }+ });+});diff --git a/src/providers/aimlapi-attribution.ts b/src/providers/aimlapi-attribution.tsnew file mode 100644index 00000000..2c79abff--- /dev/null+++ b/src/providers/aimlapi-attribution.ts@@ -0,0 +1,47 @@+/**+ * AI/ML API attributes traffic by header. A request without them is served+ * normally and simply counts for nobody, so a missing or misspelled value+ * fails silently — which is why the host check below is exact and why the+ * tests cover the near-misses rather than only the hit.+ *+ * `X-AIMLAPI-Partner-ID` must match `^part_[A-Za-z0-9]{1,64}$`: alphanumerics+ * only after the prefix. `HTTP-Referer` and `X-Title` are the OpenRouter+ * convention that most gateways already understand.+ */+export const AIMLAPI_HOST = 'api.aimlapi.com';+export const AIMLAPI_BASE_URL = `https://${AIMLAPI_HOST}/v1`;++const PARTNER_ID = 'part_nl32eeP4aNn6xzoF09Cn2SOQ';+const SOURCE = 'agent/mercury-agent';+const REFERER = 'https://github.com/cosmicstack-labs/mercury-agent';+const TITLE = 'Mercury Agent';++/**+ * Parse the URL and compare the host, rather than matching a prefix.+ *+ * The failure a substring check invites is one-directional and expensive:+ * `https://api.aimlapi.com.example.test/v1` is a different origin, and sending+ * a partner id there hands our attribution to whoever owns it. A user is free+ * to point `openaiCompat` anywhere, so this runs on untrusted input.+ */+export function isAimlapiBaseUrl(baseUrl: string): boolean {+ let url: URL;+ try {+ url = new URL(baseUrl);+ } catch {+ return false;+ }+ if (url.protocol !== 'https:' && url.protocol !== 'http:') return false;+ return url.hostname.toLowerCase() === AIMLAPI_HOST;+}++/** Attribution headers for AI/ML API, or `undefined` for every other host. */+export function aimlapiHeaders(baseUrl: string): Record<string, string> | undefined {+ if (!isAimlapiBaseUrl(baseUrl)) return undefined;+ return {+ 'X-AIMLAPI-Partner-ID': PARTNER_ID,+ 'X-AIMLAPI-Source': SOURCE,+ 'HTTP-Referer': REFERER,+ 'X-Title': TITLE,+ };+}diff --git a/src/providers/openai-compat.aimlapi.test.ts b/src/providers/openai-compat.aimlapi.test.tsnew file mode 100644index 00000000..1f7f8191--- /dev/null+++ b/src/providers/openai-compat.aimlapi.test.ts@@ -0,0 +1,44 @@+import { describe, it, expect, vi, beforeEach } from 'vitest';++type ClientOptions = { baseURL?: string; headers?: Record<string, string> };++const createOpenAI = vi.fn((_options: ClientOptions) => {+ const client: any = vi.fn(() => ({ id: 'model' }));+ client.chat = vi.fn(() => ({ id: 'model' }));+ return client;+});++vi.mock('@ai-sdk/openai', () => ({ createOpenAI: (options: ClientOptions) => createOpenAI(options) }));++import { OpenAICompatProvider } from './openai-compat.js';+import type { ProviderConfig } from '../utils/config.js';++const config = (name: string, baseUrl: string): ProviderConfig => ({+ name,+ apiKey: 'test-key',+ baseUrl,+ model: 'some-model',+ enabled: true,+});++describe('OpenAICompatProvider header wiring', () => {+ beforeEach(() => createOpenAI.mockClear());++ it('hands the attribution headers to the client for AI/ML API', () => {+ // The unit tests next door prove which headers are chosen; this proves+ // they actually reach the SDK, which is the half a refactor would drop.+ new OpenAICompatProvider(config('aimlapi', 'https://api.aimlapi.com/v1'), { useChatApi: true });++ const options = createOpenAI.mock.calls[0]![0];+ expect(options.baseURL).toBe('https://api.aimlapi.com/v1');+ expect(options.headers?.['X-AIMLAPI-Partner-ID']).toMatch(/^part_[A-Za-z0-9]{1,64}$/);+ expect(options.headers?.['X-AIMLAPI-Source']).toBe('agent/mercury-agent');+ });++ it('hands no headers to any other provider served by the same class', () => {+ new OpenAICompatProvider(config('openaiCompat', 'https://api.openai.com/v1'), { useChatApi: true });++ const options = createOpenAI.mock.calls[0]![0];+ expect(options.headers).toBeUndefined();+ });+});diff --git a/src/providers/openai-compat.ts b/src/providers/openai-compat.tsindex 225a1c7f..876272ad 100644--- a/src/providers/openai-compat.ts+++ b/src/providers/openai-compat.ts@@ -4,6 +4,7 @@ import { BaseProvider } from './base.js';import type { ProviderConfig } from '../utils/config.js';import type { LLMResponse, LLMStreamChunk } from './base.js';import { logger } from '../utils/logger.js';+import { aimlapiHeaders } from './aimlapi-attribution.js';export class OpenAICompatProvider extends BaseProvider {readonly name: string;@@ -19,6 +20,9 @@ export class OpenAICompatProvider extends BaseProvider {this.client = createOpenAI({apiKey: config.apiKey || 'no-key',baseURL: config.baseUrl,+ // `undefined` for every host but AI/ML API's, so no other provider+ // reached through this class sends anything extra.+ headers: aimlapiHeaders(config.baseUrl),});this.modelInstance = useChatApi? this.client.chat(config.model)diff --git a/src/providers/registry.ts b/src/providers/registry.tsindex 047fa6d0..266f0b2e 100644--- a/src/providers/registry.ts+++ b/src/providers/registry.ts@@ -21,6 +21,11 @@ export async function createProvider(pc: ProviderConfig, tokenStore?: import('..// this entirely.const { OpenAICompatProvider } = await import('./openai-compat.js');return new OpenAICompatProvider(pc, { useChatApi: true });+ } else if (pc.name === 'aimlapi') {+ // OpenAI-compatible gateway. Chat Completions rather than Responses: the+ // catalogue is mostly third-party models reached through that surface.+ const { OpenAICompatProvider } = await import('./openai-compat.js');+ return new OpenAICompatProvider(pc, { useChatApi: true });} else if (pc.name === 'atlascloud' || pc.name === 'ollamaCloud' || pc.name === 'openaiCompat') {const { OpenAICompatProvider } = await import('./openai-compat.js');return new OpenAICompatProvider(pc, { useChatApi: true });@@ -57,6 +62,10 @@ export class ProviderRegistry {apiKey: config.providers.mercuryCloud.apiKey || config.cloud.jwt,baseUrl: config.cloud.apiUrl || config.providers.mercuryCloud.baseUrl,},+ // Registered after mercuryCloud on purpose. This array is the fallback+ // order, and moving a first-party hosted provider off the front of it is+ // a behaviour change for existing installs rather than a listing choice.+ config.providers.aimlapi,config.providers.deepseek,config.providers.openai,config.providers.anthropic,diff --git a/src/utils/config.ts b/src/utils/config.tsindex 6ad7a20a..3a4540a4 100644--- a/src/utils/config.ts+++ b/src/utils/config.ts@@ -56,6 +56,7 @@ export interface TelegramPendingRequest {export type ProviderName =| 'mercuryCloud'+ | 'aimlapi'| 'openai'| 'anthropic'| 'deepseek'@@ -90,6 +91,7 @@ export interface MercuryConfig {cloud: CloudConfig;providers: {default: ProviderName;+ aimlapi: ProviderConfig;mercuryCloud: ProviderConfig;openai: ProviderConfig;anthropic: ProviderConfig;@@ -249,6 +251,13 @@ export function getDefaultConfig(): MercuryConfig {},providers: {default: getEnv('DEFAULT_PROVIDER', 'deepseek') as ProviderName,+ aimlapi: {+ name: 'aimlapi',+ apiKey: getEnv('AIMLAPI_API_KEY', ''),+ baseUrl: getEnv('AIMLAPI_BASE_URL', 'https://api.aimlapi.com/v1'),+ model: getEnv('AIMLAPI_MODEL', 'anthropic/claude-sonnet-4.6'),+ enabled: getEnvBool('AIMLAPI_ENABLED', true),+ },mercuryCloud: {name: 'mercuryCloud',apiKey: '',diff --git a/src/utils/provider-models.aimlapi.test.ts b/src/utils/provider-models.aimlapi.test.tsnew file mode 100644index 00000000..84655a7c--- /dev/null+++ b/src/utils/provider-models.aimlapi.test.ts@@ -0,0 +1,56 @@+import { describe, it, expect, vi, afterEach } from 'vitest';+import { fetchProviderModelCatalog } from './provider-models.js';+import type { ProviderConfig } from './config.js';++const config: ProviderConfig = {+ name: 'aimlapi',+ apiKey: 'k',+ baseUrl: 'https://api.aimlapi.com/v1',+ model: 'anthropic/claude-sonnet-4.6',+ enabled: true,+};++// Shaped like the real listing: one row per surface, ids repeated across them,+// and not a single id that looks like an OpenAI model name.+const payload = {+ data: [+ { id: 'anthropic/claude-sonnet-4.6', type: 'openai/chat-completions' },+ { id: 'anthropic/claude-sonnet-4.6', type: 'anthropic/batches' },+ { id: 'anthropic/claude-sonnet-4.6', type: 'anthropic/messages' },+ { id: 'deepseek/deepseek-chat', type: 'openai/chat-completions' },+ { id: 'google/veo-3', type: 'internal/video-generations/submit' },+ { id: 'openai/dall-e-3', type: 'openai/image-generations' },+ { id: 'elevenlabs/tts', type: 'internal/text-to-speech' },+ ],+};++afterEach(() => vi.unstubAllGlobals());++describe('AI/ML API model discovery', () => {+ it('keeps the chat surface, collapses the repeats, drops the rest', async () => {+ vi.stubGlobal('fetch', vi.fn(async () => new Response(JSON.stringify(payload), {+ status: 200, headers: { 'content-type': 'application/json' },+ })));++ const catalog = await fetchProviderModelCatalog('aimlapi', config);+ const all = [catalog.recommendedModel, ...catalog.models];++ expect(all).toContain('anthropic/claude-sonnet-4.6');+ expect(all).toContain('deepseek/deepseek-chat');+ expect(all).toHaveLength(2);+ expect(all).not.toContain('google/veo-3');+ expect(all).not.toContain('openai/dall-e-3');+ });++ it('does not fall back to the id-text rule, which empties this catalogue', async () => {+ // The bug this replaces: the default filter accepts `gpt-*` and `o<digit>`+ // only, so every namespaced id was dropped and the UI reported "could not+ // find any supported chat models" against a listing that had 353 of them.+ vi.stubGlobal('fetch', vi.fn(async () => new Response(JSON.stringify({+ data: [{ id: 'alibaba/qwen3.8-max', type: 'openai/chat-completions' }],+ }), { status: 200, headers: { 'content-type': 'application/json' } })));++ const catalog = await fetchProviderModelCatalog('aimlapi', config);+ expect([catalog.recommendedModel, ...catalog.models]).toContain('alibaba/qwen3.8-max');+ });+});diff --git a/src/utils/provider-models.ts b/src/utils/provider-models.tsindex b9f23d18..cc30df55 100644--- a/src/utils/provider-models.ts+++ b/src/utils/provider-models.ts@@ -10,6 +10,16 @@ export interface ProviderModelCatalog {const MAX_MODEL_OPTIONS = 50;+// Verified present in the AI/ML API catalogue on 2026-09-10. The ids are+// namespaced by lab there, so they do not collide with the bare ids other+// providers in this file use.+const AIMLAPI_PREFERRED_MODELS = [+ 'anthropic/claude-sonnet-4.6',+ 'openai/gpt-5.2-chat-latest',+ 'deepseek/deepseek-chat',+ 'openai/gpt-4o-mini',+] as const;+const OPENAI_PREFERRED_MODELS = ['gpt-5.2','gpt-5.2-chat-latest',@@ -117,6 +127,7 @@ export class ProviderModelFetchError extends Error {export function getPreferredModelsForProvider(provider: ProviderName): string[] {const preferredByProvider: Record<ProviderName, readonly string[]> = {mercuryCloud: MERCURY_CLOUD_PREFERRED_MODELS,+ aimlapi: AIMLAPI_PREFERRED_MODELS,deepseek: DEEPSEEK_PREFERRED_MODELS,openai: OPENAI_PREFERRED_MODELS,anthropic: ANTHROPIC_PREFERRED_MODELS,@@ -135,9 +146,22 @@ export function getPreferredModelsForProvider(provider: ProviderName): string[]}interface OpenAIModelResponse {- data?: Array<{ id?: string; output_modalities?: string[] }>;+ data?: Array<{ id?: string; output_modalities?: string[]; type?: string }>;}+/**+ * AI/ML API lists every surface it serves — chat, images, video, speech,+ * batches — as separate rows, and the same model id appears once per surface.+ * `type` names the surface, so the chat set is the rows that carry the+ * OpenAI-compatible one; `uniq` in `buildModelCatalog` collapses the repeats.+ *+ * Filtering by id text the way `isOpenAIChatModel` does cannot work here: ids+ * are namespaced by lab (`anthropic/claude-sonnet-4.6`, `deepseek/...`), so a+ * `gpt-`/`o<digit>` rule discards all 353 chat models and the catalogue comes+ * back empty.+ */+const AIMLAPI_CHAT_SURFACE = 'openai/chat-completions';+interface AnthropicModelResponse {data?: Array<{ id?: string }>;}@@ -225,6 +249,7 @@ function chooseRecommendedModel(): string {const preferredByProvider: Record<ProviderName, readonly string[]> = {mercuryCloud: MERCURY_CLOUD_PREFERRED_MODELS,+ aimlapi: AIMLAPI_PREFERRED_MODELS,deepseek: DEEPSEEK_PREFERRED_MODELS,openai: OPENAI_PREFERRED_MODELS,anthropic: ANTHROPIC_PREFERRED_MODELS,@@ -265,6 +290,7 @@ export function buildModelCatalog(const recommendedModel = chooseRecommendedModel(provider, filtered, currentModel);const preferredByProvider: Record<ProviderName, readonly string[]> = {mercuryCloud: MERCURY_CLOUD_PREFERRED_MODELS,+ aimlapi: AIMLAPI_PREFERRED_MODELS,deepseek: DEEPSEEK_PREFERRED_MODELS,openai: OPENAI_PREFERRED_MODELS,anthropic: ANTHROPIC_PREFERRED_MODELS,@@ -301,6 +327,8 @@ async function fetchOpenAICompatModels(provider: ProviderName, config: ProviderCerrorMessage = 'Mercury could not fetch models for this Atlas Cloud key. Please re-enter it.';} else if (provider === 'deepseek') {errorMessage = 'Mercury could not fetch models for this DeepSeek key. Please re-enter it.';+ } else if (provider === 'aimlapi') {+ errorMessage = 'Mercury could not fetch models for this AI/ML API key. Please re-enter it.';} else if (provider === 'openaiCompat') {errorMessage = 'Mercury could not fetch models from this server. Please check the base URL and try again.';} else {@@ -317,8 +345,12 @@ async function fetchOpenAICompatModels(provider: ProviderName, config: ProviderC.map((model) => ({id: model.id?.trim() ?? '',outputModalities: model.output_modalities,+ surface: model.type,}))- .filter(({ id, outputModalities }) => {+ .filter(({ id, outputModalities, surface }) => {+ if (provider === 'aimlapi') {+ return id.length > 0 && surface === AIMLAPI_CHAT_SURFACE;+ }if (provider === 'deepseek') {return id.startsWith('deepseek-');}diff --git a/src/web/api/providers.ts b/src/web/api/providers.tsindex e139d707..3bb52dbb 100644--- a/src/web/api/providers.ts+++ b/src/web/api/providers.ts@@ -6,6 +6,12 @@ function maskApiKey(key: string): string {return key.slice(0, 4) + '••••' + key.slice(-4);}+/**+ * Surfaced as a badge in the UI. One name rather than a list, so the claim+ * stays reviewable and reverting it is a one-line change.+ */+const RECOMMENDED_PROVIDER = 'aimlapi';+const providers = new Hono();providers.get('/api/providers', (c) => {@@ -17,6 +23,7 @@ providers.get('/api/providers', (c) => {baseUrl: p.baseUrl,model: p.model,enabled: p.enabled,+ recommended: name === RECOMMENDED_PROVIDER,}));return c.json(list);});@@ -26,7 +33,7 @@ providers.post('/api/providers/:name', async (c) => {const body = await c.req.json();const config = loadConfig();- const validNames: ProviderName[] = ['mercuryCloud', 'openai', 'anthropic', 'deepseek', 'grok', 'atlascloud', 'ollamaCloud', 'ollamaLocal', 'openaiCompat', 'mimo', 'mimoTokenPlan'];+ const validNames: ProviderName[] = ['aimlapi', 'mercuryCloud', 'openai', 'anthropic', 'deepseek', 'grok', 'atlascloud', 'ollamaCloud', 'ollamaLocal', 'openaiCompat', 'mimo', 'mimoTokenPlan'];if (!validNames.includes(providerName)) {return c.json({ error: 'Unknown provider' }, 400);}diff --git a/ui/src/lib/api.ts b/ui/src/lib/api.tsindex 12301212..e91db3fa 100644--- a/ui/src/lib/api.ts+++ b/ui/src/lib/api.ts@@ -433,6 +433,7 @@ export interface AppConfig {export interface ProviderInfo {name: string;+ recommended?: boolean;maskedKey: string;baseUrl: string;model: string;diff --git a/ui/src/pages/Providers.tsx b/ui/src/pages/Providers.tsxindex 5e02aa20..d507a11d 100644--- a/ui/src/pages/Providers.tsx+++ b/ui/src/pages/Providers.tsx@@ -254,6 +254,14 @@ export function ProvidersPage() {>{f.enabled ? "Active" : "Disabled"}</Badge>+ {provider.recommended && (+ <Badge+ variant="secondary"+ className="text-[10px] px-1.5 py-0 bg-[#0ea5e9]/15 text-[#0ea5e9] border-[#0ea5e9]/30"+ >+ Recommended+ </Badge>+ )}</div></div><Switchdiff --git a/ui/src/pages/Usage.tsx b/ui/src/pages/Usage.tsxindex d3befc4d..7c70de85 100644--- a/ui/src/pages/Usage.tsx+++ b/ui/src/pages/Usage.tsx@@ -38,6 +38,7 @@ const PROVIDER_COLORS: Record<string, string> = {google: "#3b82f6",groq: "#ef4444",ollama: "#8b5cf6",+ aimlapi: "#0ea5e9",openrouter: "#ec4899",};