""" Genisi Agent Core - The brain of the AI Coding Agent """ import json import asyncio from typing import List, Dict, Any, Optional from openai import AsyncOpenAI from pathlib import Path from agent.tools.file_ops import FileOperationsTool from agent.tools.shell import ShellExecutionTool from agent.tools.search import CodeSearchTool from agent.tools.git_ops import GitOperationsTool class GenisiAgent: """ Real AI Coding Agent - Like Claude Code / Cursor / Kimi Code Capabilities: - Read, write, edit files - Execute shell commands safely - Search codebase - Run tests - Git operations - Multi-step planning - Self-healing on errors """ # Real tools the agent can use AGENT_TOOLS = [ { "type": "function", "function": { "name": "read_file", "description": "Read the contents of a file. Use this to understand existing code before modifying it.", "parameters": { "type": "object", "properties": { "path": {"type": "string", "description": "Path to the file (relative to workspace)"} }, "required": ["path"] } } }, { "type": "function", "function": { "name": "write_file", "description": "Write content to a file. Creates the file if it doesn't exist.", "parameters": { "type": "object", "properties": { "path": {"type": "string", "description": "Path to the file"}, "content": {"type": "string", "description": "Content to write"} }, "required": ["path", "content"] } } }, { "type": "function", "function": { "name": "edit_file", "description": "Edit specific text in a file. Replaces old_text with new_text.", "parameters": { "type": "object", "properties": { "path": {"type": "string", "description": "Path to the file"}, "old_text": {"type": "string", "description": "Text to find"}, "new_text": {"type": "string", "description": "Text to replace with"} }, "required": ["path", "old_text", "new_text"] } } }, { "type": "function", "function": { "name": "list_directory", "description": "List contents of a directory. Use to understand project structure.", "parameters": { "type": "object", "properties": { "path": {"type": "string", "description": "Directory path (default: current directory)"}, "recursive": {"type": "boolean", "description": "List recursively"} } } } }, { "type": "function", "function": { "name": "execute_command", "description": "Execute a shell command safely. Use for running scripts, installing packages, etc.", "parameters": { "type": "object", "properties": { "command": {"type": "string", "description": "The command to execute"}, "timeout": {"type": "integer", "description": "Timeout in seconds"} }, "required": ["command"] } } }, { "type": "function", "function": { "name": "run_tests", "description": "Run the project's test suite. Use after making changes to verify correctness.", "parameters": { "type": "object", "properties": { "framework": {"type": "string", "enum": ["pytest", "jest", "vitest", "mocha", "unittest"]}, "pattern": {"type": "string", "description": "Test file pattern"} } } } }, { "type": "function", "function": { "name": "grep_search", "description": "Search for a pattern in all files. Use to find code references, TODOs, etc.", "parameters": { "type": "object", "properties": { "pattern": {"type": "string", "description": "Regex pattern to search for"}, "file_pattern": {"type": "string", "description": "File glob pattern (e.g., '*.py')"} }, "required": ["pattern"] } } }, { "type": "function", "function": { "name": "analyze_project", "description": "Analyze the entire project structure, languages, and dependencies.", "parameters": {"type": "object", "properties": {}} } }, { "type": "function", "function": { "name": "git_status", "description": "Check git status to see modified files.", "parameters": {"type": "object", "properties": {}} } }, { "type": "function", "function": { "name": "git_commit", "description": "Commit changes with a message.", "parameters": { "type": "object", "properties": { "message": {"type": "string", "description": "Commit message"} }, "required": ["message"] } } }, { "type": "function", "function": { "name": "install_package", "description": "Install a package using pip, npm, etc.", "parameters": { "type": "object", "properties": { "package": {"type": "string", "description": "Package name"}, "manager": {"type": "string", "enum": ["pip", "npm", "yarn", "cargo"]} }, "required": ["package"] } } } ] def __init__(self, workspace: str = "./workspace", model: str = "glm-5.3-flash"): self.workspace = Path(workspace).resolve() self.workspace.mkdir(parents=True, exist_ok=True) # Initialize real tools self.file_ops = FileOperationsTool(str(self.workspace)) self.shell = ShellExecutionTool(str(self.workspace)) self.search = CodeSearchTool(str(self.workspace)) self.git = GitOperationsTool(str(self.workspace)) # AI client self.client = AsyncOpenAI( base_url="https://h1kcr7a93tg0-d.space-z.ai/api/provider/v1", api_key=os.getenv("ZAI_API_KEY"), timeout=180 ) self.model = model self.conversation_history = [] self.execution_log = [] async def execute_tool(self, tool_name: str, args: Dict[str, Any]) -> Dict[str, Any]: """Execute a real tool and return result""" print(f"🔧 Agent executing: {tool_name}({json.dumps(args, ensure_ascii=False)[:100]})") try: if tool_name == "read_file": return await self.file_ops.read_file(args["path"]) elif tool_name == "write_file": return await self.file_ops.write_file(args["path"], args["content"]) elif tool_name == "edit_file": return await self.file_ops.edit_file(args["path"], args["old_text"], args["new_text"]) elif tool_name == "list_directory": return await self.file_ops.list_directory(args.get("path", "."), recursive=args.get("recursive", False)) elif tool_name == "execute_command": return await self.shell.execute(args["command"], timeout=args.get("timeout", 30)) elif tool_name == "run_tests": return await self.shell.run_tests(args.get("framework", "pytest"), args.get("pattern", "test_*.py")) elif tool_name == "grep_search": return await self.search.grep(args["pattern"], file_pattern=args.get("file_pattern", "*")) elif tool_name == "analyze_project": return await self.search.analyze_project() elif tool_name == "git_status": return await self.git.status() elif tool_name == "git_commit": # Stage all changes first await self.git.add(['.']) return await self.git.commit(args["message"]) elif tool_name == "install_package": return await self.shell.install_package(args["package"], args.get("manager", "pip")) else: return {"success": False, "error": f"Unknown tool: {tool_name}"} except Exception as e: return {"success": False, "error": f"Tool execution failed: {str(e)}"} async def run(self, user_request: str, max_iterations: int = 20) -> Dict[str, Any]: """ Run the Agent with a user request. The Agent will plan, execute tools, and complete the task autonomously. """ system_prompt = f"""You are Genisi Agent, an elite AI coding assistant with REAL file system access. You can: - Read, write, and edit files - Execute shell commands safely - Search the codebase - Run tests - Use Git for version control - Install packages IMPORTANT RULES: 1. ALWAYS read files before modifying them 2. ALWAYS run tests after making changes 3. Use git to track changes 4. If an error occurs, analyze it and fix it 5. Break complex tasks into smaller steps 6. Verify your work before completing Current workspace: {self.workspace} When you need to perform an action, use the available tools. The tools will execute REAL operations on the file system. Be methodical, thorough, and verify everything works.""" messages = [ {"role": "system", "content": system_prompt}, {"role": "user", "content": user_request} ] iterations = 0 final_response = "" tool_executions = [] while iterations < max_iterations: iterations += 1 # Call AI with tools response = await self.client.chat.completions.create( model=self.model, messages=messages, tools=self.AGENT_TOOLS, tool_choice="auto", temperature=0.1 ) message = response.choices[0].message # If AI wants to use tools if message.tool_calls: # Add assistant message to history messages.append(message.model_dump()) # Execute each tool for tool_call in message.tool_calls: tool_name = tool_call.function.name try: args = json.loads(tool_call.function.arguments or "{}") except: args = {} # Execute the REAL tool result = await self.execute_tool(tool_name, args) tool_executions.append({ "tool": tool_name, "args": args, "result": result }) # Add tool result to conversation messages.append({ "role": "tool", "tool_call_id": tool_call.id, "content": json.dumps(result, ensure_ascii=False)[:5000] }) continue # Let AI see results and decide next step else: # AI is done with tools, give final response final_response = message.content or "" break return { "success": True, "response": final_response, "iterations": iterations, "tool_executions": tool_executions, "workspace": str(self.workspace) }