Skip to content

An open-source, faster Devin alternative

TypeScript

add codeagent files

Brian Reardon097197a33248
diff --git a/examples/code-agent b/examples/code-agent
deleted file mode 160000
index b1cc7fa0..00000000
--- a/examples/code-agent
+++ /dev/null
@@ -1 +0,0 @@
-Subproject commit b1cc7fa0cefe914936bf54bdd045aa11c568ff3e
diff --git a/examples/code-agent/.env.example b/examples/code-agent/.env.example
new file mode 100644
index 00000000..d6ee5663
--- /dev/null
+++ b/examples/code-agent/.env.example
@@ -0,0 +1,9 @@
+# Required API Keys (at least one LLM provider needed)
+OPENAI_API_KEY=sk-your-openai-api-key-here
+ANTHROPIC_API_KEY=sk-ant-your-anthropic-api-key-here
+
+# Optional: OpenSandbox URL (defaults to localhost:8080)
+# OPENSANDBOX_URL=http://localhost:8080
+
+# Optional: E2B API key (only needed if using E2B sandbox instead of OpenSandbox)
+# E2B_API_KEY=your-e2b-api-key-here
\ No newline at end of file
diff --git a/examples/code-agent/.gitignore b/examples/code-agent/.gitignore
new file mode 100644
index 00000000..ee32de52
--- /dev/null
+++ b/examples/code-agent/.gitignore
@@ -0,0 +1,83 @@
+# Environment variables
+.env
+
+# Python
+__pycache__/
+*.py[cod]
+*$py.class
+*.so
+.Python
+build/
+develop-eggs/
+dist/
+downloads/
+eggs/
+.eggs/
+lib/
+lib64/
+parts/
+sdist/
+var/
+wheels/
+share/python-wheels/
+*.egg-info/
+.installed.cfg
+*.egg
+MANIFEST
+
+# Virtual environments
+env/
+venv/
+ENV/
+env.bak/
+venv.bak/
+.venv/
+
+# IDE
+.vscode/
+.idea/
+*.swp
+*.swo
+*~
+
+# OS
+.DS_Store
+.DS_Store?
+._*
+.Spotlight-V100
+.Trashes
+ehthumbs.db
+Thumbs.db
+
+# Data and logs
+data/
+logs/
+*.log
+
+# Temporary files
+tmp/
+temp/
+.tmp/
+
+# FAISS indexes and repo data
+data/repos/
+data/indexes/
+data/repos.db
+
+# Streamlit
+.streamlit/
+
+# Jupyter
+.ipynb_checkpoints/
+
+# Coverage
+.coverage
+htmlcov/
+
+# pytest
+.pytest_cache/
+
+# mypy
+.mypy_cache/
+.dmypy.json
+dmypy.json
\ No newline at end of file
diff --git a/examples/code-agent/README.md b/examples/code-agent/README.md
new file mode 100644
index 00000000..3d4c14d8
--- /dev/null
+++ b/examples/code-agent/README.md
@@ -0,0 +1,192 @@
+# Code Agent
+
+A LangGraph-powered coding agent that uses E2B sandboxes to safely clone repositories, modify code, and create pull requests.
+
+## Features
+
+- **Sandboxed Execution**: Code runs in isolated E2B sandboxes for safety
+- **Git Integration**: Clones repos, creates branches, commits, and opens PRs via GitHub CLI
+- **Multiple LLM Support**: Works with both Anthropic Claude and OpenAI GPT-4
+- **REST API**: FastAPI server for programmatic access
+- **Web UI**: Streamlit interface for easy interaction
+- **Extensible**: Abstract sandbox interface allows adding new providers
+
+## Quick Start
+
+### 1. Install Dependencies
+
+```bash
+pip install -r requirements.txt
+```
+
+### 2. Configure Environment
+
+Create a `.env` file with your API keys:
+
+```env
+OPENAI_API_KEY=sk-...
+ANTHROPIC_API_KEY=sk-ant-...
+E2B_API_KEY=e2b_...
+```
+
+### 3. Start the API Server
+
+```bash
+python -m src.api.server
+```
+
+The API will be available at `http://localhost:8000`.
+
+### 4. Start the Web UI
+
+In a new terminal:
+
+```bash
+streamlit run src/ui/app.py
+```
+
+The UI will be available at `http://localhost:8501`.
+
+## Usage
+
+### Web UI
+
+1. Open `http://localhost:8501` in your browser
+2. Enter a GitHub repository URL
+3. Describe your task (e.g., "Fix issue #123", "Add unit tests for auth module")
+4. Provide your GitHub personal access token
+5. Click "Start Task" and watch the agent work
+
+### API
+
+Create a task:
+
+```bash
+curl -X POST http://localhost:8000/task \
+ -H "Content-Type: application/json" \
+ -d '{
+ "repo_url": "https://github.com/owner/repo",
+ "task": "Fix the bug in login.py",
+ "github_token": "ghp_...",
+ "llm_provider": "anthropic"
+ }'
+```
+
+Check task status:
+
+```bash
+curl http://localhost:8000/task/{task_id}
+```
+
+Stream logs:
+
+```bash
+curl http://localhost:8000/task/{task_id}/logs
+```
+
+### Programmatic Usage
+
+```python
+import asyncio
+from src.agent.graph import run_agent
+
+async def main():
+ result = await run_agent(
+ repo_url="https://github.com/owner/repo",
+ task="Add error handling to the API endpoints",
+ github_token="ghp_...",
+ llm_provider="anthropic",
+ )
+
+ print(f"Status: {result['status']}")
+ print(f"PR URL: {result.get('pr_url')}")
+
+asyncio.run(main())
+```
+
+## Architecture
+
+```
+code-agent/
+├── src/
+│ ├── config.py # Configuration management
+│ ├── models.py # Pydantic models
+│ ├── agent/
+│ │ ├── graph.py # LangGraph workflow
+│ │ ├── state.py # Agent state schema
+│ │ └── nodes.py # Workflow nodes
+│ ├── sandbox/
+│ │ ├── base.py # Abstract sandbox interface
+│ │ └── e2b.py # E2B implementation
+│ ├── tools/
+│ │ ├── git.py # Git operations
+│ │ └── code.py # Code manipulation
+│ ├── llm/
+│ │ └── provider.py # LLM abstraction
+│ ├── api/
+│ │ └── server.py # FastAPI server
+│ └── ui/
+│ └── app.py # Streamlit interface
+```
+
+## Agent Workflow
+
+1. **Setup**: Creates E2B sandbox, clones repository, creates feature branch
+2. **Execute**: LLM agent explores code, makes changes, runs tests
+3. **Create PR**: Pushes branch and creates pull request
+4. **Cleanup**: Destroys sandbox
+
+## Configuration
+
+Environment variables:
+
+| Variable | Description | Default |
+|----------|-------------|---------|
+| `OPENAI_API_KEY` | OpenAI API key | - |
+| `ANTHROPIC_API_KEY` | Anthropic API key | - |
+| `E2B_API_KEY` | E2B API key | - |
+| `DEFAULT_LLM_PROVIDER` | Default LLM | `anthropic` |
+| `ANTHROPIC_MODEL` | Anthropic model | `claude-sonnet-4-20250514` |
+| `OPENAI_MODEL` | OpenAI model | `gpt-4o` |
+| `SANDBOX_TIMEOUT` | Sandbox timeout (seconds) | `1800` |
+| `API_HOST` | API host | `0.0.0.0` |
+| `API_PORT` | API port | `8000` |
+
+## Adding New Sandbox Providers
+
+Implement the `BaseSandbox` interface:
+
+```python
+from src.sandbox.base import BaseSandbox
+
+class MySandbox(BaseSandbox):
+ async def create(self, timeout: int = 1800) -> str:
+ # Create sandbox, return ID
+ pass
+
+ async def run_command(self, command: str, workdir=None, env=None):
+ # Execute command, return CommandResult
+ pass
+
+ async def read_file(self, path: str) -> str:
+ # Read file contents
+ pass
+
+ async def write_file(self, path: str, content: str):
+ # Write file
+ pass
+
+ async def list_files(self, path: str = ".") -> list[str]:
+ # List directory
+ pass
+
+ async def destroy(self):
+ # Cleanup
+ pass
+```
+
+Then add it to `src/sandbox/__init__.py`.
+
+## License
+
+MIT
diff --git a/examples/code-agent/requirements.txt b/examples/code-agent/requirements.txt
new file mode 100644
index 00000000..c017840d
--- /dev/null
+++ b/examples/code-agent/requirements.txt
@@ -0,0 +1,29 @@
+# LangGraph and LangChain
+langgraph>=0.2.0
+langchain>=0.3.0
+langchain-anthropic>=0.2.0
+langchain-openai>=0.2.0
+
+# E2B Sandbox
+e2b>=1.0.0
+
+# API Server
+fastapi>=0.115.0
+uvicorn>=0.32.0
+
+# Web UI
+streamlit>=1.40.0
+
+# Utilities
+pydantic>=2.9.0
+pydantic-settings>=2.6.0
+python-dotenv>=1.0.0
+httpx>=0.27.0
+
+# Async support
+aiofiles>=24.1.0
+
+# Vector search / Indexing
+faiss-cpu>=1.8.0
+openai>=1.50.0
+numpy>=1.26.0
diff --git a/examples/code-agent/run_api.py b/examples/code-agent/run_api.py
new file mode 100644
index 00000000..5da2fff4
--- /dev/null
+++ b/examples/code-agent/run_api.py
@@ -0,0 +1,19 @@
+#!/usr/bin/env python3
+"""Entry point to run the API server."""
+
+import uvicorn
+from src.config import get_settings
+
+
+def main():
+ settings = get_settings()
+ uvicorn.run(
+ "src.api.server:app",
+ host=settings.api_host,
+ port=settings.api_port,
+ reload=True,
+ )
+
+
+if __name__ == "__main__":
+ main()
diff --git a/examples/code-agent/run_ui.py b/examples/code-agent/run_ui.py
new file mode 100644
index 00000000..d074ed63
--- /dev/null
+++ b/examples/code-agent/run_ui.py
@@ -0,0 +1,13 @@
+#!/usr/bin/env python3
+"""Entry point to run the Streamlit UI."""
+
+import subprocess
+import sys
+
+
+def main():
+ subprocess.run([sys.executable, "-m", "streamlit", "run", "src/ui/app.py"])
+
+
+if __name__ == "__main__":
+ main()
diff --git a/examples/code-agent/src/__init__.py b/examples/code-agent/src/__init__.py
new file mode 100644
index 00000000..8f5427ff
--- /dev/null
+++ b/examples/code-agent/src/__init__.py
@@ -0,0 +1 @@
+"""LangGraph Sandbox Coding Agent."""
diff --git a/examples/code-agent/src/agent/__init__.py b/examples/code-agent/src/agent/__init__.py
new file mode 100644
index 00000000..5e29643f
--- /dev/null
+++ b/examples/code-agent/src/agent/__init__.py
@@ -0,0 +1,6 @@
+"""LangGraph agent module."""
+
+from .graph import create_agent_graph
+from .state import AgentState
+
+__all__ = ["create_agent_graph", "AgentState"]
diff --git a/examples/code-agent/src/agent/graph.py b/examples/code-agent/src/agent/graph.py
new file mode 100644
index 00000000..dcee17e5
--- /dev/null
+++ b/examples/code-agent/src/agent/graph.py
@@ -0,0 +1,129 @@
+"""LangGraph workflow definition."""
+
+import uuid
+from langgraph.graph import StateGraph, END
+
+from src.agent.state import AgentState
+from src.agent.nodes import (
+ setup_node,
+ execute_node,
+ create_pr_node,
+ cleanup_node,
+ should_continue,
+)
+
+
+def create_agent_graph():
+ """
+ Create the LangGraph workflow for the coding agent.
+
+ Workflow:
+ 1. Setup: Create sandbox, clone repo, create branch
+ 2. Execute: LLM agent makes code changes
+ 3. Create PR: Push and create pull request
+ 4. Cleanup: Destroy sandbox
+
+ Returns:
+ Compiled LangGraph workflow
+ """
+ # Create the graph
+ workflow = StateGraph(AgentState)
+
+ # Add nodes
+ workflow.add_node("setup", setup_node)
+ workflow.add_node("execute", execute_node)
+ workflow.add_node("create_pr", create_pr_node)
+ workflow.add_node("cleanup", cleanup_node)
+
+ # Set entry point
+ workflow.set_entry_point("setup")
+
+ # Add edges
+ workflow.add_conditional_edges(
+ "setup",
+ should_continue,
+ {
+ "execute": "execute",
+ "cleanup": "cleanup",
+ }
+ )
+
+ workflow.add_conditional_edges(
+ "execute",
+ should_continue,
+ {
+ "create_pr": "create_pr",
+ "cleanup": "cleanup",
+ }
+ )
+
+ workflow.add_conditional_edges(
+ "create_pr",
+ should_continue,
+ {
+ "cleanup": "cleanup",
+ }
+ )
+
+ # Cleanup always ends
+ workflow.add_edge("cleanup", END)
+
+ # Compile the graph
+ return workflow.compile()
+
+
+async def run_agent(
+ repo_url: str,
+ task: str,
+ github_token: str,
+ branch_name: str | None = None,
+ base_branch: str | None = None,
+ llm_provider: str = "anthropic",
+ model: str | None = None,
+ max_iterations: int | None = None,
+ sandbox_provider: str | None = None,
+) -> dict:
+ """
+ Run the coding agent.
+
+ Args:
+ repo_url: GitHub repository URL
+ task: Task description
+ github_token: GitHub personal access token
+ branch_name: Optional custom branch name
+ base_branch: Base branch for PR (None = auto-detect from repo)
+ llm_provider: LLM provider to use ("anthropic" or "openai")
+ model: Specific model to use (None = use provider default)
+ max_iterations: Max LLM iterations (None = use config default)
+ sandbox_provider: Sandbox provider ("opensandbox" or "e2b", None = use config default)
+
+ Returns:
+ Final state dict with results
+ """
+ graph = create_agent_graph()
+
+ # Create initial state
+ initial_state: AgentState = {
+ "messages": [],
+ "task": task,
+ "repo_url": repo_url,
+ "branch_name": branch_name or f"agent/{uuid.uuid4().hex[:8]}",
+ "base_branch": base_branch, # None means auto-detect
+ "github_token": github_token,
+ "llm_provider": llm_provider,
+ "model": model,
+ "max_iterations": max_iterations,
+ "sandbox_provider": sandbox_provider, # None means use config default
+ "sandbox_id": None,
+ "workdir": "/home/user/repo",
+ "status": "pending",
+ "current_step": "setup",
+ "pr_url": None,
+ "error": None,
+ "logs": [],
+ }
+
+ # Run the graph
+ final_state = await graph.ainvoke(initial_state)
+
+ return final_state
diff --git a/examples/code-agent/src/agent/nodes.py b/examples/code-agent/src/agent/nodes.py
new file mode 100644
index 00000000..9197f77f
--- /dev/null
+++ b/examples/code-agent/src/agent/nodes.py
@@ -0,0 +1,406 @@
+"""Node implementations for the LangGraph workflow."""
+
+import logging
+import uuid
+from datetime import datetime
+from langchain_core.messages import HumanMessage, SystemMessage
+
+from src.agent.state import AgentState
+from src.sandbox import get_sandbox
+from src.sandbox.base import BaseSandbox
+from src.tools.git import GitTools, create_git_tools
+from src.tools.code import create_code_tools
+from src.llm import get_llm
+from src.config import get_settings
+
+logger = logging.getLogger(__name__)
+
+# Store sandbox instances by sandbox_id for cleanup
+_sandboxes: dict[str, BaseSandbox] = {}
+
+
+def add_log(state: AgentState, message: str) -> list[str]:
+ """Add a timestamped log message."""
+ timestamp = datetime.now().strftime("%H:%M:%S")
+ return state["logs"] + [f"[{timestamp}] {message}"]
+
+
+async def setup_node(state: AgentState) -> dict:
+ """
+ Setup node: Create sandbox and clone repository.
+ """
+ import time
+
+ setup_start = time.time()
+ logs = add_log(state, "Starting setup...")
+
+ try:
+ # Create sandbox using configured provider
+ settings = get_settings()
+ provider = state.get("sandbox_provider") or settings.sandbox_provider
+ logs = logs + [f"[{datetime.now().strftime('%H:%M:%S')}] Creating {provider} sandbox..."]
+
+ sandbox_kwargs = {}
+ if provider == "opensandbox":
+ sandbox_kwargs["base_url"] = settings.opensandbox_url
+
+ sandbox_start = time.time()
+ sandbox = get_sandbox(provider, **sandbox_kwargs)
+ sandbox_id = await sandbox.create(timeout=settings.sandbox_timeout)
+ _sandboxes[sandbox_id] = sandbox
+ sandbox_time = time.time() - sandbox_start
+
+ logs = logs + [f"[{datetime.now().strftime('%H:%M:%S')}] Sandbox created: {sandbox_id} ({sandbox_time:.1f}s)"]
+
+ # Setup git authentication
+ auth_start = time.time()
+ git = GitTools(sandbox, state["github_token"], state["workdir"])
+ await git.setup_git_auth()
+ auth_time = time.time() - auth_start
+ logs = logs + [f"[{datetime.now().strftime('%H:%M:%S')}] GitHub authentication configured ({auth_time:.1f}s)"]
+
+ # Clone repository
+ clone_start = time.time()
+ logs = logs + [f"[{datetime.now().strftime('%H:%M:%S')}] Cloning {state['repo_url']}..."]
+ await git.clone_repo(state["repo_url"])
+ clone_time = time.time() - clone_start
+ logs = logs + [f"[{datetime.now().strftime('%H:%M:%S')}] Repository cloned ({clone_time:.1f}s)"]
+
+ # Determine base branch and checkout
+ base_branch = state.get("base_branch")
+ if not base_branch:
+ base_branch = await git.get_default_branch()
+ logs = logs + [f"[{datetime.now().strftime('%H:%M:%S')}] Auto-detected base branch: {base_branch}"]
+
+ # Checkout base branch before creating feature branch
+ await git.checkout_branch(base_branch)
+ logs = logs + [f"[{datetime.now().strftime('%H:%M:%S')}] Checked out base branch: {base_branch}"]
+
+ # Create feature branch from base
+ branch_name = state["branch_name"] or f"agent/{uuid.uuid4().hex[:8]}"
+ await git.create_branch(branch_name)
+
+ total_setup_time = time.time() - setup_start
+ logs = logs + [f"[{datetime.now().strftime('%H:%M:%S')}] Created branch: {branch_name} (from {base_branch})"]
+ logs = logs + [f"[{datetime.now().strftime('%H:%M:%S')}] ✅ Setup complete in {total_setup_time:.1f}s"]
+
+ return {
+ "sandbox_id": sandbox_id,
+ "branch_name": branch_name,
+ "base_branch": base_branch, # Store detected base branch
+ "status": "running",
+ "current_step": "execute",
+ "logs": logs
+ }
+
+ except Exception as e:
+ logger.exception("Setup failed")
+ return {
+ "status": "failed",
+ "error": str(e),
+ "current_step": "cleanup",
+ "logs": logs + [f"[{datetime.now().strftime('%H:%M:%S')}] ERROR: {str(e)}"]
+ }
+
+
+async def execute_node(state: AgentState) -> dict:
+ """
+ Execute node: Use LLM with tools to complete the task.
+ """
+ logs = add_log(state, "Starting task execution...")
+
+ sandbox_id = state["sandbox_id"]
+ if not sandbox_id or sandbox_id not in _sandboxes:
+ return {
+ "status": "failed",
+ "error": "Sandbox not found",
+ "current_step": "cleanup",
+ "logs": logs + [f"[{datetime.now().strftime('%H:%M:%S')}] ERROR: Sandbox not found"]
+ }
+
+ sandbox = _sandboxes[sandbox_id]
+ workdir = state["workdir"]
+
+ try:
+ # Create tools
+ git_tools, _ = create_git_tools(sandbox, state["github_token"], workdir)
+ code_tools, _ = create_code_tools(sandbox, workdir)
+ all_tools = git_tools + code_tools
+
+ # Check if semantic search index is available
+ from src.tools.search import create_search_tools, check_index_available
+ repo_url = state.get("repo_url", "")
+
+ # Extract repo name from URL (e.g., "https://github.com/owner/repo" -> "owner/repo")
+ repo_name = None
+ if "github.com" in repo_url:
+ parts = repo_url.rstrip("/").split("/")
+ if len(parts) >= 2:
+ repo_name = f"{parts[-2]}/{parts[-1]}"
+
+ has_index = False
+ if repo_name and check_index_available(repo_name):
+ search_tools = create_search_tools(repo_name)
+ all_tools = search_tools + all_tools # Prioritize search tools
+ has_index = True
+ logs = logs + [f"[{datetime.now().strftime('%H:%M:%S')}] Semantic search index available for {repo_name}"]
+ else:
+ logs = logs + [f"[{datetime.now().strftime('%H:%M:%S')}] No semantic search index (using grep-based search)"]
+
+ # Get LLM with specified provider and model
+ llm_provider = state.get("llm_provider", "anthropic")
+ model = state.get("model") # None uses provider default
+ llm = get_llm(provider=llm_provider, model=model)
+ llm_with_tools = llm.bind_tools(all_tools)
+
+ model_name = model or f"{llm_provider} default"
+ logs = logs + [f"[{datetime.now().strftime('%H:%M:%S')}] Using model: {model_name}"]
+
+ # Build system prompt based on available tools
+ search_tools_section = ""
+ search_workflow = ""
+
+ if has_index:
+ search_tools_section = """
+**Semantic Search Tools (FAST - use these first for finding code!):**
+- semantic_search: Search the codebase by meaning/concept. Much faster than grep!
+- find_similar_code: Find code patterns similar to a description
+
+"""
+ search_workflow = """
+2. Use semantic_search to quickly find relevant code (e.g., "terragrunt configuration handling")
+"""
+
+ # System prompt for the coding agent
+ system_prompt = f"""You are an expert coding agent. You have been given a task to complete in a GitHub repository.
+
+You have access to the following tools:
+
+**GitHub Tools (use these first!):**
+- fetch_github_issue: Fetch issue content (title, body, comments). ALWAYS use this first if task mentions an issue number!
+- fetch_github_pr: Fetch PR content (title, body, files)
+- run_gh_command: Run any gh CLI command (e.g., 'issue list', 'pr list')
+{search_tools_section}
+**Code Tools:**
+- read_file: Read file contents
+- write_file: Write/modify files
+- list_directory: List directory contents
+- find_files: Find files by pattern
+- search_code: Search for text in files (grep)
+- run_shell_command: Run shell commands (tests, builds, etc.)
+- get_repo_structure: Get directory tree
+
+**Git Tools:**
+- git_diff: See current changes
+- git_status: Check git status
+- git_commit: Commit changes
+- git_push: Push branch
+
+CRITICAL WORKFLOW:
+1. **If the task mentions an issue number (e.g., "fix issue #123", "implement #456"):**
+ - FIRST use fetch_github_issue to get the actual issue content
+ - Read and understand what the issue is asking for
+ - Do NOT guess based on code patterns alone
+{search_workflow}
+3. Explore the repository structure to understand the codebase
+4. Find relevant files for the task
+5. Read and understand the existing code
+6. Make necessary changes to complete the task
+7. Run any tests if applicable
+8. Commit your changes with a descriptive message
+9. Push the branch
+
+Be thorough but efficient. Make sure your changes are correct and follow the project's coding style.
+When you have completed all necessary changes and pushed the branch, respond with TASK_COMPLETE."""
+
+ # Build messages
+ messages = [
+ SystemMessage(content=system_prompt),
+ HumanMessage(content=f"""Task: {state['task']}
+
+Repository: {state['repo_url']}
+Working directory: {workdir}
+Branch: {state['branch_name']}
+
+Please complete this task. Start by exploring the repository structure.""")
+ ]
+
+ # Add any previous messages from state
+ messages.extend(state.get("messages", []))
+
+ # Agentic loop - configurable iterations for complex tasks
+ from src.config import get_settings
+ max_iterations = state.get("max_iterations") or get_settings().max_iterations
+ logs = logs + [f"[{datetime.now().strftime('%H:%M:%S')}] Max iterations: {max_iterations}"]
+ iteration = 0
+
+ while iteration < max_iterations:
+ iteration += 1
+ logs = logs + [f"[{datetime.now().strftime('%H:%M:%S')}] LLM iteration {iteration}"]
+
+ # Get LLM response
+ response = await llm_with_tools.ainvoke(messages)
+ messages.append(response)
+
+ # Check if done
+ if "TASK_COMPLETE" in str(response.content):
+ logs = logs + [f"[{datetime.now().strftime('%H:%M:%S')}] Task marked complete by agent"]
+ break
+
+ # Process tool calls
+ if response.tool_calls:
+ from langchain_core.messages import ToolMessage
+
+ for tool_call in response.tool_calls:
+ tool_name = tool_call["name"]
+ tool_args = tool_call["args"]
+
+ # Log tool call with arguments for visibility
+ args_summary = ", ".join(f"{k}={repr(v)[:50]}" for k, v in tool_args.items())
+ logs = logs + [f"[{datetime.now().strftime('%H:%M:%S')}] Tool: {tool_name}({args_summary})"]
+
+ # Find and execute the tool
+ tool_fn = next((t for t in all_tools if t.name == tool_name), None)
+ if tool_fn:
+ try:
+ result = await tool_fn.ainvoke(tool_args)
+ # Log brief result summary
+ result_preview = str(result)[:200].replace('\n', ' ')
+ if len(str(result)) > 200:
+ result_preview += "..."
+ logs = logs + [f"[{datetime.now().strftime('%H:%M:%S')}] → {result_preview}"]
+ # Truncate long results for LLM context
+ if len(str(result)) > 5000:
+ result = str(result)[:5000] + "\n... (truncated)"
+ except Exception as e:
+ result = f"Error: {str(e)}"
+ logs = logs + [f"[{datetime.now().strftime('%H:%M:%S')}] → ERROR: {str(e)}"]
+ else:
+ result = f"Unknown tool: {tool_name}"
+
+ messages.append(ToolMessage(content=str(result), tool_call_id=tool_call["id"]))
+ else:
+ # No tool calls and not complete - might be stuck
+ if iteration > 5:
+ logs = logs + [f"[{datetime.now().strftime('%H:%M:%S')}] No tool calls, prompting agent"]
+ messages.append(HumanMessage(content="Continue with the task. Use the available tools to make progress."))
+
+ if iteration >= max_iterations:
+ logs = logs + [f"[{datetime.now().strftime('%H:%M:%S')}] WARNING: Max iterations reached"]
+
+ return {
+ "messages": messages,
+ "status": "running",
+ "current_step": "create_pr",
+ "logs": logs
+ }
+
+ except Exception as e:
+ logger.exception("Execution failed")
+ return {
+ "status": "failed",
+ "error": str(e),
+ "current_step": "cleanup",
+ "logs": logs + [f"[{datetime.now().strftime('%H:%M:%S')}] ERROR: {str(e)}"]
+ }
+
+
+async def create_pr_node(state: AgentState) -> dict:
+ """
+ Create PR node: Push changes and create pull request.
+ """
+ logs = add_log(state, "Creating pull request...")
+
+ sandbox_id = state["sandbox_id"]
+ if not sandbox_id or sandbox_id not in _sandboxes:
+ return {
+ "status": "failed",
+ "error": "Sandbox not found",
+ "current_step": "cleanup",
+ "logs": logs
+ }
+
+ sandbox = _sandboxes[sandbox_id]
+
+ try:
+ git = GitTools(sandbox, state["github_token"], state["workdir"])
+
+ # Get base branch (auto-detect if not specified)
+ base_branch = state.get("base_branch")
+ if not base_branch:
+ base_branch = await git.get_default_branch()
+ logs = logs + [f"[{datetime.now().strftime('%H:%M:%S')}] Auto-detected base branch: {base_branch}"]
+
+ # Create PR (this will push the branch automatically)
+ logs = logs + [f"[{datetime.now().strftime('%H:%M:%S')}] Creating PR against {base_branch}..."]
+ pr_title = f"[Agent] {state['task'][:50]}"
+ pr_body = f"""## Summary
+This PR was automatically created by the Code Agent.
+
+**Task:** {state['task']}
+
+**Branch:** {state['branch_name']} → {base_branch}
+
+---
+*Generated by Code Agent*
+"""
+
+ pr_url = await git.create_pr(pr_title, pr_body, base=base_branch)
+ logs = logs + [f"[{datetime.now().strftime('%H:%M:%S')}] PR created: {pr_url}"]
+
+ return {
+ "pr_url": pr_url,
+ "status": "running",
+ "current_step": "cleanup",
+ "logs": logs
+ }
+
+ except Exception as e:
+ logger.exception("PR creation failed")
+ return {
+ "status": "failed",
+ "error": str(e),
+ "current_step": "cleanup",
+ "logs": logs + [f"[{datetime.now().strftime('%H:%M:%S')}] ERROR: {str(e)}"]
+ }
+
+
+async def cleanup_node(state: AgentState) -> dict:
+ """
+ Cleanup node: Destroy sandbox.
+ """
+ logs = add_log(state, "Cleaning up...")
+
+ sandbox_id = state["sandbox_id"]
+ if sandbox_id and sandbox_id in _sandboxes:
+ try:
+ sandbox = _sandboxes.pop(sandbox_id)
+ await sandbox.destroy()
+ logs = logs + [f"[{datetime.now().strftime('%H:%M:%S')}] Sandbox destroyed"]
+ except Exception as e:
+ logs = logs + [f"[{datetime.now().strftime('%H:%M:%S')}] Warning: Cleanup error: {str(e)}"]
+
+ # Determine final status
+ final_status = "completed" if state.get("pr_url") else state.get("status", "failed")
+ if state.get("error"):
+ final_status = "failed"
+
+ logs = logs + [f"[{datetime.now().strftime('%H:%M:%S')}] Finished with status: {final_status}"]
+
+ return {
+ "sandbox_id": None,
+ "status": final_status,
+ "current_step": "done",
+ "logs": logs
+ }
+
+
+def should_continue(state: AgentState) -> str:
+ """Determine the next node based on current step."""
+ step = state.get("current_step", "setup")
+ status = state.get("status", "pending")
+
+ if status == "failed":
+ return "cleanup"
+
+ return step
diff --git a/examples/code-agent/src/agent/state.py b/examples/code-agent/src/agent/state.py
new file mode 100644
index 00000000..1972532b
--- /dev/null
+++ b/examples/code-agent/src/agent/state.py
@@ -0,0 +1,48 @@
+"""Agent state definition for LangGraph."""
+
+from typing import Annotated, Optional
+from typing_extensions import TypedDict
+from langgraph.graph.message import add_messages
+
+
+class AgentState(TypedDict):
+ """
+ State schema for the coding agent.
+
+ This state is passed between nodes in the LangGraph workflow.
+ """
+
+ # Conversation history - automatically merged using add_messages
+ messages: Annotated[list, add_messages]
+
+ # Task information
+ task: str # User's task description
+ repo_url: str # GitHub repository URL
+ branch_name: str # Working branch name
+ base_branch: Optional[str] # Base branch for PR (None = auto-detect)
+
+ # Authentication
+ github_token: str # GitHub PAT for gh CLI
+
+ # LLM configuration
+ llm_provider: str # "anthropic" or "openai"
+ model: Optional[str] # Specific model (None = use default)
+ max_iterations: Optional[int] # Max LLM iterations (None = use config default)
+
+ # Sandbox configuration
+ sandbox_provider: Optional[str] # "opensandbox" or "e2b" (None = use config default)
+
+ # Sandbox state
+ sandbox_id: Optional[str] # Sandbox/session instance ID
+ workdir: str # Working directory in sandbox
+
+ # Execution state
+ status: str # Current status (pending, running, completed, failed)
+ current_step: str # Current step in workflow
+
+ # Results
+ pr_url: Optional[str] # URL of created PR
+ error: Optional[str] # Error message if failed
+
+ # Logs for debugging/streaming
+ logs: list[str] # Execution logs
diff --git a/examples/code-agent/src/api/__init__.py b/examples/code-agent/src/api/__init__.py
new file mode 100644
index 00000000..dd384bfe
--- /dev/null
+++ b/examples/code-agent/src/api/__init__.py
@@ -0,0 +1 @@
+"""API server module."""
diff --git a/examples/code-agent/src/api/server.py b/examples/code-agent/src/api/server.py
new file mode 100644
index 00000000..58990f55
--- /dev/null
+++ b/examples/code-agent/src/api/server.py
@@ -0,0 +1,231 @@
+"""FastAPI server for the coding agent."""
+
+import asyncio
+import uuid
+import logging
+from datetime import datetime
+from contextlib import asynccontextmanager
+from fastapi import FastAPI, HTTPException, BackgroundTasks
+from fastapi.middleware.cors import CORSMiddleware
+from fastapi.responses import StreamingResponse
+
+from src.models import TaskRequest, TaskResponse, TaskStatusResponse, TaskStatus
+from src.agent.graph import run_agent
+from src.config import get_settings
+
+# Configure logging
+logging.basicConfig(level=logging.INFO)
+logger = logging.getLogger(__name__)
+
+# In-memory task storage (use Redis/DB for production)
+tasks: dict[str, dict] = {}
+
+
+@asynccontextmanager
+async def lifespan(app: FastAPI):
+ """Application lifespan handler."""
+ logger.info("Starting Code Agent API...")
+ yield
+ logger.info("Shutting down Code Agent API...")
+
+
+app = FastAPI(
+ title="Code Agent API",
+ description="LangGraph-powered coding agent with E2B sandbox execution",
+ version="0.1.0",
+ lifespan=lifespan,
+)
+
+# Add CORS middleware
+app.add_middleware(
+ CORSMiddleware,
+ allow_origins=["*"], # Configure appropriately for production
+ allow_credentials=True,
+ allow_methods=["*"],
+ allow_headers=["*"],
+)
+
+
+async def execute_task(task_id: str, request: TaskRequest):
+ """Background task to execute the agent."""
+ try:
+ tasks[task_id]["status"] = TaskStatus.RUNNING
+ tasks[task_id]["updated_at"] = datetime.now()
+
+ # Run the agent
+ result = await run_agent(
+ repo_url=request.repo_url,
+ task=request.task,
+ github_token=request.github_token,
+ branch_name=request.branch_name,
+ base_branch=request.base_branch,
+ llm_provider=request.llm_provider.value,
+ model=request.model,
+ max_iterations=request.max_iterations,
+ sandbox_provider=request.sandbox_provider.value,
+ )
+
+ # Update task with results
+ tasks[task_id]["status"] = TaskStatus(result.get("status", "failed"))
+ tasks[task_id]["pr_url"] = result.get("pr_url")
+ tasks[task_id]["error"] = result.get("error")
+ tasks[task_id]["logs"] = result.get("logs", [])
+ tasks[task_id]["branch_name"] = result.get("branch_name")
+ tasks[task_id]["updated_at"] = datetime.now()
+
+ except Exception as e:
+ logger.exception(f"Task {task_id} failed")
+ tasks[task_id]["status"] = TaskStatus.FAILED
+ tasks[task_id]["error"] = str(e)
+ tasks[task_id]["updated_at"] = datetime.now()
+
+
[email protected]("/task", response_model=TaskResponse)
+async def create_task(request: TaskRequest, background_tasks: BackgroundTasks):
+ """
+ Create a new coding task.
+
+ The task will be executed in the background. Use the task_id to check status.
+ """
+ task_id = str(uuid.uuid4())
+
+ # Store task info
+ tasks[task_id] = {
+ "task_id": task_id,
+ "status": TaskStatus.PENDING,
+ "created_at": datetime.now(),
+ "updated_at": datetime.now(),
+ "repo_url": request.repo_url,
+ "task": request.task,
+ "branch_name": request.branch_name,
+ "pr_url": None,
+ "error": None,
+ "logs": [],
+ }
+
+ # Start background execution
+ background_tasks.add_task(execute_task, task_id, request)
+
+ return TaskResponse(
+ task_id=task_id,
+ status=TaskStatus.PENDING,
+ message="Task created and queued for execution"
+ )
+
+
[email protected]("/task/{task_id}", response_model=TaskStatusResponse)
+async def get_task_status(task_id: str):
+ """Get the status of a task."""
+ if task_id not in tasks:
+ raise HTTPException(status_code=404, detail="Task not found")
+
+ task = tasks[task_id]
+ return TaskStatusResponse(
+ task_id=task["task_id"],
+ status=task["status"],
+ created_at=task["created_at"],
+ updated_at=task["updated_at"],
+ repo_url=task["repo_url"],
+ task=task["task"],
+ branch_name=task.get("branch_name"),
+ pr_url=task.get("pr_url"),
+ error=task.get("error"),
+ logs=task.get("logs", []),
+ )
+
+
[email protected]("/task/{task_id}/logs")
+async def stream_task_logs(task_id: str):
+ """Stream task logs as server-sent events."""
+ if task_id not in tasks:
+ raise HTTPException(status_code=404, detail="Task not found")
+
+ async def log_generator():
+ last_log_count = 0
+ while True:
+ if task_id not in tasks:
+ break
+
+ task = tasks[task_id]
+ logs = task.get("logs", [])
+
+ # Send new logs
+ if len(logs) > last_log_count:
+ for log in logs[last_log_count:]:
+ yield f"data: {log}\n\n"
+ last_log_count = len(logs)
+
+ # Check if task is done
+ if task["status"] in [TaskStatus.COMPLETED, TaskStatus.FAILED, TaskStatus.CANCELLED]:
+ yield f"data: [DONE] Status: {task['status'].value}\n\n"
+ break
+
+ await asyncio.sleep(1)
+
+ return StreamingResponse(
+ log_generator(),
+ media_type="text/event-stream",
+ headers={
+ "Cache-Control": "no-cache",
+ "Connection": "keep-alive",
+ }
+ )
+
+
[email protected]("/task/{task_id}/cancel")
+async def cancel_task(task_id: str):
+ """Cancel a running task."""
+ if task_id not in tasks:
+ raise HTTPException(status_code=404, detail="Task not found")
+
+ task = tasks[task_id]
+ if task["status"] == TaskStatus.RUNNING:
+ task["status"] = TaskStatus.CANCELLED
+ task["updated_at"] = datetime.now()
+ return {"message": "Task cancellation requested"}
+ else:
+ return {"message": f"Task is not running (status: {task['status'].value})"}
+
+
+async def list_tasks(limit: int = 10):
+ """List recent tasks."""
+ sorted_tasks = sorted(
+ tasks.values(),
+ key=lambda t: t["created_at"],
+ reverse=True
+ )[:limit]
+
+ return [
+ {
+ "task_id": t["task_id"],
+ "status": t["status"].value,
+ "repo_url": t["repo_url"],
+ "task": t["task"][:100],
+ "created_at": t["created_at"].isoformat(),
+ "pr_url": t.get("pr_url"),
+ }
+ for t in sorted_tasks
+ ]
+
+
+async def health_check():
+ """Health check endpoint."""
+ return {"status": "healthy"}
+
+
+def start_server():
+ """Start the API server."""
+ import uvicorn
+ settings = get_settings()
+ uvicorn.run(
+ "src.api.server:app",
+ host=settings.api_host,
+ port=settings.api_port,
+ reload=True,
+ )
+
+
+if __name__ == "__main__":
+ start_server()
diff --git a/examples/code-agent/src/config.py b/examples/code-agent/src/config.py
new file mode 100644
index 00000000..9e0645b2
--- /dev/null
+++ b/examples/code-agent/src/config.py
@@ -0,0 +1,42 @@
+"""Configuration management for the coding agent."""
+
+from pydantic_settings import BaseSettings
+from pydantic import Field
+from functools import lru_cache
+
+
+class Settings(BaseSettings):
+ """Application settings loaded from environment variables."""
+
+ # API Keys
+ openai_api_key: str = Field(default="", alias="OPENAI_API_KEY")
+ anthropic_api_key: str = Field(default="", alias="ANTHROPIC_API_KEY")
+ e2b_api_key: str = Field(default="", alias="E2B_API_KEY")
+
+ # LLM Configuration
+ default_llm_provider: str = Field(default="anthropic", alias="DEFAULT_LLM_PROVIDER")
+ anthropic_model: str = Field(default="claude-sonnet-4-5-20250929", alias="ANTHROPIC_MODEL")
+ openai_model: str = Field(default="gpt-5.2", alias="OPENAI_MODEL")
+
+ # Sandbox Configuration
+ sandbox_provider: str = Field(default="opensandbox", alias="SANDBOX_PROVIDER")
+ sandbox_timeout: int = Field(default=1800, alias="SANDBOX_TIMEOUT") # 30 minutes
+ opensandbox_url: str = Field(default="http://localhost:8080", alias="OPENSANDBOX_URL")
+
+ # Agent Configuration
+ max_iterations: int = Field(default=50, alias="MAX_ITERATIONS") # Max LLM tool-calling iterations
+
+ # Server Configuration
+ api_host: str = Field(default="0.0.0.0", alias="API_HOST")
+ api_port: int = Field(default=8000, alias="API_PORT")
+
+ class Config:
+ env_file = ".env"
+ env_file_encoding = "utf-8"
+ extra = "ignore"
+
+
+@lru_cache
+def get_settings() -> Settings:
+ """Get cached settings instance."""
+ return Settings()
diff --git a/examples/code-agent/src/indexer/__init__.py b/examples/code-agent/src/indexer/__init__.py
new file mode 100644
index 00000000..6834350a
--- /dev/null
+++ b/examples/code-agent/src/indexer/__init__.py
@@ -0,0 +1,16 @@
+"""Codebase indexer for semantic search."""
+
+from .embeddings import get_embeddings_client, embed_texts, embed_single
+from .chunker import chunk_file, chunk_codebase
+from .faiss_store import FAISSStore
+from .repo_manager import RepoManager
+
+__all__ = [
+ "get_embeddings_client",
+ "embed_texts",
+ "embed_single",
+ "chunk_file",
+ "chunk_codebase",
+ "FAISSStore",
+ "RepoManager",
+]
diff --git a/examples/code-agent/src/indexer/chunker.py b/examples/code-agent/src/indexer/chunker.py
new file mode 100644
index 00000000..d14a5609
--- /dev/null
+++ b/examples/code-agent/src/indexer/chunker.py
@@ -0,0 +1,207 @@
+"""Code chunking for indexing."""
+
+import os
+import logging
+from typing import List, Dict, Any
+from pathlib import Path
+from dataclasses import dataclass
+
+logger = logging.getLogger(__name__)
+
+# File extensions to index
+CODE_EXTENSIONS = {
+ ".py", ".js", ".ts", ".tsx", ".jsx", ".go", ".rs", ".java", ".c", ".cpp",
+ ".h", ".hpp", ".cs", ".rb", ".php", ".swift", ".kt", ".scala", ".sh",
+ ".yaml", ".yml", ".json", ".toml", ".md", ".txt", ".sql", ".graphql"
+}
+
+# Files/directories to skip
+SKIP_PATTERNS = {
+ "node_modules", "vendor", "dist", "build", ".git", "__pycache__",
+ ".venv", "venv", "env", ".env", ".idea", ".vscode", "target",
+ "coverage", ".next", ".nuxt", "*.min.js", "*.min.css",
+ "package-lock.json", "yarn.lock", "Cargo.lock", "go.sum"
+}
+
+# Target chunk size in characters (roughly 500-800 tokens)
+TARGET_CHUNK_SIZE = 2000
+CHUNK_OVERLAP = 200
+
+
+@dataclass
+class CodeChunk:
+ """A chunk of code with metadata."""
+ content: str
+ file_path: str
+ start_line: int
+ end_line: int
+ language: str
+
+ def to_dict(self) -> Dict[str, Any]:
+ return {
+ "content": self.content,
+ "file_path": self.file_path,
+ "start_line": self.start_line,
+ "end_line": self.end_line,
+ "language": self.language,
+ }
+
+ @classmethod
+ def from_dict(cls, data: Dict[str, Any]) -> "CodeChunk":
+ return cls(**data)
+
+
+def should_skip(path: Path) -> bool:
+ """Check if a path should be skipped."""
+ name = path.name
+
+ for pattern in SKIP_PATTERNS:
+ if pattern.startswith("*"):
+ if name.endswith(pattern[1:]):
+ return True
+ elif name == pattern or pattern in str(path):
+ return True
+
+ return False
+
+
+def get_language(file_path: str) -> str:
+ """Get language from file extension."""
+ ext = Path(file_path).suffix.lower()
+
+ lang_map = {
+ ".py": "python",
+ ".js": "javascript",
+ ".ts": "typescript",
+ ".tsx": "typescript",
+ ".jsx": "javascript",
+ ".go": "go",
+ ".rs": "rust",
+ ".java": "java",
+ ".c": "c",
+ ".cpp": "cpp",
+ ".h": "c",
+ ".hpp": "cpp",
+ ".cs": "csharp",
+ ".rb": "ruby",
+ ".php": "php",
+ ".swift": "swift",
+ ".kt": "kotlin",
+ ".scala": "scala",
+ ".sh": "bash",
+ ".yaml": "yaml",
+ ".yml": "yaml",
+ ".json": "json",
+ ".toml": "toml",
+ ".md": "markdown",
+ ".sql": "sql",
+ }
+
+ return lang_map.get(ext, "text")
+
+
+def chunk_file(file_path: str, content: str) -> List[CodeChunk]:
+ """
+ Chunk a single file into smaller pieces.
+
+ Uses a simple line-based chunking strategy that tries to break
+ at logical boundaries (blank lines, function definitions).
+ """
+ lines = content.split("\n")
+ chunks = []
+ language = get_language(file_path)
+
+ current_chunk_lines = []
+ current_start_line = 1
+ current_size = 0
+
+ for i, line in enumerate(lines, 1):
+ line_size = len(line) + 1 # +1 for newline
+
+ # Check if adding this line would exceed target size
+ if current_size + line_size > TARGET_CHUNK_SIZE and current_chunk_lines:
+ # Save current chunk
+ chunk_content = "\n".join(current_chunk_lines)
+ chunks.append(CodeChunk(
+ content=chunk_content,
+ file_path=file_path,
+ start_line=current_start_line,
+ end_line=i - 1,
+ language=language,
+ ))
+
+ # Start new chunk with overlap
+ overlap_lines = current_chunk_lines[-3:] if len(current_chunk_lines) > 3 else []
+ current_chunk_lines = overlap_lines + [line]
+ current_start_line = max(1, i - len(overlap_lines))
+ current_size = sum(len(l) + 1 for l in current_chunk_lines)
+ else:
+ current_chunk_lines.append(line)
+ current_size += line_size
+
+ # Don't forget the last chunk
+ if current_chunk_lines:
+ chunk_content = "\n".join(current_chunk_lines)
+ chunks.append(CodeChunk(
+ content=chunk_content,
+ file_path=file_path,
+ start_line=current_start_line,
+ end_line=len(lines),
+ language=language,
+ ))
+
+ return chunks
+
+
+def chunk_codebase(repo_path: str) -> List[CodeChunk]:
+ """
+ Chunk all files in a codebase.
+
+ Args:
+ repo_path: Path to the repository root
+
+ Returns:
+ List of CodeChunk objects
+ """
+ repo_path = Path(repo_path)
+ all_chunks = []
+ files_processed = 0
+
+ logger.info(f"Chunking codebase at {repo_path}")
+
+ for root, dirs, files in os.walk(repo_path):
+ root_path = Path(root)
+
+ # Skip directories
+ dirs[:] = [d for d in dirs if not should_skip(root_path / d)]
+
+ for file in files:
+ file_path = root_path / file
+
+ # Skip non-code files
+ if file_path.suffix.lower() not in CODE_EXTENSIONS:
+ continue
+
+ if should_skip(file_path):
+ continue
+
+ try:
+ content = file_path.read_text(encoding="utf-8", errors="ignore")
+
+ # Skip very large files
+ if len(content) > 500000: # 500KB
+ logger.warning(f"Skipping large file: {file_path}")
+ continue
+
+ # Get relative path for storage
+ relative_path = str(file_path.relative_to(repo_path))
+
+ chunks = chunk_file(relative_path, content)
+ all_chunks.extend(chunks)
+ files_processed += 1
+
+ except Exception as e:
+ logger.warning(f"Error processing {file_path}: {e}")
+
+ logger.info(f"Processed {files_processed} files, created {len(all_chunks)} chunks")
+ return all_chunks
diff --git a/examples/code-agent/src/indexer/embeddings.py b/examples/code-agent/src/indexer/embeddings.py
new file mode 100644
index 00000000..9b9b1221
--- /dev/null
+++ b/examples/code-agent/src/indexer/embeddings.py
@@ -0,0 +1,70 @@
+"""Embeddings generation using OpenAI."""
+
+import logging
+from typing import List
+from openai import OpenAI
+
+from src.config import get_settings
+
+logger = logging.getLogger(__name__)
+
+# Embedding model - good balance of quality and cost
+EMBEDDING_MODEL = "text-embedding-3-small"
+EMBEDDING_DIMENSIONS = 1536
+
+
+def get_embeddings_client() -> OpenAI:
+ """Get OpenAI client for embeddings."""
+ settings = get_settings()
+ return OpenAI(api_key=settings.openai_api_key)
+
+
+def embed_texts(texts: List[str], batch_size: int = 100) -> List[List[float]]:
+ """
+ Generate embeddings for a list of texts.
+
+ Args:
+ texts: List of text strings to embed
+ batch_size: Number of texts to embed per API call
+
+ Returns:
+ List of embedding vectors
+ """
+ client = get_embeddings_client()
+ all_embeddings = []
+
+ # Process in batches
+ for i in range(0, len(texts), batch_size):
+ batch = texts[i:i + batch_size]
+ logger.debug(f"Embedding batch {i // batch_size + 1}, size {len(batch)}")
+
+ response = client.embeddings.create(
+ model=EMBEDDING_MODEL,
+ input=batch
+ )
+
+ # Extract embeddings in order
+ batch_embeddings = [item.embedding for item in response.data]
+ all_embeddings.extend(batch_embeddings)
+
+ return all_embeddings
+
+
+def embed_single(text: str) -> List[float]:
+ """
+ Generate embedding for a single text.
+
+ Args:
+ text: Text string to embed
+
+ Returns:
+ Embedding vector
+ """
+ client = get_embeddings_client()
+
+ response = client.embeddings.create(
+ model=EMBEDDING_MODEL,
+ input=text
+ )
+
+ return response.data[0].embedding
diff --git a/examples/code-agent/src/indexer/faiss_store.py b/examples/code-agent/src/indexer/faiss_store.py
new file mode 100644
index 00000000..02893af4
--- /dev/null
+++ b/examples/code-agent/src/indexer/faiss_store.py
@@ -0,0 +1,167 @@
+"""FAISS vector store for code search."""
+
+import json
+import logging
+import numpy as np
+from pathlib import Path
+from typing import List, Dict, Any, Optional, Tuple
+
+import faiss
+
+from .chunker import CodeChunk
+from .embeddings import embed_texts, embed_single, EMBEDDING_DIMENSIONS
+
+logger = logging.getLogger(__name__)
+
+
+class FAISSStore:
+ """
+ FAISS-based vector store for code chunks.
+
+ Stores embeddings in a FAISS index and metadata in a JSON file.
+ """
+
+ def __init__(self, index_path: str):
+ """
+ Initialize the FAISS store.
+
+ Args:
+ index_path: Directory to store the index files
+ """
+ self.index_path = Path(index_path)
+ self.index_path.mkdir(parents=True, exist_ok=True)
+
+ self.faiss_file = self.index_path / "index.faiss"
+ self.metadata_file = self.index_path / "metadata.json"
+
+ self.index: Optional[faiss.IndexFlatIP] = None
+ self.chunks: List[CodeChunk] = []
+
+ def build_index(self, chunks: List[CodeChunk], batch_size: int = 100) -> None:
+ """
+ Build a FAISS index from code chunks.
+
+ Args:
+ chunks: List of CodeChunk objects to index
+ batch_size: Batch size for embedding generation
+ """
+ if not chunks:
+ logger.warning("No chunks to index")
+ return
+
+ logger.info(f"Building index for {len(chunks)} chunks...")
+
+ # Generate embeddings
+ texts = [self._chunk_to_text(chunk) for chunk in chunks]
+ embeddings = embed_texts(texts, batch_size=batch_size)
+
+ # Convert to numpy array
+ embeddings_array = np.array(embeddings, dtype=np.float32)
+
+ # Normalize for cosine similarity (using inner product index)
+ faiss.normalize_L2(embeddings_array)
+
+ # Create FAISS index (Inner Product = cosine similarity for normalized vectors)
+ self.index = faiss.IndexFlatIP(EMBEDDING_DIMENSIONS)
+ self.index.add(embeddings_array)
+
+ self.chunks = chunks
+
+ logger.info(f"Index built with {self.index.ntotal} vectors")
+
+ def _chunk_to_text(self, chunk: CodeChunk) -> str:
+ """Convert a chunk to text for embedding."""
+ # Include file path in the text for better context
+ return f"File: {chunk.file_path}\nLines {chunk.start_line}-{chunk.end_line}\n\n{chunk.content}"
+
+ def search(self, query: str, top_k: int = 10) -> List[Tuple[CodeChunk, float]]:
+ """
+ Search for similar code chunks.
+
+ Args:
+ query: Search query
+ top_k: Number of results to return
+
+ Returns:
+ List of (chunk, score) tuples
+ """
+ if self.index is None or self.index.ntotal == 0:
+ logger.warning("Index is empty")
+ return []
+
+ # Embed query
+ query_embedding = np.array([embed_single(query)], dtype=np.float32)
+ faiss.normalize_L2(query_embedding)
+
+ # Search
+ scores, indices = self.index.search(query_embedding, min(top_k, self.index.ntotal))
+
+ results = []
+ for score, idx in zip(scores[0], indices[0]):
+ if idx >= 0 and idx < len(self.chunks):
+ results.append((self.chunks[idx], float(score)))
+
+ return results
+
+ def save(self) -> None:
+ """Save the index and metadata to disk."""
+ if self.index is None:
+ logger.warning("No index to save")
+ return
+
+ # Save FAISS index
+ faiss.write_index(self.index, str(self.faiss_file))
+
+ # Save metadata (chunks)
+ metadata = {
+ "chunks": [chunk.to_dict() for chunk in self.chunks],
+ "total_chunks": len(self.chunks),
+ }
+
+ with open(self.metadata_file, "w") as f:
+ json.dump(metadata, f)
+
+ logger.info(f"Index saved to {self.index_path}")
+
+ def load(self) -> bool:
+ """
+ Load the index and metadata from disk.
+
+ Returns:
+ True if loaded successfully, False otherwise
+ """
+ if not self.faiss_file.exists() or not self.metadata_file.exists():
+ logger.info("No existing index found")
+ return False
+
+ try:
+ # Load FAISS index
+ self.index = faiss.read_index(str(self.faiss_file))
+
+ # Load metadata
+ with open(self.metadata_file, "r") as f:
+ metadata = json.load(f)
+
+ self.chunks = [CodeChunk.from_dict(c) for c in metadata["chunks"]]
+
+ logger.info(f"Loaded index with {self.index.ntotal} vectors")
+ return True
+
+ except Exception as e:
+ logger.error(f"Error loading index: {e}")
+ return False
+
+ def get_stats(self) -> Dict[str, Any]:
+ """Get index statistics."""
+ if self.index is None:
+ return {"status": "not_built", "chunks": 0, "vectors": 0}
+
+ # Count files
+ files = set(chunk.file_path for chunk in self.chunks)
+
+ return {
+ "status": "ready",
+ "chunks": len(self.chunks),
+ "vectors": self.index.ntotal,
+ "files": len(files),
+ }
diff --git a/examples/code-agent/src/indexer/repo_manager.py b/examples/code-agent/src/indexer/repo_manager.py
new file mode 100644
index 00000000..d87538bb
--- /dev/null
+++ b/examples/code-agent/src/indexer/repo_manager.py
@@ -0,0 +1,328 @@
+"""Repository manager with SQLite persistence."""
+
+import os
+import sqlite3
+import logging
+import subprocess
+import shutil
+from datetime import datetime
+from pathlib import Path
+from typing import List, Optional, Dict, Any
+from dataclasses import dataclass
+
+from .chunker import chunk_codebase
+from .faiss_store import FAISSStore
+
+logger = logging.getLogger(__name__)
+
+# Default paths
+DATA_DIR = Path("data")
+REPOS_DIR = DATA_DIR / "repos"
+INDEXES_DIR = DATA_DIR / "indexes"
+DB_PATH = DATA_DIR / "repos.db"
+
+
+@dataclass
+class RepoInfo:
+ """Information about a tracked repository."""
+ id: int
+ name: str # owner/repo format
+ url: str
+ local_path: str
+ index_status: str # "not_indexed", "indexing", "indexed", "error"
+ chunk_count: int
+ last_indexed: Optional[datetime]
+ created_at: datetime
+
+ @property
+ def display_name(self) -> str:
+ return self.name
+
+ @property
+ def index_path(self) -> str:
+ """Get the path to the index directory."""
+ safe_name = self.name.replace("/", "_")
+ return str(INDEXES_DIR / safe_name)
+
+
+class RepoManager:
+ """
+ Manages repositories and their indexes.
+
+ Uses SQLite for persistence and FAISS for vector search.
+ """
+
+ def __init__(self):
+ """Initialize the repo manager."""
+ # Ensure directories exist
+ DATA_DIR.mkdir(exist_ok=True)
+ REPOS_DIR.mkdir(exist_ok=True)
+ INDEXES_DIR.mkdir(exist_ok=True)
+
+ self._init_db()
+
+ def _init_db(self):
+ """Initialize the SQLite database."""
+ conn = sqlite3.connect(DB_PATH)
+ cursor = conn.cursor()
+
+ cursor.execute("""
+ CREATE TABLE IF NOT EXISTS repos (
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
+ name TEXT UNIQUE NOT NULL,
+ url TEXT NOT NULL,
+ local_path TEXT NOT NULL,
+ index_status TEXT DEFAULT 'not_indexed',
+ chunk_count INTEGER DEFAULT 0,
+ last_indexed TIMESTAMP,
+ created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
+ )
+ """)
+
+ conn.commit()
+ conn.close()
+
+ def _get_conn(self) -> sqlite3.Connection:
+ """Get a database connection."""
+ conn = sqlite3.connect(DB_PATH)
+ conn.row_factory = sqlite3.Row
+ return conn
+
+ def add_repo(self, url: str, clone: bool = True) -> RepoInfo:
+ """
+ Add a repository to track.
+
+ Args:
+ url: GitHub repository URL
+ clone: Whether to clone the repo
+
+ Returns:
+ RepoInfo for the added repo
+ """
+ # Parse repo name from URL
+ # https://github.com/owner/repo or owner/repo
+ if "github.com" in url:
+ parts = url.rstrip("/").split("/")
+ name = f"{parts[-2]}/{parts[-1]}"
+ if name.endswith(".git"):
+ name = name[:-4]
+ else:
+ name = url
+ url = f"https://github.com/{name}"
+
+ # Local path for cloned repo
+ safe_name = name.replace("/", "_")
+ local_path = str(REPOS_DIR / safe_name)
+
+ # Clone if needed
+ if clone and not Path(local_path).exists():
+ logger.info(f"Cloning {url} to {local_path}")
+ result = subprocess.run(
+ ["git", "clone", url, local_path],
+ capture_output=True,
+ text=True
+ )
+ if result.returncode != 0:
+ raise RuntimeError(f"Failed to clone: {result.stderr}")
+
+ # Add to database
+ conn = self._get_conn()
+ cursor = conn.cursor()
+
+ try:
+ cursor.execute(
+ "INSERT INTO repos (name, url, local_path) VALUES (?, ?, ?)",
+ (name, url, local_path)
+ )
+ conn.commit()
+ repo_id = cursor.lastrowid
+ except sqlite3.IntegrityError:
+ # Repo already exists, get existing
+ cursor.execute("SELECT id FROM repos WHERE name = ?", (name,))
+ repo_id = cursor.fetchone()["id"]
+ finally:
+ conn.close()
+
+ return self.get_repo(repo_id)
+
+ def get_repo(self, repo_id: int) -> Optional[RepoInfo]:
+ """Get a repository by ID."""
+ conn = self._get_conn()
+ cursor = conn.cursor()
+
+ cursor.execute("SELECT * FROM repos WHERE id = ?", (repo_id,))
+ row = cursor.fetchone()
+ conn.close()
+
+ if row:
+ return self._row_to_repo_info(row)
+ return None
+
+ def get_repo_by_name(self, name: str) -> Optional[RepoInfo]:
+ """Get a repository by name (owner/repo)."""
+ conn = self._get_conn()
+ cursor = conn.cursor()
+
+ cursor.execute("SELECT * FROM repos WHERE name = ?", (name,))
+ row = cursor.fetchone()
+ conn.close()
+
+ if row:
+ return self._row_to_repo_info(row)
+ return None
+
+ def list_repos(self) -> List[RepoInfo]:
+ """List all tracked repositories."""
+ conn = self._get_conn()
+ cursor = conn.cursor()
+
+ cursor.execute("SELECT * FROM repos ORDER BY created_at DESC")
+ rows = cursor.fetchall()
+ conn.close()
+
+ return [self._row_to_repo_info(row) for row in rows]
+
+ def _row_to_repo_info(self, row: sqlite3.Row) -> RepoInfo:
+ """Convert a database row to RepoInfo."""
+ return RepoInfo(
+ id=row["id"],
+ name=row["name"],
+ url=row["url"],
+ local_path=row["local_path"],
+ index_status=row["index_status"],
+ chunk_count=row["chunk_count"],
+ last_indexed=datetime.fromisoformat(row["last_indexed"]) if row["last_indexed"] else None,
+ created_at=datetime.fromisoformat(row["created_at"]),
+ )
+
+ def build_index(self, repo_id: int) -> FAISSStore:
+ """
+ Build a FAISS index for a repository.
+
+ Args:
+ repo_id: Repository ID
+
+ Returns:
+ The FAISSStore with the built index
+ """
+ repo = self.get_repo(repo_id)
+ if not repo:
+ raise ValueError(f"Repo {repo_id} not found")
+
+ # Update status
+ self._update_status(repo_id, "indexing")
+
+ try:
+ # Pull latest changes
+ logger.info(f"Pulling latest changes for {repo.name}")
+ subprocess.run(
+ ["git", "pull"],
+ cwd=repo.local_path,
+ capture_output=True
+ )
+
+ # Chunk the codebase
+ logger.info(f"Chunking codebase for {repo.name}")
+ chunks = chunk_codebase(repo.local_path)
+
+ # Build FAISS index
+ logger.info(f"Building FAISS index for {repo.name}")
+ store = FAISSStore(repo.index_path)
+ store.build_index(chunks)
+ store.save()
+
+ # Update database
+ conn = self._get_conn()
+ cursor = conn.cursor()
+ cursor.execute(
+ "UPDATE repos SET index_status = ?, chunk_count = ?, last_indexed = ? WHERE id = ?",
+ ("indexed", len(chunks), datetime.now().isoformat(), repo_id)
+ )
+ conn.commit()
+ conn.close()
+
+ logger.info(f"Index built successfully for {repo.name}: {len(chunks)} chunks")
+ return store
+
+ except Exception as e:
+ logger.error(f"Error building index: {e}")
+ self._update_status(repo_id, "error")
+ raise
+
+ def get_index(self, repo_id: int) -> Optional[FAISSStore]:
+ """
+ Get the FAISS index for a repository.
+
+ Returns None if index doesn't exist or isn't built.
+ """
+ repo = self.get_repo(repo_id)
+ if not repo or repo.index_status != "indexed":
+ return None
+
+ store = FAISSStore(repo.index_path)
+ if store.load():
+ return store
+ return None
+
+ def delete_repo(self, repo_id: int, delete_files: bool = True) -> None:
+ """Delete a repository and optionally its files."""
+ repo = self.get_repo(repo_id)
+ if not repo:
+ return
+
+ if delete_files:
+ # Delete cloned repo
+ if Path(repo.local_path).exists():
+ shutil.rmtree(repo.local_path)
+
+ # Delete index
+ if Path(repo.index_path).exists():
+ shutil.rmtree(repo.index_path)
+
+ # Remove from database
+ conn = self._get_conn()
+ cursor = conn.cursor()
+ cursor.execute("DELETE FROM repos WHERE id = ?", (repo_id,))
+ conn.commit()
+ conn.close()
+
+ def _update_status(self, repo_id: int, status: str) -> None:
+ """Update repository index status."""
+ conn = self._get_conn()
+ cursor = conn.cursor()
+ cursor.execute(
+ "UPDATE repos SET index_status = ? WHERE id = ?",
+ (status, repo_id)
+ )
+ conn.commit()
+ conn.close()
+
+ def search(self, repo_id: int, query: str, top_k: int = 10) -> List[Dict[str, Any]]:
+ """
+ Search a repository's index.
+
+ Args:
+ repo_id: Repository ID
+ query: Search query
+ top_k: Number of results
+
+ Returns:
+ List of search results with chunk info and scores
+ """
+ store = self.get_index(repo_id)
+ if not store:
+ return []
+
+ results = store.search(query, top_k)
+
+ return [
+ {
+ "file_path": chunk.file_path,
+ "start_line": chunk.start_line,
+ "end_line": chunk.end_line,
+ "content": chunk.content,
+ "language": chunk.language,
+ "score": score,
+ }
+ for chunk, score in results
+ ]
diff --git a/examples/code-agent/src/llm/__init__.py b/examples/code-agent/src/llm/__init__.py
new file mode 100644
index 00000000..55fd9d72
--- /dev/null
+++ b/examples/code-agent/src/llm/__init__.py
@@ -0,0 +1,5 @@
+"""LLM provider module."""
+
+from .provider import get_llm
+
+__all__ = ["get_llm"]
diff --git a/examples/code-agent/src/llm/provider.py b/examples/code-agent/src/llm/provider.py
new file mode 100644
index 00000000..24a6ad0c
--- /dev/null
+++ b/examples/code-agent/src/llm/provider.py
@@ -0,0 +1,41 @@
+"""LLM provider abstraction."""
+
+from langchain_anthropic import ChatAnthropic
+from langchain_openai import ChatOpenAI
+from langchain_core.language_models.chat_models import BaseChatModel
+
+from src.config import get_settings
+
+
+def get_llm(provider: str | None = None, model: str | None = None) -> BaseChatModel:
+ """
+ Get an LLM instance based on the provider and model.
+
+ Args:
+ provider: "anthropic" or "openai". If None, uses default from settings.
+ model: Specific model to use. If None, uses default for the provider.
+
+ Returns:
+ A LangChain chat model instance
+
+ Raises:
+ ValueError: If provider is not supported
+ """
+ settings = get_settings()
+ provider = provider or settings.default_llm_provider
+
+ if provider == "anthropic":
+ model_name = model or settings.anthropic_model
+ return ChatAnthropic(
+ model=model_name,
+ api_key=settings.anthropic_api_key,
+ max_tokens=8192,
+ )
+ elif provider == "openai":
+ model_name = model or settings.openai_model
+ return ChatOpenAI(
+ model=model_name,
+ api_key=settings.openai_api_key,
+ )
+ else:
+ raise ValueError(f"Unknown LLM provider: {provider}. Supported: ['anthropic', 'openai']")
diff --git a/examples/code-agent/src/models.py b/examples/code-agent/src/models.py
new file mode 100644
index 00000000..3aa03053
--- /dev/null
+++ b/examples/code-agent/src/models.py
@@ -0,0 +1,90 @@
+"""Pydantic models for API requests and responses."""
+
+from pydantic import BaseModel, Field
+from typing import Optional
+from enum import Enum
+from datetime import datetime
+
+
+class TaskStatus(str, Enum):
+ """Status of a task."""
+ PENDING = "pending"
+ RUNNING = "running"
+ COMPLETED = "completed"
+ FAILED = "failed"
+ CANCELLED = "cancelled"
+
+
+class LLMProvider(str, Enum):
+ """Supported LLM providers."""
+ ANTHROPIC = "anthropic"
+ OPENAI = "openai"
+
+
+class SandboxProvider(str, Enum):
+ """Supported sandbox providers."""
+ OPENSANDBOX = "opensandbox"
+ E2B = "e2b"
+
+
+# Available models for each provider
+AVAILABLE_MODELS = {
+ "anthropic": [
+ ("claude-sonnet-4-5-20250929", "Claude Sonnet 4.5 - Best for coding/agents"),
+ ("claude-haiku-4-5-20251001", "Claude Haiku 4.5 - Fastest"),
+ ("claude-opus-4-5-20251101", "Claude Opus 4.5 - Most intelligent"),
+ ],
+ "openai": [
+ ("gpt-5.2", "GPT-5.2 - Latest, best for coding"),
+ ("gpt-5-mini", "GPT-5 mini - Fast, cost-efficient"),
+ ("gpt-5-nano", "GPT-5 nano - Fastest, cheapest"),
+ ("gpt-4.1", "GPT-4.1 - Smart non-reasoning"),
+ ("gpt-4o", "GPT-4o - Fast, flexible"),
+ ("gpt-4o-mini", "GPT-4o mini - Fast, affordable"),
+ ],
+}
+
+
+class TaskRequest(BaseModel):
+ """Request to create a new task."""
+ repo_url: str = Field(..., description="GitHub repository URL")
+ task: str = Field(..., description="Task description (e.g., 'fix issue #123')")
+ github_token: str = Field(..., description="GitHub personal access token")
+ llm_provider: LLMProvider = Field(default=LLMProvider.ANTHROPIC, description="LLM provider to use")
+ model: Optional[str] = Field(default=None, description="Specific model to use (uses provider default if not specified)")
+ sandbox_provider: SandboxProvider = Field(default=SandboxProvider.OPENSANDBOX, description="Sandbox provider to use")
+ branch_name: Optional[str] = Field(default=None, description="Custom branch name (auto-generated if not provided)")
+ base_branch: Optional[str] = Field(default=None, description="Base branch for PR (auto-detected from repo default if not provided)")
+ max_iterations: Optional[int] = Field(default=None, description="Max LLM iterations (uses config default if not specified)")
+
+
+class TaskResponse(BaseModel):
+ """Response after creating a task."""
+ task_id: str
+ status: TaskStatus
+ message: str
+
+
+class TaskStatusResponse(BaseModel):
+ """Response for task status query."""
+ task_id: str
+ status: TaskStatus
+ created_at: datetime
+ updated_at: datetime
+ repo_url: str
+ task: str
+ branch_name: Optional[str] = None
+ pr_url: Optional[str] = None
+ error: Optional[str] = None
+ logs: list[str] = Field(default_factory=list)
+
+
+class CommandResult(BaseModel):
+ """Result of a command execution in sandbox."""
+ stdout: str
+ stderr: str
+ exit_code: int
+
+ @property
+ def success(self) -> bool:
+ return self.exit_code == 0
diff --git a/examples/code-agent/src/sandbox/__init__.py b/examples/code-agent/src/sandbox/__init__.py
new file mode 100644
index 00000000..31419087
--- /dev/null
+++ b/examples/code-agent/src/sandbox/__init__.py
@@ -0,0 +1,30 @@
+"""Sandbox abstraction layer."""
+
+from .base import BaseSandbox
+from .e2b import E2BSandbox
+from .opensandbox import OpenSandbox
+
+
+def get_sandbox(provider: str = "opensandbox", **kwargs) -> BaseSandbox:
+ """
+ Factory function to get a sandbox instance.
+
+ Args:
+ provider: The sandbox provider to use ("e2b" or "opensandbox")
+ **kwargs: Additional arguments passed to the sandbox constructor
+
+ Returns:
+ A sandbox instance implementing BaseSandbox
+
+ Raises:
+ ValueError: If provider is not supported
+ """
+ if provider == "e2b":
+ return E2BSandbox()
+ elif provider == "opensandbox":
+ base_url = kwargs.get("base_url", "http://localhost:8080")
+ return OpenSandbox(base_url=base_url)
+ raise ValueError(f"Unknown sandbox provider: {provider}. Supported: ['e2b', 'opensandbox']")
+
+
+__all__ = ["BaseSandbox", "E2BSandbox", "OpenSandbox", "get_sandbox"]
diff --git a/examples/code-agent/src/sandbox/base.py b/examples/code-agent/src/sandbox/base.py
new file mode 100644
index 00000000..73e6bb0c
--- /dev/null
+++ b/examples/code-agent/src/sandbox/base.py
@@ -0,0 +1,117 @@
+"""Abstract base class for sandbox providers."""
+
+from abc import ABC, abstractmethod
+from typing import Optional
+from src.models import CommandResult
+
+
+class BaseSandbox(ABC):
+ """
+ Abstract interface for sandbox providers.
+
+ Implementations must provide methods to:
+ - Create and destroy sandbox instances
+ - Execute commands in the sandbox
+ - Read and write files in the sandbox
+ """
+
+ @property
+ @abstractmethod
+ def sandbox_id(self) -> Optional[str]:
+ """Get the current sandbox ID, or None if not created."""
+ pass
+
+ @property
+ @abstractmethod
+ def is_active(self) -> bool:
+ """Check if the sandbox is currently active."""
+ pass
+
+ @abstractmethod
+ async def create(self, timeout: int = 1800) -> str:
+ """
+ Create a new sandbox instance.
+
+ Args:
+ timeout: Sandbox timeout in seconds (default 30 minutes)
+
+ Returns:
+ The sandbox ID
+ """
+ pass
+
+ @abstractmethod
+ async def run_command(
+ self,
+ command: str,
+ workdir: Optional[str] = None,
+ env: Optional[dict[str, str]] = None
+ ) -> CommandResult:
+ """
+ Execute a command in the sandbox.
+
+ Args:
+ command: The command to execute
+ workdir: Working directory (optional)
+ env: Additional environment variables (optional)
+
+ Returns:
+ CommandResult with stdout, stderr, and exit_code
+ """
+ pass
+
+ @abstractmethod
+ async def read_file(self, path: str) -> str:
+ """
+ Read a file from the sandbox.
+
+ Args:
+ path: Path to the file in the sandbox
+
+ Returns:
+ File contents as string
+
+ Raises:
+ FileNotFoundError: If file doesn't exist
+ """
+ pass
+
+ @abstractmethod
+ async def write_file(self, path: str, content: str) -> None:
+ """
+ Write content to a file in the sandbox.
+
+ Args:
+ path: Path to the file in the sandbox
+ content: Content to write
+ """
+ pass
+
+ @abstractmethod
+ async def list_files(self, path: str = ".") -> list[str]:
+ """
+ List files in a directory.
+
+ Args:
+ path: Directory path (default current directory)
+
+ Returns:
+ List of file/directory names
+ """
+ pass
+
+ @abstractmethod
+ async def destroy(self) -> None:
+ """
+ Destroy the sandbox instance and clean up resources.
+ """
+ pass
+
+ async def __aenter__(self) -> "BaseSandbox":
+ """Async context manager entry."""
+ await self.create()
+ return self
+
+ async def __aexit__(self, exc_type, exc_val, exc_tb) -> None:
+ """Async context manager exit - always cleanup."""
+ await self.destroy()
diff --git a/examples/code-agent/src/sandbox/e2b.py b/examples/code-agent/src/sandbox/e2b.py
new file mode 100644
index 00000000..61346ea9
--- /dev/null
+++ b/examples/code-agent/src/sandbox/e2b.py
@@ -0,0 +1,191 @@
+"""E2B sandbox implementation."""
+
+import logging
+import os
+from typing import Optional
+from e2b import Sandbox
+
+from .base import BaseSandbox
+from src.models import CommandResult
+from src.config import get_settings
+
+logger = logging.getLogger(__name__)
+
+
+class E2BSandbox(BaseSandbox):
+ """
+ E2B sandbox implementation.
+
+ Uses E2B's cloud sandbox for secure code execution.
+ """
+
+ def __init__(self):
+ self._sandbox: Optional[Sandbox] = None
+ self._sandbox_id: Optional[str] = None
+
+ @property
+ def sandbox_id(self) -> Optional[str]:
+ """Get the current sandbox ID."""
+ return self._sandbox_id
+
+ @property
+ def is_active(self) -> bool:
+ """Check if the sandbox is active."""
+ return self._sandbox is not None
+
+ async def create(self, timeout: int = 1800) -> str:
+ """
+ Create a new E2B sandbox.
+
+ Args:
+ timeout: Sandbox timeout in seconds
+
+ Returns:
+ The sandbox ID
+ """
+ settings = get_settings()
+
+ # E2B SDK reads API key from environment variable
+ os.environ["E2B_API_KEY"] = settings.e2b_api_key
+
+ logger.info("Creating E2B sandbox...")
+
+ # Create sandbox using the class method (constructor is deprecated)
+ self._sandbox = Sandbox.create(timeout=timeout)
+ self._sandbox_id = self._sandbox.sandbox_id
+
+ logger.info(f"Created sandbox: {self._sandbox_id}")
+
+ # Install GitHub CLI
+ await self._setup_sandbox()
+
+ return self._sandbox_id
+
+ async def _setup_sandbox(self) -> None:
+ """Set up the sandbox with required tools."""
+ if not self._sandbox:
+ return
+
+ # Install gh CLI if not present
+ logger.info("Setting up sandbox environment...")
+
+ # Check if gh is installed, install if not
+ result = self._sandbox.commands.run("which gh || echo 'not found'")
+ if "not found" in result.stdout:
+ logger.info("Installing GitHub CLI...")
+ self._sandbox.commands.run(
+ "curl -fsSL https://cli.github.com/packages/githubcli-archive-keyring.gpg | sudo dd of=/usr/share/keyrings/githubcli-archive-keyring.gpg && "
+ "echo 'deb [arch=$(dpkg --print-architecture) signed-by=/usr/share/keyrings/githubcli-archive-keyring.gpg] https://cli.github.com/packages stable main' | sudo tee /etc/apt/sources.list.d/github-cli.list > /dev/null && "
+ "sudo apt update && sudo apt install gh -y",
+ timeout=120
+ )
+
+ logger.info("Sandbox setup complete")
+
+ async def run_command(
+ self,
+ command: str,
+ workdir: Optional[str] = None,
+ env: Optional[dict[str, str]] = None
+ ) -> CommandResult:
+ """
+ Execute a command in the sandbox.
+
+ Args:
+ command: The command to execute
+ workdir: Working directory
+ env: Additional environment variables
+
+ Returns:
+ CommandResult with stdout, stderr, exit_code
+ """
+ if not self._sandbox:
+ raise RuntimeError("Sandbox not created. Call create() first.")
+
+ logger.debug(f"Running command: {command}")
+
+ result = self._sandbox.commands.run(
+ command,
+ cwd=workdir,
+ envs=env or {},
+ timeout=300 # 5 minute timeout per command
+ )
+
+ return CommandResult(
+ stdout=result.stdout,
+ stderr=result.stderr,
+ exit_code=result.exit_code
+ )
+
+ async def read_file(self, path: str) -> str:
+ """
+ Read a file from the sandbox.
+
+ Args:
+ path: Path to the file
+
+ Returns:
+ File contents
+ """
+ if not self._sandbox:
+ raise RuntimeError("Sandbox not created. Call create() first.")
+
+ try:
+ content = self._sandbox.files.read(path)
+ return content
+ except Exception as e:
+ raise FileNotFoundError(f"File not found: {path}") from e
+
+ async def write_file(self, path: str, content: str) -> None:
+ """
+ Write content to a file in the sandbox.
+
+ Args:
+ path: Path to the file
+ content: Content to write
+ """
+ if not self._sandbox:
+ raise RuntimeError("Sandbox not created. Call create() first.")
+
+ self._sandbox.files.write(path, content)
+ logger.debug(f"Wrote file: {path}")
+
+ async def list_files(self, path: str = ".") -> list[str]:
+ """
+ List files in a directory.
+
+ Args:
+ path: Directory path
+
+ Returns:
+ List of file/directory names
+ """
+ if not self._sandbox:
+ raise RuntimeError("Sandbox not created. Call create() first.")
+
+ result = await self.run_command(f"ls -la {path}")
+ if result.exit_code != 0:
+ raise FileNotFoundError(f"Directory not found: {path}")
+
+ # Parse ls output (skip total line and . / ..)
+ lines = result.stdout.strip().split("\n")
+ files = []
+ for line in lines[1:]: # Skip "total" line
+ parts = line.split()
+ if len(parts) >= 9:
+ name = parts[-1]
+ if name not in [".", ".."]:
+ files.append(name)
+ return files
+
+ async def destroy(self) -> None:
+ """Destroy the sandbox."""
+ if self._sandbox:
+ logger.info(f"Destroying sandbox: {self._sandbox_id}")
+ try:
+ self._sandbox.kill()
+ except Exception as e:
+ logger.warning(f"Error destroying sandbox: {e}")
+ finally:
+ self._sandbox = None
+ self._sandbox_id = None
diff --git a/examples/code-agent/src/sandbox/opensandbox.py b/examples/code-agent/src/sandbox/opensandbox.py
new file mode 100644
index 00000000..f52830d1
--- /dev/null
+++ b/examples/code-agent/src/sandbox/opensandbox.py
@@ -0,0 +1,252 @@
+"""OpenSandbox implementation using HTTP API."""
+
+import logging
+import uuid
+import httpx
+from typing import Optional
+
+from .base import BaseSandbox
+from src.models import CommandResult
+from src.config import get_settings
+
+logger = logging.getLogger(__name__)
+
+
+class OpenSandbox(BaseSandbox):
+ """
+ OpenSandbox implementation.
+
+ Uses a local OpenSandbox server for Linux-based sandboxed execution.
+ Communicates via HTTP API.
+ """
+
+ def __init__(self, base_url: str = "http://localhost:8080"):
+ self._base_url = base_url
+ self._session_id: Optional[str] = None
+ self._client = httpx.Client(timeout=300) # 5 minute timeout
+ self._workdir = "/home/user/repo"
+
+ @property
+ def sandbox_id(self) -> Optional[str]:
+ """Get the current session ID."""
+ return self._session_id
+
+ @property
+ def is_active(self) -> bool:
+ """Check if session is active."""
+ return self._session_id is not None
+
+ async def create(self, timeout: int = 1800) -> str:
+ """
+ Create a new OpenSandbox session.
+
+ Args:
+ timeout: Session timeout (not directly used, sessions auto-expire)
+
+ Returns:
+ The session ID
+ """
+ logger.info("Creating OpenSandbox session...")
+
+ # Create session with initial environment
+ response = self._client.post(
+ f"{self._base_url}/sessions",
+ json={"env": {}}
+ )
+ response.raise_for_status()
+
+ data = response.json()
+ self._session_id = data["session_id"]
+
+ logger.info(f"Created session: {self._session_id}")
+
+ # Set up the sandbox environment
+ await self._setup_sandbox()
+
+ return self._session_id
+
+ async def _setup_sandbox(self) -> None:
+ """Set up the sandbox with required directories."""
+ if not self._session_id:
+ return
+
+ logger.info("Setting up sandbox environment...")
+
+ # Create parent directory for repo (but not the repo dir itself - clone will create it)
+ await self.run_command("mkdir -p /home/user")
+
+ # Set initial working directory to /home/user
+ response = self._client.post(
+ f"{self._base_url}/sessions/{self._session_id}/cwd",
+ json={"cwd": "/home/user"}
+ )
+
+ # Check git and gh are available
+ result = await self.run_command("git --version")
+ logger.info(f"Git version: {result.stdout.strip()}")
+
+ result = await self.run_command("gh --version")
+ logger.info(f"GitHub CLI: {result.stdout.split(chr(10))[0] if result.exit_code == 0 else 'not available'}")
+
+ logger.info("Sandbox setup complete")
+
+ async def run_command(
+ self,
+ command: str,
+ workdir: Optional[str] = None,
+ env: Optional[dict[str, str]] = None
+ ) -> CommandResult:
+ """
+ Execute a command in the sandbox.
+
+ Args:
+ command: The command to execute
+ workdir: Working directory
+ env: Additional environment variables
+
+ Returns:
+ CommandResult with stdout, stderr, exit_code
+ """
+ if not self._session_id:
+ raise RuntimeError("Session not created. Call create() first.")
+
+ logger.debug(f"Running command: {command}")
+
+ # Set environment variables if provided
+ if env:
+ self._client.post(
+ f"{self._base_url}/sessions/{self._session_id}/env",
+ json={"env": env}
+ )
+
+ # Set working directory if provided
+ if workdir:
+ self._client.post(
+ f"{self._base_url}/sessions/{self._session_id}/cwd",
+ json={"cwd": workdir}
+ )
+
+ # Run the command via shell
+ # OpenSandbox expects command as array, wrap in shell for string commands
+ response = self._client.post(
+ f"{self._base_url}/sessions/{self._session_id}/run",
+ json={
+ "command": ["/bin/sh", "-c", command],
+ "time": 300000, # 5 minute timeout in ms
+ "mem": 4194304, # 4GB memory limit in KB
+ "fsize": 102400, # 100MB max file size in KB
+ "nofile": 1024, # 1024 open files (git clone needs many)
+ }
+ )
+
+ if response.status_code != 200:
+ error_text = response.text
+ logger.error(f"Command failed: {error_text}")
+ return CommandResult(
+ stdout="",
+ stderr=f"HTTP error: {error_text}",
+ exit_code=1
+ )
+
+ data = response.json()
+
+ exit_code = data.get("exit_code", 0)
+ if data.get("signal"):
+ # Process was killed by signal
+ exit_code = 128 + data["signal"]
+
+ return CommandResult(
+ stdout=data.get("stdout", ""),
+ stderr=data.get("stderr", ""),
+ exit_code=exit_code
+ )
+
+ async def read_file(self, path: str) -> str:
+ """
+ Read a file from the sandbox.
+
+ Args:
+ path: Path to the file
+
+ Returns:
+ File contents
+ """
+ if not self._session_id:
+ raise RuntimeError("Session not created. Call create() first.")
+
+ result = await self.run_command(f"cat {path}")
+ if result.exit_code != 0:
+ raise FileNotFoundError(f"File not found: {path}")
+
+ return result.stdout
+
+ async def write_file(self, path: str, content: str) -> None:
+ """
+ Write content to a file in the sandbox.
+
+ Args:
+ path: Path to the file
+ content: Content to write
+ """
+ if not self._session_id:
+ raise RuntimeError("Session not created. Call create() first.")
+
+ # Ensure parent directory exists
+ dir_path = "/".join(path.rsplit("/", 1)[:-1]) if "/" in path else "."
+ if dir_path and dir_path != ".":
+ await self.run_command(f"mkdir -p {dir_path}")
+
+ # Use heredoc to write file content safely
+ # Escape any backticks and dollar signs in content
+ escaped_content = content.replace("\\", "\\\\").replace("$", "\\$").replace("`", "\\`")
+
+ # Write via base64 to handle special characters
+ import base64
+ b64_content = base64.b64encode(content.encode()).decode()
+ result = await self.run_command(f"echo '{b64_content}' | base64 -d > {path}")
+
+ if result.exit_code != 0:
+ raise RuntimeError(f"Failed to write file: {result.stderr}")
+
+ logger.debug(f"Wrote file: {path}")
+
+ async def list_files(self, path: str = ".") -> list[str]:
+ """
+ List files in a directory.
+
+ Args:
+ path: Directory path
+
+ Returns:
+ List of file/directory names
+ """
+ if not self._session_id:
+ raise RuntimeError("Session not created. Call create() first.")
+
+ result = await self.run_command(f"ls -la {path}")
+ if result.exit_code != 0:
+ raise FileNotFoundError(f"Directory not found: {path}")
+
+ # Parse ls output (skip total line and . / ..)
+ lines = result.stdout.strip().split("\n")
+ files = []
+ for line in lines[1:]: # Skip "total" line
+ parts = line.split()
+ if len(parts) >= 9:
+ name = parts[-1]
+ if name not in [".", ".."]:
+ files.append(name)
+ return files
+
+ async def destroy(self) -> None:
+ """Destroy the session."""
+ if self._session_id:
+ logger.info(f"Destroying session: {self._session_id}")
+ try:
+ self._client.delete(f"{self._base_url}/sessions/{self._session_id}")
+ except Exception as e:
+ logger.warning(f"Error destroying session: {e}")
+ finally:
+ self._session_id = None
+
+ self._client.close()
diff --git a/examples/code-agent/src/tools/__init__.py b/examples/code-agent/src/tools/__init__.py
new file mode 100644
index 00000000..5a2185d2
--- /dev/null
+++ b/examples/code-agent/src/tools/__init__.py
@@ -0,0 +1,7 @@
+"""Agent tools module."""
+
+from .git import GitTools
+from .code import CodeTools
+from .search import create_search_tools, check_index_available
+
+__all__ = ["GitTools", "CodeTools", "create_search_tools", "check_index_available"]
diff --git a/examples/code-agent/src/tools/code.py b/examples/code-agent/src/tools/code.py
new file mode 100644
index 00000000..386e72b8
--- /dev/null
+++ b/examples/code-agent/src/tools/code.py
@@ -0,0 +1,190 @@
+"""Code manipulation tools for the agent."""
+
+import logging
+from langchain_core.tools import tool
+
+from src.sandbox.base import BaseSandbox
+
+logger = logging.getLogger(__name__)
+
+
+class CodeTools:
+ """
+ Code manipulation operations that run in a sandbox.
+
+ Provides tools for reading, writing, and exploring code files.
+ """
+
+ def __init__(self, sandbox: BaseSandbox, workdir: str = "/home/user/repo"):
+ self.sandbox = sandbox
+ self.workdir = workdir
+
+ async def read_file(self, path: str) -> str:
+ """
+ Read a file's contents.
+
+ Args:
+ path: Path relative to workdir, or absolute path
+
+ Returns:
+ File contents
+ """
+ full_path = self._resolve_path(path)
+ logger.debug(f"Reading file: {full_path}")
+ return await self.sandbox.read_file(full_path)
+
+ async def write_file(self, path: str, content: str) -> None:
+ """
+ Write content to a file.
+
+ Args:
+ path: Path relative to workdir, or absolute path
+ content: Content to write
+ """
+ full_path = self._resolve_path(path)
+ logger.debug(f"Writing file: {full_path}")
+
+ # Ensure parent directory exists
+ parent = "/".join(full_path.split("/")[:-1])
+ await self.sandbox.run_command(f"mkdir -p {parent}")
+
+ await self.sandbox.write_file(full_path, content)
+
+ async def list_directory(self, path: str = ".") -> list[str]:
+ """
+ List contents of a directory.
+
+ Args:
+ path: Path relative to workdir, or absolute path
+
+ Returns:
+ List of file/directory names
+ """
+ full_path = self._resolve_path(path)
+ result = await self.sandbox.run_command(f"ls -la {full_path}")
+ return result.stdout
+
+ async def find_files(self, pattern: str, path: str = ".") -> str:
+ """
+ Find files matching a pattern.
+
+ Args:
+ pattern: Glob pattern (e.g., "*.py", "**/*.ts")
+ path: Starting directory
+
+ Returns:
+ List of matching file paths
+ """
+ full_path = self._resolve_path(path)
+ result = await self.sandbox.run_command(
+ f'find {full_path} -name "{pattern}" -type f 2>/dev/null | head -100'
+ )
+ return result.stdout
+
+ async def search_in_files(self, pattern: str, file_pattern: str = "*", path: str = ".") -> str:
+ """
+ Search for a pattern in files (like grep).
+
+ Args:
+ pattern: Text/regex pattern to search for
+ file_pattern: File glob pattern to search in
+ path: Starting directory
+
+ Returns:
+ Matching lines with file paths
+ """
+ full_path = self._resolve_path(path)
+ result = await self.sandbox.run_command(
+ f'grep -rn "{pattern}" {full_path} --include="{file_pattern}" 2>/dev/null | head -100'
+ )
+ return result.stdout
+
+ async def run_command(self, command: str) -> str:
+ """
+ Run an arbitrary shell command in the repo directory.
+
+ Args:
+ command: Shell command to run
+
+ Returns:
+ Command output (stdout + stderr)
+ """
+ result = await self.sandbox.run_command(command, workdir=self.workdir)
+ output = result.stdout
+ if result.stderr:
+ output += f"\nSTDERR:\n{result.stderr}"
+ if result.exit_code != 0:
+ output += f"\n(exit code: {result.exit_code})"
+ return output
+
+ async def get_file_tree(self, max_depth: int = 3) -> str:
+ """
+ Get a tree view of the repository structure.
+
+ Args:
+ max_depth: Maximum depth to traverse
+
+ Returns:
+ Tree-formatted directory structure
+ """
+ result = await self.sandbox.run_command(
+ f"find . -maxdepth {max_depth} -type f | head -200 | sort",
+ workdir=self.workdir
+ )
+ return result.stdout
+
+ def _resolve_path(self, path: str) -> str:
+ """Resolve a path relative to workdir."""
+ if path.startswith("/"):
+ return path
+ return f"{self.workdir}/{path}"
+
+
+def create_code_tools(sandbox: BaseSandbox, workdir: str = "/home/user/repo"):
+ """
+ Create LangChain tools for code operations.
+
+ Returns a list of tools that can be bound to an LLM.
+ """
+ code = CodeTools(sandbox, workdir)
+
+ @tool
+ async def read_file(path: str) -> str:
+ """Read the contents of a file. Path is relative to the repo root."""
+ try:
+ return await code.read_file(path)
+ except FileNotFoundError:
+ return f"Error: File not found: {path}"
+
+ @tool
+ async def write_file(path: str, content: str) -> str:
+ """Write content to a file. Path is relative to the repo root. Creates parent directories if needed."""
+ await code.write_file(path, content)
+ return f"Successfully wrote to {path}"
+
+ @tool
+ async def list_directory(path: str = ".") -> str:
+ """List contents of a directory. Path is relative to the repo root."""
+ return await code.list_directory(path)
+
+ @tool
+ async def find_files(pattern: str, path: str = ".") -> str:
+ """Find files matching a glob pattern (e.g., '*.py', '*.ts'). Returns list of file paths."""
+ return await code.find_files(pattern, path)
+
+ @tool
+ async def search_code(pattern: str, file_pattern: str = "*") -> str:
+ """Search for a text pattern in files (like grep). Returns matching lines with file paths."""
+ return await code.search_in_files(pattern, file_pattern)
+
+ @tool
+ async def run_shell_command(command: str) -> str:
+ """Run a shell command in the repo directory. Use for running tests, builds, etc."""
+ return await code.run_command(command)
+
+ @tool
+ async def get_repo_structure(max_depth: int = 3) -> str:
+ """Get a tree view of the repository structure up to the specified depth."""
+ return await code.get_file_tree(max_depth)
+
+ return [read_file, write_file, list_directory, find_files, search_code, run_shell_command, get_repo_structure], code
diff --git a/examples/code-agent/src/tools/git.py b/examples/code-agent/src/tools/git.py
new file mode 100644
index 00000000..7cf9979c
--- /dev/null
+++ b/examples/code-agent/src/tools/git.py
@@ -0,0 +1,417 @@
+"""Git operations tools for the agent."""
+
+import logging
+from typing import Optional
+from langchain_core.tools import tool
+
+from src.sandbox.base import BaseSandbox
+
+logger = logging.getLogger(__name__)
+
+
+class GitTools:
+ """
+ Git operations that run in a sandbox.
+
+ Provides tools for cloning repos, creating branches, committing, and PRs.
+ """
+
+ def __init__(self, sandbox: BaseSandbox, github_token: str, workdir: str = "/home/user/repo"):
+ self.sandbox = sandbox
+ self.github_token = github_token
+ self.workdir = workdir
+
+ async def setup_git_auth(self) -> None:
+ """Configure git for commits. GH_TOKEN is passed to commands that need auth."""
+ # Set up git config
+ await self.sandbox.run_command('git config --global user.email "[email protected]"')
+ await self.sandbox.run_command('git config --global user.name "Code Agent"')
+
+ # Configure git to use gh as credential helper (uses GH_TOKEN)
+ await self.sandbox.run_command(
+ 'gh auth setup-git',
+ env={"GH_TOKEN": self.github_token}
+ )
+
+ logger.info("Git configured with GitHub authentication.")
+
+ async def clone_repo(self, repo_url: str, shallow: bool = True) -> str:
+ """
+ Clone a repository into the sandbox.
+
+ Args:
+ repo_url: GitHub repository URL (https://github.com/owner/repo)
+ shallow: Use shallow clone (--depth 1) to save disk space (default True)
+
+ Returns:
+ Path to the cloned repository
+ """
+ logger.info(f"Cloning repository: {repo_url} (shallow={shallow})")
+
+ # Extract owner/repo from URL
+ # https://github.com/owner/repo -> owner/repo
+ if "github.com" in repo_url:
+ parts = repo_url.rstrip("/").split("/")
+ owner_repo = f"{parts[-2]}/{parts[-1]}"
+ else:
+ owner_repo = repo_url
+
+ # Use git clone with token in URL for auth
+ # This avoids issues with gh auth and allows --depth flag
+ auth_url = f"https://{self.github_token}@github.com/{owner_repo}"
+
+ depth_flag = "--depth 1" if shallow else ""
+ result = await self.sandbox.run_command(
+ f"git clone {depth_flag} {auth_url} {self.workdir}",
+ env={"GH_TOKEN": self.github_token}
+ )
+
+ if result.exit_code != 0:
+ raise RuntimeError(f"Failed to clone repository: {result.stderr}")
+
+ # Remove token from remote URL for safety (use gh for push instead)
+ await self.sandbox.run_command(
+ f"git remote set-url origin https://github.com/{owner_repo}",
+ workdir=self.workdir
+ )
+
+ logger.info(f"Repository cloned to {self.workdir}")
+ return self.workdir
+
+ async def checkout_branch(self, branch_name: str) -> None:
+ """
+ Checkout an existing branch.
+
+ Args:
+ branch_name: Name of the branch to checkout
+ """
+ logger.info(f"Checking out branch: {branch_name}")
+
+ result = await self.sandbox.run_command(
+ f"git checkout {branch_name}",
+ workdir=self.workdir
+ )
+
+ if result.exit_code != 0:
+ # Try fetching and checking out origin/branch
+ result = await self.sandbox.run_command(
+ f"git checkout -b {branch_name} origin/{branch_name}",
+ workdir=self.workdir
+ )
+ if result.exit_code != 0:
+ raise RuntimeError(f"Failed to checkout branch: {result.stderr}")
+
+ async def create_branch(self, branch_name: str) -> None:
+ """
+ Create and checkout a new branch.
+
+ Args:
+ branch_name: Name for the new branch
+ """
+ logger.info(f"Creating branch: {branch_name}")
+
+ result = await self.sandbox.run_command(
+ f"git checkout -b {branch_name}",
+ workdir=self.workdir
+ )
+
+ if result.exit_code != 0:
+ raise RuntimeError(f"Failed to create branch: {result.stderr}")
+
+ async def get_current_branch(self) -> str:
+ """Get the current branch name."""
+ result = await self.sandbox.run_command(
+ "git branch --show-current",
+ workdir=self.workdir
+ )
+ return result.stdout.strip()
+
+ async def get_default_branch(self) -> str:
+ """Get the repository's default branch (e.g., main, master, develop)."""
+ # Try to get the default branch from the remote
+ result = await self.sandbox.run_command(
+ "git remote show origin | grep 'HEAD branch' | awk '{print $NF}'",
+ workdir=self.workdir,
+ env={"GH_TOKEN": self.github_token}
+ )
+
+ if result.exit_code == 0 and result.stdout.strip():
+ default_branch = result.stdout.strip()
+ logger.info(f"Detected default branch: {default_branch}")
+ return default_branch
+
+ # Fallback: check if common branches exist
+ for branch in ["main", "master", "develop"]:
+ result = await self.sandbox.run_command(
+ f"git rev-parse --verify origin/{branch} 2>/dev/null",
+ workdir=self.workdir
+ )
+ if result.exit_code == 0:
+ logger.info(f"Using fallback default branch: {branch}")
+ return branch
+
+ # Last resort
+ logger.warning("Could not detect default branch, using 'main'")
+ return "main"
+
+ async def stage_all(self) -> None:
+ """Stage all changes."""
+ await self.sandbox.run_command("git add -A", workdir=self.workdir)
+
+ async def commit(self, message: str) -> None:
+ """
+ Commit staged changes.
+
+ Args:
+ message: Commit message
+ """
+ logger.info(f"Committing: {message}")
+
+ await self.stage_all()
+
+ result = await self.sandbox.run_command(
+ f'git commit -m "{message}"',
+ workdir=self.workdir
+ )
+
+ if result.exit_code != 0:
+ if "nothing to commit" in result.stdout:
+ logger.warning("Nothing to commit")
+ return
+ raise RuntimeError(f"Failed to commit: {result.stderr}")
+
+ async def push(self, branch_name: str) -> None:
+ """
+ Push branch to remote.
+
+ Args:
+ branch_name: Branch to push
+ """
+ logger.info(f"Pushing branch: {branch_name}")
+
+ # Get the remote URL and update it to use token auth
+ result = await self.sandbox.run_command(
+ "git remote get-url origin",
+ workdir=self.workdir
+ )
+ remote_url = result.stdout.strip()
+
+ # Convert to authenticated URL if it's a GitHub HTTPS URL
+ if "github.com" in remote_url and not "@" in remote_url:
+ # https://github.com/owner/repo -> https://[email protected]/owner/repo
+ auth_url = remote_url.replace("https://github.com", f"https://{self.github_token}@github.com")
+ await self.sandbox.run_command(
+ f'git remote set-url origin "{auth_url}"',
+ workdir=self.workdir
+ )
+
+ result = await self.sandbox.run_command(
+ f"git push -u origin {branch_name}",
+ workdir=self.workdir
+ )
+
+ # Restore original URL (don't leave token in git config)
+ if "github.com" in remote_url:
+ await self.sandbox.run_command(
+ f'git remote set-url origin "{remote_url}"',
+ workdir=self.workdir
+ )
+
+ if result.exit_code != 0:
+ # Log more details for debugging
+ logger.error(f"Push failed. Exit code: {result.exit_code}")
+ logger.error(f"Push stderr: {result.stderr}")
+ logger.error(f"Push stdout: {result.stdout}")
+
+ # Check git status for debugging
+ status_result = await self.sandbox.run_command("git status", workdir=self.workdir)
+ logger.error(f"Git status: {status_result.stdout}")
+
+ raise RuntimeError(f"Failed to push branch '{branch_name}': {result.stderr}")
+
+ async def create_pr(self, title: str, body: str, base: str | None = None) -> str:
+ """
+ Create a pull request.
+
+ Args:
+ title: PR title
+ body: PR description
+ base: Base branch (None = auto-detect from repo)
+
+ Returns:
+ URL of the created PR
+ """
+ # Auto-detect base branch if not specified
+ if base is None:
+ base = await self.get_default_branch()
+
+ # Get current branch name
+ result = await self.sandbox.run_command(
+ "git branch --show-current",
+ workdir=self.workdir
+ )
+ current_branch = result.stdout.strip()
+
+ logger.info(f"Creating PR: {title} (base: {base}, branch: {current_branch})")
+
+ # Push the current branch first
+ await self.push(current_branch)
+
+ result = await self.sandbox.run_command(
+ f'gh pr create --title "{title}" --body "{body}" --base {base}',
+ workdir=self.workdir,
+ env={"GH_TOKEN": self.github_token}
+ )
+
+ if result.exit_code != 0:
+ raise RuntimeError(f"Failed to create PR: {result.stderr}")
+
+ # Extract PR URL from output
+ pr_url = result.stdout.strip().split("\n")[-1]
+ logger.info(f"Created PR: {pr_url}")
+ return pr_url
+
+ async def get_diff(self) -> str:
+ """Get the current diff."""
+ result = await self.sandbox.run_command("git diff", workdir=self.workdir)
+ return result.stdout
+
+ async def get_status(self) -> str:
+ """Get git status."""
+ result = await self.sandbox.run_command("git status", workdir=self.workdir)
+ return result.stdout
+
+ async def fetch_issue(self, issue_number: int) -> str:
+ """
+ Fetch a GitHub issue's content.
+
+ Args:
+ issue_number: The issue number (e.g., 2552)
+
+ Returns:
+ Issue title, body, and comments
+ """
+ logger.info(f"Fetching issue #{issue_number}")
+
+ # Get issue details
+ result = await self.sandbox.run_command(
+ f"gh issue view {issue_number} --json title,body,comments,state,labels",
+ workdir=self.workdir,
+ env={"GH_TOKEN": self.github_token}
+ )
+
+ if result.exit_code != 0:
+ return f"Error fetching issue: {result.stderr}"
+
+ return result.stdout
+
+ async def fetch_pr(self, pr_number: int) -> str:
+ """
+ Fetch a GitHub PR's content.
+
+ Args:
+ pr_number: The PR number
+
+ Returns:
+ PR title, body, and diff
+ """
+ logger.info(f"Fetching PR #{pr_number}")
+
+ # Get PR details
+ result = await self.sandbox.run_command(
+ f"gh pr view {pr_number} --json title,body,state,files",
+ workdir=self.workdir,
+ env={"GH_TOKEN": self.github_token}
+ )
+
+ if result.exit_code != 0:
+ return f"Error fetching PR: {result.stderr}"
+
+ return result.stdout
+
+ async def run_gh_command(self, command: str) -> str:
+ """
+ Run an arbitrary gh CLI command with authentication.
+
+ Args:
+ command: The gh command (without 'gh' prefix)
+
+ Returns:
+ Command output
+ """
+ result = await self.sandbox.run_command(
+ f"gh {command}",
+ workdir=self.workdir,
+ env={"GH_TOKEN": self.github_token}
+ )
+
+ output = result.stdout
+ if result.stderr:
+ output += f"\nSTDERR: {result.stderr}"
+ if result.exit_code != 0:
+ output += f"\n(exit code: {result.exit_code})"
+ return output
+
+
+def create_git_tools(sandbox: BaseSandbox, github_token: str, workdir: str = "/home/user/repo"):
+ """
+ Create LangChain tools for git operations.
+
+ Returns a list of tools that can be bound to an LLM.
+ """
+ git = GitTools(sandbox, github_token, workdir)
+
+ @tool
+ async def git_clone(repo_url: str) -> str:
+ """Clone a GitHub repository. Returns the path to the cloned repo."""
+ return await git.clone_repo(repo_url)
+
+ @tool
+ async def git_create_branch(branch_name: str) -> str:
+ """Create and checkout a new git branch."""
+ await git.create_branch(branch_name)
+ return f"Created and checked out branch: {branch_name}"
+
+ @tool
+ async def git_commit(message: str) -> str:
+ """Stage all changes and commit with the given message."""
+ await git.commit(message)
+ return f"Committed changes: {message}"
+
+ @tool
+ async def git_push(branch_name: str) -> str:
+ """Push the branch to the remote repository."""
+ await git.push(branch_name)
+ return f"Pushed branch: {branch_name}"
+
+ @tool
+ async def git_create_pr(title: str, body: str, base: str = "main") -> str:
+ """Create a pull request. Returns the PR URL."""
+ return await git.create_pr(title, body, base)
+
+ @tool
+ async def git_diff() -> str:
+ """Get the current git diff showing all changes."""
+ return await git.get_diff()
+
+ @tool
+ async def git_status() -> str:
+ """Get the current git status."""
+ return await git.get_status()
+
+ @tool
+ async def fetch_github_issue(issue_number: int) -> str:
+ """Fetch a GitHub issue's content including title, body, and comments. Use this to understand what an issue is asking for before making changes."""
+ return await git.fetch_issue(issue_number)
+
+ @tool
+ async def fetch_github_pr(pr_number: int) -> str:
+ """Fetch a GitHub PR's content including title, body, and changed files."""
+ return await git.fetch_pr(pr_number)
+
+ @tool
+ async def run_gh_command(command: str) -> str:
+ """Run a GitHub CLI (gh) command with authentication. Example: 'issue list', 'pr list', 'repo view'. Do NOT include 'gh' prefix."""
+ return await git.run_gh_command(command)
+
+ return [git_clone, git_create_branch, git_commit, git_push, git_create_pr, git_diff, git_status, fetch_github_issue, fetch_github_pr, run_gh_command], git
diff --git a/examples/code-agent/src/tools/search.py b/examples/code-agent/src/tools/search.py
new file mode 100644
index 00000000..703a0b7a
--- /dev/null
+++ b/examples/code-agent/src/tools/search.py
@@ -0,0 +1,121 @@
+"""Semantic search tools using FAISS indexes."""
+
+import logging
+from typing import Optional
+from langchain_core.tools import tool
+
+from src.indexer.repo_manager import RepoManager
+
+logger = logging.getLogger(__name__)
+
+# Global repo manager instance
+_repo_manager: Optional[RepoManager] = None
+
+
+def get_repo_manager() -> RepoManager:
+ """Get or create the repo manager instance."""
+ global _repo_manager
+ if _repo_manager is None:
+ _repo_manager = RepoManager()
+ return _repo_manager
+
+
+def create_search_tools(repo_name: str):
+ """
+ Create semantic search tools for a specific repository.
+
+ Args:
+ repo_name: Repository name (owner/repo format)
+
+ Returns:
+ List of LangChain tools for semantic search
+ """
+ manager = get_repo_manager()
+ repo = manager.get_repo_by_name(repo_name)
+
+ if not repo:
+ logger.warning(f"Repository {repo_name} not found in index")
+ return []
+
+ if repo.index_status != "indexed":
+ logger.warning(f"Repository {repo_name} is not indexed (status: {repo.index_status})")
+ return []
+
+ @tool
+ def semantic_search(query: str, top_k: int = 10) -> str:
+ """
+ Search the codebase semantically to find relevant code.
+
+ This is much faster than grep for finding conceptually related code.
+ Use this to find code related to a feature, bug, or concept.
+
+ Args:
+ query: Natural language description of what you're looking for
+ top_k: Number of results to return (default 10)
+
+ Returns:
+ Relevant code snippets with file paths and line numbers
+ """
+ results = manager.search(repo.id, query, top_k)
+
+ if not results:
+ return "No relevant code found."
+
+ output = []
+ for i, result in enumerate(results, 1):
+ output.append(f"### Result {i} (score: {result['score']:.3f})")
+ output.append(f"**File:** {result['file_path']}")
+ output.append(f"**Lines:** {result['start_line']}-{result['end_line']}")
+ output.append(f"```{result['language']}")
+ output.append(result['content'])
+ output.append("```\n")
+
+ return "\n".join(output)
+
+ @tool
+ def find_similar_code(file_path: str, description: str) -> str:
+ """
+ Find code similar to a description or concept.
+
+ Useful for finding implementations of similar features,
+ patterns, or understanding how things are done elsewhere.
+
+ Args:
+ file_path: File to use as context (or "none" to skip)
+ description: Description of the code pattern to find
+
+ Returns:
+ Similar code snippets from the codebase
+ """
+ # Combine file context with description if provided
+ if file_path and file_path.lower() != "none":
+ query = f"In {file_path}: {description}"
+ else:
+ query = description
+
+ results = manager.search(repo.id, query, top_k=5)
+
+ if not results:
+ return "No similar code found."
+
+ output = ["Found similar code patterns:\n"]
+ for result in results:
+ output.append(f"- **{result['file_path']}** (lines {result['start_line']}-{result['end_line']})")
+ # Show just first few lines
+ preview = result['content'].split('\n')[:5]
+ output.append(" ```")
+ output.append(" " + "\n ".join(preview))
+ if len(result['content'].split('\n')) > 5:
+ output.append(" ...")
+ output.append(" ```")
+
+ return "\n".join(output)
+
+ return [semantic_search, find_similar_code]
+
+
+def check_index_available(repo_name: str) -> bool:
+ """Check if an index is available for a repository."""
+ manager = get_repo_manager()
+ repo = manager.get_repo_by_name(repo_name)
+ return repo is not None and repo.index_status == "indexed"
diff --git a/examples/code-agent/src/ui/__init__.py b/examples/code-agent/src/ui/__init__.py
new file mode 100644
index 00000000..651ca306
--- /dev/null
+++ b/examples/code-agent/src/ui/__init__.py
@@ -0,0 +1 @@
+"""UI module."""
diff --git a/examples/code-agent/src/ui/app.py b/examples/code-agent/src/ui/app.py
new file mode 100644
index 00000000..e3e2cdc7
--- /dev/null
+++ b/examples/code-agent/src/ui/app.py
@@ -0,0 +1,562 @@
+"""Streamlit UI for the coding agent."""
+
+import streamlit as st
+import httpx
+import time
+from datetime import datetime
+
+# Configuration
+API_URL = "http://localhost:8000"
+
+st.set_page_config(
+ page_title="Code Agent",
+ page_icon="🤖",
+ layout="wide",
+)
+
+# Custom CSS
+st.markdown("""
+<style>
+ .stTextArea textarea {
+ font-family: monospace;
+ }
+ .log-container {
+ background-color: #1e1e1e;
+ color: #d4d4d4;
+ padding: 1rem;
+ border-radius: 0.5rem;
+ font-family: monospace;
+ font-size: 0.85rem;
+ max-height: 400px;
+ overflow-y: auto;
+ }
+ .status-badge {
+ padding: 0.25rem 0.5rem;
+ border-radius: 0.25rem;
+ font-weight: bold;
+ }
+ .status-pending { background-color: #ffc107; color: black; }
+ .status-running { background-color: #17a2b8; color: white; }
+ .status-completed { background-color: #28a745; color: white; }
+ .status-failed { background-color: #dc3545; color: white; }
+ .repo-card {
+ border: 1px solid #ddd;
+ border-radius: 8px;
+ padding: 12px;
+ margin-bottom: 8px;
+ }
+</style>
+""", unsafe_allow_html=True)
+
+# Header
+st.title("🤖 Code Agent")
+st.markdown("*LangGraph-powered coding agent with sandboxed execution*")
+
+# Create tabs for different sections
+tab1, tab2 = st.tabs(["📝 Tasks", "📂 Repositories"])
+
+# Import repo manager for the repositories tab
+try:
+ from src.indexer.repo_manager import RepoManager
+ repo_manager = RepoManager()
+ REPO_MANAGER_AVAILABLE = True
+except ImportError:
+ REPO_MANAGER_AVAILABLE = False
+ repo_manager = None
+
+
+# Sidebar for configuration
+with st.sidebar:
+ st.header("⚙️ Configuration")
+
+ llm_provider = st.selectbox(
+ "LLM Provider",
+ ["anthropic", "openai"],
+ index=0,
+ help="Select the LLM provider to use"
+ )
+
+ # Model selection based on provider
+ model_options = {
+ "anthropic": [
+ ("", "Default (Claude Sonnet 4.5)"),
+ ("claude-sonnet-4-5-20250929", "Claude Sonnet 4.5 - Best for coding"),
+ ("claude-haiku-4-5-20251001", "Claude Haiku 4.5 - Fastest"),
+ ("claude-opus-4-5-20251101", "Claude Opus 4.5 - Most intelligent"),
+ ],
+ "openai": [
+ ("", "Default (GPT-5.2)"),
+ ("gpt-5.2", "GPT-5.2 - Latest, best for coding"),
+ ("gpt-5-mini", "GPT-5 mini - Fast, cost-efficient"),
+ ("gpt-5-nano", "GPT-5 nano - Fastest, cheapest"),
+ ("gpt-4.1", "GPT-4.1 - Smart non-reasoning"),
+ ("gpt-4o", "GPT-4o - Fast, flexible"),
+ ("gpt-4o-mini", "GPT-4o mini - Affordable"),
+ ],
+ }
+
+ available_models = model_options.get(llm_provider, [])
+ model_display = [m[1] for m in available_models]
+ model_values = [m[0] for m in available_models]
+
+ selected_model_idx = st.selectbox(
+ "Model",
+ range(len(model_display)),
+ format_func=lambda i: model_display[i],
+ help="Select specific model (or use provider default)"
+ )
+ selected_model = model_values[selected_model_idx] if selected_model_idx else ""
+
+ st.divider()
+
+ # Sandbox provider selection
+ sandbox_provider = st.selectbox(
+ "Sandbox Provider",
+ ["opensandbox", "e2b"],
+ index=0,
+ help="OpenSandbox (local) or E2B (cloud)"
+ )
+
+ if sandbox_provider == "opensandbox":
+ st.caption("🖥️ Using local OpenSandbox (localhost:8080)")
+ else:
+ st.caption("☁️ Using E2B cloud sandbox")
+
+ st.divider()
+
+ # Iterations slider
+ max_iterations = st.slider(
+ "Max Iterations",
+ min_value=10,
+ max_value=200,
+ value=50,
+ step=10,
+ help="Maximum number of LLM tool-calling iterations"
+ )
+
+ st.divider()
+
+ st.header("📋 Recent Tasks")
+
+ # Fetch recent tasks
+ try:
+ response = httpx.get(f"{API_URL}/tasks", timeout=5)
+ if response.status_code == 200:
+ recent_tasks = response.json()
+ for task in recent_tasks[:5]:
+ status = task["status"]
+ status_color = {
+ "pending": "🟡",
+ "running": "🔵",
+ "completed": "🟢",
+ "failed": "🔴",
+ "cancelled": "⚪"
+ }.get(status, "⚪")
+
+ with st.expander(f"{status_color} {task['task'][:30]}..."):
+ st.text(f"ID: {task['task_id'][:8]}...")
+ st.text(f"Repo: {task['repo_url']}")
+ if task.get("pr_url"):
+ st.markdown(f"[View PR]({task['pr_url']})")
+ else:
+ st.info("No recent tasks")
+ except Exception:
+ st.warning("API not available")
+
+
+# Tab 1: Tasks
+with tab1:
+ col1, col2 = st.columns([1, 1])
+
+ with col1:
+ st.header("📝 New Task")
+
+ # Get list of indexed repos for dropdown
+ indexed_repos = []
+ if REPO_MANAGER_AVAILABLE and repo_manager:
+ repos = repo_manager.list_repos()
+ indexed_repos = [r for r in repos if r.index_status == "indexed"]
+
+ # Option to use indexed repo or enter URL
+ use_indexed_repo = st.checkbox(
+ "Use indexed repository",
+ value=len(indexed_repos) > 0,
+ help="Select from pre-indexed repos for faster search"
+ )
+
+ if use_indexed_repo and indexed_repos:
+ repo_options = {r.name: r.url for r in indexed_repos}
+ selected_repo_name = st.selectbox(
+ "Repository",
+ options=list(repo_options.keys()),
+ help="Select a pre-indexed repository"
+ )
+ repo_url = repo_options.get(selected_repo_name, "")
+ st.caption(f"✅ Semantic search enabled ({indexed_repos[0].chunk_count} chunks indexed)")
+ else:
+ repo_url = st.text_input(
+ "Repository URL",
+ placeholder="https://github.com/owner/repo",
+ help="GitHub repository URL to work on"
+ )
+ if repo_url:
+ st.caption("⚠️ No index - agent will use grep-based search")
+
+ task_description = st.text_area(
+ "Task Description",
+ placeholder="Describe what you want the agent to do...\n\nExamples:\n- Fix issue #123\n- Add unit tests for the auth module\n- Refactor the database connection code",
+ height=150,
+ help="Describe the task for the agent"
+ )
+
+ with st.expander("🔐 Authentication & Branch Settings"):
+ github_token = st.text_input(
+ "GitHub Token",
+ type="password",
+ help="Personal access token with repo permissions"
+ )
+
+ branch_name = st.text_input(
+ "Branch Name (optional)",
+ placeholder="agent/my-feature",
+ help="Custom branch name (auto-generated if empty)"
+ )
+
+ base_branch = st.text_input(
+ "Base Branch (optional)",
+ placeholder="main, develop, master...",
+ help="Branch to base PR against (auto-detected from repo if empty)"
+ )
+
+ submit_col1, submit_col2 = st.columns([1, 1])
+
+ with submit_col1:
+ submit_button = st.button("🚀 Start Task", type="primary", use_container_width=True)
+
+ with submit_col2:
+ if st.button("🔄 Check API", use_container_width=True):
+ try:
+ response = httpx.get(f"{API_URL}/health", timeout=5)
+ if response.status_code == 200:
+ st.success("API is healthy!")
+ else:
+ st.error("API returned error")
+ except Exception as e:
+ st.error(f"Cannot connect to API: {e}")
+
+ with col2:
+ st.header("📊 Task Status")
+
+ # Task ID input for checking status
+ check_task_id = st.text_input(
+ "Task ID",
+ placeholder="Enter task ID to check status",
+ key="check_task_id"
+ )
+
+ # Session state for current task
+ if "current_task_id" not in st.session_state:
+ st.session_state.current_task_id = None
+
+ # Use either the input task ID or the current session task
+ active_task_id = check_task_id or st.session_state.current_task_id
+
+ if active_task_id:
+ try:
+ response = httpx.get(f"{API_URL}/task/{active_task_id}", timeout=10)
+ if response.status_code == 200:
+ task_data = response.json()
+
+ # Status display
+ status = task_data["status"]
+ status_emoji = {
+ "pending": "🟡",
+ "running": "🔵",
+ "completed": "🟢",
+ "failed": "🔴",
+ "cancelled": "⚪"
+ }.get(status, "⚪")
+
+ st.markdown(f"### Status: {status_emoji} {status.upper()}")
+
+ # Extract sandbox provider from logs
+ logs = task_data.get("logs", [])
+ sandbox_used = "unknown"
+ for log in logs:
+ if "Creating opensandbox" in log:
+ sandbox_used = "opensandbox"
+ break
+ elif "Creating e2b" in log:
+ sandbox_used = "e2b"
+ break
+
+ info_cols = st.columns(3)
+ with info_cols[0]:
+ st.text(f"Repository: {task_data['repo_url']}")
+ with info_cols[1]:
+ st.text(f"Branch: {task_data.get('branch_name', 'N/A')}")
+ with info_cols[2]:
+ sandbox_icon = "🖥️" if sandbox_used == "opensandbox" else "☁️"
+ st.text(f"Sandbox: {sandbox_icon} {sandbox_used}")
+
+ if task_data.get("pr_url"):
+ st.success(f"✅ PR Created!")
+ st.markdown(f"[🔗 View Pull Request]({task_data['pr_url']})")
+
+ if task_data.get("error"):
+ st.error(f"Error: {task_data['error']}")
+
+ # Parse timing metrics from logs (logs already fetched above)
+ import re
+ timings = {}
+ for log in logs:
+ # Parse "Sandbox created: abc (1.2s)"
+ if "Sandbox created:" in log:
+ match = re.search(r'\((\d+\.?\d*)s\)', log)
+ if match:
+ timings["sandbox"] = float(match.group(1))
+ # Parse "GitHub authentication configured (0.3s)"
+ elif "authentication configured" in log:
+ match = re.search(r'\((\d+\.?\d*)s\)', log)
+ if match:
+ timings["auth"] = float(match.group(1))
+ # Parse "Repository cloned (14.2s)"
+ elif "Repository cloned" in log:
+ match = re.search(r'\((\d+\.?\d*)s\)', log)
+ if match:
+ timings["clone"] = float(match.group(1))
+ # Parse "Setup complete in 15.8s"
+ elif "Setup complete in" in log:
+ match = re.search(r'in (\d+\.?\d*)s', log)
+ if match:
+ timings["total_setup"] = float(match.group(1))
+
+ # Display timing metrics if available
+ if timings:
+ st.subheader("⏱️ Performance Metrics")
+ metric_cols = st.columns(4)
+ with metric_cols[0]:
+ if "sandbox" in timings:
+ st.metric("Sandbox Spin-up", f"{timings['sandbox']:.1f}s")
+ with metric_cols[1]:
+ if "auth" in timings:
+ st.metric("Git Auth", f"{timings['auth']:.1f}s")
+ with metric_cols[2]:
+ if "clone" in timings:
+ st.metric("Clone", f"{timings['clone']:.1f}s")
+ with metric_cols[3]:
+ if "total_setup" in timings:
+ st.metric("Total Setup", f"{timings['total_setup']:.1f}s")
+
+ # Logs
+ st.subheader("📜 Logs")
+ if logs:
+ log_text = "\n".join(logs)
+ st.code(log_text, language="text")
+ else:
+ st.info("No logs yet...")
+
+ # Auto-refresh for running tasks
+ if status == "running":
+ time.sleep(2)
+ st.rerun()
+
+ elif response.status_code == 404:
+ st.warning("Task not found")
+ else:
+ st.error(f"Error fetching task: {response.status_code}")
+
+ except Exception as e:
+ st.error(f"Error: {e}")
+ else:
+ st.info("Submit a task or enter a task ID to see status")
+
+ # Handle task submission
+ if submit_button:
+ if not repo_url:
+ st.error("Please enter a repository URL")
+ elif not task_description:
+ st.error("Please enter a task description")
+ elif not github_token:
+ st.error("Please enter your GitHub token")
+ else:
+ try:
+ payload = {
+ "repo_url": repo_url,
+ "task": task_description,
+ "github_token": github_token,
+ "llm_provider": llm_provider,
+ "sandbox_provider": sandbox_provider,
+ "max_iterations": max_iterations,
+ }
+ if selected_model:
+ payload["model"] = selected_model
+ if branch_name:
+ payload["branch_name"] = branch_name
+ if base_branch:
+ payload["base_branch"] = base_branch
+
+ response = httpx.post(
+ f"{API_URL}/task",
+ json=payload,
+ timeout=30
+ )
+
+ if response.status_code == 200:
+ result = response.json()
+ st.session_state.current_task_id = result["task_id"]
+ st.success(f"Task created! ID: {result['task_id']}")
+ st.rerun()
+ else:
+ st.error(f"Failed to create task: {response.text}")
+
+ except Exception as e:
+ st.error(f"Error submitting task: {e}")
+
+
+# Tab 2: Repositories
+with tab2:
+ st.header("📂 Repository Management")
+ st.markdown("Index repositories for faster semantic search during tasks.")
+
+ if not REPO_MANAGER_AVAILABLE:
+ st.error("Repository manager not available. Make sure dependencies are installed: `pip install faiss-cpu openai numpy`")
+ else:
+ # Add new repository
+ st.subheader("➕ Add Repository")
+
+ col1, col2 = st.columns([3, 1])
+ with col1:
+ new_repo_url = st.text_input(
+ "Repository URL",
+ placeholder="https://github.com/owner/repo or owner/repo",
+ key="new_repo_url"
+ )
+ with col2:
+ add_repo_button = st.button("Add Repository", type="primary", use_container_width=True)
+
+ if add_repo_button and new_repo_url:
+ with st.spinner("Cloning repository..."):
+ try:
+ repo_info = repo_manager.add_repo(new_repo_url)
+ st.success(f"Added repository: {repo_info.name}")
+ st.rerun()
+ except Exception as e:
+ st.error(f"Failed to add repository: {e}")
+
+ st.divider()
+
+ # List repositories
+ st.subheader("📋 Indexed Repositories")
+
+ repos = repo_manager.list_repos()
+
+ if not repos:
+ st.info("No repositories added yet. Add a repository above to get started.")
+ else:
+ for repo in repos:
+ with st.container():
+ col1, col2, col3 = st.columns([3, 1, 1])
+
+ with col1:
+ status_icon = {
+ "indexed": "✅",
+ "indexing": "⏳",
+ "not_indexed": "⚪",
+ "error": "❌"
+ }.get(repo.index_status, "❓")
+
+ st.markdown(f"### {status_icon} {repo.name}")
+ st.caption(f"URL: {repo.url}")
+
+ if repo.index_status == "indexed":
+ st.caption(f"📊 {repo.chunk_count} chunks indexed")
+ if repo.last_indexed:
+ st.caption(f"🕐 Last indexed: {repo.last_indexed.strftime('%Y-%m-%d %H:%M')}")
+ elif repo.index_status == "error":
+ st.caption("❌ Indexing failed")
+
+ with col2:
+ if repo.index_status == "not_indexed":
+ if st.button("🔨 Build Index", key=f"build_{repo.id}", use_container_width=True):
+ with st.spinner(f"Building index for {repo.name}..."):
+ try:
+ repo_manager.build_index(repo.id)
+ st.success("Index built successfully!")
+ st.rerun()
+ except Exception as e:
+ st.error(f"Failed to build index: {e}")
+ elif repo.index_status == "indexed":
+ if st.button("🔄 Rebuild", key=f"rebuild_{repo.id}", use_container_width=True):
+ with st.spinner(f"Rebuilding index for {repo.name}..."):
+ try:
+ repo_manager.build_index(repo.id)
+ st.success("Index rebuilt successfully!")
+ st.rerun()
+ except Exception as e:
+ st.error(f"Failed to rebuild index: {e}")
+ elif repo.index_status == "indexing":
+ st.button("⏳ Indexing...", key=f"indexing_{repo.id}", disabled=True, use_container_width=True)
+ elif repo.index_status == "error":
+ if st.button("🔄 Retry", key=f"retry_{repo.id}", use_container_width=True):
+ with st.spinner(f"Retrying index for {repo.name}..."):
+ try:
+ repo_manager.build_index(repo.id)
+ st.success("Index built successfully!")
+ st.rerun()
+ except Exception as e:
+ st.error(f"Failed to build index: {e}")
+
+ with col3:
+ if st.button("🗑️ Delete", key=f"delete_{repo.id}", use_container_width=True):
+ repo_manager.delete_repo(repo.id)
+ st.success(f"Deleted {repo.name}")
+ st.rerun()
+
+ st.divider()
+
+ # Search test section
+ if repos:
+ st.subheader("🔍 Test Semantic Search")
+
+ indexed_repos = [r for r in repos if r.index_status == "indexed"]
+ if indexed_repos:
+ search_repo = st.selectbox(
+ "Repository",
+ options=[r.name for r in indexed_repos],
+ key="search_repo"
+ )
+
+ search_query = st.text_input(
+ "Search Query",
+ placeholder="e.g., authentication handling, database connection, error handling",
+ key="search_query"
+ )
+
+ if st.button("🔍 Search", use_container_width=False):
+ if search_query:
+ repo = next(r for r in indexed_repos if r.name == search_repo)
+ with st.spinner("Searching..."):
+ results = repo_manager.search(repo.id, search_query, top_k=5)
+
+ if results:
+ st.success(f"Found {len(results)} results")
+ for i, result in enumerate(results, 1):
+ with st.expander(f"Result {i}: {result['file_path']} (score: {result['score']:.3f})"):
+ st.caption(f"Lines {result['start_line']}-{result['end_line']}")
+ st.code(result['content'], language=result['language'])
+ else:
+ st.warning("No results found")
+ else:
+ st.warning("Enter a search query")
+ else:
+ st.info("No indexed repositories available. Build an index first.")
+
+
+# Footer
+st.divider()
+st.markdown("""
+<div style="text-align: center; color: #666;">
+ <small>Code Agent v0.1.0 | Powered by LangGraph + E2B + FAISS</small>
+</div>
+""", unsafe_allow_html=True)
diff --git a/examples/code-agent/tests/__init__.py b/examples/code-agent/tests/__init__.py
new file mode 100644
index 00000000..fc86f5ee
--- /dev/null
+++ b/examples/code-agent/tests/__init__.py
@@ -0,0 +1 @@
+"""Tests for the code agent."""
diff --git a/examples/code-agent/tests/test_sandbox.py b/examples/code-agent/tests/test_sandbox.py
new file mode 100644
index 00000000..bcfcfd65
--- /dev/null
+++ b/examples/code-agent/tests/test_sandbox.py
@@ -0,0 +1,67 @@
+"""Tests for sandbox functionality."""
+
+import pytest
+from src.sandbox import get_sandbox, BaseSandbox, E2BSandbox
+
+
+def test_get_sandbox_e2b():
+ """Test that get_sandbox returns E2BSandbox for 'e2b' provider."""
+ sandbox = get_sandbox("e2b")
+ assert isinstance(sandbox, E2BSandbox)
+ assert isinstance(sandbox, BaseSandbox)
+
+
+def test_get_sandbox_unknown_provider():
+ """Test that get_sandbox raises for unknown provider."""
+ with pytest.raises(ValueError, match="Unknown sandbox provider"):
+ get_sandbox("unknown")
+
+
+def test_sandbox_not_active_initially():
+ """Test that sandbox is not active before create() is called."""
+ sandbox = E2BSandbox()
+ assert not sandbox.is_active
+ assert sandbox.sandbox_id is None
+
+
+# Integration tests (require E2B API key)
+async def test_sandbox_create_and_destroy():
+ """Test creating and destroying a sandbox."""
+ sandbox = E2BSandbox()
+
+ try:
+ sandbox_id = await sandbox.create(timeout=300)
+ assert sandbox_id is not None
+ assert sandbox.is_active
+
+ # Test running a command
+ result = await sandbox.run_command("echo 'hello world'")
+ assert result.exit_code == 0
+ assert "hello world" in result.stdout
+
+ finally:
+ await sandbox.destroy()
+ assert not sandbox.is_active
+
+
+async def test_sandbox_file_operations():
+ """Test file read/write in sandbox."""
+ sandbox = E2BSandbox()
+
+ try:
+ await sandbox.create(timeout=300)
+
+ # Write a file
+ test_content = "Hello, World!"
+ await sandbox.write_file("/tmp/test.txt", test_content)
+
+ # Read it back
+ content = await sandbox.read_file("/tmp/test.txt")
+ assert content == test_content
+
+ finally:
+ await sandbox.destroy()