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

feat(G4): WASM agent prompt routes to Anthropic when WASM echoes input

Reuven591839304b36
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 3cbfbf1b1e..1aab4bc087 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
@@ -61,6 +61,109 @@ const MODEL_MAP: Record<string, string> = {
inherit: 'claude-3-5-sonnet-latest',
};
+export interface AnthropicCallInput {
+ prompt: string;
+ systemPrompt?: string;
+ model?: string; // already-resolved Anthropic model id (e.g. 'claude-3-5-sonnet-latest')
+ maxTokens?: number;
+ temperature?: number;
+ timeoutMs?: number;
+}
+
+export interface AnthropicCallResult {
+ success: boolean;
+ model?: string;
+ messageId?: string;
+ stopReason?: string;
+ output?: string;
+ usage?: { inputTokens: number; outputTokens: number; totalTokens: number };
+ durationMs?: number;
+ error?: string;
+}
+
+/**
+ * Generic Anthropic Messages API call. No agent registry coupling — used
+ * by agent_execute (with the agent's configured model) and by the WASM
+ * agent runtime (G4) when the bundled WASM only echoes input.
+ */
+export async function callAnthropicMessages(input: AnthropicCallInput): Promise<AnthropicCallResult> {
+ const apiKey = process.env.ANTHROPIC_API_KEY;
+ if (!apiKey) {
+ return { success: false, error: 'ANTHROPIC_API_KEY not set in environment' };
+ }
+ const model = input.model || 'claude-3-5-sonnet-latest';
+ const startedAt = Date.now();
+ try {
+ const controller = new AbortController();
+ const timer = setTimeout(() => controller.abort(), input.timeoutMs || 60000);
+ 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,
+ max_tokens: input.maxTokens || 1024,
+ temperature: typeof input.temperature === 'number' ? input.temperature : 0.7,
+ ...(input.systemPrompt ? { system: input.systemPrompt } : {}),
+ messages: [{ role: 'user', content: input.prompt }],
+ }),
+ signal: controller.signal,
+ });
+ clearTimeout(timer);
+ if (!res.ok) {
+ const errText = await res.text().catch(() => '<unreadable error body>');
+ return { success: false, model, 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('');
+ return {
+ success: true,
+ model: data.model,
+ messageId: data.id,
+ 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,
+ };
+ } catch (err) {
+ return {
+ success: false,
+ model,
+ error: err instanceof Error ? err.message : String(err),
+ durationMs: Date.now() - startedAt,
+ };
+ }
+}
+
+/**
+ * Resolve a model identifier to an Anthropic model ID. Accepts:
+ * - logical names: 'haiku', 'sonnet', 'opus', 'inherit'
+ * - prefixed: 'anthropic:claude-3-5-sonnet-latest'
+ * - direct: 'claude-3-5-sonnet-latest'
+ */
+export function resolveAnthropicModel(input: string | undefined): string {
+ if (!input) return 'claude-3-5-sonnet-latest';
+ if (input in MODEL_MAP) return MODEL_MAP[input];
+ if (input.startsWith('anthropic:')) return input.slice('anthropic:'.length);
+ return input;
+}
+
export interface AgentExecuteInput {
agentId: string;
prompt: string;
diff --git a/v3/@claude-flow/cli/src/ruvector/agent-wasm.ts b/v3/@claude-flow/cli/src/ruvector/agent-wasm.ts
index 1e8e12be20..3966381e24 100644
--- a/v3/@claude-flow/cli/src/ruvector/agent-wasm.ts
+++ b/v3/@claude-flow/cli/src/ruvector/agent-wasm.ts
@@ -135,7 +135,18 @@ export async function createWasmAgent(config: WasmAgentConfig = {}): Promise<Was
}
/**
- * Send a prompt to a WASM agent. Requires a model provider to be set.
+ * Send a prompt to a WASM agent.
+ *
+ * ADR-095 G4: the bundled @ruvector/rvagent-wasm doesn't actually run an
+ * LLM — its prompt() method echoes input back as `"echo: <input>"`. We
+ * detect that stub output and route the prompt through Anthropic's
+ * Messages API so users get a real response. The WASM agent's sandbox
+ * (virtual filesystem, tool execution) still works for non-LLM ops via
+ * executeWasmTool — we're just patching the "talk to a model" hole.
+ *
+ * If ANTHROPIC_API_KEY is not set, returns the stub output verbatim so
+ * the failure mode is obvious to the caller (matches the previous
+ * behaviour rather than throwing for users without keys configured).
*/
export async function promptWasmAgent(agentId: string, input: string): Promise<string> {
const entry = agents.get(agentId);
@@ -143,10 +154,38 @@ export async function promptWasmAgent(agentId: string, input: string): Promise<s
entry.info.state = 'running';
try {
- const result = await entry.agent.prompt(input);
+ const wasmResult = await entry.agent.prompt(input);
entry.info.state = 'idle';
syncAgentInfo(entry);
- return result;
+
+ // Detect the WASM echo stub.
+ const isEchoStub = typeof wasmResult === 'string' &&
+ (wasmResult === `echo: ${input}` || /^echo: /.test(wasmResult.slice(0, 12)));
+
+ if (!isEchoStub) {
+ return wasmResult;
+ }
+
+ // Echo stub detected — route through a real LLM call.
+ if (!process.env.ANTHROPIC_API_KEY) {
+ // No key configured; surface the stub honestly with a hint.
+ return `${wasmResult}\n[NOTE: bundled WASM agent has no LLM; set ANTHROPIC_API_KEY to enable real responses via Anthropic Messages API]`;
+ }
+
+ const { callAnthropicMessages, resolveAnthropicModel } = await import('../mcp-tools/agent-execute-core.js');
+ const model = resolveAnthropicModel(entry.info.config.model);
+ const systemPrompt = entry.info.config.instructions || 'You are a helpful coding assistant running in a Ruflo WASM agent sandbox.';
+ const result = await callAnthropicMessages({
+ prompt: input,
+ systemPrompt,
+ model,
+ maxTokens: 2048,
+ });
+ if (!result.success) {
+ return `${wasmResult}\n[NOTE: bundled WASM agent has no LLM; Anthropic fallback failed: ${result.error}]`;
+ }
+ // Return the real LLM output, not the echo stub.
+ return result.output ?? '';
} catch (err) {
entry.info.state = 'error';
throw err;