Skip to content

armgit / ruflo

Public Imported from GitHub
0

🌊 The original agent harness. Deploy intelligent multi-player swarms, coordinate autonomous workflows, and build conversational AI systems. Features adaptive memory, self-learning intelligence, federation, vector RAG integration, and native Claude Code / Codex / Hermes and many more Integrated

fix(agent): propagate explicit provider/model config into agent execution (#2962) (#3007)

rUv1e24bb8878f2
diff --git a/scripts/smoke-agent-execute-providers.mjs b/scripts/smoke-agent-execute-providers.mjs
index 890673376f..7dfcc64b53 100644
--- a/scripts/smoke-agent-execute-providers.mjs
+++ b/scripts/smoke-agent-execute-providers.mjs
@@ -76,7 +76,13 @@ if (!callAnthropicBody) {
fail('callAnthropicMessages body not found');
} else {
const body = callAnthropicBody[0];
- const openrouterIdx = body.search(/useOpenRouter\s*&&\s*openrouterKey/);
+ // #2962 β€” the OpenRouter branch condition widened from
+ // `useOpenRouter && openrouterKey` to `if (useOpenRouter) { const apiKey =
+ // openrouterKey || persistedOpenRouter?.apiKey; if (apiKey) {...} }` so a
+ // persisted `agents.providers` config can supply the key when no env var
+ // is set. Match on the branch entry point rather than the literal old
+ // condition β€” the ordering guarantee this smoke checks is unchanged.
+ const openrouterIdx = body.search(/if\s*\(\s*useOpenRouter\s*\)/);
const noKeyIdx = body.search(/if\s*\(\s*!anthropicKey\s*\)/);
if (openrouterIdx < 0) {
fail('useOpenRouter dispatch not found in callAnthropicMessages');
diff --git a/v3/@claude-flow/cli/__tests__/agent-provider-model-propagation.test.ts b/v3/@claude-flow/cli/__tests__/agent-provider-model-propagation.test.ts
new file mode 100644
index 0000000000..1d748090e5
--- /dev/null
+++ b/v3/@claude-flow/cli/__tests__/agent-provider-model-propagation.test.ts
@@ -0,0 +1,182 @@
+/**
+ * Regression guard for ruvnet/ruflo#2962 β€” explicit provider/model selection
+ * (`providers configure`, `agent spawn --provider/--model`) did not
+ * propagate into actual agent execution. Backend/model selection at
+ * `agent_execute` time was driven solely by env vars, never by the
+ * persisted `agents.providers` config or the agent's own `config.provider`
+ * / `config.model`.
+ *
+ * Precedence implemented: explicit per-agent flag β†’ env vars β†’ persisted
+ * `agents.providers` config β†’ key-presence inference (unchanged, last
+ * resort).
+ */
+import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';
+import { mkdtempSync, writeFileSync, rmSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { agentTools } from '../src/mcp-tools/agent-tools.js';
+import { callAnthropicMessages, executeAgentTask } from '../src/mcp-tools/agent-execute-core.js';
+import { configManager } from '../src/services/config-file-manager.js';
+
+const tool = (name: string) => {
+ const t = agentTools.find(t => t.name === name);
+ if (!t) throw new Error(`MCP tool not registered: ${name}`);
+ return t;
+};
+
+const ENV_KEYS = [
+ 'ANTHROPIC_API_KEY',
+ 'OPENROUTER_API_KEY',
+ 'OLLAMA_API_KEY',
+ 'OLLAMA_BASE_URL',
+ 'RUFLO_PROVIDER',
+] as const;
+
+describe('#2962 β€” provider/model config propagates into agent execution', () => {
+ let dir: string;
+ let prevCwd: string | undefined;
+ let prevEnv: Record<string, string | undefined>;
+ let fetchSpy: ReturnType<typeof vi.spyOn>;
+
+ beforeEach(() => {
+ dir = mkdtempSync(join(tmpdir(), 'ruflo-2962-'));
+ prevCwd = process.env.CLAUDE_FLOW_CWD;
+ process.env.CLAUDE_FLOW_CWD = dir;
+
+ prevEnv = {};
+ for (const key of ENV_KEYS) {
+ prevEnv[key] = process.env[key];
+ delete process.env[key];
+ }
+
+ // configManager is a module-level singleton that caches its loaded
+ // config + resolved path across calls; reset its private state so each
+ // test's fresh tmp-dir config file is actually re-read from disk
+ // instead of reusing a previous test's cached config/path.
+ (configManager as unknown as { config: unknown }).config = null;
+ (configManager as unknown as { configPath: unknown }).configPath = null;
+ });
+
+ afterEach(() => {
+ if (prevCwd === undefined) delete process.env.CLAUDE_FLOW_CWD;
+ else process.env.CLAUDE_FLOW_CWD = prevCwd;
+ for (const key of ENV_KEYS) {
+ if (prevEnv[key] === undefined) delete process.env[key];
+ else process.env[key] = prevEnv[key];
+ }
+ (configManager as unknown as { config: unknown }).config = null;
+ (configManager as unknown as { configPath: unknown }).configPath = null;
+ rmSync(dir, { recursive: true, force: true });
+ fetchSpy?.mockRestore();
+ });
+
+ function writeConfig(agentsProviders: unknown[]): void {
+ writeFileSync(
+ join(dir, 'claude-flow.config.json'),
+ JSON.stringify({ agents: { providers: agentsProviders } }),
+ );
+ }
+
+ function mockOpenAICompatFetch() {
+ fetchSpy = vi.spyOn(globalThis, 'fetch').mockResolvedValue({
+ ok: true,
+ json: async () => ({
+ id: 'chatcmpl-test',
+ model: 'qwen3.6:27b',
+ choices: [{ message: { role: 'assistant', content: 'hi' }, finish_reason: 'stop' }],
+ usage: { prompt_tokens: 1, completion_tokens: 1, total_tokens: 2 },
+ }),
+ } as unknown as Response);
+ }
+
+ // (1) callAnthropicMessages() selects Ollama from the persisted config,
+ // not just env vars β€” no OLLAMA_API_KEY set, agents.providers has an
+ // enabled ollama entry with a self-hosted baseUrl β†’ the Ollama branch is
+ // taken with no Authorization header sent (no fake credential required).
+ it('callAnthropicMessages() dispatches to a self-hosted Ollama endpoint from persisted config alone', async () => {
+ writeConfig([
+ { name: 'ollama', enabled: true, baseUrl: 'http://127.0.0.1:11434', model: 'qwen3.6:27b' },
+ ]);
+ mockOpenAICompatFetch();
+
+ const result = await callAnthropicMessages({ prompt: 'say hi' });
+
+ expect(result.success).toBe(true);
+ expect(fetchSpy).toHaveBeenCalledTimes(1);
+ const [url, init] = fetchSpy.mock.calls[0] as [string, RequestInit];
+ expect(url).toBe('http://127.0.0.1:11434/v1/chat/completions');
+ // Self-hosted, unauthenticated endpoint: no Authorization header, no
+ // fake 'local' credential should have been required to reach it.
+ expect((init.headers as Record<string, string>).Authorization).toBeUndefined();
+ });
+
+ // (2) determineAgentModel() accepts an arbitrary non-Claude model string
+ // as an explicit selection (via the modelId fast-path), and that
+ // selection is NOT silently substituted for a default when re-read
+ // downstream by executeAgentTask β€” verified by inspecting the actual
+ // model sent on the wire, not just the stored record.
+ it('an arbitrary non-alias --model string survives spawn and reaches the dispatch call unchanged', async () => {
+ process.env.ANTHROPIC_API_KEY = 'sk-ant-test';
+ mockOpenAICompatFetch();
+ fetchSpy.mockResolvedValue({
+ ok: true,
+ json: async () => ({
+ id: 'msg-test',
+ model: 'qwen3.6:27b',
+ content: [{ type: 'text', text: 'hi' }],
+ stop_reason: 'end_turn',
+ usage: { input_tokens: 1, output_tokens: 1 },
+ }),
+ } as unknown as Response);
+
+ const spawnResult = (await tool('agent_spawn').handler({
+ agentType: 'researcher',
+ config: { model: 'qwen3.6:27b' },
+ })) as { agentId: string; model: string; modelRoutedBy: string; modelId?: string };
+
+ expect(spawnResult.modelRoutedBy).toBe('explicit');
+ expect(spawnResult.modelId).toBe('qwen3.6:27b');
+
+ await executeAgentTask({ agentId: spawnResult.agentId, prompt: 'say hi' });
+
+ expect(fetchSpy).toHaveBeenCalledTimes(1);
+ const [, init] = fetchSpy.mock.calls[0] as [string, RequestInit];
+ const body = JSON.parse(init.body as string);
+ // Before the fix: config.model fell through determineAgentModel's
+ // alias-only check, agent.modelId was never set, and this would be
+ // 'claude-sonnet-5' (the silently-substituted default).
+ expect(body.model).toBe('qwen3.6:27b');
+ });
+
+ // (3) Full round-trip with no environment variables set at all:
+ // providers configure (config-file write) β†’ agent spawn
+ // --provider ollama --model <tag> β†’ the resulting agent record's
+ // provider/modelId fields are populated β†’ executeAgentTask's dispatch
+ // call is constructed with that provider forwarded to a self-hosted
+ // endpoint.
+ it('round-trip: providers-configure + spawn --provider ollama --model reaches Ollama with zero env vars', async () => {
+ // Simulates `providers configure -p ollama -m qwen3.6:27b -e http://127.0.0.1:11434`
+ writeConfig([
+ { name: 'ollama', enabled: true, baseUrl: 'http://127.0.0.1:11434', model: 'qwen3.6:27b' },
+ ]);
+ mockOpenAICompatFetch();
+
+ // Simulates `agent spawn --type researcher --provider ollama --model qwen3.6:27b`
+ // (commands/agent.ts always sets config.provider β€” 'ollama' here is an
+ // unambiguous explicit choice, unlike the CLI's silent 'anthropic' default)
+ const spawnResult = (await tool('agent_spawn').handler({
+ agentType: 'researcher',
+ config: { provider: 'ollama', model: 'qwen3.6:27b' },
+ })) as { agentId: string; provider?: string; modelId?: string };
+
+ expect(spawnResult.provider).toBe('ollama');
+ expect(spawnResult.modelId).toBe('qwen3.6:27b');
+
+ const execResult = await executeAgentTask({ agentId: spawnResult.agentId, prompt: 'say hi' });
+
+ expect(execResult.success).toBe(true);
+ expect(fetchSpy).toHaveBeenCalledTimes(1);
+ const [url] = fetchSpy.mock.calls[0] as [string, RequestInit];
+ expect(url).toBe('http://127.0.0.1:11434/v1/chat/completions');
+ });
+});
diff --git a/v3/@claude-flow/cli/src/mcp-tools/agent-execute-core.ts b/v3/@claude-flow/cli/src/mcp-tools/agent-execute-core.ts
index c10af2ed89..f49a8dc4a5 100644
--- a/v3/@claude-flow/cli/src/mcp-tools/agent-execute-core.ts
+++ b/v3/@claude-flow/cli/src/mcp-tools/agent-execute-core.ts
@@ -11,6 +11,7 @@
import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';
import { join } from 'node:path';
import { getProjectCwd } from './types.js';
+import { configManager } from '../services/config-file-manager.js';
const STORAGE_DIR = '.claude-flow';
const AGENT_DIR = 'agents';
@@ -37,8 +38,8 @@ export interface AgentRecord {
* falling back to MODEL_MAP[tier].
*/
modelId?: string;
- /** ADR-148 phase 2 β€” execution provider hint. */
- provider?: 'anthropic' | 'openrouter';
+ /** ADR-148 phase 2 β€” execution provider hint. #2962 widened to include 'ollama'. */
+ provider?: 'anthropic' | 'openrouter' | 'ollama';
/** ADR-148 phase 2 β€” concrete OpenRouter slug when provider='openrouter'. */
openrouterModel?: string;
lastResult?: Record<string, unknown>;
@@ -100,6 +101,47 @@ export interface AnthropicCallInput {
maxTokens?: number;
temperature?: number;
timeoutMs?: number;
+ /**
+ * #2962 β€” explicit provider carried from the agent record (agent.provider,
+ * itself populated from a user's `--provider` flag or persisted
+ * `providers configure`). When set, this outranks the env-var-only
+ * inference callAnthropicMessages otherwise does β€” see the precedence
+ * comment on that function.
+ */
+ provider?: 'anthropic' | 'openrouter' | 'ollama';
+}
+
+/** A single entry from the persisted `agents.providers` config array. */
+interface PersistedProviderEntry {
+ name: string;
+ enabled?: boolean;
+ apiKey?: string;
+ baseUrl?: string;
+ model?: string;
+}
+
+/**
+ * #2962 β€” read the enabled `agents.providers` entry matching `name` from
+ * cwd-scoped `claude-flow.config.json` (written by `providers configure`,
+ * `commands/providers.ts`). Best-effort: any failure (no config file, wrong
+ * shape, etc.) returns undefined rather than throwing β€” this must never
+ * break execution, and env vars remain a fully-supported override that
+ * doesn't require this file to exist.
+ */
+function getPersistedProviderConfig(name: string): PersistedProviderEntry | undefined {
+ try {
+ const providers = configManager.get(getProjectCwd(), 'agents.providers');
+ if (!Array.isArray(providers)) return undefined;
+ const entry = providers.find(
+ (p): p is PersistedProviderEntry =>
+ !!p && typeof p === 'object' && typeof (p as PersistedProviderEntry).name === 'string' &&
+ (p as PersistedProviderEntry).name.toLowerCase() === name.toLowerCase(),
+ );
+ if (!entry || entry.enabled === false) return undefined;
+ return entry;
+ } catch {
+ return undefined;
+ }
}
export interface AnthropicCallResult {
@@ -125,7 +167,13 @@ export interface AnthropicCallResult {
* don't need to know which provider answered.
*/
export async function callAnthropicMessages(input: AnthropicCallInput): Promise<AnthropicCallResult> {
- const explicitProvider = (process.env.RUFLO_PROVIDER || '').toLowerCase();
+ // #2962 β€” precedence: explicit per-agent flag (input.provider, forwarded
+ // from agent.provider by executeAgentTask, itself populated from a
+ // user's `agent spawn --provider` flag) β†’ env vars (RUFLO_PROVIDER + the
+ // *_API_KEY family β€” unchanged back-compat surface) β†’ persisted
+ // `agents.providers` config (`providers configure`) β†’ the original
+ // key-presence inference, kept below as the last-resort fallback.
+ const explicitProvider = (input.provider || process.env.RUFLO_PROVIDER || '').toLowerCase();
const ollamaKey = process.env.OLLAMA_API_KEY;
const anthropicKey = process.env.ANTHROPIC_API_KEY;
// #2042 β€” OpenRouter is an OpenAI-compat endpoint that fronts dozens of
@@ -137,24 +185,51 @@ export async function callAnthropicMessages(input: AnthropicCallInput): Promise<
const openrouterKey = process.env.OPENROUTER_API_KEY;
const useOpenRouter =
explicitProvider === 'openrouter' || (!anthropicKey && !!openrouterKey);
+ // #2962 β€” only consult the persisted config when a candidate is actually
+ // relevant (explicit choice, or no env key found anywhere), so a normal
+ // ANTHROPIC_API_KEY-only setup never pays a config-file read.
+ const persistedOllama =
+ explicitProvider === 'ollama' || (!anthropicKey && !openrouterKey && !ollamaKey)
+ ? getPersistedProviderConfig('ollama')
+ : undefined;
+ const persistedOpenRouter =
+ explicitProvider === 'openrouter' && !openrouterKey ? getPersistedProviderConfig('openrouter') : undefined;
const useOllama =
- explicitProvider === 'ollama' || (!anthropicKey && !!ollamaKey && !openrouterKey);
-
- if (useOpenRouter && openrouterKey) {
- return callOpenAICompat({
- ...input,
- apiKey: openrouterKey,
- baseUrl: process.env.OPENROUTER_BASE_URL || 'https://openrouter.ai/api',
- providerLabel: 'openrouter',
- // #2357 Finding C: anthropic/claude-3.5-sonnet was retired Oct 2025.
- // Default to the same canonical family the rest of the resolver uses
- // (MODEL_MAP). `OPENROUTER_DEFAULT_MODEL` still wins for callers who
- // want to pin a specific OpenRouter slug.
- defaultModel: process.env.OPENROUTER_DEFAULT_MODEL || 'anthropic/claude-sonnet-4-6',
- });
+ explicitProvider === 'ollama' || (!anthropicKey && !openrouterKey && (!!ollamaKey || !!persistedOllama));
+
+ if (useOpenRouter) {
+ const apiKey = openrouterKey || persistedOpenRouter?.apiKey;
+ if (apiKey) {
+ return callOpenAICompat({
+ ...input,
+ apiKey,
+ baseUrl: process.env.OPENROUTER_BASE_URL || persistedOpenRouter?.baseUrl || 'https://openrouter.ai/api',
+ providerLabel: 'openrouter',
+ // #2357 Finding C: anthropic/claude-3.5-sonnet was retired Oct 2025.
+ // Default to the same canonical family the rest of the resolver uses
+ // (MODEL_MAP). `OPENROUTER_DEFAULT_MODEL` still wins for callers who
+ // want to pin a specific OpenRouter slug.
+ defaultModel: process.env.OPENROUTER_DEFAULT_MODEL || persistedOpenRouter?.model || 'anthropic/claude-sonnet-4-6',
+ });
+ }
}
- if (useOllama && ollamaKey) {
- return callOllamaCompat({ ...input, apiKey: ollamaKey });
+ if (useOllama) {
+ // #2962 β€” retire the undocumented OLLAMA_API_KEY=local sentinel
+ // requirement. A self-hosted, unauthenticated Ollama daemon shouldn't
+ // need a fake credential to become reachable; "self-hosted" is any
+ // resolved base URL that isn't the public Ollama Cloud endpoint
+ // (persisted `providers configure -e` baseUrl, or OLLAMA_BASE_URL,
+ // checked in that order β€” matching callOllamaCompat's own precedence).
+ const resolvedBaseUrl = process.env.OLLAMA_BASE_URL || persistedOllama?.baseUrl;
+ const isSelfHosted = !!resolvedBaseUrl && !/^https:\/\/ollama\.com\/?$/i.test(resolvedBaseUrl);
+ if (ollamaKey || persistedOllama?.apiKey || isSelfHosted) {
+ return callOllamaCompat({
+ ...input,
+ apiKey: ollamaKey || persistedOllama?.apiKey || 'local',
+ baseUrl: resolvedBaseUrl,
+ model: input.model || persistedOllama?.model,
+ });
+ }
}
if (!anthropicKey) {
return {
@@ -249,19 +324,22 @@ export async function callAnthropicMessages(input: AnthropicCallInput): Promise<
* - explicit 'ollama:<model>' or bare provider-native name β†’ passed through
*/
async function callOllamaCompat(
- input: AnthropicCallInput & { apiKey: string },
+ input: AnthropicCallInput & { apiKey: string; baseUrl?: string },
): Promise<AnthropicCallResult> {
const model = resolveOllamaModel(input.model);
const startedAt = Date.now();
- // OLLAMA_BASE_URL lets users point at local/self-hosted endpoints
- // (e.g. http://ruvultra:11434, http://localhost:11434) instead of
- // Ollama Cloud. Default is the public cloud endpoint.
- const base = (process.env.OLLAMA_BASE_URL || 'https://ollama.com').replace(/\/+$/, '');
+ // #2962 β€” input.baseUrl (resolved by the caller from persisted
+ // `providers configure` config, then OLLAMA_BASE_URL) takes precedence
+ // over re-reading OLLAMA_BASE_URL here, so a persisted-config-only setup
+ // (no env vars) still reaches a self-hosted endpoint instead of Ollama
+ // Cloud. Falls back to the original OLLAMA_BASE_URL-or-cloud behavior
+ // for any direct caller that doesn't pass baseUrl.
+ const base = (input.baseUrl || process.env.OLLAMA_BASE_URL || 'https://ollama.com').replace(/\/+$/, '');
const url = `${base}/v1/chat/completions`;
// Self-hosted endpoints typically don't need an Authorization header
// (the daemon binds to 11434 with no auth by default), but Ollama Cloud
// does. Send the bearer when the key is non-empty AND looks cloud-shaped.
- const sendAuth = input.apiKey && input.apiKey !== 'local';
+ const sendAuth = !!input.apiKey && input.apiKey !== 'local';
try {
const controller = new AbortController();
const timer = setTimeout(() => controller.abort(), input.timeoutMs || 60000);
@@ -521,6 +599,11 @@ export async function executeAgentTask(input: AgentExecuteInput): Promise<AgentE
// #2042 β€” delegate to callAnthropicMessages so the v3 provider router
// (Anthropic / Ollama / OpenRouter) governs which backend is hit.
+ // #2962 β€” forward the agent's own explicit provider (set at spawn time
+ // from --provider / persisted config) so it outranks env-var inference.
+ // Only the first-attempt call; the ADR-149 fallback-retry call below is
+ // driven by the cost-optimal neural router picking model-id alternatives,
+ // an orthogonal mechanism left as-is to avoid unintended interaction.
let result = await callAnthropicMessages({
model: anthropicModel,
prompt: input.prompt,
@@ -528,6 +611,7 @@ export async function executeAgentTask(input: AgentExecuteInput): Promise<AgentE
maxTokens: input.maxTokens,
temperature: input.temperature,
timeoutMs: input.timeoutMs,
+ provider: agent.provider,
});
// ADR-149 iter 7 β€” fallback chain on retryable failures (429, 5xx,
diff --git a/v3/@claude-flow/cli/src/mcp-tools/agent-tools.ts b/v3/@claude-flow/cli/src/mcp-tools/agent-tools.ts
index 47f791be3b..63e5538cf1 100644
--- a/v3/@claude-flow/cli/src/mcp-tools/agent-tools.ts
+++ b/v3/@claude-flow/cli/src/mcp-tools/agent-tools.ts
@@ -38,8 +38,8 @@ interface AgentRecord {
modelRoutedBy?: 'explicit' | 'router' | 'codemod' | 'default' | 'hybrid'; // ADR-026/143/149
/** ADR-149 β€” concrete picked model id (e.g. inclusionai/ling-2.6-flash). */
modelId?: string;
- /** ADR-148 β€” execution provider hint. */
- provider?: 'anthropic' | 'openrouter';
+ /** ADR-148 β€” execution provider hint. #2962 widened to include 'ollama'. */
+ provider?: 'anthropic' | 'openrouter' | 'ollama';
/** ADR-148 β€” concrete OpenRouter slug when provider='openrouter'. */
openrouterModel?: string;
lastResult?: Record<string, unknown>;
@@ -184,14 +184,25 @@ async function determineAgentModel(
tier?: 1 | 2 | 3;
/** ADR-149 β€” concrete picked model id when the neural backend fired. */
modelId?: string;
- /** ADR-148 β€” execution provider hint. */
- provider?: 'anthropic' | 'openrouter';
+ /** ADR-148 β€” execution provider hint. #2962 widened to include 'ollama'. */
+ provider?: 'anthropic' | 'openrouter' | 'ollama';
/** ADR-148 β€” concrete OpenRouter slug when provider='openrouter'. */
openrouterModel?: string;
}> {
// 1. Explicit model in config
- if (config.model && ['haiku', 'sonnet', 'opus', 'opus-4.7', 'inherit'].includes(config.model as string)) {
- return { model: config.model as ClaudeModel, routedBy: 'explicit' };
+ if (config.model) {
+ const explicitModel = config.model as string;
+ if (['haiku', 'sonnet', 'opus', 'opus-4.7', 'inherit'].includes(explicitModel)) {
+ return { model: explicitModel as ClaudeModel, routedBy: 'explicit' };
+ }
+ // #2962 β€” a non-alias model string (e.g. an Ollama tag like
+ // 'qwen3.6:27b', or any other provider-native model id) is still an
+ // explicit user selection. Route it through the modelId fast-path
+ // (executeAgentTask already prefers agent.modelId over
+ // MODEL_MAP[agent.model] β€” ADR-149 iter 13) instead of falling through
+ // to task-based routing / agent-type defaults, which silently
+ // substituted 'sonnet' and discarded the user's request.
+ return { model: 'sonnet', routedBy: 'explicit', modelId: explicitModel };
}
// 2. Enhanced task-based routing with deterministic Tier-1 codemods
@@ -327,6 +338,17 @@ export const agentTools: MCPTool[] = [
task
);
+ // #2962 β€” an explicit, unambiguous provider choice in config wins over
+ // the router's own pick. 'anthropic' is deliberately excluded: the CLI's
+ // `agent spawn` action always sets config.provider (defaulting to
+ // 'anthropic' when --provider isn't passed β€” commands/agent.ts), so
+ // 'anthropic' here is indistinguishable from that silent default.
+ // 'ollama'/'openrouter' are never silently defaulted and are unambiguous.
+ const explicitConfigProvider =
+ config.provider === 'ollama' || config.provider === 'openrouter'
+ ? (config.provider as 'ollama' | 'openrouter')
+ : undefined;
+
const agent: AgentRecord = {
agentId,
agentType,
@@ -339,7 +361,9 @@ export const agentTools: MCPTool[] = [
model: routingResult.model,
modelRoutedBy: routingResult.routedBy,
...(routingResult.modelId ? { modelId: routingResult.modelId } : {}),
- ...(routingResult.provider ? { provider: routingResult.provider } : {}),
+ ...(explicitConfigProvider
+ ? { provider: explicitConfigProvider }
+ : routingResult.provider ? { provider: routingResult.provider } : {}),
...(routingResult.openrouterModel ? { openrouterModel: routingResult.openrouterModel } : {}),
};
@@ -414,7 +438,11 @@ export const agentTools: MCPTool[] = [
model: agent.model,
modelRoutedBy: routingResult.routedBy,
...(routingResult.modelId ? { modelId: routingResult.modelId } : {}),
- ...(routingResult.provider ? { provider: routingResult.provider } : {}),
+ // #2962 β€” mirror the same precedence used for the stored agent
+ // record, so the response a caller sees matches what was actually
+ // persisted (previously this always reported the router's own
+ // pick, silently dropping an explicit config.provider override).
+ ...(agent.provider ? { provider: agent.provider } : {}),
...(routingResult.openrouterModel ? { openrouterModel: routingResult.openrouterModel } : {}),
status: 'registered',
createdAt: agent.createdAt,