Skip to content

armgit / cua

Public Imported from GitHub
0

Scale computer-use 2.0 with open-source drivers, cross-OS sandboxes, and benchmarks for training, evaluation, and data generation.

docs: update custom agent guides to match actual BaseAgent interface (#1158)

ddupontf90eadc1ef9c
diff --git a/docs/content/docs/cuabench/examples/custom-agent.mdx b/docs/content/docs/cuabench/examples/custom-agent.mdx
index ad2c44ced1..87d4342739 100644
--- a/docs/content/docs/cuabench/examples/custom-agent.mdx
+++ b/docs/content/docs/cuabench/examples/custom-agent.mdx
@@ -1,148 +1,34 @@
---
title: Build a Custom Agent
-description: Create your own agent to solve computer-use tasks
+description: Add your own agent to cua-bench
---
-In this tutorial, you'll build a custom agent that can interact with desktop environments. You'll start with a simple rule-based agent and progressively add intelligence.
+# Build a Custom Agent
-**Time:** ~20 minutes
-**Prerequisites:** cua-bench installed, basic Python knowledge
+Add a custom agent to cua-bench by extending `BaseAgent` and registering it.
-## What You'll Build
+## 1. Create your agent file
-A custom agent that can:
-
-1. Take screenshots of the desktop
-2. Analyze what it sees
-3. Decide on actions (click, type, etc.)
-4. Execute those actions
-
-## Agent Architecture
-
-Every agent in cua-bench extends the `BaseAgent` class and implements the `perform_task()` method:
+Create `cua_bench/agents/my_agent.py`:
```python
-from cua_bench.agents import BaseAgent, AgentResult
-
-class MyAgent(BaseAgent):
- @staticmethod
- def name() -> str:
- return "my-agent"
-
- async def perform_task(
- self,
- task_description: str,
- session: DesktopSession,
- logging_dir: Path | None = None,
- ) -> AgentResult:
- # Your agent logic here
- pass
-```
-
-## Step 1: Scaffold the Agent
-
-Use the CLI to create the agent structure:
-
-```bash
-cb agent init my-agent --output-dir ./agents
-```
-
-This creates:
-
-```
-agents/
-├── __init__.py
-├── agent.py
-└── requirements.txt
-```
-
-## Step 2: Implement a Basic Agent
-
-Edit `agents/agent.py`:
-
-```python
-import cua_bench as cb
-from cua_bench.agents import BaseAgent, AgentResult, FailureMode
+import base64
from pathlib import Path
+from typing import TYPE_CHECKING
+from . import register_agent
+from .base import AgentResult, BaseAgent, FailureMode
-class MyAgent(BaseAgent):
- """A simple rule-based agent."""
-
- @staticmethod
- def name() -> str:
- return "my-agent"
-
- async def perform_task(
- self,
- task_description: str,
- session: cb.DesktopSession,
- logging_dir: Path | None = None,
- ) -> AgentResult:
- """Perform the task by taking screenshots and clicking."""
-
- # Step 1: Take a screenshot
- screenshot = await session.screenshot()
-
- # Step 2: Simple strategy - click the center of the screen
- # (We'll make this smarter later)
- center_x = 256
- center_y = 256
-
- await session.execute_action(cb.ClickAction(x=center_x, y=center_y))
-
- # Return result with token counts (for cost tracking)
- return AgentResult(
- total_input_tokens=0,
- total_output_tokens=0,
- failure_mode=FailureMode.NONE
- )
-```
-
-This basic agent just clicks the center of the screen—not very smart, but it's a starting point!
-
-## Step 3: Register the Agent
-
-Create or edit `.cua/agents.yaml` in your project root:
-
-```yaml
-agents:
- - name: my-agent
- import_path: agents.agent:MyAgent
- defaults:
- max_steps: 20
-```
-
-## Step 4: Test the Agent
-
-Run the agent against a simple task:
-
-```bash
-# First, create a simple button task (from previous example)
-# Then run your agent against it
-
-cb run task tasks/my-button-task --agent my-agent
-```
-
-The agent will click the center—which probably won't hit the button. Let's make it smarter.
-
-## Step 5: Add Screenshot Analysis
-
-Now let's add actual intelligence. We'll use a simple approach: look for elements and click them.
-
-```python
-import cua_bench as cb
-from cua_bench.agents import BaseAgent, AgentResult, FailureMode
-from pathlib import Path
-import base64
+if TYPE_CHECKING:
+ from ..computers import DesktopSession
+@register_agent("my-agent")
class MyAgent(BaseAgent):
- """An agent that analyzes screenshots to find targets."""
-
def __init__(self, **kwargs):
super().__init__(**kwargs)
- self.max_steps = kwargs.get("max_steps", 20)
+ self.model = kwargs.get("model", "claude-sonnet-4-20250514")
+ self.max_steps = int(kwargs.get("max_steps", 50))
@staticmethod
def name() -> str:
@@ -151,427 +37,102 @@ class MyAgent(BaseAgent):
async def perform_task(
self,
task_description: str,
- session: cb.DesktopSession,
+ session: "DesktopSession",
logging_dir: Path | None = None,
+ tracer=None,
) -> AgentResult:
- """Perform task with screenshot analysis."""
+ instruction = self._render_instruction(task_description)
- total_input_tokens = 0
- total_output_tokens = 0
+ total_input = 0
+ total_output = 0
for step in range(self.max_steps):
- # Take screenshot
screenshot_bytes = await session.screenshot()
- # Save screenshot for debugging
if logging_dir:
- screenshot_path = logging_dir / f"step_{step}.png"
- screenshot_path.write_bytes(screenshot_bytes)
-
- # Analyze and decide action
- action = await self._decide_action(
- task_description,
- screenshot_bytes,
- step
- )
+ (logging_dir / f"step_{step}.png").write_bytes(screenshot_bytes)
- if action is None:
- # Agent thinks task is complete
- break
+ # Your logic: send screenshot to an LLM, parse action, etc.
+ # action = await self._decide(instruction, screenshot_bytes)
- # Execute the action
- await session.execute_action(action)
+ # if action is None:
+ # break
+ # await session.execute_action(action)
return AgentResult(
- total_input_tokens=total_input_tokens,
- total_output_tokens=total_output_tokens,
- failure_mode=FailureMode.NONE
+ total_input_tokens=total_input,
+ total_output_tokens=total_output,
+ failure_mode=FailureMode.NONE,
)
-
- async def _decide_action(
- self,
- task_description: str,
- screenshot: bytes,
- step: int
- ) -> cb.Action | None:
- """Decide what action to take based on the screenshot."""
-
- # For now, use a simple heuristic:
- # Click slightly below center where buttons often are
- if step == 0:
- return cb.ClickAction(x=256, y=300)
-
- # After first click, assume done
- return None
```
-## Step 6: Integrate with an LLM
+## 2. Register the import
-For real intelligence, integrate with a language model. Here's an example using Anthropic's Claude:
+Add one line to `cua_bench/agents/__init__.py`:
```python
-import anthropic
-import cua_bench as cb
-from cua_bench.agents import BaseAgent, AgentResult, FailureMode
-from pathlib import Path
-import base64
-
-
-class MyAgent(BaseAgent):
- """An LLM-powered agent."""
-
- def __init__(self, **kwargs):
- super().__init__(**kwargs)
- self.model = kwargs.get("model", "claude-sonnet-4-20250514")
- self.max_steps = kwargs.get("max_steps", 20)
- self.client = anthropic.Anthropic()
-
- @staticmethod
- def name() -> str:
- return "my-agent"
-
- async def perform_task(
- self,
- task_description: str,
- session: cb.DesktopSession,
- logging_dir: Path | None = None,
- ) -> AgentResult:
- """Perform task using LLM for decisions."""
-
- total_input_tokens = 0
- total_output_tokens = 0
-
- for step in range(self.max_steps):
- # Take screenshot
- screenshot_bytes = await session.screenshot()
-
- # Ask LLM what to do
- action, input_tokens, output_tokens = await self._ask_llm(
- task_description,
- screenshot_bytes
- )
-
- total_input_tokens += input_tokens
- total_output_tokens += output_tokens
-
- if action is None:
- break
-
- await session.execute_action(action)
-
- return AgentResult(
- total_input_tokens=total_input_tokens,
- total_output_tokens=total_output_tokens,
- failure_mode=FailureMode.NONE
- )
-
- async def _ask_llm(
- self,
- task_description: str,
- screenshot: bytes
- ) -> tuple[cb.Action | None, int, int]:
- """Ask the LLM what action to take."""
-
- # Encode screenshot as base64
- screenshot_b64 = base64.standard_b64encode(screenshot).decode()
-
- response = self.client.messages.create(
- model=self.model,
- max_tokens=1024,
- messages=[{
- "role": "user",
- "content": [
- {
- "type": "image",
- "source": {
- "type": "base64",
- "media_type": "image/png",
- "data": screenshot_b64,
- }
- },
- {
- "type": "text",
- "text": f"""Task: {task_description}
-
-Look at this screenshot and decide what action to take.
-
-Respond with ONE of:
-- CLICK x y (to click at coordinates)
-- TYPE text (to type text)
-- DONE (if task is complete)
-
-Example: CLICK 150 200"""
- }
- ]
- }]
- )
-
- # Parse response
- response_text = response.content[0].text.strip()
- action = self._parse_action(response_text)
-
- return (
- action,
- response.usage.input_tokens,
- response.usage.output_tokens
- )
-
- def _parse_action(self, response: str) -> cb.Action | None:
- """Parse LLM response into an action."""
-
- if response.startswith("DONE"):
- return None
-
- if response.startswith("CLICK"):
- parts = response.split()
- if len(parts) >= 3:
- x, y = int(parts[1]), int(parts[2])
- return cb.ClickAction(x=x, y=y)
-
- if response.startswith("TYPE"):
- text = response[5:].strip()
- return cb.TypeAction(text=text)
-
- # Default: no action
- return None
+from .my_agent import MyAgent # noqa: E402
```
-## Step 7: Run with Custom Model
-
-Update your agent registration to accept model configuration:
-
-```yaml
-agents:
- - name: my-agent
- import_path: agents.agent:MyAgent
- defaults:
- model: claude-sonnet-4-20250514
- max_steps: 20
-```
+This triggers `@register_agent("my-agent")` at import time.
-Then run:
+## 3. Run it
```bash
-export ANTHROPIC_API_KEY=sk-...
-cb run task tasks/my-button-task --agent my-agent
+cb run task tasks/my-task --agent my-agent
+cb run task tasks/my-task --agent my-agent --agent-kwarg model=gpt-4o --agent-kwarg max_steps=100
```
-## Advanced: Build a Docker Image
+## 4. Develop without rebuilding the Docker image
-For production use, package your agent as a Docker image:
-
-### Create Dockerfile
-
-```dockerfile
-FROM python:3.11-slim
-
-WORKDIR /app
-
-# Install dependencies
-COPY requirements.txt .
-RUN pip install --no-cache-dir -r requirements.txt
-
-# Copy agent code
-COPY agents/ ./agents/
-
-# Set entrypoint
-ENTRYPOINT ["python", "-m", "agents.agent"]
-```
-
-### Build and Push
+Use `--with` to mount your local cua-bench (or any local package) into the agent container:
```bash
-# Build
-docker build -t myregistry/my-agent:latest .
-
-# Push to registry
-cb agent push myregistry/my-agent:latest
-```
-
-### Register Docker Agent
-
-```yaml
-agents:
- - name: my-agent-docker
- image: myregistry/my-agent:latest
- defaults:
- model: claude-sonnet-4-20250514
- max_steps: 50
+cb run task tasks/my-task --agent my-agent --with ../libs/cua-bench
```
-## Available Actions
+This mounts the path into the container and runs `pip install` on it before the agent starts. You can repeat `--with` for multiple packages.
-Your agent can execute these actions via `session.execute_action()`:
+## Reference
-| Action | Description |
-| ---------------------------------------- | --------------------------------------------- |
-| `ClickAction(x, y)` | Single click at coordinates |
-| `RightClickAction(x, y)` | Right-click |
-| `DoubleClickAction(x, y)` | Double-click |
-| `DragAction(from_x, from_y, to_x, to_y)` | Drag from one point to another |
-| `TypeAction(text)` | Type text |
-| `KeyAction(key)` | Press a single key (e.g., "return", "escape") |
-| `HotkeyAction(keys)` | Press key combination (e.g., ["ctrl", "c"]) |
-| `ScrollAction(direction, amount)` | Scroll up/down |
-| `WaitAction(seconds)` | Wait for a duration |
+### BaseAgent interface
-## Complete Code
+| Method / Property | Description |
+| --- | --- |
+| `name()` (static, abstract) | Return the agent name string |
+| `perform_task(task_description, session, logging_dir, tracer)` (abstract) | Run the agent loop, return `AgentResult` |
+| `version` | Optional version string (set via `kwargs`) |
+| `_render_instruction(text)` | Render through a Jinja2 `prompt_template` if one was provided |
-<details>
-<summary>agents/agent.py (LLM-powered)</summary>
+### AgentResult
```python
-import anthropic
-import cua_bench as cb
-from cua_bench.agents import BaseAgent, AgentResult, FailureMode
-from pathlib import Path
-import base64
-
-
-class MyAgent(BaseAgent):
- """An LLM-powered computer-use agent."""
-
- def __init__(self, **kwargs):
- super().__init__(**kwargs)
- self.model = kwargs.get("model", "claude-sonnet-4-20250514")
- self.max_steps = kwargs.get("max_steps", 20)
- self.client = anthropic.Anthropic()
-
- @staticmethod
- def name() -> str:
- return "my-agent"
-
- async def perform_task(
- self,
- task_description: str,
- session: cb.DesktopSession,
- logging_dir: Path | None = None,
- ) -> AgentResult:
- """Perform task using LLM for decisions."""
-
- total_input_tokens = 0
- total_output_tokens = 0
-
- for step in range(self.max_steps):
- screenshot_bytes = await session.screenshot()
-
- if logging_dir:
- (logging_dir / f"step_{step}.png").write_bytes(screenshot_bytes)
-
- action, in_tokens, out_tokens = await self._ask_llm(
- task_description, screenshot_bytes
- )
-
- total_input_tokens += in_tokens
- total_output_tokens += out_tokens
-
- if action is None:
- break
-
- await session.execute_action(action)
-
- return AgentResult(
- total_input_tokens=total_input_tokens,
- total_output_tokens=total_output_tokens,
- failure_mode=FailureMode.NONE
- )
-
- async def _ask_llm(
- self, task_description: str, screenshot: bytes
- ) -> tuple[cb.Action | None, int, int]:
- """Ask the LLM what action to take."""
-
- screenshot_b64 = base64.standard_b64encode(screenshot).decode()
-
- response = self.client.messages.create(
- model=self.model,
- max_tokens=1024,
- messages=[{
- "role": "user",
- "content": [
- {
- "type": "image",
- "source": {
- "type": "base64",
- "media_type": "image/png",
- "data": screenshot_b64,
- }
- },
- {
- "type": "text",
- "text": f"""Task: {task_description}
-
-Look at this screenshot and decide what action to take.
-
-Respond with ONE of:
-- CLICK x y (to click at coordinates)
-- TYPE text (to type text)
-- KEY key (to press a key like "return")
-- DONE (if task is complete)
-
-Example: CLICK 150 200"""
- }
- ]
- }]
- )
-
- response_text = response.content[0].text.strip()
- action = self._parse_action(response_text)
-
- return (action, response.usage.input_tokens, response.usage.output_tokens)
-
- def _parse_action(self, response: str) -> cb.Action | None:
- """Parse LLM response into an action."""
-
- response = response.upper().strip()
-
- if response.startswith("DONE"):
- return None
-
- if response.startswith("CLICK"):
- parts = response.split()
- if len(parts) >= 3:
- return cb.ClickAction(x=int(parts[1]), y=int(parts[2]))
-
- if response.startswith("TYPE"):
- text = response[5:].strip()
- return cb.TypeAction(text=text)
-
- if response.startswith("KEY"):
- key = response[4:].strip().lower()
- return cb.KeyAction(key=key)
-
- return None
-```
-
-</details>
-
-<details>
-<summary>.cua/agents.yaml</summary>
-
-```yaml
-agents:
- - name: my-agent
- import_path: agents.agent:MyAgent
- defaults:
- model: claude-sonnet-4-20250514
- max_steps: 20
-```
-
-</details>
-
-<details>
-<summary>agents/requirements.txt</summary>
-
-```
-cua-bench
-anthropic>=0.20.0
-```
-
-</details>
-
-## Next Steps
-
-- Build a [Universal Task](/cuabench/examples/universal-task) with custom GUIs
-- See the [Custom Agents Guide](/cuabench/guide/advanced/custom-agents) for more details
-- Explore the [Adapters](/cuabench/guide/fundamentals/adapters) for benchmark integrations
+@dataclass
+class AgentResult:
+ total_input_tokens: int = 0
+ total_output_tokens: int = 0
+ failure_mode: FailureMode = FailureMode.UNSET # NONE, UNKNOWN, MAX_STEPS_EXCEEDED
+```
+
+### Available actions
+
+All importable from `cua_bench` (e.g. `from cua_bench import ClickAction`):
+
+| Action | Fields |
+| --- | --- |
+| `ClickAction` | `x, y` |
+| `RightClickAction` | `x, y` |
+| `DoubleClickAction` | `x, y` |
+| `MiddleClickAction` | `x, y` |
+| `DragAction` | `from_x, from_y, to_x, to_y, duration=1.0` |
+| `MoveToAction` | `x, y, duration=0.0` |
+| `ScrollAction` | `direction="up", amount=100` |
+| `TypeAction` | `text` |
+| `KeyAction` | `key` |
+| `HotkeyAction` | `keys` (list) |
+| `WaitAction` | `seconds=1.0` |
+| `DoneAction` | (none) |
+
+### kwargs
+
+All `--agent-kwarg` values from the CLI arrive as strings in `**kwargs`. Cast as needed (e.g. `int(kwargs.get("max_steps", 50))`). Built-in kwargs handled by `BaseAgent`: `version`, `prompt_template`.
diff --git a/docs/content/docs/cuabench/guide/advanced/custom-agents.mdx b/docs/content/docs/cuabench/guide/advanced/custom-agents.mdx
index b9d89f1028..87b8c59cbe 100644
--- a/docs/content/docs/cuabench/guide/advanced/custom-agents.mdx
+++ b/docs/content/docs/cuabench/guide/advanced/custom-agents.mdx
@@ -1,245 +1,86 @@
---
title: Custom Agents
-description: Define and run custom agents with Docker images or Python import paths
+description: Register and run custom agents in cua-bench
---
# Custom Agents
-Cua-Bench supports custom agents through the `.cua/agents.yaml` configuration file. Agents can be defined as Docker images (cloud-ready) or Python import paths (local development).
+## Adding an agent to the source
-## Architecture
+1. Create `cua_bench/agents/your_agent.py` — extend `BaseAgent`, decorate with `@register_agent("your-agent")`
+2. Add the import to `cua_bench/agents/__init__.py`
+3. Run with `cb run task <path> --agent your-agent`
-Cua-Bench uses a **2-container architecture** where the agent and environment run in separate Docker containers communicating via Docker network:
+See the [Build a Custom Agent](/cuabench/examples/custom-agent) example for full code.
-```
-┌─────────────────────────────────────────────────────────────┐
-│ Docker Network: cua-task-{id} │
-│ │
-│ ┌─────────────────────┐ ┌─────────────────────────────┐│
-│ │ cua-agent-{id} │ │ cua-env-{id} ││
-│ │ │ │ ││
-│ │ Your agent image │───►│ trycua/cua-qemu-windows ││
-│ │ (or default) │HTTP│ (or linux-docker, etc.) ││
-│ │ │ │ ││
-│ │ Runs your agent │ │ cua-computer-server:5000 ││
-│ └─────────────────────┘ └─────────────────────────────┘│
-└─────────────────────────────────────────────────────────────┘
-```
-
-This architecture mirrors cloud deployments (Cloud Run Jobs + Azure Batch) for consistent behavior between local and production.
-
-## Agent Configuration
+## Local registry (without modifying source)
-Create a `.cua/agents.yaml` file in your project:
+Register an agent via `.cua/agents.yaml` in your project root:
```yaml
-# .cua/agents.yaml
agents:
- # Built-in agents (use default cua-agent image)
- - name: cua-agent
- builtin: true
- defaults:
- model: anthropic/claude-sonnet-4-20250514
- max_steps: 50
-
- - name: gemini
- builtin: true
- defaults:
- model: gemini-2.0-flash
- max_steps: 50
-
- # Custom Docker image agent (cloud-ready)
- name: my-agent
- image: myregistry/my-agent:latest
- command: ['python', '-m', 'my_agent.main']
- defaults:
- model: gpt-4o
- max_steps: 100
-
- # Import path agent (local development)
- - name: dev-agent
- import_path: my_agents.custom:CustomAgent
+ import_path: my_package.agents:MyAgent
defaults:
model: claude-sonnet-4-20250514
+ max_steps: 50
```
-## Agent Types
-
-### 1. Docker Image Agents (Cloud-Ready)
-
-Best for production and CI/CD. Your agent is fully self-contained in a Docker image.
-
-```yaml
-- name: my-agent
- image: myregistry/my-agent:latest
- command: ['python', '-m', 'my_agent.main'] # Optional
- defaults:
- model: gpt-4o
-```
-
-Your Docker image can include **any dependencies** - the only requirement is that it can:
-
-1. Read environment variables (to know where to connect)
-2. Make HTTP requests (to communicate with the environment)
-
-### 2. Import Path Agents (Local Development)
-
-Best for rapid iteration during development. No Docker build needed.
-
-```yaml
-- name: dev-agent
- import_path: my_agents.custom:CustomAgent
-```
-
-The import path format is `module.path:ClassName`. Your agent class runs inside the default `trycua/cua-agent` container with your code mounted.
+The `import_path` format is `module.path:ClassName`. The module must be importable from the Python environment.
-### 3. Built-in Agents
+## Docker image agents
-Use the pre-configured agents without any setup:
+For production or CI, package your agent as a Docker image:
```yaml
-- name: cua-agent
- builtin: true
- defaults:
- model: anthropic/claude-sonnet-4-20250514
+agents:
+ - name: my-agent
+ image: myregistry/my-agent:latest
+ command: ['python', '-m', 'my_agent.main']
+ defaults:
+ model: gpt-4o
```
-## Environment Variables
-
-Custom Docker image agents receive these environment variables:
-
-| Variable | Description | Example |
-| ------------------- | ---------------------------- | ----------------------------- |
-| `CUA_ENV_API_URL` | API endpoint for environment | `http://cua-env:5000` |
-| `CUA_ENV_VNC_URL` | VNC endpoint for debugging | `http://cua-env:8006` |
-| `CUA_ENV_TYPE` | OS type | `linux`, `windows`, `android` |
-| `CUA_TASK_PATH` | Mounted task config path | `/app/env` |
-| `CUA_TASK_INDEX` | Task index to run | `0` |
-| `CUA_MODEL` | Model to use (if specified) | `gpt-4o` |
-| `ANTHROPIC_API_KEY` | Passed through from host | `sk-...` |
-| `OPENAI_API_KEY` | Passed through from host | `sk-...` |
-| `GOOGLE_API_KEY` | Passed through from host | `...` |
+The agent container receives these environment variables:
-## Building a Docker Image Agent
+| Variable | Description |
+| --- | --- |
+| `CUA_ENV_API_URL` | API endpoint for the environment container |
+| `CUA_ENV_VNC_URL` | VNC endpoint for debugging |
+| `CUA_ENV_TYPE` | OS type (`linux`, `windows`, `android`) |
+| `CUA_TASK_PATH` | Mounted task config path (`/app/env`) |
+| `CUA_TASK_INDEX` | Task index to run |
+| `CUA_MODEL` | Model override (if specified) |
+| `ANTHROPIC_API_KEY` | Passed through from host |
+| `OPENAI_API_KEY` | Passed through from host |
+| `GOOGLE_API_KEY` | Passed through from host |
-### Dockerfile
+## Development with `--with`
-```dockerfile
-FROM python:3.12-slim
-WORKDIR /app
-
-# Install any dependencies you need
-RUN pip install httpx pillow anthropic openai
-
-# Copy your agent code
-COPY my_agent/ /app/my_agent/
-
-# Entry point
-CMD ["python", "-m", "my_agent.main"]
-```
-
-### Agent Implementation
-
-```python
-# my_agent/main.py
-import os
-import base64
-import httpx
-from PIL import Image
-from io import BytesIO
-
-# Read environment variables
-API_URL = os.environ["CUA_ENV_API_URL"]
-TASK_INDEX = int(os.environ["CUA_TASK_INDEX"])
-
-def screenshot():
- """Get screenshot from environment."""
- r = httpx.post(f"{API_URL}/screenshot")
- b64 = r.json()["screenshot"]
- return Image.open(BytesIO(base64.b64decode(b64)))
-
-def click(x, y):
- """Click at coordinates."""
- httpx.post(f"{API_URL}/execute", json={
- "action": "click",
- "coordinate": [x, y]
- })
-
-def type_text(text):
- """Type text."""
- httpx.post(f"{API_URL}/execute", json={
- "action": "type",
- "text": text
- })
-
-def main():
- import anthropic
-
- client = anthropic.Anthropic()
-
- for step in range(50):
- img = screenshot()
-
- # Your agent logic here...
- # Call LLM, parse response, execute action
-
- response = client.messages.create(
- model="claude-sonnet-4-20250514",
- messages=[...],
- )
-
- action = parse_response(response)
- if action["type"] == "click":
- click(action["x"], action["y"])
- elif action["type"] == "type":
- type_text(action["text"])
- elif action["type"] == "done":
- break
-
-if __name__ == "__main__":
- main()
-```
-
-### Build and Register
+Mount and pip install local packages into the agent container without rebuilding:
```bash
-# Build image
-docker build -t myregistry/my-agent:latest .
-
-# Push to registry (for cloud deployment)
-docker push myregistry/my-agent:latest
+cb run task tasks/my-task --agent my-agent --with ./path/to/local/package
```
-## Running Custom Agents
+Can be repeated for multiple packages:
```bash
-# Run with your custom agent
-cb run task tasks/my_task --task-index 0 --eval --agent my-agent
-
-# Run with VNC debugging
-cb run task tasks/my_task --task-index 0 --eval --agent my-agent --vnc-port 8006
-
-# Override model
-cb run task tasks/my_task --eval --agent my-agent --model gpt-4-turbo
+cb run task tasks/my-task --agent my-agent --with ../cua-bench --with ../my-utils
```
-## What You Can Include
+## Agent lookup order
-Since you control the Docker image, you can include any dependencies:
+When you pass `--agent <name>`:
-| Use Case | Dependencies |
-| ---------------------- | -------------------------------------------- |
-| Vision model agent | `torch`, `transformers`, CUDA runtime |
-| Browser automation | `playwright`, `selenium`, Chrome |
-| OCR-based agent | `tesseract`, `pytesseract`, `opencv` |
-| Multi-modal LLM | `openai`, `anthropic`, `google-generativeai` |
-| Local LLM | `llama-cpp-python`, GGUF models |
-| Reinforcement learning | `stable-baselines3`, `gymnasium` |
+1. `.cua/agents.yaml` (local registry) — checked first
+2. Built-in registry (`@register_agent` decorators) — fallback
-## Best Practices
+## CLI options
-1. **Start with import paths** for rapid development, then containerize for production
-2. **Handle connection retries** - the environment may take a few seconds to start
-3. **Log to stdout** - container logs are captured automatically
-4. **Exit with code 0** on success, non-zero on failure
-5. **Read task config** from `/app/env/main.py` if needed
+```bash
+cb run task <path> --agent <name> # Use a registered agent
+cb run task <path> --agent-kwarg key=value # Pass kwargs to agent __init__
+cb run task <path> --model <model> # Override model
+cb run task <path> --with <path> # Mount local package (repeatable)
+```