Self-improving AI Employees for everyone
Python ai-agentsai-employeeai-employeesassistantautonomous-agentsco-employeescompanygrok-botinstinctloop-agentsmuseown-your-datapersonalself-hosted
feat: add Claude Code Agent specialized node
trohitg6cd39c6687ea
diff --git a/client/src/components/AIAgentNode.tsx b/client/src/components/AIAgentNode.tsxindex d51e21e8..b48a18ae 100644--- a/client/src/components/AIAgentNode.tsx+++ b/client/src/components/AIAgentNode.tsx@@ -6,6 +6,7 @@ import AIAgentExecutionService from '../services/execution/aiAgentExecutionServiimport { useAppTheme } from '../hooks/useAppTheme';import { useNodeStatus } from '../contexts/WebSocketContext';import { dracula } from '../styles/theme';+import { ClaudeIcon } from './icons/AIProviderIcons';// LangGraph phase icons and labelsconst PHASE_CONFIG: Record<string, { icon: string; label: string; color: string }> = {@@ -361,6 +362,23 @@ const AGENT_CONFIGS: Record<string, AgentConfig> = {width: 300,height: 200,},+ claude_code_agent: {+ icon: <ClaudeIcon size={28} />,+ title: 'Claude Code',+ subtitle: 'Agentic Coding',+ themeColorKey: 'cyan',+ bottomHandles: [+ { id: 'input-skill', label: 'Skill', position: '25%' },+ { id: 'input-tools', label: 'Tool', position: '75%' },+ ],+ leftHandles: [+ { id: 'input-memory', label: 'Memory', position: '65%' },+ { id: 'input-task', label: 'Task', position: '85%' },+ ],+ topOutputHandle: { id: 'output-top', label: 'Output' },+ width: 300,+ height: 200,+ },};const AIAgentNode: React.FC<NodeProps<NodeData>> = ({ id, type, data, isConnectable, selected }) => {diff --git a/client/src/components/parameterPanel/InputSection.tsx b/client/src/components/parameterPanel/InputSection.tsxindex d6065af0..44c53aad 100644--- a/client/src/components/parameterPanel/InputSection.tsx+++ b/client/src/components/parameterPanel/InputSection.tsx@@ -89,7 +89,7 @@ const InputSection: React.FC<InputSectionProps> = ({ nodeId, visible = true }) ='aiAgent', 'chatAgent', 'android_agent', 'coding_agent','web_agent', 'task_agent', 'social_agent', 'travel_agent','tool_agent', 'productivity_agent', 'payments_agent', 'consumer_agent',- 'autonomous_agent', 'orchestrator_agent', 'ai_employee', 'rlm_agent'+ 'autonomous_agent', 'orchestrator_agent', 'ai_employee', 'rlm_agent', 'claude_code_agent'];// Check if current node is an agent that shows skills in Middle Sectionconst isAgentWithSkills = AGENT_WITH_SKILLS_TYPES.includes(currentNodeType || '');@@ -729,7 +729,7 @@ const InputSection: React.FC<InputSectionProps> = ({ nodeId, visible = true }) =const isMemory = nodeType === 'simpleMemory';const nodeTypeLower = nodeType.toLowerCase();// AI agent types that use the AI output schema- const aiAgentTypes = ['aiAgent', 'chatAgent', 'android_agent', 'coding_agent', 'web_agent', 'task_agent', 'social_agent', 'travel_agent', 'tool_agent', 'productivity_agent', 'payments_agent', 'consumer_agent', 'autonomous_agent', 'orchestrator_agent', 'ai_employee', 'rlm_agent'];+ const aiAgentTypes = ['aiAgent', 'chatAgent', 'android_agent', 'coding_agent', 'web_agent', 'task_agent', 'social_agent', 'travel_agent', 'tool_agent', 'productivity_agent', 'payments_agent', 'consumer_agent', 'autonomous_agent', 'orchestrator_agent', 'ai_employee', 'rlm_agent', 'claude_code_agent'];const isAI = !isMemory && (nodeTypeLower.includes('chatmodel') || aiAgentTypes.includes(nodeType));const isFile = nodeType.includes('file');const isWhatsAppDb = nodeType === 'whatsappDb';diff --git a/client/src/components/parameterPanel/MiddleSection.tsx b/client/src/components/parameterPanel/MiddleSection.tsxindex a21e7443..bdf8abde 100644--- a/client/src/components/parameterPanel/MiddleSection.tsx+++ b/client/src/components/parameterPanel/MiddleSection.tsx@@ -33,7 +33,8 @@ const AGENT_WITH_SKILLS_TYPES = ['autonomous_agent','orchestrator_agent','ai_employee',- 'rlm_agent'+ 'rlm_agent',+ 'claude_code_agent'];interface ConnectedSkill {diff --git a/client/src/nodeDefinitions/specializedAgentNodes.ts b/client/src/nodeDefinitions/specializedAgentNodes.tsindex fd9a51eb..77777d9f 100644--- a/client/src/nodeDefinitions/specializedAgentNodes.ts+++ b/client/src/nodeDefinitions/specializedAgentNodes.ts@@ -455,6 +455,80 @@ export const specializedAgentNodes: Record<string, INodeTypeDescription> = {description: 'Enable detailed REPL output logging'}]+ },++ claude_code_agent: {+ displayName: 'Claude Code Agent',+ name: 'claude_code_agent',+ icon: '>/\_',+ group: ['agent', 'ai'],+ version: 1,+ subtitle: 'Agentic Coding',+ description: 'AI Agent powered by Claude Code CLI for agentic code generation, file editing, and command execution',+ defaults: { name: 'Claude Code Agent', color: dracula.cyan },+ inputs: AI_AGENT_INPUTS,+ outputs: AI_AGENT_OUTPUTS,+ properties: [+ {+ displayName: 'Prompt',+ name: 'prompt',+ type: 'string' as any,+ default: '',+ required: true,+ description: 'Task or instruction for Claude Code',+ typeOptions: { rows: 4 },+ },+ {+ displayName: 'Model',+ name: 'model',+ type: 'options' as any,+ default: 'claude-sonnet-4-6',+ options: [+ { name: 'Claude Opus 4.6', value: 'claude-opus-4-6' },+ { name: 'Claude Sonnet 4.6', value: 'claude-sonnet-4-6' },+ { name: 'Claude Haiku 4.5', value: 'claude-haiku-4-5' },+ ],+ description: 'Claude model to use',+ },+ {+ displayName: 'System Prompt',+ name: 'systemPrompt',+ type: 'string' as any,+ default: '',+ description: 'Additional system instructions appended to Claude Code',+ typeOptions: { rows: 3 },+ },+ {+ displayName: 'Allowed Tools',+ name: 'allowedTools',+ type: 'string' as any,+ default: 'Read,Edit,Bash,Glob,Grep,Write',+ description: 'Comma-separated Claude Code tools (Read,Edit,Bash,Glob,Grep,Write,WebSearch,WebFetch)',+ },+ {+ displayName: 'Max Turns',+ name: 'maxTurns',+ type: 'number' as any,+ default: 10,+ typeOptions: { minValue: 1, maxValue: 50 },+ description: 'Maximum agentic iterations',+ },+ {+ displayName: 'Max Budget (USD)',+ name: 'maxBudgetUsd',+ type: 'number' as any,+ default: 5.0,+ typeOptions: { minValue: 0, maxValue: 100, numberStepSize: 0.5 },+ description: 'Maximum USD spend per execution (0 = unlimited)',+ },+ {+ displayName: 'Working Directory',+ name: 'workingDirectory',+ type: 'string' as any,+ default: '',+ description: 'Working directory for Claude Code (empty = server default)',+ },+ ],}};@@ -463,4 +537,4 @@ export const specializedAgentNodes: Record<string, INodeTypeDescription> = {// ============================================================================// List of specialized agent node types for identification-export const SPECIALIZED_AGENT_TYPES = ['android_agent', 'coding_agent', 'web_agent', 'task_agent', 'social_agent', 'travel_agent', 'tool_agent', 'productivity_agent', 'payments_agent', 'consumer_agent', 'autonomous_agent', 'orchestrator_agent', 'ai_employee', 'rlm_agent'];+export const SPECIALIZED_AGENT_TYPES = ['android_agent', 'coding_agent', 'web_agent', 'task_agent', 'social_agent', 'travel_agent', 'tool_agent', 'productivity_agent', 'payments_agent', 'consumer_agent', 'autonomous_agent', 'orchestrator_agent', 'ai_employee', 'rlm_agent', 'claude_code_agent'];diff --git a/server/constants.py b/server/constants.pyindex f5fa132b..8776f6e8 100644--- a/server/constants.py+++ b/server/constants.py@@ -36,6 +36,7 @@ AI_AGENT_TYPES: FrozenSet[str] = frozenset(['orchestrator_agent','ai_employee','rlm_agent',+ 'claude_code_agent',])AI_MEMORY_TYPES: FrozenSet[str] = frozenset([diff --git a/server/services/ai.py b/server/services/ai.pyindex 386dc87a..3765ff8d 100644--- a/server/services/ai.py+++ b/server/services/ai.py@@ -2409,6 +2409,7 @@ class AIService:'orchestrator_agent': 'delegate_to_orchestrator_agent','ai_employee': 'delegate_to_ai_employee','rlm_agent': 'delegate_to_rlm_agent',+ 'claude_code_agent': 'delegate_to_claude_code_agent',# Android service nodes (direct tool usage)'batteryMonitor': 'android_battery','networkMonitor': 'android_network',@@ -2476,6 +2477,7 @@ class AIService:'orchestrator_agent': 'ONE-SHOT delegation to Orchestrator Agent. Call ONCE per task, returns task_id. Coordinates multiple agents - do NOT re-call.','ai_employee': 'ONE-SHOT delegation to AI Employee. Call ONCE per task, returns task_id. Coordinates multiple agents - do NOT re-call.','rlm_agent': 'ONE-SHOT delegation to RLM Agent. Call ONCE per task, returns task_id. Uses recursive REPL-based reasoning with code execution - do NOT re-call.',+ 'claude_code_agent': 'ONE-SHOT delegation to Claude Code Agent. Call ONCE per task, returns task_id. Agentic coding with file reading, editing, and command execution - do NOT re-call.',# Android service nodes (direct tool usage)'batteryMonitor': 'Monitor Android battery status, level, charging state, temperature, and health.','networkMonitor': 'Monitor Android network connectivity, type, and internet availability.',@@ -3390,7 +3392,7 @@ class AIService:return CheckDelegatedTasksSchema# AI Agent delegation schema (fire-and-forget async delegation)- if node_type in ('aiAgent', 'chatAgent', 'android_agent', 'coding_agent', 'web_agent', 'task_agent', 'social_agent', 'travel_agent', 'tool_agent', 'productivity_agent', 'payments_agent', 'consumer_agent', 'autonomous_agent', 'orchestrator_agent', 'ai_employee', 'rlm_agent'):+ if node_type in ('aiAgent', 'chatAgent', 'android_agent', 'coding_agent', 'web_agent', 'task_agent', 'social_agent', 'travel_agent', 'tool_agent', 'productivity_agent', 'payments_agent', 'consumer_agent', 'autonomous_agent', 'orchestrator_agent', 'ai_employee', 'rlm_agent', 'claude_code_agent'):agent_label = params.get('label', node_type)class DelegateToAgentSchema(BaseModel):diff --git a/server/services/claude_code_service.py b/server/services/claude_code_service.pynew file mode 100644index 00000000..633fba02--- /dev/null+++ b/server/services/claude_code_service.py@@ -0,0 +1,102 @@+"""Claude Code service - manages CLI execution with session persistence."""++import asyncio+import json+import os+import shutil+from typing import Any, Dict, List, Optional++from core.logging import get_logger++logger = get_logger(__name__)+++def _find_claude_cmd() -> List[str]:+ """Find claude CLI cross-platform."""+ if shutil.which("claude"):+ return ["claude"]+ npx = shutil.which("npx")+ if npx:+ return [npx, "-y", "@anthropic-ai/claude-code"]+ raise FileNotFoundError("Neither 'claude' nor 'npx' found in PATH")+++class ClaudeCodeService:+ """Executes tasks via Claude Code CLI with session tracking."""++ def __init__(self):+ self._session_map: Dict[str, str] = {} # node_id -> session_id++ async def execute(+ self,+ prompt: str,+ node_id: str = "",+ model: str = "claude-sonnet-4-6",+ cwd: Optional[str] = None,+ allowed_tools: str = "Read,Edit,Bash,Glob,Grep,Write",+ max_turns: int = 10,+ max_budget_usd: float = 5.0,+ system_prompt: Optional[str] = None,+ ) -> Dict[str, Any]:+ """Run claude CLI and return parsed JSON result."""+ cmd = _find_claude_cmd() + [+ "-p", prompt,+ "--output-format", "json",+ "--model", model,+ "--max-turns", str(max_turns),+ "--allowedTools", allowed_tools,+ ]++ if max_budget_usd > 0:+ cmd += ["--max-cost", str(max_budget_usd)]++ # Resume existing session for this node+ session_id = self._session_map.get(node_id)+ if session_id:+ cmd += ["--resume", session_id]++ if system_prompt:+ cmd += ["--append-system-prompt", system_prompt]++ work_dir = cwd or os.getcwd()++ proc = await asyncio.create_subprocess_exec(+ *cmd,+ stdout=asyncio.subprocess.PIPE,+ stderr=asyncio.subprocess.PIPE,+ cwd=work_dir,+ )+ stdout, stderr = await asyncio.wait_for(proc.communicate(), timeout=300)++ if proc.returncode != 0:+ err = stderr.decode("utf-8", errors="replace").strip()+ logger.error("Claude Code failed (exit %d): %s", proc.returncode, err)+ raise RuntimeError(err or f"Exit code {proc.returncode}")++ raw = stdout.decode("utf-8", errors="replace").strip()+ try:+ data = json.loads(raw)+ except json.JSONDecodeError:+ data = {"result": raw}++ # Track session for future resume+ if data.get("session_id") and node_id:+ self._session_map[node_id] = data["session_id"]++ return data++ def get_session_id(self, node_id: str) -> Optional[str]:+ return self._session_map.get(node_id)++ def clear_session(self, node_id: str) -> None:+ self._session_map.pop(node_id, None)+++_instance: Optional[ClaudeCodeService] = None+++def get_claude_code_service() -> ClaudeCodeService:+ global _instance+ if _instance is None:+ _instance = ClaudeCodeService()+ return _instancediff --git a/server/services/handlers/claude_code.py b/server/services/handlers/claude_code.pynew file mode 100644index 00000000..bc89e590--- /dev/null+++ b/server/services/handlers/claude_code.py@@ -0,0 +1,97 @@+"""Claude Code Agent handler."""++import time+from datetime import datetime+from typing import Any, Dict++from core.logging import get_logger+from services.status_broadcaster import get_status_broadcaster+from services.claude_code_service import get_claude_code_service++logger = get_logger(__name__)+++async def handle_claude_code_agent(+ node_id: str,+ node_type: str,+ parameters: Dict[str, Any],+ context: Dict[str, Any],+ ai_service=None,+ database=None,+) -> Dict[str, Any]:+ """Execute task via Claude Code CLI."""+ start_time = time.time()+ broadcaster = get_status_broadcaster()+ workflow_id = context.get("workflow_id")++ await broadcaster.update_node_status(+ node_id, "executing", {"message": "Starting Claude Code..."}, workflow_id=workflow_id+ )++ try:+ # Resolve prompt from params or connected input+ prompt = parameters.get("prompt", "")+ if not prompt:+ for edge in context.get("edges", []):+ if edge.get("target") == node_id and edge.get("targetHandle") in ("input-main", None):+ src = context.get("outputs", {}).get(edge.get("source"), {})+ if isinstance(src, dict):+ prompt = src.get("message") or src.get("text") or src.get("content") or str(src)+ elif src:+ prompt = str(src)+ if prompt:+ break++ if not prompt:+ return {"success": False, "node_id": node_id, "error": "No prompt provided", "execution_time": time.time() - start_time}++ # Collect skill instructions+ from services.handlers.ai import _collect_agent_connections+ _, skill_data, _, _, _ = await _collect_agent_connections(node_id, context, database)++ system_parts = []+ if parameters.get("systemPrompt"):+ system_parts.append(parameters["systemPrompt"])+ for skill in skill_data:+ instr = skill.get("parameters", {}).get("instructions", "")+ if instr:+ system_parts.append(instr)++ model = parameters.get("model", "claude-sonnet-4-6")+ await broadcaster.update_node_status(+ node_id, "executing", {"message": f"Running Claude Code ({model})..."}, workflow_id=workflow_id+ )++ service = get_claude_code_service()+ data = await service.execute(+ prompt=prompt,+ node_id=node_id,+ model=model,+ cwd=parameters.get("workingDirectory") or None,+ allowed_tools=parameters.get("allowedTools", "Read,Edit,Bash,Glob,Grep,Write"),+ max_turns=int(parameters.get("maxTurns", 10)),+ max_budget_usd=float(parameters.get("maxBudgetUsd", 5.0)),+ system_prompt="\n\n".join(system_parts) if system_parts else None,+ )++ execution_time = time.time() - start_time+ await broadcaster.update_node_status(node_id, "success", {"message": "Claude Code completed"}, workflow_id=workflow_id)++ return {+ "success": True,+ "node_id": node_id,+ "node_type": node_type,+ "result": {+ "response": data.get("result", ""),+ "model": model,+ "provider": "anthropic",+ "session_id": data.get("session_id", ""),+ "usage": data.get("usage", {}),+ "timestamp": datetime.now().isoformat(),+ },+ "execution_time": execution_time,+ }++ except Exception as e:+ logger.error("Claude Code error for node %s: %s", node_id, e)+ return {"success": False, "node_id": node_id, "error": str(e), "execution_time": time.time() - start_time}diff --git a/server/services/handlers/tools.py b/server/services/handlers/tools.pyindex 7c458810..32436cb3 100644--- a/server/services/handlers/tools.py+++ b/server/services/handlers/tools.py@@ -190,7 +190,7 @@ async def execute_tool(tool_name: str, tool_args: Dict[str, Any],# AI Agent delegation (fire-and-forget async delegation)# Includes specialized agents: android_agent, coding_agent, web_agent, task_agent, social_agent, autonomous_agent- if node_type in ('aiAgent', 'chatAgent', 'android_agent', 'coding_agent', 'web_agent', 'task_agent', 'social_agent', 'travel_agent', 'tool_agent', 'productivity_agent', 'payments_agent', 'consumer_agent', 'autonomous_agent', 'orchestrator_agent', 'ai_employee', 'rlm_agent'):+ if node_type in ('aiAgent', 'chatAgent', 'android_agent', 'coding_agent', 'web_agent', 'task_agent', 'social_agent', 'travel_agent', 'tool_agent', 'productivity_agent', 'payments_agent', 'consumer_agent', 'autonomous_agent', 'orchestrator_agent', 'ai_employee', 'rlm_agent', 'claude_code_agent'):return await _execute_delegated_agent(tool_args, config)# Generic fallback for unknown node typesdiff --git a/server/services/node_executor.py b/server/services/node_executor.pyindex a37fc3bd..85d53d4b 100644--- a/server/services/node_executor.py+++ b/server/services/node_executor.py@@ -40,6 +40,7 @@ from services.handlers import (handle_brave_search, handle_serper_search, handle_perplexity_search,handle_rlm_agent,)+from services.handlers.claude_code import handle_claude_code_agentfrom services.handlers.telegram import handle_telegram_sendfrom services.handlers.apify import handle_apify_actorfrom services.handlers.crawlee import handle_crawlee_scraper@@ -138,6 +139,7 @@ class NodeExecutor:'orchestrator_agent': partial(handle_chat_agent, ai_service=self.ai_service, database=self.database),'ai_employee': partial(handle_chat_agent, ai_service=self.ai_service, database=self.database),'rlm_agent': partial(handle_rlm_agent, ai_service=self.ai_service, database=self.database),+ 'claude_code_agent': partial(handle_claude_code_agent, ai_service=self.ai_service, database=self.database),'simpleMemory': handle_simple_memory,# Maps'gmaps_create': partial(handle_create_map, maps_service=self.maps_service),