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(mcp): #2042 β€” agent_execute routes through v3 provider system (Anthropic / OpenRouter / Ollama)

ruv94b98c90cd7d
diff --git a/.github/workflows/v3-ci.yml b/.github/workflows/v3-ci.yml
index 0ce0fa2901..3ef20ca630 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,32 @@ 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: Install root deps
+ run: npm install --legacy-peer-deps --no-audit --no-fund --ignore-scripts
+
+ - name: Build CLI (smoke uses the dist artifact)
+ run: cd v3/@claude-flow/cli && npm install --legacy-peer-deps --no-audit --no-fund --ignore-scripts && npm run build
+
+ - 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..70358adeb4
--- /dev/null
+++ b/scripts/smoke-agent-execute-providers.mjs
@@ -0,0 +1,97 @@
+#!/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');
+const DIST = resolve(__dirname, '../v3/@claude-flow/cli/dist/src/mcp-tools/agent-execute-core.js');
+
+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. Behavioral check via the built artifact: OPENROUTER_API_KEY routes
+// to the openrouter branch (any error returned must come from
+// callOpenAICompat, not the Anthropic fetch).
+try {
+ // Clear env to avoid network calls leaking other providers.
+ process.env.ANTHROPIC_API_KEY = '';
+ process.env.OPENROUTER_API_KEY = 'sk-or-test-not-real';
+ process.env.OLLAMA_API_KEY = '';
+ delete process.env.RUFLO_PROVIDER;
+ const mod = await import(DIST);
+ const res = await mod.callAnthropicMessages({ prompt: 'ping', model: 'sonnet' });
+ if (res.success) {
+ fail('Unexpected success in behavioral smoke (env should not authenticate)');
+ } else if (/Anthropic API error/i.test(res.error || '')) {
+ fail('OPENROUTER_API_KEY set but error names Anthropic β€” router did not dispatch');
+ } else if (/openrouter/i.test(res.error || '') || /HTTP-Referer|api\.openrouter/i.test(res.error || '') || /401|authentication/i.test(res.error || '')) {
+ pass('OPENROUTER_API_KEY routes to openrouter dispatch (auth error from openrouter, not anthropic)');
+ } else {
+ pass(`OPENROUTER_API_KEY routes to non-anthropic path (error: ${(res.error || '').slice(0, 80)})`);
+ }
+} catch (err) {
+ fail(`behavioral smoke threw: ${err.message}`);
+}
+
+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<AnthropicCallResult> {
+ 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(() => '<unreadable error body>');
+ 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<AgentExecuteResult> {
- 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<AgentE
const startedAt = Date.now();
- try {
- const controller = new AbortController();
- const timeoutMs = input.timeoutMs || 60000;
- const timer = setTimeout(() => controller.abort(), 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(() => '<unreadable error body>');
- 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('');
+ // #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 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<string, unknown>;
+ agent.lastResult = out as unknown as Record<string, unknown>;
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.',
+ }),
+ };
}
+