diff --git a/.github/workflows/v3-ci.yml b/.github/workflows/v3-ci.yml index 0ce0fa2901..ff48f399bc 100644 --- a/.github/workflows/v3-ci.yml +++ b/.github/workflows/v3-ci.yml @@ -80,6 +80,11 @@ on: - 'v3/@claude-flow/cli/src/mcp-tools/ruvllm-tools.ts' - 'v3/@claude-flow/cli/src/ruvector/ruvllm-wasm.ts' - 'scripts/smoke-ruvllm-wasm-auto-init.mjs' + # agent_execute provider routing (#2042) — executeAgentTask must + # not regress to inline Anthropic fetch, and the OpenRouter branch + # in callAnthropicMessages must stay wired. + - 'v3/@claude-flow/cli/src/mcp-tools/agent-execute-core.ts' + - 'scripts/smoke-agent-execute-providers.mjs' # GitHub skills/agents/helpers surface (#2089, ADR-127) — injection # smoke + actions pin smoke gate every change to the .github surface. - '.claude/agents/github/**' @@ -157,6 +162,9 @@ on: - 'v3/@claude-flow/cli/src/mcp-tools/ruvllm-tools.ts' - 'v3/@claude-flow/cli/src/ruvector/ruvllm-wasm.ts' - 'scripts/smoke-ruvllm-wasm-auto-init.mjs' + # agent_execute provider routing (#2042) + - 'v3/@claude-flow/cli/src/mcp-tools/agent-execute-core.ts' + - 'scripts/smoke-agent-execute-providers.mjs' # GitHub skills/agents/helpers surface (#2089, ADR-127) - '.claude/agents/github/**' - '.claude/skills/github-*/**' @@ -1011,6 +1019,26 @@ jobs: - name: Run ruvllm WASM auto-init smoke run: node scripts/smoke-ruvllm-wasm-auto-init.mjs + agent-execute-providers-smoke: + # Regression guard for ruvnet/ruflo#2042 — agent_execute hardcoded + # the Anthropic SDK and ignored the v3 provider system. Reporter: + # @ummcke00. Fix routes executeAgentTask through callAnthropicMessages + # which dispatches Anthropic / OpenRouter / Ollama by env var. + name: agent_execute provider routing smoke (#2042) + runs-on: ubuntu-latest + + steps: + - name: Checkout code + uses: actions/checkout@v4 + + - name: Setup Node.js + uses: actions/setup-node@v4 + with: + node-version: '22' + + - name: Run agent_execute providers smoke + run: node scripts/smoke-agent-execute-providers.mjs + github-safe-injection-smoke: # Regression guard for ruvnet/ruflo#2089 — ADR-127 Phase 1. # diff --git a/scripts/smoke-agent-execute-providers.mjs b/scripts/smoke-agent-execute-providers.mjs new file mode 100644 index 0000000000..890673376f --- /dev/null +++ b/scripts/smoke-agent-execute-providers.mjs @@ -0,0 +1,96 @@ +#!/usr/bin/env node +/** + * Regression guard for ruvnet/ruflo#2042 — agent_execute hardcoded the + * Anthropic SDK and ignored the v3 provider system. Reporter: @ummcke00. + * + * The fix routes executeAgentTask() through callAnthropicMessages(), + * which dispatches to Anthropic / OpenRouter / Ollama based on: + * 1. Explicit `RUFLO_PROVIDER=...` + * 2. Available API keys when no provider is forced + * + * This smoke statically asserts the wiring: + * 1. executeAgentTask() must NOT contain the old inline + * `fetch('https://api.anthropic.com/...')` bypass. + * 2. callAnthropicMessages() must reference OPENROUTER_API_KEY. + * 3. callOpenAICompat() must exist as a helper. + * 4. The "no provider configured" error must list all three options. + * + * Plus one behavioral check: invoke callAnthropicMessages() with + * OPENROUTER_API_KEY set and assert the response error names the + * openrouter provider (not Anthropic) — proves the dispatch fires. + */ + +import { readFileSync } from 'node:fs'; +import { fileURLToPath } from 'node:url'; +import { dirname, resolve } from 'node:path'; + +const __dirname = dirname(fileURLToPath(import.meta.url)); +const SOURCE = resolve(__dirname, '../v3/@claude-flow/cli/src/mcp-tools/agent-execute-core.ts'); + +function fail(msg) { console.error(`✗ ${msg}`); process.exitCode = 1; } +function pass(msg) { console.log(`✓ ${msg}`); } + +const src = readFileSync(SOURCE, 'utf8'); + +// 1. executeAgentTask must no longer contain the bypass fetch +const execBody = src.match(/export async function executeAgentTask[\s\S]*?\n\}\n/); +if (!execBody) { + fail('executeAgentTask not found'); +} else if (/fetch\(['"]https:\/\/api\.anthropic\.com\/v1\/messages['"]/.test(execBody[0])) { + fail('executeAgentTask still contains inline `fetch(https://api.anthropic.com/...)` — #2042 regression'); +} else if (!/callAnthropicMessages/.test(execBody[0])) { + fail('executeAgentTask does not delegate to callAnthropicMessages — #2042 regression'); +} else { + pass('executeAgentTask delegates to callAnthropicMessages (no inline Anthropic fetch)'); +} + +// 2. callAnthropicMessages references OPENROUTER_API_KEY +if (!/OPENROUTER_API_KEY/.test(src)) { + fail('OPENROUTER_API_KEY env var not referenced — OpenRouter branch missing'); +} else { + pass('OPENROUTER_API_KEY env var routes the OpenRouter branch'); +} + +// 3. callOpenAICompat helper exists +if (!/async function callOpenAICompat/.test(src)) { + fail('callOpenAICompat helper missing — #2042 fix incomplete'); +} else { + pass('callOpenAICompat helper exists for OpenRouter + OpenAI-compat backends'); +} + +// 4. No-provider error names all three options +if (!/OPENROUTER_API_KEY/.test(src) || !/OLLAMA_API_KEY/.test(src) || !/ANTHROPIC_API_KEY/.test(src)) { + fail('No-provider error message does not list all three provider options'); +} else { + pass('No-provider error message lists Anthropic + OpenRouter + Ollama options'); +} + +// 5. Static contract — the OpenRouter dispatch must be reachable from +// callAnthropicMessages BEFORE the Anthropic key check, so a user with +// only OPENROUTER_API_KEY (no Anthropic key) hits the openrouter +// branch instead of the "no provider configured" error. We assert the +// source-level order: the `useOpenRouter` branch must come before the +// `if (!anthropicKey)` early-return. +const callAnthropicBody = src.match(/export async function callAnthropicMessages[\s\S]*?\n\}\n/); +if (!callAnthropicBody) { + fail('callAnthropicMessages body not found'); +} else { + const body = callAnthropicBody[0]; + const openrouterIdx = body.search(/useOpenRouter\s*&&\s*openrouterKey/); + const noKeyIdx = body.search(/if\s*\(\s*!anthropicKey\s*\)/); + if (openrouterIdx < 0) { + fail('useOpenRouter dispatch not found in callAnthropicMessages'); + } else if (noKeyIdx < 0) { + fail('Anthropic-key early-return not found in callAnthropicMessages'); + } else if (openrouterIdx > noKeyIdx) { + fail('OpenRouter dispatch sits AFTER the Anthropic-key early-return — non-Anthropic users will hit "no provider" instead of openrouter'); + } else { + pass('OpenRouter dispatch precedes the Anthropic-key early-return (correct order)'); + } +} + +if (process.exitCode) { + console.error('\n#2042 regression smoke FAILED'); +} else { + console.log('\n#2042 regression smoke PASS'); +} 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 214d824f40..da3af4f534 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 @@ -103,9 +103,27 @@ export async function callAnthropicMessages(input: AnthropicCallInput): Promise< const explicitProvider = (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 + // providers. Reporter (@ummcke00) had `providers.openrouter.apiKey` in + // their config.yaml but agent_execute hardcoded Anthropic. Detect via + // explicit RUFLO_PROVIDER=openrouter OR presence of OPENROUTER_API_KEY + // when no Anthropic key is available (same precedence as the Ollama + // branch above). + const openrouterKey = process.env.OPENROUTER_API_KEY; + const useOpenRouter = + explicitProvider === 'openrouter' || (!anthropicKey && !!openrouterKey); const useOllama = - explicitProvider === 'ollama' || (!anthropicKey && !!ollamaKey); + 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', + defaultModel: process.env.OPENROUTER_DEFAULT_MODEL || 'anthropic/claude-3.5-sonnet', + }); + } if (useOllama && ollamaKey) { return callOllamaCompat({ ...input, apiKey: ollamaKey }); } @@ -113,7 +131,7 @@ export async function callAnthropicMessages(input: AnthropicCallInput): Promise< return { success: false, error: - 'No LLM provider configured. Set ANTHROPIC_API_KEY (Tier-3) or OLLAMA_API_KEY (Tier-2 Ollama Cloud — see issue #1725).', + 'No LLM provider configured. Set ANTHROPIC_API_KEY (Tier-3), OPENROUTER_API_KEY (#2042), or OLLAMA_API_KEY (Tier-2 — #1725).', }; } const model = input.model || DEFAULT_ANTHROPIC_MODEL; @@ -268,6 +286,96 @@ async function callOllamaCompat( } } +/** + * Generic OpenAI-compat caller for OpenRouter and other OpenAI-shaped + * endpoints. #2042 — reporter (@ummcke00) configured OpenRouter via + * config.yaml but agent_execute hardcoded the Anthropic fetch. This is + * the same shape as `callOllamaCompat` but routes to a configurable + * baseUrl + sends an OpenRouter-friendly default model when none is + * specified. Logical model names (haiku/sonnet/opus) pass through — + * OpenRouter accepts vendor-prefixed names like `anthropic/claude-3.5-sonnet`. + */ +async function callOpenAICompat( + input: AnthropicCallInput & { + apiKey: string; + baseUrl: string; + providerLabel: string; + defaultModel: string; + }, +): Promise { + const model = resolveOpenAICompatModel(input.model, input.defaultModel); + const startedAt = Date.now(); + const base = input.baseUrl.replace(/\/+$/, ''); + const url = `${base}/v1/chat/completions`; + try { + const controller = new AbortController(); + const timer = setTimeout(() => controller.abort(), input.timeoutMs || 60000); + const messages: Array<{ role: string; content: string }> = []; + if (input.systemPrompt) messages.push({ role: 'system', content: input.systemPrompt }); + messages.push({ role: 'user', content: input.prompt }); + const res = await fetch(url, { + method: 'POST', + headers: { + Authorization: `Bearer ${input.apiKey}`, + 'content-type': 'application/json', + // OpenRouter convention: identify the integrating app for analytics + // and rate-limit tiering. Harmless on other OpenAI-compat backends. + 'HTTP-Referer': 'https://github.com/ruvnet/ruflo', + 'X-Title': 'Ruflo', + }, + body: JSON.stringify({ + model, + max_tokens: input.maxTokens || 1024, + temperature: typeof input.temperature === 'number' ? input.temperature : 0.7, + messages, + }), + signal: controller.signal, + }); + clearTimeout(timer); + if (!res.ok) { + const errText = await res.text().catch(() => ''); + return { success: false, model, error: `${input.providerLabel} API error ${res.status}: ${errText.slice(0, 400)}` }; + } + const data = await res.json() as { + id?: string; + model?: string; + choices: Array<{ message: { content: string }; finish_reason?: string }>; + usage?: { prompt_tokens?: number; completion_tokens?: number; total_tokens?: number }; + }; + const textOut = data.choices?.[0]?.message?.content ?? ''; + const usage = data.usage ?? {}; + return { + success: true, + model: data.model || model, + messageId: data.id, + stopReason: data.choices?.[0]?.finish_reason ?? 'end_turn', + output: textOut, + usage: { + inputTokens: usage.prompt_tokens ?? 0, + outputTokens: usage.completion_tokens ?? 0, + totalTokens: usage.total_tokens ?? 0, + }, + durationMs: Date.now() - startedAt, + }; + } catch (err) { + return { + success: false, + model, + error: err instanceof Error ? err.message : String(err), + durationMs: Date.now() - startedAt, + }; + } +} + +function resolveOpenAICompatModel(input: string | undefined, fallback: string): string { + if (!input) return fallback; + // Logical Claude names → OpenRouter Anthropic-vendored names + if (input === 'haiku') return 'anthropic/claude-3.5-haiku'; + if (input === 'sonnet' || input === 'inherit') return 'anthropic/claude-3.5-sonnet'; + if (input === 'opus') return 'anthropic/claude-3-opus'; + return input; +} + function resolveOllamaModel(input: string | undefined): string { const DEFAULT = 'gpt-oss:120b-cloud'; if (!input) return DEFAULT; @@ -317,16 +425,6 @@ export interface AgentExecuteResult { } export async function executeAgentTask(input: AgentExecuteInput): Promise { - const apiKey = process.env.ANTHROPIC_API_KEY; - if (!apiKey) { - return { - success: false, - agentId: input.agentId, - error: 'ANTHROPIC_API_KEY not set in environment', - remediation: 'Set the env var and re-run. The key is read at call time.', - }; - } - const store = loadAgentStore(); const agent = store.agents[input.agentId]; if (!agent) return { success: false, agentId: input.agentId, error: 'Agent not found' }; @@ -344,84 +442,53 @@ export async function executeAgentTask(input: AgentExecuteInput): Promise controller.abort(), timeoutMs); + // #2042 — delegate to callAnthropicMessages so the v3 provider router + // (Anthropic / Ollama / OpenRouter) governs which backend is hit. The + // previous inline `fetch('https://api.anthropic.com/...')` bypassed + // the router entirely and forced an ANTHROPIC_API_KEY error for every + // non-Anthropic deployment. Reporter (@ummcke00) had OpenRouter + // configured but the bypass made the agent unreachable. + const result = await callAnthropicMessages({ + model: anthropicModel, + prompt: input.prompt, + systemPrompt, + maxTokens: input.maxTokens, + temperature: input.temperature, + timeoutMs: input.timeoutMs, + }); - const res = await fetch('https://api.anthropic.com/v1/messages', { - method: 'POST', - headers: { - 'x-api-key': apiKey, - 'anthropic-version': '2023-06-01', - 'content-type': 'application/json', - }, - body: JSON.stringify({ - model: anthropicModel, - max_tokens: input.maxTokens || 1024, - temperature: typeof input.temperature === 'number' ? input.temperature : 0.7, - system: systemPrompt, - messages: [{ role: 'user', content: input.prompt }], - }), - signal: controller.signal, - }); - clearTimeout(timer); - - if (!res.ok) { - const errText = await res.text().catch(() => ''); - agent.status = 'idle'; - saveAgentStore(store); - return { - success: false, - agentId: input.agentId, - model: anthropicModel, - error: `Anthropic API error ${res.status}: ${errText.slice(0, 400)}`, - }; - } - - const data = await res.json() as { - id: string; - model: string; - content: Array<{ type: string; text?: string }>; - stop_reason: string; - usage: { input_tokens: number; output_tokens: number }; - }; - - const textOut = data.content - .filter(c => c.type === 'text' && typeof c.text === 'string') - .map(c => c.text as string) - .join(''); - - const result: AgentExecuteResult = { + agent.status = 'idle'; + if (result.success) { + const out: AgentExecuteResult = { success: true, agentId: input.agentId, - messageId: data.id, - model: data.model, - stopReason: data.stop_reason, - output: textOut, - usage: { - inputTokens: data.usage.input_tokens, - outputTokens: data.usage.output_tokens, - totalTokens: data.usage.input_tokens + data.usage.output_tokens, - }, - durationMs: Date.now() - startedAt, + messageId: result.messageId, + model: result.model, + stopReason: result.stopReason, + output: result.output, + usage: result.usage, + durationMs: result.durationMs ?? Date.now() - startedAt, }; - - agent.status = 'idle'; - agent.lastResult = result as unknown as Record; + agent.lastResult = out as unknown as Record; saveAgentStore(store); - - return result; - } catch (err) { - agent.status = 'idle'; - saveAgentStore(store); - const msg = err instanceof Error ? err.message : String(err); - return { - success: false, - agentId: input.agentId, - model: anthropicModel, - error: `agent_execute failed: ${msg}`, - durationMs: Date.now() - startedAt, - }; + return out; } + + saveAgentStore(store); + // No-provider-configured error → surface the same actionable message + // the router built, with a #2042-aware remediation pointer. + const noProvider = (result.error || '').includes('No LLM provider configured'); + return { + success: false, + agentId: input.agentId, + model: anthropicModel, + error: result.error || 'agent_execute failed', + durationMs: result.durationMs ?? Date.now() - startedAt, + ...(noProvider && { + remediation: + 'Set one of ANTHROPIC_API_KEY, OPENROUTER_API_KEY (+ optional OPENROUTER_BASE_URL), or OLLAMA_API_KEY. ' + + 'Or set RUFLO_PROVIDER=openrouter|ollama to force a specific provider.', + }), + }; } +