Scale computer-use 2.0 with open-source drivers, cross-OS sandboxes, and benchmarks for training, evaluation, and data generation.
Rust agentai-agentapplecomputer-usecomputer-use-agentcontainerizationcuadesktop-automationhacktoberfestlumemacosmanusoperatorswiftvirtualizationvirtualization-frameworkwindowswindows-sandbox
docs: move Cua VLM Router to Fundamentals and improve landing page
f-trycua0a58198fe3c9
diff --git a/docs/content/docs/guide/advanced/chat-history.mdx b/docs/content/docs/guide/advanced/chat-history.mdxnew file mode 100644index 0000000000..d0a2276ed9--- /dev/null+++ b/docs/content/docs/guide/advanced/chat-history.mdx@@ -0,0 +1,148 @@+---+title: Chat History+description: Managing conversation history for multi-turn agent interactions+---++**Chat history** tracks the conversation between you and the agent across multiple turns. Each run builds on the previous context, enabling complex multi-step workflows and conversational interactions.++## Basic Multi-Turn Conversation++Pass a message history to continue from previous context:++```python+from computer import Computer+from agent import ComputerAgent++computer = Computer(os_type="linux", provider_type="docker", image="trycua/cua-xfce:latest")+await computer.run()++agent = ComputerAgent(+ model="anthropic/claude-sonnet-4-5-20250929",+ tools=[computer]+)++# First turn+messages = [{"role": "user", "content": "Open Firefox"}]+async for result in agent.run(messages):+ messages.extend(result["output"])++# Second turn - agent remembers Firefox is open+messages.append({"role": "user", "content": "Now go to github.com"})+async for result in agent.run(messages):+ messages.extend(result["output"])+```++## Interactive Loop++Build a chat interface where each response adds to the history:++```python+history = []++while True:+ user_input = input("> ")+ if user_input.lower() == "quit":+ break++ history.append({"role": "user", "content": user_input})++ async for result in agent.run(history):+ history.extend(result["output"])++ # Print assistant responses+ for item in result["output"]:+ if item["type"] == "message":+ print(item["content"][0]["text"])+```++## Message Structure++A conversation history contains these message types:++```python+messages = [+ # User input+ {"role": "user", "content": "go to trycua on github"},++ # Agent reasoning (internal thought process)+ {+ "type": "reasoning",+ "summary": [{"type": "summary_text", "text": "Searching for Trycua GitHub"}]+ },++ # Computer action+ {+ "type": "computer_call",+ "call_id": "call_abc123",+ "status": "completed",+ "action": {"type": "type", "text": "Trycua GitHub"}+ },++ # Screenshot result+ {+ "type": "computer_call_output",+ "call_id": "call_abc123",+ "output": {"type": "input_image", "image_url": "data:image/png;base64,..."}+ },++ # Final response+ {+ "type": "message",+ "role": "assistant",+ "content": [{"type": "output_text", "text": "Done! The Trycua GitHub page is now open."}]+ }+]+```++See [Message Format](/docs/guide/advanced/message-format) for complete type definitions.++## Managing Context Size++Screenshots accumulate in the history and consume context window space. Use `only_n_most_recent_images` to limit how many are kept:++```python+agent = ComputerAgent(+ model="anthropic/claude-sonnet-4-5-20250929",+ tools=[computer],+ only_n_most_recent_images=3 # Keep only last 3 screenshots+)+```++Older screenshots are automatically removed, preventing context overflow during long sessions.++## Clearing History++Start fresh by resetting the messages array:++```python+# Reset to start a new conversation+messages = []++# Or keep system context but clear conversation+messages = [{"role": "system", "content": "You are a helpful assistant."}]+```++## Saving and Loading History++Persist conversations for later use:++```python+import json++# Save+with open("conversation.json", "w") as f:+ # Filter out large image data if needed+ saveable = [+ {**m, "output": {"type": m["output"]["type"]}}+ if m.get("type") == "computer_call_output"+ else m+ for m in messages+ ]+ json.dump(saveable, f)++# Load+with open("conversation.json", "r") as f:+ messages = json.load(f)+```++For full conversation recording including screenshots, use [Trajectories](/docs/guide/fundamentals/trajectories) instead.diff --git a/docs/content/docs/guide/advanced/composed-models.mdx b/docs/content/docs/guide/advanced/composed-models.mdxnew file mode 100644index 0000000000..3303f3b762--- /dev/null+++ b/docs/content/docs/guide/advanced/composed-models.mdx@@ -0,0 +1,99 @@+---+title: Composed Models+description: Combine grounding and planning models for optimized computer-use+---++Some models excel at **grounding** (finding UI elements) but can't reason about tasks. Others are great at **planning** but can't precisely locate elements. Composed models combine both capabilities for better results.++## How It Works++Use the `+` syntax to combine a grounding model with a planning model:++```python+from computer import Computer+from agent import ComputerAgent++computer = Computer(os_type="linux", provider_type="docker", image="trycua/cua-xfce:latest")+await computer.run()++# Format: grounding_model+planning_model+agent = ComputerAgent(+ model="huggingface-local/HelloKKMe/GTA1-7B+anthropic/claude-sonnet-4-5-20250929",+ tools=[computer]+)+```++Cua uses a two-stage approach:++1. **Grounding stage** - The first model analyzes the screenshot and identifies UI element coordinates+2. **Planning stage** - The second model receives the element list and decides which to interact with++## Common Combinations++### Local Grounding + Cloud Planning++Run visual processing locally while using cloud models for reasoning:++```python+# GTA1 for grounding + Claude for planning+agent = ComputerAgent(+ model="huggingface-local/HelloKKMe/GTA1-7B+anthropic/claude-sonnet-4-5-20250929",+ tools=[computer]+)++# Moondream3 for grounding + Claude for planning+agent = ComputerAgent(+ model="moondream3+anthropic/claude-sonnet-4-5-20250929",+ tools=[computer]+)++# OmniParser for grounding + GPT-4o for planning+agent = ComputerAgent(+ model="omniparser+openai/gpt-4o",+ tools=[computer]+)++# UI-TARS for grounding + GPT-4o for planning+agent = ComputerAgent(+ model="huggingface-local/ByteDance-Seed/UI-TARS-1.5-7B+openai/gpt-4o",+ tools=[computer]+)+```++## Grounding Models++These models locate UI elements but can't reason about actions:++| Model | Description |+|-------|-------------|+| `huggingface-local/HelloKKMe/GTA1-7B` | General-purpose grounding |+| `omniparser` | Microsoft's UI element detection |+| `moondream3` | Lightweight, fast grounding |++## Planning Models++Any full computer-use model can serve as a planner:++| Model | Description |+|-------|-------------|+| `anthropic/claude-sonnet-4-5-20250929` | Best balance of speed and accuracy |+| `anthropic/claude-haiku-4-5-20250929` | Faster, lower cost |+| `openai/gpt-4o` | Strong reasoning capabilities |++## When to Use Composed Models++**Privacy** - Run grounding locally so screenshots never leave your machine. Only text descriptions of UI elements go to the cloud.++**Cost** - Grounding models process images locally, reducing API calls to cloud providers.++**Latency** - Local grounding can be faster than sending full screenshots over the network.++**Accuracy** - Some grounding models detect UI elements more precisely than general-purpose VLMs.++## Limitations++- Requires a local GPU for the grounding model (typically 16GB+ VRAM for 7B models)+- Two-stage processing adds some overhead+- Not all grounding models work with all planning models++For simpler setups, consider using a single full computer-use model like Claude or OpenAI computer-use-preview.diff --git a/docs/content/docs/guide/fundamentals/custom-tools.mdx b/docs/content/docs/guide/advanced/custom-tools.mdxsimilarity index 100%rename from docs/content/docs/guide/fundamentals/custom-tools.mdxrename to docs/content/docs/guide/advanced/custom-tools.mdxdiff --git a/docs/content/docs/guide/advanced/human-in-the-loop.mdx b/docs/content/docs/guide/advanced/human-in-the-loop.mdxnew file mode 100644index 0000000000..50b22f2072--- /dev/null+++ b/docs/content/docs/guide/advanced/human-in-the-loop.mdx@@ -0,0 +1,121 @@+---+title: Human-in-the-Loop+description: Use humans as agents for evaluation, demonstrations, and interactive control+---++**Human-in-the-loop** lets you use a human operator as the agent instead of an AI model. This is useful for creating training data, evaluating agent performance, or taking manual control when automation needs guidance.++## Setup++Start the human agent tool:++```bash+python -m agent.human_tool+```++This opens a UI that shows pending completions. Select a completion to take control.++## Basic Usage++Use `human/human` as the model:++```python+from computer import Computer+from agent import ComputerAgent++computer = Computer(os_type="linux", provider_type="docker", image="trycua/cua-xfce:latest")+await computer.run()++agent = ComputerAgent(+ model="human/human",+ tools=[computer]+)++async for result in agent.run("Navigate to settings and enable dark mode"):+ print(result)+```++The agent waits for a human to perform each action through the UI.++## Composed with Grounding++Combine human planning with automated grounding:++```python+agent = ComputerAgent(+ model="huggingface-local/HelloKKMe/GTA1-7B+human/human",+ tools=[computer]+)++async for result in agent.run("Click the submit button"):+ print(result)+```++The grounding model finds UI elements, then the human decides which to interact with.++## Use Cases++### Creating Training Data++Record human demonstrations to train or fine-tune models:++```python+agent = ComputerAgent(+ model="human/human",+ tools=[computer],+ trajectory_dir="demonstrations"+)++# Human performs task, trajectory is saved+async for result in agent.run("Complete the checkout flow"):+ pass+```++The saved trajectory contains the human's actions and screenshots, ready for training.++### Evaluating Agent Performance++Compare AI agent outputs to human ground truth:++```python+# Run AI agent+ai_agent = ComputerAgent(model="anthropic/claude-sonnet-4-5-20250929", tools=[computer])+async for result in ai_agent.run(task):+ ai_results.append(result)++# Run human agent on same task+human_agent = ComputerAgent(model="human/human", tools=[computer])+async for result in human_agent.run(task):+ human_results.append(result)++# Compare trajectories+```++### Interactive Control++Take over when automated agents get stuck:++```python+try:+ async for result in ai_agent.run(task):+ process(result)+except AgentStuckError:+ # Switch to human control+ async for result in human_agent.run("Continue from here"):+ process(result)+```++### Testing and Debugging++Manually validate tool and environment behavior:++```python+agent = ComputerAgent(+ model="human/human",+ tools=[computer, custom_tool]+)++# Human can test each tool manually+async for result in agent.run("Test the database query tool"):+ print(result)+```diff --git a/docs/content/docs/guide/advanced/local-computer-server.mdx b/docs/content/docs/guide/advanced/local-computer-server.mdxnew file mode 100644index 0000000000..c7619a615d--- /dev/null+++ b/docs/content/docs/guide/advanced/local-computer-server.mdx@@ -0,0 +1,180 @@+---+title: Local Computer Server+description: Run the computer server on your host machine for direct desktop control+---++The **computer server** is a local HTTP service that exposes your desktop for programmatic control. Use it when you want agents to control your actual machine instead of a sandbox, or when connecting to a self-hosted VM.++## When to Use++- **Development/debugging** - Test agents on your real desktop+- **Self-hosted VMs** - Connect to Windows/Linux VMs you manage yourself+- **Air-gapped environments** - Run everything locally without cloud dependencies+- **MCP integrations** - Let Claude Desktop control your computer++## Installation++Install the computer server package:++```bash+pip install cua-computer-server+```++Or install dependencies manually:++```bash+pip install uvicorn fastapi+pip install cua-computer+```++## Starting the Server++Run the server on the default port (8000):++```bash+python -m computer_server+```++With debug logging:++```bash+python -m computer_server --log-level debug+```++Custom port:++```bash+python -m computer_server --port 9000+```++The server exposes endpoints for screenshots, mouse/keyboard input, and other computer operations.++## Connecting from Python++Use `use_host_computer_server=True` to connect to a running computer server:++```python+from computer import Computer++# Connect to local computer server+computer = Computer(use_host_computer_server=True)+await computer.run()++# Now you can control your desktop+screenshot = await computer.interface.screenshot()+await computer.interface.left_click(500, 300)+await computer.interface.type_text("Hello from the agent!")+```++### Custom Host/Port++Connect to a computer server running on a different machine:++```python+computer = Computer(+ use_host_computer_server=True,+ computer_server_host="192.168.1.100",+ computer_server_port=8000+)+```++## With ComputerAgent++Run agents against your desktop:++```python+from computer import Computer+from agent import ComputerAgent++computer = Computer(use_host_computer_server=True)+await computer.run()++agent = ComputerAgent(+ model="anthropic/claude-sonnet-4-5-20250929",+ tools=[computer]+)++async for result in agent.run("Open Firefox and go to github.com"):+ print(result)+```++## Self-Hosted VMs++For VMs you manage yourself (e.g., Windows behind a VPN), install the computer server inside the VM and connect remotely:++```python+# Connect to Windows VM running computer-server+computer = Computer(+ use_host_computer_server=True,+ computer_server_host="windows-vm.local",+ computer_server_port=8000+)+```++See the [Windows App Behind VPN](/docs/examples/platform-specific/windows-app-behind-vpn) example for a complete walkthrough.++## MCP Server Integration++To use with Claude Desktop, start the computer server and configure the MCP server:++```bash+# Terminal 1: Start computer server+python -m computer_server --log-level debug+```++```json+// Claude Desktop config+{+ "mcpServers": {+ "cua-agent": {+ "command": "/bin/bash",+ "args": ["~/.cua/start_mcp_server.sh"],+ "env": {+ "CUA_MODEL_NAME": "anthropic/claude-sonnet-4-20250514",+ "ANTHROPIC_API_KEY": "your-key",+ "CUA_USE_HOST_COMPUTER_SERVER": "true"+ }+ }+ }+}+```++See [MCP Server Installation](/docs/reference/mcp-server/installation) for full setup instructions.++## Security Warning++The computer server gives full control over your desktop. Anyone who can reach the server can:++- Take screenshots of your screen+- Click anywhere on your desktop+- Type text and press keys+- Launch applications++**Recommendations:**++- Only run on localhost or trusted networks+- Don't expose to the public internet+- Stop the server when not in use+- Consider using sandboxes for untrusted workloads++## Troubleshooting++**Port already in use:**++```bash+lsof -i :8000 # Find what's using the port+kill -9 <PID> # Stop it+```++**Connection refused:**++- Ensure the server is running+- Check the host and port match+- Verify firewall allows the connection++**Permission errors (Linux):**++```bash+# May need to run with display access+DISPLAY=:0 python -m computer_server+```diff --git a/docs/content/docs/guide/advanced/message-format.mdx b/docs/content/docs/guide/advanced/message-format.mdxnew file mode 100644index 0000000000..1646d2e3d2--- /dev/null+++ b/docs/content/docs/guide/advanced/message-format.mdx@@ -0,0 +1,226 @@+---+title: Message Format+description: Type definitions for agent messages and actions+---++The Agent SDK uses a consistent message format for all conversations. This page provides type definitions for building custom integrations or processing agent outputs programmatically.++## Agent Response++Each iteration of `agent.run()` yields a response with outputs and usage:++```python+class AgentResponse(TypedDict):+ output: list[AgentMessage] # Messages from this iteration+ usage: Usage # Token counts and cost++class Usage(TypedDict, total=False):+ prompt_tokens: int+ completion_tokens: int+ total_tokens: int+ response_cost: float # Cost in USD+```++## Message Types++The `output` list contains different message types:++### User Message++Input from the user or system:++```python+class UserMessage(TypedDict, total=False):+ type: Literal["message"]+ role: Literal["user", "system", "developer"]+ content: str | list[InputContent]+```++### Assistant Message++Text output from the agent:++```python+class AssistantMessage(TypedDict):+ type: Literal["message"]+ role: Literal["assistant"]+ content: list[OutputContent]++class OutputContent(TypedDict):+ type: Literal["output_text"]+ text: str+```++### Reasoning Message++Agent's internal reasoning (when available):++```python+class ReasoningMessage(TypedDict):+ type: Literal["reasoning"]+ summary: list[SummaryContent]++class SummaryContent(TypedDict):+ type: Literal["summary_text"]+ text: str+```++### Computer Call++Action the agent wants to perform:++```python+class ComputerCallMessage(TypedDict):+ type: Literal["computer_call"]+ call_id: str+ status: Literal["completed", "failed", "pending"]+ action: ComputerAction+```++### Computer Call Output++Result of a computer action (screenshot):++```python+class ComputerCallOutputMessage(TypedDict):+ type: Literal["computer_call_output"]+ call_id: str+ output: ComputerResultContent++class ComputerResultContent(TypedDict):+ type: Literal["computer_screenshot", "input_image"]+ image_url: str # Base64 data URL+```++### Function Call++Call to a custom tool:++```python+class FunctionCallMessage(TypedDict):+ type: Literal["function_call"]+ call_id: str+ status: Literal["completed", "failed", "pending"]+ name: str+ arguments: str # JSON string++class FunctionCallOutputMessage(TypedDict):+ type: Literal["function_call_output"]+ call_id: str+ output: str+```++## Computer Actions++Actions represent operations the agent performs. The format varies by provider.++### Common Actions++```python+class ClickAction(TypedDict):+ type: Literal["click"]+ button: Literal["left", "right", "wheel", "back", "forward"]+ x: int+ y: int++class DoubleClickAction(TypedDict):+ type: Literal["double_click"]+ x: int+ y: int++class TypeAction(TypedDict):+ type: Literal["type"]+ text: str++class KeyPressAction(TypedDict):+ type: Literal["keypress"]+ keys: list[str] # e.g., ["ctrl", "c"]++class ScrollAction(TypedDict):+ type: Literal["scroll"]+ x: int+ y: int+ scroll_x: int+ scroll_y: int++class MoveAction(TypedDict):+ type: Literal["move"]+ x: int+ y: int++class DragAction(TypedDict):+ type: Literal["drag"]+ path: list[tuple[int, int]] # [(x1, y1), (x2, y2), ...]++class ScreenshotAction(TypedDict):+ type: Literal["screenshot"]++class WaitAction(TypedDict):+ type: Literal["wait"]+```++### Anthropic-Specific Actions++```python+class LeftMouseDownAction(TypedDict):+ type: Literal["left_mouse_down"]+ x: int+ y: int++class LeftMouseUpAction(TypedDict):+ type: Literal["left_mouse_up"]+ x: int+ y: int+```++## Processing Messages++Handle different message types in your code:++```python+async for result in agent.run(messages):+ for item in result["output"]:+ match item["type"]:+ case "message":+ print(f"Agent: {item['content'][0]['text']}")+ case "reasoning":+ print(f"Thinking: {item['summary'][0]['text']}")+ case "computer_call":+ print(f"Action: {item['action']['type']}")+ case "computer_call_output":+ print("Screenshot received")+ case "function_call":+ print(f"Tool call: {item['name']}")+```++## Full Type Union++For type checking, use the union of all message types:++```python+from typing import Union++AgentMessage = Union[+ UserMessage,+ AssistantMessage,+ ReasoningMessage,+ ComputerCallMessage,+ ComputerCallOutputMessage,+ FunctionCallMessage,+ FunctionCallOutputMessage,+]++ComputerAction = Union[+ ClickAction,+ DoubleClickAction,+ TypeAction,+ KeyPressAction,+ ScrollAction,+ MoveAction,+ DragAction,+ ScreenshotAction,+ WaitAction,+ LeftMouseDownAction,+ LeftMouseUpAction,+]+```diff --git a/docs/content/docs/guide/advanced/meta.json b/docs/content/docs/guide/advanced/meta.jsonnew file mode 100644index 0000000000..7a47a83863--- /dev/null+++ b/docs/content/docs/guide/advanced/meta.json@@ -0,0 +1,18 @@+{+ "title": "Advanced",+ "description": "Advanced topics for building with Cua",+ "icon": "Layers",+ "pages": [+ "composed-models",+ "custom-tools",+ "sandboxed-python",+ "local-computer-server",+ "human-in-the-loop",+ "trajectories",+ "tracing",+ "chat-history",+ "message-format",+ "prompt-caching",+ "telemetry"+ ]+}diff --git a/docs/content/docs/guide/advanced/prompt-caching.mdx b/docs/content/docs/guide/advanced/prompt-caching.mdxnew file mode 100644index 0000000000..14496e0af4--- /dev/null+++ b/docs/content/docs/guide/advanced/prompt-caching.mdx@@ -0,0 +1,114 @@+---+title: Prompt Caching+description: Reduce costs and latency with provider-specific prompt caching+---++**Prompt caching** avoids reprocessing the same prompt content on repeated calls. This reduces costs and latency for long-running tasks or iterative workflows where the context stays mostly the same.++## Enabling Prompt Caching++Set `use_prompt_caching=True` when creating your agent:++```python+from computer import Computer+from agent import ComputerAgent++computer = Computer(os_type="linux", provider_type="docker", image="trycua/cua-xfce:latest")+await computer.run()++agent = ComputerAgent(+ model="anthropic/claude-sonnet-4-5-20250929",+ tools=[computer],+ use_prompt_caching=True+)+```++## Provider Behavior++### Anthropic++When enabled, Cua adds `{"cache_control": "ephemeral"}` to messages. This tells Anthropic to cache the prompt for the duration of the session.++```python+# Required for Anthropic models+agent = ComputerAgent(+ model="anthropic/claude-sonnet-4-5-20250929",+ tools=[computer],+ use_prompt_caching=True+)+```++### OpenAI++OpenAI automatically caches prompts over 1000 tokens. You don't need to set `use_prompt_caching`—it happens automatically.++```python+# Caching is automatic for OpenAI+agent = ComputerAgent(+ model="openai/computer-use-preview",+ tools=[computer]+)+```++### Other Providers++For providers that don't support caching, the parameter is ignored.++## When to Use++**Iterative tasks** - When the agent runs multiple turns with similar context:++```python+agent = ComputerAgent(+ model="anthropic/claude-sonnet-4-5-20250929",+ tools=[computer],+ use_prompt_caching=True+)++# Each turn reuses cached context+for task in tasks:+ async for result in agent.run(task):+ process(result)+```++**Long system prompts** - When using detailed instructions that repeat across calls:++```python+agent = ComputerAgent(+ model="anthropic/claude-sonnet-4-5-20250929",+ tools=[computer],+ instructions="Very long system prompt with detailed rules...",+ use_prompt_caching=True+)+```++**Multi-turn conversations** - When conversation history grows but the beginning stays constant:++```python+agent = ComputerAgent(+ model="anthropic/claude-sonnet-4-5-20250929",+ tools=[computer],+ use_prompt_caching=True+)++messages = [{"role": "system", "content": "Long context..."}]+for user_input in inputs:+ messages.append({"role": "user", "content": user_input})+ async for result in agent.run(messages):+ messages.extend(result["output"])+```++## Cost Impact++With Anthropic's prompt caching:+- Cached input tokens cost 90% less than regular input tokens+- Cache writes have a small additional cost+- Cache hits provide significant savings on repeated runs++Check your usage in the response:++```python+async for result in agent.run(messages):+ usage = result["usage"]+ print(f"Tokens: {usage['total_tokens']}, Cost: ${usage['response_cost']:.4f}")+```diff --git a/docs/content/docs/guide/fundamentals/sandboxed-python.mdx b/docs/content/docs/guide/advanced/sandboxed-python.mdxsimilarity index 89%rename from docs/content/docs/guide/fundamentals/sandboxed-python.mdxrename to docs/content/docs/guide/advanced/sandboxed-python.mdxindex 4599af62cf..87c7e97e38 100644--- a/docs/content/docs/guide/fundamentals/sandboxed-python.mdx+++ b/docs/content/docs/guide/advanced/sandboxed-python.mdx@@ -3,17 +3,14 @@ title: Sandboxed Pythondescription: Execute Python functions securely in isolated virtual environments----**Sandboxed Python** lets you run Python code inside your sandbox rather than on your host machine. This bridges the gap between UI automation (clicking buttons, filling forms) and data processing (API calls, file manipulation, computation).+Sometimes you don't want to rely on UI automation or shell commands—you just want to run Python code directly inside the sandbox. **Sandboxed Python** lets you execute Python functions in isolated virtual environments within your sandbox, giving you programmatic control without clicking through UIs.## Why Run Code in the Sandbox?-When your agent scrapes data from a UI, you often need to process it—call an API, transform the data, or save it somewhere. Running this code on your host has drawbacks:--- **Security risk** - Untrusted code could affect your system-- **Dependency conflicts** - Packages might clash with your local environment-- **Reproducibility** - Different hosts have different setups--Sandboxed Python executes your functions inside the sandbox's isolated environment, using virtual environments you control.+- **Faster than UI** - Skip the clicks and run code directly+- **More reliable** - No flaky element detection or timing issues+- **Full Python power** - Use any library for data processing, API calls, or computation+- **Isolated** - Code runs in the sandbox, not on your host, with its own dependencies## Running a Function in the Sandboxdiff --git a/docs/content/docs/guide/advanced/telemetry.mdx b/docs/content/docs/guide/advanced/telemetry.mdxnew file mode 100644index 0000000000..9214832b8e--- /dev/null+++ b/docs/content/docs/guide/advanced/telemetry.mdx@@ -0,0 +1,111 @@+---+title: Telemetry+description: Understanding and controlling Cua's anonymous usage collection+---++Cua collects anonymous usage statistics to improve the product. No personal data, screenshots, or conversation content is collected by default. You can opt out completely at any time.++## What's Collected++### By Default (Opt-Out)++Basic performance metrics:++- **System info** - OS, OS version, Python version+- **Module initialization** - When packages are imported and their versions+- **Performance** - Agent run durations, step counts, token usage, API costs+- **Session tracking** - Anonymous UUIDs for sessions and runs++### Opt-In Only++**Trajectory logging** captures full conversation history and must be explicitly enabled:++- User messages and agent responses+- Computer actions and outputs+- Agent reasoning traces++### Never Collected++- Personal information or user identifiers+- API keys or credentials+- File contents or application data+- Screenshots (unless trajectory logging is enabled)+- Text being typed or model outputs (unless trajectory logging is enabled)++## Disabling Telemetry++### Environment Variable++Set `CUA_TELEMETRY_ENABLED` to disable globally:++```bash+export CUA_TELEMETRY_ENABLED=false+```++### Per Instance++Disable on individual objects:++```python+from computer import Computer+from agent import ComputerAgent++# Disable for Computer+computer = Computer(+ os_type="linux",+ provider_type="docker",+ telemetry_enabled=False+)++# Disable for Agent+agent = ComputerAgent(+ model="anthropic/claude-sonnet-4-5-20250929",+ tools=[computer],+ telemetry_enabled=False+)+```++### Check Status++```python+print(computer.telemetry_enabled) # True or False+print(agent.telemetry_enabled) # True, False, or dict+```++## Enabling Trajectory Logging++To opt in to full conversation logging:++```python+agent = ComputerAgent(+ model="anthropic/claude-sonnet-4-5-20250929",+ tools=[computer],+ telemetry_enabled={"log_trajectory": True}+)+```++This sends complete conversation items to help improve Cua's models.++## Events Reference++### Computer SDK Events++| Event | Data | Trigger |+|-------|------|---------|+| `computer_initialized` | OS, OS version, Python version | Computer instance created |+| `module_init` | Module name, version, Python version | Package first imported |++### Agent SDK Events++| Event | Data | Trigger |+|-------|------|---------|+| `module_init` | Module name, version, Python version | Package first imported |+| `agent_session_start` | Session ID, agent type, model, system info | Agent instantiated |+| `agent_run_start` | Session/run IDs, input size, message count | `agent.run()` called |+| `agent_run_end` | Session/run IDs, duration, steps, usage | `agent.run()` completes |+| `agent_step` | Session/run IDs, step number, timestamp | Each agent iteration |+| `agent_usage` | Session/run IDs, token counts, cost | Usage info received |++## Questions++Questions about telemetry? Open an issue on [GitHub](https://github.com/trycua/cua).diff --git a/docs/content/docs/guide/fundamentals/tracing.mdx b/docs/content/docs/guide/advanced/tracing.mdxsimilarity index 100%rename from docs/content/docs/guide/fundamentals/tracing.mdxrename to docs/content/docs/guide/advanced/tracing.mdxdiff --git a/docs/content/docs/guide/fundamentals/trajectories.mdx b/docs/content/docs/guide/advanced/trajectories.mdxsimilarity index 100%rename from docs/content/docs/guide/fundamentals/trajectories.mdxrename to docs/content/docs/guide/advanced/trajectories.mdxdiff --git a/docs/content/docs/guide/agents/callbacks.mdx b/docs/content/docs/guide/agents/callbacks.mdxdeleted file mode 100644index 0f6a5c7bde..0000000000--- a/docs/content/docs/guide/agents/callbacks.mdx+++ /dev/null@@ -1,272 +0,0 @@-----title: Callbacks-description: Hooks into the agent lifecycle for logging, cost management, and data handling------import { Tabs, Tab } from 'fumadocs-ui/components/tabs';--Callbacks provide hooks into the agent's lifecycle, allowing for custom functionality at various stages of an agent's run. They enable extensibility for tasks such as logging, cost management, and data handling.--## Quick Start--```python-from cua import ComputerAgent-from cua.agent.callbacks import (- ImageRetentionCallback,- TrajectorySaverCallback,- BudgetManagerCallback,- LoggingCallback-)--agent = ComputerAgent(- model="anthropic/claude-sonnet-4-5-20250929",- tools=[computer],- callbacks=[- ImageRetentionCallback(only_n_most_recent_images=3),- TrajectorySaverCallback(trajectory_dir="trajectories"),- BudgetManagerCallback(max_budget=10.0, raise_error=True),- LoggingCallback(level=logging.INFO)- ]-)-```--## Built-in Callbacks--<Tabs items={['Cost Optimization', 'Trajectories', 'Logging']}>-<Tab value="Cost Optimization">--### Budget Manager--Control spending with budget limits:--```python-from cua.agent.callbacks import BudgetManagerCallback--agent = ComputerAgent(- model="anthropic/claude-sonnet-4-5-20250929",- tools=[computer],- callbacks=[- BudgetManagerCallback(- max_budget=5.0, # $5 limit- reset_after_each_run=False,- raise_error=True- )- ]-)-```--**Shorthand:**--```python-agent = ComputerAgent(- model="anthropic/claude-sonnet-4-5-20250929",- max_trajectory_budget=5.0 # $5 limit-)-```--**Options:**-- `max_budget`: Dollar limit for trajectory-- `reset_after_each_run`: Reset budget per run (default: True)-- `raise_error`: Raise exception vs. graceful stop (default: False)--### Image Retention--Reduce token usage by limiting images in context:--```python-from cua.agent.callbacks import ImageRetentionCallback--agent = ComputerAgent(- model="anthropic/claude-sonnet-4-5-20250929",- tools=[computer],- callbacks=[- ImageRetentionCallback(only_n_most_recent_images=3)- ]-)-```--**Shorthand:**--```python-agent = ComputerAgent(- model="anthropic/claude-sonnet-4-5-20250929",- only_n_most_recent_images=3 # Auto-adds ImageRetentionCallback-)-```--### Combined Cost Optimization--```python-agent = ComputerAgent(- model="anthropic/claude-sonnet-4-5-20250929",- tools=[computer],- max_trajectory_budget=5.0, # Budget limit- only_n_most_recent_images=3, # Image retention- trajectory_dir="trajectories" # Track spending-)-```--</Tab>-<Tab value="Trajectories">--### TrajectorySaverCallback--Records complete agent conversations including messages, actions, and screenshots for debugging and analysis.--```python-from cua.agent.callbacks import TrajectorySaverCallback--agent = ComputerAgent(- model="anthropic/claude-sonnet-4-5-20250929",- tools=[computer],- callbacks=[- TrajectorySaverCallback(- trajectory_dir="my_trajectories",- save_screenshots=True- )- ]-)-```--**Shorthand:**--```python-agent = ComputerAgent(- model="anthropic/claude-sonnet-4-5-20250929",- trajectory_dir="trajectories", # Auto-save trajectories- tools=[computer]-)-```--### View Trajectories Online--View trajectories in the browser at **[cua.ai/trajectory-viewer](https://cua.ai/trajectory-viewer)**--The viewer provides:-- Interactive conversation replay-- Screenshot galleries-- No data collection--### Trajectory Structure--Each trajectory contains:-- **metadata.json**: Run info, timestamps, usage stats (`total_tokens`, `response_cost`)-- **turn_000/**: Turn-by-turn conversation history (api calls, responses, computer calls, screenshots)--</Tab>-<Tab value="Logging">--### LoggingCallback--Built-in logging for agent monitoring:--```python-from cua.agent.callbacks import LoggingCallback-import logging--agent = ComputerAgent(- model="anthropic/claude-sonnet-4-5-20250929",- tools=[computer],- callbacks=[- LoggingCallback(- logger=logging.getLogger("cua"),- level=logging.INFO- )- ]-)-```--**Shorthand:**--```python-agent = ComputerAgent(- model="anthropic/claude-sonnet-4-5-20250929",- tools=[computer],- verbosity=logging.INFO # Auto-adds LoggingCallback-)-```--### Custom Logger--Create custom loggers by extending AsyncCallbackHandler:--```python-from cua.agent.callbacks.base import AsyncCallbackHandler-import logging--class CustomLogger(AsyncCallbackHandler):- def __init__(self, logger_name="agent"):- self.logger = logging.getLogger(logger_name)- self.logger.setLevel(logging.INFO)-- handler = logging.StreamHandler()- formatter = logging.Formatter(- '%(asctime)s - %(name)s - %(levelname)s - %(message)s'- )- handler.setFormatter(formatter)- self.logger.addHandler(handler)-- async def on_run_start(self, kwargs, old_items):- self.logger.info(f"Agent run started with model: {kwargs.get('model')}")-- async def on_computer_call_start(self, item):- action = item.get('action', {})- self.logger.info(f"Computer action: {action.get('type')}")-- async def on_usage(self, usage):- cost = usage.get('response_cost', 0)- self.logger.info(f"API call cost: ${cost:.4f}")-- async def on_run_end(self, kwargs, old_items, new_items):- self.logger.info("Agent run completed")--# Use custom logger-agent = ComputerAgent(- model="anthropic/claude-sonnet-4-5-20250929",- tools=[computer],- callbacks=[CustomLogger("my_agent")]-)-```--</Tab>-</Tabs>--## Callback Lifecycle--Callbacks are called in a specific order during agent execution:--| Order | Method | Description |-|-------|--------|-------------|-| 1 | `on_run_start(kwargs, old_items)` | Called once when agent run begins |-| 2 | `on_run_continue(kwargs, old_items, new_items)` | Called before each iteration. Return `False` to stop |-| 3 | `on_llm_start(messages)` | Preprocess messages before LLM call |-| 4 | `on_api_start(kwargs)` | Called before each LLM API call |-| 5 | `on_api_end(kwargs, result)` | Called after each LLM API call |-| 6 | `on_usage(usage)` | Called when usage info is received |-| 7 | `on_llm_end(messages)` | Postprocess messages after LLM call |-| 8 | `on_responses(kwargs, responses)` | Called when responses are received |-| 9 | Response hooks | `on_text`, `on_computer_call_start/end`, `on_function_call_start/end`, `on_screenshot` |-| 10 | `on_run_end(kwargs, old_items, new_items)` | Called when agent run completes |--## Custom Callbacks--Create custom callbacks by subclassing `AsyncCallbackHandler`:--```python-from cua.agent.callbacks.base import AsyncCallbackHandler--class CustomCallback(AsyncCallbackHandler):- async def on_llm_start(self, messages):- """Preprocess messages before LLM call"""- # Add custom preprocessing logic- return messages-- async def on_llm_end(self, messages):- """Postprocess messages after LLM call"""- # Add custom postprocessing logic- return messages-- async def on_usage(self, usage):- """Track usage information"""- print(f"Tokens used: {usage.total_tokens}")-```diff --git a/docs/content/docs/guide/agents/chat-history.mdx b/docs/content/docs/guide/agents/chat-history.mdxdeleted file mode 100644index e6740fc339..0000000000--- a/docs/content/docs/guide/agents/chat-history.mdx+++ /dev/null@@ -1,92 +0,0 @@-----title: Chat History-description: Managing conversation history and message arrays------Managing conversation history is essential for multi-turn agent interactions. The agent maintains a messages array that tracks the entire conversation flow.--## Managing History--### Continuous Conversation--```python-history = []--while True:- user_input = input("> ")- history.append({"role": "user", "content": user_input})-- async for result in agent.run(history, stream=False):- history += result["output"]-```--## Message Array Structure--The messages array contains different types of messages that represent the conversation state:--```python-messages = [- # user input- {- "role": "user",- "content": "go to trycua on gh"- },- # first agent turn adds the model output to the history- {- "summary": [- {- "text": "Searching Firefox for Trycua GitHub",- "type": "summary_text"- }- ],- "type": "reasoning"- },- {- "action": {- "text": "Trycua GitHub",- "type": "type"- },- "call_id": "call_QI6OsYkXxl6Ww1KvyJc4LKKq",- "status": "completed",- "type": "computer_call"- },- # second agent turn adds the computer output to the history- {- "type": "computer_call_output",- "call_id": "call_QI6OsYkXxl6Ww1KvyJc4LKKq",- "output": {- "type": "input_image",- "image_url": "data:image/png;base64,..."- }- },- # final agent turn adds the agent output text to the history- {- "type": "message",- "role": "assistant",- "content": [- {- "text": "Success! The Trycua GitHub page has been opened.",- "type": "output_text"- }- ]- }-]-```--## Message Types--See the complete schema in [Message Format](./message-format).--### Memory Management--For long conversations, consider using the `only_n_most_recent_images` parameter to manage memory:--```python-agent = ComputerAgent(- model="cua/anthropic/claude-sonnet-4.5",- tools=[computer],- only_n_most_recent_images=3-)-```--This automatically removes old images from the conversation history to prevent context window overflow.diff --git a/docs/content/docs/guide/agents/custom-tools.mdx b/docs/content/docs/guide/agents/custom-tools.mdxdeleted file mode 100644index cf1652dd29..0000000000--- a/docs/content/docs/guide/agents/custom-tools.mdx+++ /dev/null@@ -1,49 +0,0 @@-----title: Custom Tools-slug: custom-tools------The Agent SDK supports defining custom Python tools that run securely in sandboxed environments on remote Cua Computer Frameworks. This enables safe execution of user-defined functions, isolation of dependencies, and robust automation workflows.--## Custom Tools--Define a custom tool for an agent:--```python-def calculate(a: int, b: int) -> int:- """Calculate the sum of two integers"""- return a + b--# Use with agent-agent = ComputerAgent(- model="cua/anthropic/claude-sonnet-4.5",- tools=[computer, calculate]-)-```--## Sandboxed Tools--Define a sandboxed tool:--```python-from computer.helpers import sandboxed--@sandboxed()-def read_file(location: str) -> str:- """Read contents of a file"""- with open(location, 'r') as f:- return f.read()-```--You can then register this as a tool for your agent:--```python-from agent import ComputerAgent-from computer import Computer--computer = Computer(...)-agent = ComputerAgent(- model="cua/anthropic/claude-sonnet-4.5",- tools=[computer, read_file],-)-```diff --git a/docs/content/docs/guide/agents/customizing-computeragent.mdx b/docs/content/docs/guide/agents/customizing-computeragent.mdxdeleted file mode 100644index 158495e07c..0000000000--- a/docs/content/docs/guide/agents/customizing-computeragent.mdx+++ /dev/null@@ -1,130 +0,0 @@-----title: Customize ComputerAgent------<Callout>- A corresponding{' '}- <a- href="https://github.com/trycua/cua/blob/main/notebooks/customizing_computeragent.ipynb"- target="_blank"- >- Jupyter Notebook- </a>{' '}- is available for this documentation.-</Callout>--The `ComputerAgent` interface provides an easy proxy to any computer-using model configuration, and it is a powerful framework for extending and building your own agentic systems.--This guide shows four proven ways to increase capabilities and success rate:--- 1 — Simple: Prompt engineering-- 2 — Easy: Tools-- 3 — Intermediate: Callbacks-- 4 — Expert: Custom `@register_agent`--## 1) Simple: Prompt engineering--Provide guiding instructions to shape behavior. `ComputerAgent` accepts an optional `instructions: str | None` which acts like a system-style preface. Internally, this uses a callback that pre-pends a user message before each LLM call.--```python-from agent.agent import ComputerAgent--agent = ComputerAgent(- model="openai/computer-use-preview",- tools=[computer],- instructions=(- "You are a meticulous software operator. Prefer safe, deterministic actions. "- "Always confirm via on-screen text before proceeding."- ),-)-```--## 2) Easy: Tools--Expose deterministic capabilities as tools (Python functions or custom computer handlers). The agent will call them when appropriate.--```python-def calculate_percentage(numerator: float, denominator: float) -> str:- """Calculate percentage as a string.-- Args:- numerator: Numerator value- denominator: Denominator value- Returns:- A formatted percentage string (e.g., '75.00%').- """- if denominator == 0:- return "0.00%"- return f"{(numerator/denominator)*100:.2f}%"--agent = ComputerAgent(- model="openai/computer-use-preview",- tools=[computer, calculate_percentage],-)-```--- See `docs/agent-sdk/custom-tools` for authoring function tools.-- See `docs/agent-sdk/custom-computer-handlers` for building full computer interfaces.--## 3) Intermediate: Callbacks--Callbacks provide lifecycle hooks to preprocess messages, postprocess outputs, record trajectories, manage costs, and more.--```python-from agent.callbacks import ImageRetentionCallback, TrajectorySaverCallback, BudgetManagerCallback--agent = ComputerAgent(- model="cua/anthropic/claude-sonnet-4.5",- tools=[computer],- callbacks=[- ImageRetentionCallback(only_n_most_recent_images=3),- TrajectorySaverCallback("./trajectories"),- BudgetManagerCallback(max_budget=10.0, raise_error=True),- ],-)-```--- Browse implementations in `libs/python/agent/agent/loops/`.--## 4) Expert: Custom `@register_agent`--Build your own agent configuration class to control prompting, message shaping, and tool handling. This is the most flexible option for specialized domains.--- Register your own `model=...` loop using `@register_agent`-- Browse implementations in `libs/python/agent/agent/loops/`.-- Implement `predict_step()` (and optionally `predict_click()`) and return the standardized output schema.--```python-from agent.decorators import register_agent--@register_agent(models=r".*my-special-model.*", priority=10)-class MyCustomAgentConfig:- async def predict_step(self, messages, model, tools, **kwargs):- # 1) Format messages for your provider- # 2) Call provider- # 3) Convert responses to the agent output schema- return {"output": [], "usage": {}}-- async def predict_click(self, model, image_b64, instruction):- # Optional: click-only capability- return None-- def get_capabilities(self):- return ["step"]-```--## HUD integration (optional)--When using the HUD evaluation integration (`agent/integrations/hud/`), you can pass `instructions`, `tools`, and `callbacks` directly--```python-from agent.integrations.hud import run_single_task--await run_single_task(- dataset="username/dataset-name",- model="openai/computer-use-preview",- instructions="Operate carefully. Always verify on-screen text before actions.",- # tools=[your_custom_function],- # callbacks=[YourCustomCallback()],-)-```diff --git a/docs/content/docs/guide/agents/message-format.mdx b/docs/content/docs/guide/agents/message-format.mdxdeleted file mode 100644index ac329d4d20..0000000000--- a/docs/content/docs/guide/agents/message-format.mdx+++ /dev/null@@ -1,201 +0,0 @@-----title: Message Format------This page documents the Python message and response schema used by the Agent SDK.-It mirrors the structure shown in Chat History and provides precise type definitions you can target in your own code.--All examples below use Python type hints with `TypedDict` and `Literal` from the standard `typing` module.--## Response--The agent yields response chunks as an async generator of objects with `output` and `usage`.--```python-from typing import List, TypedDict--class Usage(TypedDict, total=False):- prompt_tokens: int- completion_tokens: int- total_tokens: int- response_cost: float # USD cost if available--class AgentResponse(TypedDict):- output: List["AgentMessage"]- usage: Usage-```--## Messages--Agent messages represent the state of the conversation and the agent's actions.--```python-from typing import List, Literal, Optional, TypedDict, Union--# Union of all message variants-AgentMessage = Union[- "UserMessage",- "AssistantMessage",- "ReasoningMessage",- "ComputerCallMessage",- "ComputerCallOutputMessage",- "FunctionCallMessage",- "FunctionCallOutputMessage",-]--# Input message (role: user/system/developer)-class UserMessage(TypedDict, total=False):- type: Literal["message"] # optional for user input- role: Literal["user", "system", "developer"]- content: Union[str, List["InputContent"]]--# Output message (assistant text)-class AssistantMessage(TypedDict):- type: Literal["message"]- role: Literal["assistant"]- content: List["OutputContent"]--# Output reasoning/thinking message-class ReasoningMessage(TypedDict):- type: Literal["reasoning"]- summary: List["SummaryContent"]--# Output computer action call (agent intends to act)-class ComputerCallMessage(TypedDict):- type: Literal["computer_call"]- call_id: str- status: Literal["completed", "failed", "pending"]- action: "ComputerAction"--# Output computer action result (always a screenshot)-class ComputerCallOutputMessage(TypedDict):- type: Literal["computer_call_output"]- call_id: str- output: "ComputerResultContent"--# Output function call (agent calls a Python tool)-class FunctionCallMessage(TypedDict):- type: Literal["function_call"]- call_id: str- status: Literal["completed", "failed", "pending"]- name: str- arguments: str # JSON-serialized kwargs--# Output function call result (text)-class FunctionCallOutputMessage(TypedDict):- type: Literal["function_call_output"]- call_id: str- output: str-```--## Message Content--These content items appear inside `content` arrays for the message types above.--```python-# Input content kinds-class InputContent(TypedDict):- type: Literal["input_image", "input_text"]- text: Optional[str]- image_url: Optional[str] # e.g., data URL--# Assistant output content-class OutputContent(TypedDict):- type: Literal["output_text"]- text: str--# Reasoning/summary output content-class SummaryContent(TypedDict):- type: Literal["summary_text"]- text: str--# Computer call outputs (screenshots)-class ComputerResultContent(TypedDict):- type: Literal["computer_screenshot", "input_image"]- image_url: str # data URL (e.g., "data:image/png;base64,....")-```--## Actions--Computer actions represent concrete operations the agent will perform on the computer.--Two broad families exist depending on the provider: OpenAI-style and Anthropic-style.--```python-# Union of all supported computer actions-ComputerAction = Union[- "ClickAction",- "DoubleClickAction",- "DragAction",- "KeyPressAction",- "MoveAction",- "ScreenshotAction",- "ScrollAction",- "TypeAction",- "WaitAction",- # Anthropic variants- "LeftMouseDownAction",- "LeftMouseUpAction",-]--# OpenAI Computer Actions-class ClickAction(TypedDict):- type: Literal["click"]- button: Literal["left", "right", "wheel", "back", "forward"]- x: int- y: int--class DoubleClickAction(TypedDict, total=False):- type: Literal["double_click"]- button: Literal["left", "right", "wheel", "back", "forward"]- x: int- y: int--class DragAction(TypedDict, total=False):- type: Literal["drag"]- button: Literal["left", "right", "wheel", "back", "forward"]- path: List[tuple[int, int]] # [(x1, y1), (x2, y2), ...]--class KeyPressAction(TypedDict):- type: Literal["keypress"]- keys: List[str] # e.g., ["ctrl", "a"]--class MoveAction(TypedDict):- type: Literal["move"]- x: int- y: int--class ScreenshotAction(TypedDict):- type: Literal["screenshot"]--class ScrollAction(TypedDict):- type: Literal["scroll"]- scroll_x: int- scroll_y: int- x: int- y: int--class TypeAction(TypedDict):- type: Literal["type"]- text: str--class WaitAction(TypedDict):- type: Literal["wait"]--# Anthropic Computer Actions-class LeftMouseDownAction(TypedDict):- type: Literal["left_mouse_down"]- x: int- y: int--class LeftMouseUpAction(TypedDict):- type: Literal["left_mouse_up"]- x: int- y: int-```--## Notes--- The agent runtime may add provider-specific fields when available (e.g., usage cost). Unknown fields should be ignored for forward compatibility.-- Computer action outputs are screenshots as data URLs. For security and storage, some serializers may redact or omit large fields in persisted metadata.-- The message flow typically alternates between reasoning, actions, screenshots, and concluding assistant text. See [Chat History](./chat-history) for a step-by-step example.diff --git a/docs/content/docs/guide/agents/meta.json b/docs/content/docs/guide/agents/meta.jsondeleted file mode 100644index 29ce8297c1..0000000000--- a/docs/content/docs/guide/agents/meta.json+++ /dev/null@@ -1,17 +0,0 @@-{- "title": "Agents",- "description": "Building and configuring computer-use agents",- "icon": "Bot",- "pages": [- "supported-agents",- "callbacks",- "custom-tools",- "chat-history",- "customizing-computeragent",- "prompt-caching",- "message-format",- "usage-tracking",- "telemetry",- "migration-guide"- ]-}diff --git a/docs/content/docs/guide/agents/migration-guide.mdx b/docs/content/docs/guide/agents/migration-guide.mdxdeleted file mode 100644index fd67b282dc..0000000000--- a/docs/content/docs/guide/agents/migration-guide.mdx+++ /dev/null@@ -1,140 +0,0 @@-----title: Migration Guide------This guide lists **breaking changes** when migrating from the original `ComputerAgent` (v0.3.x) to the rewritten `ComputerAgent` (v0.4.x) and shows old vs new usage for all four agent loops.--## Breaking Changes--- **Initialization:**- - `ComputerAgent` (v0.4.x) uses `model` as a string (e.g. "anthropic/claude-sonnet-4-5-20250929") instead of `LLM` and `AgentLoop` objects.- - `tools` is a list (can include multiple computers and decorated functions).- - `callbacks` are now first-class for extensibility (image retention, budget, trajectory, logging, etc).-- **No explicit `loop` parameter:**- - Loop is inferred from the `model` string (e.g. `anthropic/`, `openai/`, `omniparser+`, `ui-tars`).-- **No explicit `computer` parameter:**- - Computers are added to `tools` list.-------## Usage Examples: Old vs New--### 1. Anthropic Loop--**Old:**--```python-async with Computer() as computer:- agent = ComputerAgent(- computer=computer,- loop=AgentLoop.ANTHROPIC,- model=LLM(provider=LLMProvider.ANTHROPIC)- )- async for result in agent.run("Take a screenshot"):- print(result)-```--**New:**--```python-async with Computer() as computer:- agent = ComputerAgent(- model="anthropic/claude-sonnet-4-5-20250929",- tools=[computer]- )- messages = [{"role": "user", "content": "Take a screenshot"}]- async for result in agent.run(messages):- for item in result["output"]:- if item["type"] == "message":- print(item["content"][0]["text"])-```--### 2. OpenAI Loop--**Old:**--```python-async with Computer() as computer:- agent = ComputerAgent(- computer=computer,- loop=AgentLoop.OPENAI,- model=LLM(provider=LLMProvider.OPENAI)- )- async for result in agent.run("Take a screenshot"):- print(result)-```--**New:**--```python-async with Computer() as computer:- agent = ComputerAgent(- model="openai/computer-use-preview",- tools=[computer]- )- messages = [{"role": "user", "content": "Take a screenshot"}]- async for result in agent.run(messages):- for item in result["output"]:- if item["type"] == "message":- print(item["content"][0]["text"])-```--### 3. UI-TARS Loop--**Old:**--```python-async with Computer() as computer:- agent = ComputerAgent(- computer=computer,- loop=AgentLoop.UITARS,- model=LLM(provider=LLMProvider.OAICOMPAT, name="ByteDance-Seed/UI-TARS-1.5-7B", provider_base_url="https://.../v1")- )- async for result in agent.run("Take a screenshot"):- print(result)-```--**New:**--```python-async with Computer() as computer:- agent = ComputerAgent(- model="huggingface-local/ByteDance-Seed/UI-TARS-1.5-7B",- tools=[computer]- )- messages = [{"role": "user", "content": "Take a screenshot"}]- async for result in agent.run(messages):- for item in result["output"]:- if item["type"] == "message":- print(item["content"][0]["text"])-```--### 4. Omni Loop--**Old:**--```python-async with Computer() as computer:- agent = ComputerAgent(- computer=computer,- loop=AgentLoop.OMNI,- model=LLM(provider=LLMProvider.OLLAMA, name="gemma3")- )- async for result in agent.run("Take a screenshot"):- print(result)-```--**New:**--```python-async with Computer() as computer:- agent = ComputerAgent(- model="omniparser+ollama_chat/gemma3",- tools=[computer]- )- messages = [{"role": "user", "content": "Take a screenshot"}]- async for result in agent.run(messages):- for item in result["output"]:- if item["type"] == "message":- print(item["content"][0]["text"])-```diff --git a/docs/content/docs/guide/agents/prompt-caching.mdx b/docs/content/docs/guide/agents/prompt-caching.mdxdeleted file mode 100644index 633830ecf5..0000000000--- a/docs/content/docs/guide/agents/prompt-caching.mdx+++ /dev/null@@ -1,59 +0,0 @@-----title: Prompt Caching-sidebar_position: 8-description: How to use prompt caching in ComputerAgent and agent loops.------Prompt caching is a cost-saving feature offered by some LLM API providers that helps avoid reprocessing the same prompt, improving efficiency and reducing costs for repeated or long-running tasks.--## Usage--The `use_prompt_caching` argument is available for `ComputerAgent` and agent loops:--```python-agent = ComputerAgent(- ...,- use_prompt_caching=True,-)-```--- **Type:** `bool`-- **Default:** `False`-- **Purpose:** Use prompt caching to avoid reprocessing the same prompt.--## Anthropic CUAs--When using Anthropic-based CUAs (Claude models), setting `use_prompt_caching=True` will automatically add `{ "cache_control": "ephemeral" }` to your messages. This enables prompt caching for the session and can speed up repeated runs with the same prompt.--<Callout title="Note">- This argument is only required for Anthropic CUAs. For other providers, it is ignored.-</Callout>--## OpenAI Provider--With the OpenAI provider, prompt caching is handled automatically for prompts of 1000+ tokens. You do **not** need to set `use_prompt_caching`—caching will occur for long prompts without any extra configuration.--## Example--```python-from agent import ComputerAgent-agent = ComputerAgent(- model="anthropic/claude-sonnet-4-5-20250929",- use_prompt_caching=True,-)-```--## Implementation Details--- For Anthropic: Adds `{ "cache_control": "ephemeral" }` to messages when enabled.-- For OpenAI: Caching is automatic for long prompts; the argument is ignored.--## When to Use--- Enable for Anthropic CUAs if you want to avoid reprocessing the same prompt in repeated or iterative tasks.-- Not needed for OpenAI models unless you want explicit ephemeral cache control (not required for most users).--## See Also--- [Agent Loops](./agent-loops)-- [Migration Guide](./migration-guide)diff --git a/docs/content/docs/guide/agents/supported-agents.mdx b/docs/content/docs/guide/agents/supported-agents.mdxdeleted file mode 100644index c43d4bd18a..0000000000--- a/docs/content/docs/guide/agents/supported-agents.mdx+++ /dev/null@@ -1,219 +0,0 @@-----title: Supported Agents-description: Computer-use agents, grounding models, composed agents, and human-in-the-loop------import { Tabs, Tab } from 'fumadocs-ui/components/tabs';-import { Callout } from 'fumadocs-ui/components/callout';--The Agent SDK supports multiple types of agents for different use cases. All agent loops are compatible with any LLM provider supported by LiteLLM.--<Tabs items={['All-in-one CUAs', 'Grounding Models', 'Composed Agents', 'Human-in-the-Loop']}>-<Tab value="All-in-one CUAs">--## Computer-Use Agents--These models support complete computer-use agent functionality through `ComputerAgent.run()`. They can understand natural language instructions and autonomously perform sequences of actions.--### Anthropic Claude--Claude models with computer-use capabilities:--| Model | ID |-|-------|-----|-| Claude 4.5 | `claude-sonnet-4-5-20250929`, `claude-haiku-4-5-20251001` |-| Claude 4.1 | `claude-opus-4-1-20250805` |-| Claude 4 | `claude-opus-4-20250514`, `claude-sonnet-4-20250514` |-| Claude 3.7 | `claude-3-7-sonnet-20250219` |--```python-agent = ComputerAgent("claude-sonnet-4-5-20250929", tools=[computer])-async for _ in agent.run("Open Firefox and navigate to github.com"):- pass-```--### Google Gemini--- Gemini 2.5 CUA: `gemini-2.5-computer-use-preview-10-2025`--```python-agent = ComputerAgent("gemini-2.5-computer-use-preview-10-2025", tools=[computer])-async for _ in agent.run("Open Firefox and navigate to github.com"):- pass-```--### OpenAI--- Computer-use-preview: `computer-use-preview`--```python-agent = ComputerAgent("openai/computer-use-preview", tools=[computer])-async for _ in agent.run("Take a screenshot and describe what you see"):- pass-```--### Other Models--| Model | ID |-|-------|-----|-| GLM-4.5V | `openrouter/z-ai/glm-4.5v` |-| InternVL 3.5 | `huggingface-local/OpenGVLab/InternVL3_5-{1B,2B,4B,8B,...}` |-| Qwen3 VL | `cua/qwen/qwen3-vl-235b` (via Cua VLM Router) |-| UI-TARS 1.5 | `huggingface-local/ByteDance-Seed/UI-TARS-1.5-7B` |--</Tab>-<Tab value="Grounding Models">--## Grounding Models--These models specialize in UI element grounding and click prediction. They can identify precise coordinates for UI elements based on natural language descriptions.--Use `ComputerAgent.predict_click()` to get coordinates for specific UI elements.--<Callout type="info">-All models that support `ComputerAgent.run()` also support `ComputerAgent.predict_click()`.-</Callout>--### Specialized Grounding Models--| Model | ID |-|-------|-----|-| OpenCUA | `huggingface-local/xlangai/OpenCUA-{7B,32B}` |-| GTA1 | `huggingface-local/HelloKKMe/GTA1-{7B,32B,72B}` |-| Holo 1.5 | `huggingface-local/Hcompany/Holo1.5-{3B,7B,72B}` |-| InternVL 3.5 | `huggingface-local/OpenGVLab/InternVL3_5-{1B,2B,4B,8B,...}` |-| OmniParser | `omniparser` (requires LLM combination) |-| Moondream3 | `moondream3` |--### Usage--```python-agent = ComputerAgent("claude-sonnet-4-5-20250929", tools=[computer])--# Predict coordinates for specific elements-login_coords = agent.predict_click("find the login button")-search_coords = agent.predict_click("locate the search text field")--print(f"Login button: {login_coords}")-print(f"Search field: {search_coords}")-```--```python-# GTA1 for click prediction only-agent = ComputerAgent("huggingface-local/HelloKKMe/GTA1-7B", tools=[computer])-coords = agent.predict_click("find the submit button")-print(f"Click coordinates: {coords}") # (450, 320)--# Note: GTA1 cannot perform autonomous task planning-# Use composed agents for full capabilities-```--</Tab>-<Tab value="Composed Agents">--## Composed Agents--Combine specialized grounding models with powerful LLMs for task planning using the format `"grounding_model+planning_model"`.--### How It Works--1. **Planning Phase**: The LLM analyzes the task and decides what actions to take-2. **Grounding Phase**: The grounding model converts element descriptions to precise coordinates-3. **Execution**: Actions are performed using the predicted coordinates--### Examples--**GTA1 + Claude 4.5 Sonnet**--```python-agent = ComputerAgent(- "huggingface-local/HelloKKMe/GTA1-7B+anthropic/claude-sonnet-4-5-20250929",- tools=[computer]-)--async for _ in agent.run("Open Firefox, navigate to github.com, and search for 'computer-use'"):- pass-```--**GTA1 + GPT-5**--```python-agent = ComputerAgent(- "huggingface-local/HelloKKMe/GTA1-7B+openai/gpt-5",- tools=[computer]-)--async for _ in agent.run("Take a screenshot and click on the most prominent button"):- pass-```--**Moondream3 + GPT-4o**--```python-agent = ComputerAgent(- "moondream3+openai/gpt-4o",- tools=[computer]-)--async for _ in agent.run("Close the settings window, then open Downloads"):- pass-```--### Benefits--- **Specialized Grounding**: Use models optimized for click prediction accuracy-- **Flexible Planning**: Choose any LLM for task reasoning-- **Cost Optimization**: Use smaller grounding models with larger planning models--</Tab>-<Tab value="Human-in-the-Loop">--## Human-in-the-Loop--Use humans as agents for evaluation, demonstrations, and interactive control.--### Getting Started--Start the human agent tool:--```bash-python -m agent.human_tool-```--The UI will show pending completions. Select a completion to take control of the agent.--### Usage--**Direct Human Agent**--```python-agent = ComputerAgent(- "human/human",- tools=[computer]-)--async for _ in agent.run("Take a screenshot and click on the most prominent button"):- pass-```--**Composed with Grounding Model**--```python-agent = ComputerAgent(- "huggingface-local/HelloKKMe/GTA1-7B+human/human",- tools=[computer]-)--async for _ in agent.run("Navigate to settings and enable dark mode"):- pass-```--### Use Cases--- **Evaluation**: Have humans evaluate agent performance and provide ground truth-- **Demonstrations**: Create training data by having humans demonstrate tasks-- **Interactive Control**: Take manual control when automated agents need guidance-- **Testing**: Validate agent, tool, and environment behavior manually--</Tab>-</Tabs>diff --git a/docs/content/docs/guide/agents/telemetry.mdx b/docs/content/docs/guide/agents/telemetry.mdxdeleted file mode 100644index 4dcb80a897..0000000000--- a/docs/content/docs/guide/agents/telemetry.mdx+++ /dev/null@@ -1,135 +0,0 @@-----title: Telemetry-description: How telemetry works in Cua and how to control it------# Telemetry--Cua collects anonymized usage and error statistics. We follow [Posthog's ethical telemetry approach](https://posthog.com/blog/open-source-telemetry-ethical). To opt out, set `telemetry_enabled` to false.--## What we collect--### Enabled by default (opt-out)--- System info: OS, OS version, Python version-- Module initialization: When modules are imported and their versions-- Performance: Agent run durations, step counts, token usage, API costs-- Session tracking: Anonymous session IDs and run IDs--### Disabled by default (opt-in)--**Trajectory logging** captures full conversation history:--- User messages and agent responses-- Computer actions and outputs-- Agent reasoning traces--Must be explicitly enabled.--### We don't collect--- Personal information or user identifiers-- API keys or credentials-- File contents or application data-- Files being accessed-- Screenshots or screen contents (unless trajectory logging is enabled)-- Text being typed, user inputs, model outputs, computer outputs, or tool call outputs (unless trajectory logging is enabled)--## How to disable--### Environment variable (global)--Set `CUA_TELEMETRY_ENABLED` to a falsy value (`0`, `false`, `no`, or `off`):--```bash-export CUA_TELEMETRY_ENABLED=false-```--Or in Python:--```python-import os-os.environ["CUA_TELEMETRY_ENABLED"] = "false"-```--<Callout type="info">- **Deprecated environment variables:** The environment variables `CUA_TELEMETRY` and- `CUA_TELEMETRY_DISABLED` are deprecated and no longer have any effect. Use `CUA_TELEMETRY_ENABLED`- instead.-</Callout>--### Per instance--**Computer SDK:**--```python-from computer import Computer--computer = Computer(telemetry_enabled=False)-```--**Agent SDK:**--```python-from agent import ComputerAgent-import os--# Basic telemetry - performance metrics only (opt-out, enabled by default)-agent = ComputerAgent(- model="claude-sonnet-4-5-20250929",- telemetry_enabled=True # Default is True-)--# Enable telemetry with full conversation trajectory logging (opt-in)-agent = ComputerAgent(- model="claude-sonnet-4-5-20250929",- telemetry_enabled={- "log_trajectory": True # Logs full conversation items- }-)--# Disable completely-agent = ComputerAgent(- model="claude-sonnet-4-5-20250929",- telemetry_enabled=False-)--# Enable trajectory logging (opt-in)-agent = ComputerAgent(- model="claude-sonnet-4-5-20250929",- telemetry_enabled={"log_trajectory": True}-)-```--Check status:--```python-print(computer.telemetry_enabled) # True or False-print(agent.telemetry_enabled) # True, False, or dict-```--Telemetry settings are configured at initialization and can't be changed afterward.--## Events collected--### Computer SDK--| Event Name | Data Collected | Trigger Notes |-| ------------------------ | ------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------- |-| **computer_initialized** | • `os`: Operating system (e.g., 'windows', 'darwin', 'linux')<br />• `os_version`: OS version<br />• `python_version`: Python version | Triggered when a Computer instance is created |-| **module_init** | • `module`: "computer"<br />• `version`: Package version<br />• `python_version`: Full Python version string | Triggered once when the computer package is imported for the first time |--### Agent SDK--| Event Name | Data Collected | Trigger Notes |-| ----------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------- |-| **module_init** | • `module`: "agent"<br />• `version`: Package version<br />• `python_version`: Full Python version string | Triggered once when the agent package is imported for the first time |-| **agent_session_start** | • `session_id`: Unique UUID for this agent instance<br />• `agent_type`: Class name (e.g., "ComputerAgent")<br />• `model`: Model name (e.g., "claude-sonnet-4-5")<br />• `os`: Operating system<br />• `os_version`: OS version<br />• `python_version`: Python version | Triggered when TelemetryCallback is initialized (agent instantiation) |-| **agent_run_start** | • `session_id`: Agent session UUID<br />• `run_id`: Unique UUID for this run<br />• `start_time`: Unix timestamp<br />• `input_context_size`: Character count of input messages<br />• `num_existing_messages`: Count of existing messages<br />• `uploaded_trajectory`: Full conversation items (opt-in) | Triggered at the start of each agent.run() call |-| **agent_run_end** | • `session_id`: Agent session UUID<br />• `run_id`: Run UUID<br />• `end_time`: Unix timestamp<br />• `duration_seconds`: Total run duration<br />• `num_steps`: Total steps taken in this run<br />• `total_usage`: Accumulated token usage and costs<br />• `uploaded_trajectory`: Full conversation items (opt-in) | Triggered at the end of each agent.run() call |-| **agent_step** | • `session_id`: Agent session UUID<br />• `run_id`: Run UUID<br />• `step`: Step number (incremental)<br />• `timestamp`: Unix timestamp<br />• `duration_seconds`: Duration of previous step | Triggered on each agent response/step during a run |-| **agent_usage** | • `session_id`: Agent session UUID<br />• `run_id`: Run UUID<br />• `step`: Current step number<br />• `prompt_tokens`: Tokens in prompt<br />• `completion_tokens`: Tokens in response<br />• `total_tokens`: Total tokens used<br />• `response_cost`: Cost of this API call | Triggered whenever usage information is received from LLM API |--## Questions--Questions about telemetry? Open an issue on our [GitHub repository](https://github.com/trycua/cua).diff --git a/docs/content/docs/guide/agents/usage-tracking.mdx b/docs/content/docs/guide/agents/usage-tracking.mdxdeleted file mode 100644index 425c694e36..0000000000--- a/docs/content/docs/guide/agents/usage-tracking.mdx+++ /dev/null@@ -1,64 +0,0 @@-----title: Usage Tracking-sidebar_position: 9-description: How to track token usage and cost in ComputerAgent and agent loops.------Tracking usage is important for monitoring costs and optimizing your agent workflows. The ComputerAgent API provides easy access to token and cost usage for every run.--## Accessing Usage Data--Whenever you run an agent loop, each result contains a `usage` dictionary with token and cost information:--```python-async for result in agent.run(...):- print(result["usage"])- # Example output:- # {- # "prompt_tokens": 150,- # "completion_tokens": 75,- # "total_tokens": 225,- # "response_cost": 0.01,- # }-```--- `prompt_tokens`: Number of tokens in the prompt-- `completion_tokens`: Number of tokens in the agent's response-- `total_tokens`: Total tokens used-- `response_cost`: Estimated cost (USD) for this turn--## Tracking Total Usage--You can accumulate usage across multiple turns:--```python-total_usage = {"prompt_tokens": 0, "completion_tokens": 0, "total_tokens": 0, "response_cost": 0.0}-async for result in agent.run(...):- for k in total_usage:- total_usage[k] += result["usage"].get(k, 0)-print("Total usage:", total_usage)-```--## Using Callbacks for Usage Tracking--You can also use a callback to automatically track usage. Implement the `on_usage` method in your callback class:--```python-from agent.callbacks import AsyncCallbackHandler--class UsageTrackerCallback(AsyncCallbackHandler):- async def on_usage(self, usage):- print("Usage update:", usage)--agent = ComputerAgent(- ...,- callbacks=[UsageTrackerCallback()]-)-```--See also: [Budget Manager Callbacks](./callbacks/cost-saving)--## See Also--- [Prompt Caching](./prompt-caching)-- [Callbacks](./callbacks)diff --git a/docs/content/docs/guide/computers/cloud-vm-management.mdx b/docs/content/docs/guide/computers/cloud-vm-management.mdxdeleted file mode 100644index 21174bd4f3..0000000000--- a/docs/content/docs/guide/computers/cloud-vm-management.mdx+++ /dev/null@@ -1,267 +0,0 @@-----title: Cloud Sandbox Management-description: Manage your Cua Cloud sandboxes via Python SDK or HTTP API------import { Tab, Tabs } from 'fumadocs-ui/components/tabs';--Using the Cua Cloud API, you can manage your Cua Cloud sandboxes with Python or HTTP (curl).--All examples require a Cua API key. You can obtain one from the [Dashboard](https://www.cua.ai/dashboard/keys).-------## List Sandboxes--<Tabs items={['Python', 'curl']}>- <Tab value="Python">--```python-import asyncio-from computer.providers.cloud.provider import CloudProvider--async def main():- # CloudProvider automatically reads CUA_API_KEY from environment- # You can also pass api_key explicitly: CloudProvider(api_key="your-api-key")- # Optional: point to a different API base- # os.environ["CUA_API_BASE"] = "https://api.cua.ai"-- provider = CloudProvider(verbose=False)- async with provider:- vms = await provider.list_vms()- for vm in vms:- print({- "name": vm["name"],- "status": vm["status"],- "api_url": vm.get("api_url"),- "vnc_url": vm.get("vnc_url"),- })--if __name__ == "__main__":- asyncio.run(main())-```-- </Tab>- <Tab value="curl">--```bash-curl -H "Authorization: Bearer $CUA_API_KEY" \- "https://api.cua.ai/v1/vms"-```--Responses:--- 200: Array of minimal sandbox objects with fields `{ name, password, status }`-- 401: Unauthorized (missing/invalid API key)--```json-[- {- "name": "s-windows-x4snp46ebf",- "password": "49b8daa3",- "status": "running"- }-]-```--Status values:--- `pending`: Sandbox deployment in progress-- `running`: Sandbox is active and accessible-- `stopped`: Sandbox is stopped but not terminated-- `terminated`: Sandbox has been permanently destroyed-- `failed`: Sandbox deployment or operation failed------- </Tab>-- </Tabs>-------## Start a Sandbox--Provide the sandbox name you want to start.--<Tabs items={["Python", "curl"]}>- <Tab value="Python">--```python-import asyncio-from computer.providers.cloud.provider import CloudProvider--async def main():- # CloudProvider automatically reads CUA_API_KEY from environment- name = "my-vm-name" # e.g., "m-linux-96lcxd2c2k"-- provider = CloudProvider()- async with provider:- resp = await provider.run_vm(name)- print(resp) # { "name": name, "status": "starting" }--if __name__ == "__main__":- asyncio.run(main())-```-- </Tab>- <Tab value="curl">--```bash-curl -X POST \- -H "Authorization: Bearer $CUA_API_KEY" \- "https://api.cua.ai/v1/vms/my-vm-name/start" -i-```--Responses:--- 204: No Content (start accepted)-- 401: Unauthorized (missing/invalid API key)-- 404: Sandbox not found or not owned by the user--```text-HTTP/1.1 204 No Content-```-- </Tab>-</Tabs>-------## Stop a Sandbox--Stops the sandbox asynchronously.--<Tabs items={["Python", "curl"]}>- <Tab value="Python">--```python-import asyncio-from computer.providers.cloud.provider import CloudProvider--async def main():- # CloudProvider automatically reads CUA_API_KEY from environment- name = "my-vm-name"-- provider = CloudProvider()- async with provider:- resp = await provider.stop_vm(name)- print(resp) # { "name": name, "status": "stopping" }--if __name__ == "__main__":- asyncio.run(main())-```-- </Tab>- <Tab value="curl">--```bash-curl -X POST \- -H "Authorization: Bearer $CUA_API_KEY" \- "https://api.cua.ai/v1/vms/my-vm-name/stop"-```--Responses:--- 202: Accepted with `{ "status": "stopping" }`-- 401: Unauthorized (missing/invalid API key)-- 404: Sandbox not found or not owned by the user--```json-{ "status": "stopping" }-```-- </Tab>-</Tabs>-------## Restart a Sandbox--Restarts the sandbox asynchronously.--<Tabs items={["Python", "curl"]}>- <Tab value="Python">--```python-import asyncio-from computer.providers.cloud.provider import CloudProvider--async def main():- # CloudProvider automatically reads CUA_API_KEY from environment- name = "my-vm-name"-- provider = CloudProvider()- async with provider:- resp = await provider.restart_vm(name)- print(resp) # { "name": name, "status": "restarting" }--if __name__ == "__main__":- asyncio.run(main())-```-- </Tab>- <Tab value="curl">--```bash-curl -X POST \- -H "Authorization: Bearer $CUA_API_KEY" \- "https://api.cua.ai/v1/vms/my-vm-name/restart"-```--Responses:--- 202: Accepted with `{ "status": "restarting" }`-- 401: Unauthorized (missing/invalid API key)-- 404: Sandbox not found or not owned by the user--```json-{ "status": "restarting" }-```-- </Tab>-</Tabs>-------## Query a Sandbox by name--Query the computer-server running on the sandbox. Useful for checking details like status or OS type.--<Tabs items={["Python", "curl"]}>- <Tab value="Python">--```python-import asyncio-from computer.providers.cloud.provider import CloudProvider--async def main():- # CloudProvider automatically reads CUA_API_KEY from environment- name = "my-vm-name"-- provider = CloudProvider()- async with provider:- info = await provider.get_vm(name)- print(info)--if __name__ == "__main__":- asyncio.run(main())-```-- </Tab>- <Tab value="curl">--```bash-curl "https://my-vm-name.containers.cloud.cua.ai:8443/status"-```--Responses:--- 200: Server available--```json-{ "status": "ok", "os_type": "linux", "features": ["agent"] }-```-- </Tab>-</Tabs>diff --git a/docs/content/docs/guide/computers/commands.mdx b/docs/content/docs/guide/computers/commands.mdxdeleted file mode 100644index 4fc7b0ffdb..0000000000--- a/docs/content/docs/guide/computers/commands.mdx+++ /dev/null@@ -1,383 +0,0 @@-----title: Commands-description: Computer commands and interface methods------This page describes the set of supported **commands** you can use to control a Cua Computer Framework directly via the Python SDK.--These commands map to the same actions available in the [Computer Server API Commands Reference](/computer-sdk/computer-server/Commands), and provide low-level, async access to system operations from your agent or automation code.--## Shell Actions--Execute shell commands and get detailed results:--<Tabs items={['Python', 'TypeScript']}>- <Tab value="Python">-- ```python- # Run shell command- result = await computer.interface.run_command(cmd) # result.stdout, result.stderr, result.returncode- ```-- </Tab>- <Tab value="TypeScript">-- ```typescript- // Run shell command- const result = await computer.interface.runCommand(cmd); // result.stdout, result.stderr, result.returncode- ```-- </Tab>-</Tabs>--## Window Management--Control application launching and windows:--<Tabs items={['Python', 'TypeScript']}>- <Tab value="Python">-- ```python- # Launch applications- await computer.interface.launch("xfce4-terminal")- await computer.interface.launch("libreoffice --writer")- await computer.interface.open("https://www.google.com")-- # Window management- windows = await computer.interface.get_application_windows("xfce4-terminal")- window_id = windows[0]- await computer.interface.activate_window(window_id)-- window_id = await computer.interface.get_current_window_id() # get the current active window id- await computer.interface.window_size(window_id)- await computer.interface.get_window_title(window_id)- await computer.interface.get_window_position(window_id)- await computer.interface.set_window_size(window_id, 1200, 800)- await computer.interface.set_window_position(window_id, 100, 100)- await computer.interface.maximize_window(window_id)- await computer.interface.minimize_window(window_id)- await computer.interface.close_window(window_id)- ```-- </Tab>- <Tab value="TypeScript">-- ```typescript- // Launch applications- await computer.interface.launch("xfce4-terminal");- await computer.interface.launch("libreoffice --writer");- await computer.interface.open("https://www.google.com");-- // Window management- const windows = await computer.interface.getApplicationWindows("xfce4-terminal");- let windowId = windows[0];- await computer.interface.activateWindow(windowId);-- windowId = await computer.interface.getCurrentWindowId(); // current active window id- await computer.interface.getWindowSize(windowId);- await computer.interface.getWindowName(windowId);- await computer.interface.getWindowPosition(windowId);- await computer.interface.setWindowSize(windowId, 1200, 800);- await computer.interface.setWindowPosition(windowId, 100, 100);- await computer.interface.maximizeWindow(windowId);- await computer.interface.minimizeWindow(windowId);- await computer.interface.closeWindow(windowId);- ```-- </Tab>-</Tabs>--## Mouse Actions--Precise mouse control and interaction:--<Tabs items={['Python', 'TypeScript']}>- <Tab value="Python">-- ```python- # Basic clicks- await computer.interface.left_click(x, y) # Left click at coordinates- await computer.interface.right_click(x, y) # Right click at coordinates- await computer.interface.double_click(x, y) # Double click at coordinates-- # Cursor movement and dragging- await computer.interface.move_cursor(x, y) # Move cursor to coordinates- await computer.interface.drag_to(x, y, duration) # Drag to coordinates- await computer.interface.get_cursor_position() # Get current cursor position-- # Advanced mouse control- await computer.interface.mouse_down(x, y, button="left") # Press and hold a mouse button- await computer.interface.mouse_up(x, y, button="left") # Release a mouse button- ```-- </Tab>- <Tab value="TypeScript">-- ```typescript- // Basic clicks- await computer.interface.leftClick(x, y); // Left click at coordinates- await computer.interface.rightClick(x, y); // Right click at coordinates- await computer.interface.doubleClick(x, y); // Double click at coordinates-- // Cursor movement and dragging- await computer.interface.moveCursor(x, y); // Move cursor to coordinates- await computer.interface.dragTo(x, y, duration); // Drag to coordinates- await computer.interface.getCursorPosition(); // Get current cursor position-- // Advanced mouse control- await computer.interface.mouseDown(x, y, "left"); // Press and hold a mouse button- await computer.interface.mouseUp(x, y, "left"); // Release a mouse button- ```-- </Tab>-</Tabs>--## Keyboard Actions--Text input and key combinations:--<Tabs items={['Python', 'TypeScript']}>- <Tab value="Python">-- ```python- # Text input- await computer.interface.type_text("Hello") # Type text- await computer.interface.press_key("enter") # Press a single key-- # Key combinations and advanced control- await computer.interface.hotkey("command", "c") # Press key combination- await computer.interface.key_down("command") # Press and hold a key- await computer.interface.key_up("command") # Release a key- ```-- </Tab>- <Tab value="TypeScript">-- ```typescript- // Text input- await computer.interface.typeText("Hello"); // Type text- await computer.interface.pressKey("enter"); // Press a single key-- // Key combinations and advanced control- await computer.interface.hotkey("command", "c"); // Press key combination- await computer.interface.keyDown("command"); // Press and hold a key- await computer.interface.keyUp("command"); // Release a key- ```-- </Tab>-</Tabs>--## Scrolling Actions--Mouse wheel and scrolling control:--<Tabs items={['Python', 'TypeScript']}>- <Tab value="Python">-- ```python- # Scrolling- await computer.interface.scroll(x, y) # Scroll the mouse wheel- await computer.interface.scroll_down(clicks) # Scroll down- await computer.interface.scroll_up(clicks) # Scroll up- ```-- </Tab>- <Tab value="TypeScript">-- ```typescript- // Scrolling- await computer.interface.scroll(x, y); // Scroll the mouse wheel- await computer.interface.scrollDown(clicks); // Scroll down- await computer.interface.scrollUp(clicks); // Scroll up- ```-- </Tab>-</Tabs>--## Screen Actions--Screen capture and display information:--<Tabs items={['Python', 'TypeScript']}>- <Tab value="Python">-- ```python- # Screen operations- await computer.interface.screenshot() # Take a screenshot- await computer.interface.get_screen_size() # Get screen dimensions- ```-- </Tab>- <Tab value="TypeScript">-- ```typescript- // Screen operations- await computer.interface.screenshot(); // Take a screenshot- await computer.interface.getScreenSize(); // Get screen dimensions- ```-- </Tab>-</Tabs>--## Desktop Actions--Control desktop environment features like wallpaper:--<Tabs items={['Python', 'TypeScript']}>- <Tab value="Python">- ```python- # Get current desktop environment (e.g., 'xfce4', 'gnome', 'kde', 'mac', 'windows')- env = await computer.interface.get_desktop_environment()- print(env) # "xfce4"-- # Set desktop wallpaper to an image file accessible on the sandbox- await computer.interface.set_wallpaper("/home/cua/shared/wallpaper.png")- ```-- </Tab>- <Tab value="TypeScript">- ```typescript- // Get current desktop environment- const env = await computer.interface.getDesktopEnvironment();- print(env) # "xfce4"-- // Set desktop wallpaper to an image file accessible on the sandbox- await computer.interface.setWallpaper('/home/cua/shared/wallpaper.png');- ```-- </Tab>-</Tabs>--## Clipboard Actions--System clipboard management:--<Tabs items={['Python', 'TypeScript']}>- <Tab value="Python">-- ```python- # Clipboard operations- await computer.interface.set_clipboard(text) # Set clipboard content- await computer.interface.copy_to_clipboard() # Get clipboard content- ```-- </Tab>- <Tab value="TypeScript">-- ```typescript- // Clipboard operations- await computer.interface.setClipboard(text); // Set clipboard content- await computer.interface.copyToClipboard(); // Get clipboard content- ```-- </Tab>-</Tabs>--## File System Operations--Direct file and directory manipulation:--<Tabs items={['Python', 'TypeScript']}>- <Tab value="Python">-- ```python- # File existence checks- await computer.interface.file_exists(path) # Check if file exists- await computer.interface.directory_exists(path) # Check if directory exists-- # File content operations- await computer.interface.read_text(path, encoding="utf-8") # Read file content- await computer.interface.write_text(path, content, encoding="utf-8") # Write file content- await computer.interface.read_bytes(path) # Read file content as bytes- await computer.interface.write_bytes(path, content) # Write file content as bytes-- # File and directory management- await computer.interface.delete_file(path) # Delete file- await computer.interface.create_dir(path) # Create directory- await computer.interface.delete_dir(path) # Delete directory- await computer.interface.list_dir(path) # List directory contents- ```-- </Tab>- <Tab value="TypeScript">-- ```typescript- // File existence checks- await computer.interface.fileExists(path); // Check if file exists- await computer.interface.directoryExists(path); // Check if directory exists-- // File content operations- await computer.interface.readText(path, "utf-8"); // Read file content- await computer.interface.writeText(path, content, "utf-8"); // Write file content- await computer.interface.readBytes(path); // Read file content as bytes- await computer.interface.writeBytes(path, content); // Write file content as bytes-- // File and directory management- await computer.interface.deleteFile(path); // Delete file- await computer.interface.createDir(path); // Create directory- await computer.interface.deleteDir(path); // Delete directory- await computer.interface.listDir(path); // List directory contents- ```-- </Tab>-</Tabs>--## Accessibility--Access system accessibility information:--<Tabs items={['Python', 'TypeScript']}>- <Tab value="Python">-- ```python- # Get accessibility tree- await computer.interface.get_accessibility_tree()- ```-- </Tab>- <Tab value="TypeScript">-- ```typescript- // Get accessibility tree- await computer.interface.getAccessibilityTree();- ```-- </Tab>-</Tabs>--## Delay Configuration--Control timing between actions:--<Tabs items={['Python']}>- <Tab value="Python">-- ```python- # Set default delay between all actions (in seconds)- computer.interface.delay = 0.5 # 500ms delay between actions-- # Or specify delay for individual actions- await computer.interface.left_click(x, y, delay=1.0) # 1 second delay after click- await computer.interface.type_text("Hello", delay=0.2) # 200ms delay after typing- await computer.interface.press_key("enter", delay=0.5) # 500ms delay after key press- ```-- </Tab>-</Tabs>--## Python Virtual Environment Operations--Manage Python environments:--<Tabs items={['Python']}>- <Tab value="Python">-- ```python- # Virtual environment management- await computer.venv_install("demo_venv", ["requests", "macos-pyxa"]) # Install packages in a virtual environment- await computer.venv_cmd("demo_venv", "python -c 'import requests; print(requests.get(`https://httpbin.org/ip`).json())'') # Run a shell command in a virtual environment- await computer.venv_exec("demo_venv", python_function_or_code, *args, **kwargs) # Run a Python function in a virtual environment and return the result / raise an exception- ```-- </Tab>-</Tabs>diff --git a/docs/content/docs/guide/computers/computer-ui.mdx b/docs/content/docs/guide/computers/computer-ui.mdxdeleted file mode 100644index 3e576f03d5..0000000000--- a/docs/content/docs/guide/computers/computer-ui.mdx+++ /dev/null@@ -1,99 +0,0 @@-----title: Computer UI------<Callout type="warn" title="Deprecated">- The Computer UI is deprecated and will be replaced with a revamped playground experience soon. We- recommend using VNC or Screen Sharing for precise control of the computer instead.-</Callout>--The computer module includes a Gradio UI for creating and sharing demonstration data. We make it easy for people to build community datasets for better computer use models with an upload to Huggingface feature.--```bash-# Install with UI support-pip install "cua-computer[ui]"-```--<Callout title="Note">- For precise control of the computer, we recommend using VNC or Screen Sharing instead of the- Computer Gradio UI.-</Callout>--### Building and Sharing Demonstrations with Huggingface--Follow these steps to contribute your own demonstrations:--#### 1. Set up Huggingface Access--Set your HF_TOKEN in a .env file or in your environment variables:--```bash-# In .env file-HF_TOKEN=your_huggingface_token-```--#### 2. Launch the Computer UI--```python-# launch_ui.py-from computer.ui.gradio.app import create_gradio_ui-from dotenv import load_dotenv-load_dotenv('.env')--app = create_gradio_ui()-app.launch(share=False)-```--For examples, see [Computer UI Examples](https://github.com/trycua/cua/tree/main/examples/computer_ui_examples.py)--#### 3. Record Your Tasks--<details open>- <summary>View demonstration video</summary>- <video- src="https://github.com/user-attachments/assets/de3c3477-62fe-413c-998d-4063e48de176"- controls- width="600"- ></video>-</details>--Record yourself performing various computer tasks using the UI.--#### 4. Save Your Demonstrations--<details open>- <summary>View demonstration video</summary>- <video- src="https://github.com/user-attachments/assets/5ad1df37-026a-457f-8b49-922ae805faef"- controls- width="600"- ></video>-</details>--Save each task by picking a descriptive name and adding relevant tags (e.g., "office", "web-browsing", "coding").--#### 5. Record Additional Demonstrations--Repeat steps 3 and 4 until you have a good amount of demonstrations covering different tasks and scenarios.--#### 6. Upload to Huggingface--<details open>- <summary>View demonstration video</summary>- <video- src="https://github.com/user-attachments/assets/c586d460-3877-4b5f-a736-3248886d2134"- controls- width="600"- ></video>-</details>--Upload your dataset to Huggingface by:--- Naming it as `{your_username}/{dataset_name}`-- Choosing public or private visibility-- Optionally selecting specific tags to upload only tasks with certain tags--#### Examples and Resources--- Example Dataset: [ddupont/test-dataset](https://huggingface.co/datasets/ddupont/test-dataset)-- Find Community Datasets: 🔍 [Browse CUA Datasets on Huggingface](https://huggingface.co/datasets?other=cua)diff --git a/docs/content/docs/guide/computers/custom-computer-handlers.mdx b/docs/content/docs/guide/computers/custom-computer-handlers.mdxdeleted file mode 100644index d166888344..0000000000--- a/docs/content/docs/guide/computers/custom-computer-handlers.mdx+++ /dev/null@@ -1,130 +0,0 @@-----title: Custom Computers-slug: custom-computer-handlers------The Agent SDK supports defining custom computer handlers using a simple dictionary interface. This enables integration with custom automation backends, testing frameworks, or specialized computer control systems.--## Example: Defining a Custom Computer Handler--```python-import asyncio-from PIL import Image--# Define your custom computer functions-async def take_screenshot():- """Your custom screenshot implementation"""- # Return PIL Image, bytes, or base64 string- return Image.new('RGB', (1920, 1080), color='white')--# Create dict-based computer handler - only 'screenshot' is required-custom_computer = {- 'screenshot': take_screenshot, # required-- # everything below is optional- 'environment': 'linux', # linux, mac, windows, browser- 'dimensions': (1920, 1080), # (width, height)- 'click': lambda x, y, button: print(f"Clicking at ({x}, {y}) with {button} button"),-}-```--You can then use this as a tool for your agent:--```python-from agent import ComputerAgent--agent = ComputerAgent(- model="cua/anthropic/claude-sonnet-4.5",- tools=[custom_computer],-)--# Agent will automatically convert dict to agent.computers.CustomComputerHandler-await agent.run("Take a screenshot and click at coordinates 100, 200")-```--## Class-Based Implementation--For more complex implementations, you can create a custom class by inheriting from `AsyncComputerHandler`:--```python-from agent.computers import AsyncComputerHandler-from PIL import Image-from typing import Literal, List, Dict, Union, Optional--class MyCustomComputer(AsyncComputerHandler):- """Custom computer handler implementation."""-- def __init__(self):- # Initialize your custom computer interface here- pass-- # ==== Computer-Use-Preview Action Space ====-- async def get_environment(self) -> Literal["windows", "mac", "linux", "browser"]:- """Get the current environment type."""- ...-- async def get_dimensions(self) -> tuple[int, int]:- """Get screen dimensions as (width, height)."""- ...-- async def screenshot(self) -> str:- """Take a screenshot and return as base64 string."""- ...-- async def click(self, x: int, y: int, button: str = "left") -> None:- """Click at coordinates with specified button."""- ...-- async def double_click(self, x: int, y: int) -> None:- """Double click at coordinates."""- ...-- async def scroll(self, x: int, y: int, scroll_x: int, scroll_y: int) -> None:- """Scroll at coordinates with specified scroll amounts."""- ...-- async def type(self, text: str) -> None:- """Type text."""- ...-- async def wait(self, ms: int = 1000) -> None:- """Wait for specified milliseconds."""- ...-- async def move(self, x: int, y: int) -> None:- """Move cursor to coordinates."""- ...-- async def keypress(self, keys: Union[List[str], str]) -> None:- """Press key combination."""- ...-- async def drag(self, path: List[Dict[str, int]]) -> None:- """Drag along specified path."""- ...-- async def get_current_url(self) -> str:- """Get current URL (for browser environments)."""- ...-- # ==== Anthropic Action Space ====-- async def left_mouse_down(self, x: Optional[int] = None, y: Optional[int] = None) -> None:- """Left mouse down at coordinates."""- ...-- async def left_mouse_up(self, x: Optional[int] = None, y: Optional[int] = None) -> None:- """Left mouse up at coordinates."""- ...--# Use with agent-custom_computer = MyCustomComputer()--agent = ComputerAgent(- model="cua/anthropic/claude-sonnet-4.5",- tools=[custom_computer],-)--await agent.run("Take a screenshot and click at coordinates 100, 200")-```diff --git a/docs/content/docs/guide/computers/meta.json b/docs/content/docs/guide/computers/meta.jsondeleted file mode 100644index 676afafba5..0000000000--- a/docs/content/docs/guide/computers/meta.json+++ /dev/null@@ -1,13 +0,0 @@-{- "title": "Computers",- "description": "Working with sandboxed computers and VMs",- "icon": "Monitor",- "pages": [- "commands",- "sandboxed-python",- "computer-ui",- "tracing-api",- "custom-computer-handlers",- "cloud-vm-management"- ]-}diff --git a/docs/content/docs/guide/computers/sandboxed-python.mdx b/docs/content/docs/guide/computers/sandboxed-python.mdxdeleted file mode 100644index 8db37c13f5..0000000000--- a/docs/content/docs/guide/computers/sandboxed-python.mdx+++ /dev/null@@ -1,86 +0,0 @@-----title: Sandboxed Python-slug: sandboxed-python------<Callout>- A corresponding{' '}- <a- href="https://github.com/trycua/cua/blob/main/examples/sandboxed_functions_examples.py"- target="_blank"- >- Python example- </a>{' '}- is available for this documentation.-</Callout>--You can run Python functions securely inside a sandboxed virtual environment on a remote Cua Computer Framework. This is useful for executing untrusted user code, isolating dependencies, or providing a safe environment for automation tasks.--## How It Works--The `sandboxed` decorator from the Computer SDK wraps a Python function so that it is executed remotely in a specified virtual environment on the target Computer. The function and its arguments are serialized, sent to the remote, and executed in isolation. Results or errors are returned to the caller.--## Example Usage--```python-from computer import Computer-from computer.helpers import sandboxed--@sandboxed()-def read_file(location: str) -> str:- """Read contents of a file"""- with open(location, 'r') as f:- return f.read()--async def main():- async with Computer(os_type="linux", provider_type="cloud", name="my-sandbox", api_key="...") as computer:- # Call the sandboxed function (runs remotely)- result = await read_file("/etc/hostname")- print(result)-```--## Installing Python Packages--You can specify the virtual environment name and target computer:--```python-@sandboxed(venv_name="myenv", computer=my_computer, max_retries=5)-def my_function(...):- ...-```--You can also install packages in the virtual environment using the `venv_install` method:--```python-await my_computer.venv_install("myenv", ["requests"])-```--## Example: Interacting with macOS Applications--You can use sandboxed functions to interact with macOS applications on a local Cua Computer Framework (requires `os_type="darwin"`). This is particularly useful for automation tasks that involve GUI applications.--```python-# Example: Use sandboxed functions to execute code in a Cua Sandbox-from computer.helpers import sandboxed--await computer.venv_install("demo_venv", ["macos-pyxa"]) # Install packages in a virtual environment--@sandboxed("demo_venv")-def greet_and_print(name):- """Get the HTML of the current Safari tab"""- import PyXA- safari = PyXA.Application("Safari")- html = safari.current_document.source()- print(f"Hello from inside the sandbox, {name}!")- return {"greeted": name, "safari_html": html}--# When a @sandboxed function is called, it will execute in the sandbox-result = await greet_and_print("Cua")-# Result: {"greeted": "Cua", "safari_html": "<html>...</html>"}-# stdout and stderr are also captured and printed / raised-print("Result from sandboxed function:", result)-```--## Error Handling--If the remote execution fails, the decorator will retry up to `max_retries` times. If all attempts fail, the last exception is raised locally.diff --git a/docs/content/docs/guide/computers/tracing-api.mdx b/docs/content/docs/guide/computers/tracing-api.mdxdeleted file mode 100644index 9595b144aa..0000000000--- a/docs/content/docs/guide/computers/tracing-api.mdx+++ /dev/null@@ -1,345 +0,0 @@-----title: Tracing-description: Record computer interactions for debugging, training, and analysis------# Tracing--The Computer tracing API provides a powerful way to record computer interactions for debugging, training, analysis, and compliance purposes. Inspired by Playwright's tracing functionality, it offers flexible recording options and standardized output formats.--## Overview--The tracing API allows you to:--- Record screenshots at key moments-- Log all API calls and their results-- Capture accessibility tree snapshots-- Add custom metadata-- Export recordings in standardized formats-- Support for both automated and human-in-the-loop workflows--## Basic Usage--### Starting and Stopping Traces--```python-from computer import Computer--computer = Computer(os_type="macos")-await computer.run()--# Start tracing with default options-await computer.tracing.start()--# Perform some operations-await computer.interface.left_click(100, 200)-await computer.interface.type_text("Hello, World!")-await computer.interface.press_key("enter")--# Stop tracing and save-trace_path = await computer.tracing.stop()-print(f"Trace saved to: {trace_path}")-```--### Custom Configuration--```python-# Start tracing with custom configuration-await computer.tracing.start({- 'video': False, # Record video frames- 'screenshots': True, # Record screenshots (default: True)- 'api_calls': True, # Record API calls (default: True)- 'accessibility_tree': True, # Record accessibility snapshots- 'metadata': True, # Allow custom metadata (default: True)- 'name': 'my_custom_trace', # Custom trace name- 'path': './my_traces' # Custom output directory-})--# Add custom metadata during tracing-await computer.tracing.add_metadata('user_id', 'user123')-await computer.tracing.add_metadata('test_case', 'login_flow')--# Stop with custom options-trace_path = await computer.tracing.stop({- 'path': './exports/trace.zip',- 'format': 'zip' # 'zip' or 'dir'-})-```--## Configuration Options--### Start Options--| Option | Type | Default | Description |-| -------------------- | ---- | -------------- | ------------------------------------- |-| `video` | bool | `False` | Record video frames (future feature) |-| `screenshots` | bool | `True` | Capture screenshots after key actions |-| `api_calls` | bool | `True` | Log all interface method calls |-| `accessibility_tree` | bool | `False` | Record accessibility tree snapshots |-| `metadata` | bool | `True` | Enable custom metadata recording |-| `name` | str | auto-generated | Custom name for the trace |-| `path` | str | auto-generated | Custom directory for trace files |--### Stop Options--| Option | Type | Default | Description |-| -------- | ---- | -------------- | ---------------------------------- |-| `path` | str | auto-generated | Custom output path for final trace |-| `format` | str | `'zip'` | Output format: `'zip'` or `'dir'` |--## Use Cases--### Custom Agent Development--```python-from computer import Computer--async def test_custom_agent():- computer = Computer(os_type="linux")- await computer.run()-- # Start tracing for this test session- await computer.tracing.start({- 'name': 'custom_agent_test',- 'screenshots': True,- 'accessibility_tree': True- })-- # Your custom agent logic here- screenshot = await computer.interface.screenshot()- await computer.interface.left_click(500, 300)- await computer.interface.type_text("test input")-- # Add context about what the agent is doing- await computer.tracing.add_metadata('action', 'filling_form')- await computer.tracing.add_metadata('confidence', 0.95)-- # Save the trace- trace_path = await computer.tracing.stop()- return trace_path-```--### Training Data Collection--```python-async def collect_training_data():- computer = Computer(os_type="macos")- await computer.run()-- tasks = [- "open_browser_and_search",- "create_document",- "send_email"- ]-- for task in tasks:- # Start a new trace for each task- await computer.tracing.start({- 'name': f'training_{task}',- 'screenshots': True,- 'accessibility_tree': True,- 'metadata': True- })-- # Add task metadata- await computer.tracing.add_metadata('task_type', task)- await computer.tracing.add_metadata('difficulty', 'beginner')-- # Perform the task (automated or human-guided)- await perform_task(computer, task)-- # Save this training example- await computer.tracing.stop({- 'path': f'./training_data/{task}.zip'- })-```--### Human-in-the-Loop Recording--```python-async def record_human_demonstration():- computer = Computer(os_type="windows")- await computer.run()-- # Start recording human demonstration- await computer.tracing.start({- 'name': 'human_demo_excel_workflow',- 'screenshots': True,- 'api_calls': True, # Will capture any programmatic actions- 'metadata': True- })-- print("Trace recording started. Perform your demonstration...")- print("The system will record all computer interactions.")-- # Add metadata about the demonstration- await computer.tracing.add_metadata('demonstrator', 'expert_user')- await computer.tracing.add_metadata('workflow', 'excel_data_analysis')-- # Human performs actions manually or through other tools- # Tracing will still capture any programmatic interactions-- input("Press Enter when demonstration is complete...")-- # Stop and save the demonstration- trace_path = await computer.tracing.stop()- print(f"Human demonstration saved to: {trace_path}")-```--### RPA Debugging--```python-async def debug_rpa_workflow():- computer = Computer(os_type="linux")- await computer.run()-- # Start tracing with full debugging info- await computer.tracing.start({- 'name': 'rpa_debug_session',- 'screenshots': True,- 'accessibility_tree': True,- 'api_calls': True- })-- try:- # Your RPA workflow- await rpa_login_sequence(computer)- await rpa_data_entry(computer)- await rpa_generate_report(computer)-- await computer.tracing.add_metadata('status', 'success')-- except Exception as e:- # Record the error in the trace- await computer.tracing.add_metadata('error', str(e))- await computer.tracing.add_metadata('status', 'failed')- raise- finally:- # Always save the debug trace- trace_path = await computer.tracing.stop()- print(f"Debug trace saved to: {trace_path}")-```--## Output Format--### Directory Structure--When using `format='dir'`, traces are saved with this structure:--```-trace_20240922_143052_abc123/-├── trace_metadata.json # Overall trace information-├── event_000001_trace_start.json-├── event_000002_api_call.json-├── event_000003_api_call.json-├── 000001_initial_screenshot.png-├── 000002_after_left_click.png-├── 000003_after_type_text.png-└── event_000004_trace_end.json-```--### Metadata Format--The `trace_metadata.json` contains:--```json-{- "trace_id": "trace_20240922_143052_abc123",- "config": {- "screenshots": true,- "api_calls": true,- "accessibility_tree": false,- "metadata": true- },- "start_time": 1695392252.123,- "end_time": 1695392267.456,- "duration": 15.333,- "total_events": 12,- "screenshot_count": 5,- "events": [...] // All events in chronological order-}-```--### Event Format--Individual events follow this structure:--```json-{- "type": "api_call",- "timestamp": 1695392255.789,- "relative_time": 3.666,- "data": {- "method": "left_click",- "args": { "x": 100, "y": 200, "delay": null },- "result": null,- "error": null,- "screenshot": "000002_after_left_click.png",- "success": true- }-}-```--## Integration with ComputerAgent--The tracing API works seamlessly with existing ComputerAgent workflows:--```python-from agent import ComputerAgent-from computer import Computer--# Create computer and start tracing-computer = Computer(os_type="macos")-await computer.run()--await computer.tracing.start({- 'name': 'agent_with_tracing',- 'screenshots': True,- 'metadata': True-})--# Create agent using the same computer-agent = ComputerAgent(- model="openai/computer-use-preview",- tools=[computer]-)--# Agent operations will be automatically traced-async for _ in agent.run("open cua.ai and navigate to docs"):- pass--# Save the combined trace-trace_path = await computer.tracing.stop()-```--## Privacy Considerations--The tracing API is designed with privacy in mind:--- Clipboard content is not recorded (only content length)-- Screenshots can be disabled-- Sensitive text input can be filtered-- Custom metadata allows you to control what information is recorded--## Comparison with ComputerAgent Trajectories--| Feature | ComputerAgent Trajectories | Computer.tracing |-| ---------------------- | -------------------------- | -------------------- |-| **Scope** | ComputerAgent only | Any Computer usage |-| **Flexibility** | Fixed format | Configurable options |-| **Custom Agents** | Not supported | Fully supported |-| **Human-in-the-loop** | Limited | Full support |-| **Real-time Control** | No | Start/stop anytime |-| **Output Format** | Agent-specific | Standardized |-| **Accessibility Data** | No | Optional |--## Best Practices--1. **Start tracing early**: Begin recording before your main workflow to capture the complete session-2. **Use meaningful names**: Provide descriptive trace names for easier organization-3. **Add contextual metadata**: Include information about what you're testing or demonstrating-4. **Handle errors gracefully**: Always stop tracing in a finally block-5. **Choose appropriate options**: Only record what you need to minimize overhead-6. **Organize output**: Use custom paths to organize traces by project or use case--The Computer tracing API provides a powerful foundation for recording, analyzing, and improving computer automation workflows across all use cases.diff --git a/docs/content/docs/guide/fundamentals/computers.mdx b/docs/content/docs/guide/fundamentals/computers.mdxdeleted file mode 100644index 6cca15b914..0000000000--- a/docs/content/docs/guide/fundamentals/computers.mdx+++ /dev/null@@ -1,102 +0,0 @@-----title: Computer Types-description: Comparing sandbox providers and their capabilities------{/* prettier-ignore */}-<Callout>A corresponding <a href="https://github.com/trycua/cua/blob/main/notebooks/computer_nb.ipynb" target="_blank">Jupyter Notebook</a> and <a href="https://github.com/trycua/cua/tree/main/examples/computer-example-ts" target="_blank">NodeJS project</a> are available for this documentation.</Callout>--Cua supports multiple sandbox providers, each with different trade-offs. Choose based on your requirements for OS support, isolation, and deployment environment.--## Provider Comparison--| Provider | OS | Host Requirements | Isolation | Persistence | Best For |-|----------|-----|-------------------|-----------|-------------|----------|-| **Cloud** | Linux, Windows, macOS | Any | Full VM | Configurable | Production, teams, CI/CD |-| **Docker** | Linux | Docker installed | Container | Volume mounts | Local dev, testing |-| **Lume** | macOS | macOS host | Full VM | Snapshot-based | macOS automation |-| **Windows Sandbox** | Windows | Win 10 Pro/11 | Sandbox | Ephemeral only | Windows automation |-| **QEMU Docker** | Linux, Windows, Android | Docker + KVM | Full VM | Disk images | Multi-OS testing |-| **Host** | Any | None | None | N/A | Debugging (not recommended) |--## Provider Details--### Cloud (`provider_type="cloud"`)--Managed VMs hosted by Cua. No local setup required.--- **OS options**: Linux (Ubuntu), Windows, macOS-- **`provider_type`**: `"cloud"`-- **Required params**: `name`, `api_key` (or `CUA_API_KEY` env var)-- **Persistence**: Sandbox state persists between sessions unless explicitly reset--### Docker (`provider_type="docker"`)--Linux desktops running in Docker containers.--- **OS options**: Linux only (XFCE or Ubuntu/KASM)-- **`provider_type`**: `"docker"`-- **Required params**: `image`-- **Images**: `trycua/cua-xfce:latest` (lightweight), `trycua/cua-ubuntu:latest` (full desktop)-- **Persistence**: Ephemeral by default, use volume mounts for persistence--### Lume (`provider_type="lume"`)--Native macOS VMs using Apple's Virtualization framework.--- **OS options**: macOS only-- **`provider_type`**: `"lume"`-- **Required params**: `name` (image name)-- **Host requirement**: macOS with Lume CLI installed-- **Persistence**: Snapshot-based, can restore to clean state--### Windows Sandbox (`provider_type="winsandbox"`)--Built-in Windows isolation feature.--- **OS options**: Windows only-- **`provider_type`**: `"winsandbox"`-- **Host requirement**: Windows 10 Pro/Enterprise or Windows 11-- **Persistence**: Always ephemeral (resets on close)-- **Additional dep**: `pywinsandbox`--### QEMU Docker (`provider_type="qemu"`)--Full VMs running inside Docker via QEMU emulation.--- **OS options**: Linux, Windows, Android-- **`provider_type`**: `"qemu"`-- **Required params**: `image` (golden image path)-- **Host requirement**: Docker with KVM support-- **Persistence**: Disk image based--### Host Desktop (`use_host_computer_server=True`)--Direct control of your machine. **Use with caution.**--- **OS options**: Whatever your host runs-- **No isolation**: Agent actions affect your real system-- **Use case**: Debugging only, never in production--## Quick Reference--```python-from computer import Computer--# Cloud (recommended for production)-computer = Computer(os_type="linux", provider_type="cloud", name="my-sandbox", api_key="...")--# Docker (recommended for local dev)-computer = Computer(os_type="linux", provider_type="docker", image="trycua/cua-xfce:latest")--# Lume (macOS only)-computer = Computer(os_type="macos", provider_type="lume", name="macos-sequoia-cua:latest")--# Windows Sandbox (Windows host only)-computer = Computer(os_type="windows", provider_type="winsandbox", ephemeral=True)--# Host (debugging only)-computer = Computer(use_host_computer_server=True)-```--For setup instructions, see [Set Up a Sandbox](/docs/guide/get-started/set-up-sandbox).diff --git a/docs/content/docs/guide/fundamentals/cua-vlm-router.mdx b/docs/content/docs/guide/fundamentals/cua-vlm-router.mdxnew file mode 100644index 0000000000..8007f324c2--- /dev/null+++ b/docs/content/docs/guide/fundamentals/cua-vlm-router.mdx@@ -0,0 +1,91 @@+---+title: Cua VLM Router+description: Unified API access to multiple VLM providers without managing infrastructure+---++Instead of deploying and managing computer-use vision language models yourself on various cloud providers, Cua VLM Router gives you instant access to all supported models through a single API key. No infrastructure setup, no multiple provider accounts—just one integration for Claude, Gemini, Qwen, and more.++## Setup++```python+from computer import Computer+from agent import ComputerAgent++computer = Computer(os_type="linux", provider_type="docker", image="trycua/cua-xfce:latest")+await computer.run()++agent = ComputerAgent(+ model="cua/anthropic/claude-sonnet-4.5",+ tools=[computer]+)+```++```bash+export CUA_API_KEY="your-cua-key"+```++Get your API key at [cua.ai](https://cua.ai/signin).++## Available Models++| Model | Description |+|-------|-------------|+| `cua/anthropic/claude-sonnet-4.5` | General-purpose (recommended) |+| `cua/anthropic/claude-haiku-4.5` | Fast, cost-effective |+| `cua/anthropic/claude-opus-4.5` | Most capable |+| `cua/google/gemini-3-flash-preview` | Fastest, cheapest |+| `cua/google/gemini-3-pro-preview` | Most powerful |+| `cua/qwen/qwen3-vl-235b` | Large-scale vision tasks |++## Benefits++- **Single API key** for all supported providers+- **Cost tracking** in every response+- **Unified dashboard** for usage monitoring+- **No vendor lock-in** - switch models without changing code++## Cost Tracking++Every response includes usage information:++```python+async for result in agent.run(messages):+ print(f"Cost: ${result['usage']['response_cost']:.4f}")+ print(f"Tokens: {result['usage']['total_tokens']}")+```++## HTTP API++Use the router directly via HTTP for integrations outside Python:++### Chat Completions++```bash+curl -X POST https://inference.cua.ai/v1/chat/completions \+ -H "Authorization: Bearer $CUA_API_KEY" \+ -H "Content-Type: application/json" \+ -d '{+ "model": "anthropic/claude-sonnet-4.5",+ "messages": [{"role": "user", "content": "Hello!"}],+ "max_tokens": 100+ }'+```++### Check Balance++```bash+curl -H "Authorization: Bearer $CUA_API_KEY" \+ "https://inference.cua.ai/v1/balance"+```++## When to Use++**Multi-provider workflows** - Access Claude, Gemini, and Qwen from a single integration.++**Cost monitoring** - Track spending across all providers in one dashboard.++**Team environments** - Share a single API key with usage limits and monitoring.++**Rapid prototyping** - Try different models without setting up individual provider accounts.++For direct provider access or custom billing arrangements, use the provider-specific APIs instead. See [Vision Language Models](/guide/fundamentals/vlms) for direct provider setup.diff --git a/docs/content/docs/guide/fundamentals/meta.json b/docs/content/docs/guide/fundamentals/meta.jsonindex 066ae3a14b..b59f1c7322 100644--- a/docs/content/docs/guide/fundamentals/meta.json+++ b/docs/content/docs/guide/fundamentals/meta.json@@ -5,13 +5,9 @@"defaultOpen": true,"pages": ["agent-loops",- "computers","vlms",+ "cua-vlm-router","browser-tool",- "sandboxed-python",- "custom-tools",- "callbacks",- "trajectories",- "tracing"+ "callbacks"]}diff --git a/docs/content/docs/guide/fundamentals/vlms.mdx b/docs/content/docs/guide/fundamentals/vlms.mdxindex 9b728a534a..2d10222935 100644--- a/docs/content/docs/guide/fundamentals/vlms.mdx+++ b/docs/content/docs/guide/fundamentals/vlms.mdx@@ -116,65 +116,29 @@ The first run downloads model weights from HuggingFace. Subsequent runs load fro### Using MLX (Apple Silicon)-For M1/M2/M3 Macs, MLX provides optimized inference:+For M1/M2/M3/M4 Macs, MLX provides optimized inference:```pythonagent = ComputerAgent(- model="mlx-vlm/Qwen/Qwen2.5-VL-7B-Instruct",+ model="mlx/mlx-community/UI-TARS-1.5-7B-6bit",tools=[computer])```MLX models run efficiently on Apple's unified memory architecture.-## Composed Models+### Using Ollama-Some models excel at **grounding** (finding UI elements) but can't reason about tasks. Others are great at **planning** but can't precisely locate elements. Composed models combine both:+Run models locally via Ollama:```python-# Format: grounding_model+planning_modelagent = ComputerAgent(- model="huggingface-local/HelloKKMe/GTA1-7B+anthropic/claude-sonnet-4-5-20250929",+ model="ollama_chat/llama3.2:latest",tools=[computer])```-The `+` syntax tells Cua to use a two-stage approach:--1. **Grounding stage** - The first model (GTA1) analyzes the screenshot and identifies UI element coordinates-2. **Planning stage** - The second model (Claude) receives the element list and decides which to interact with--This is useful when you want local grounding (privacy, cost) with cloud reasoning (accuracy):--```python-# Local grounding + cloud planning-"moondream3+anthropic/claude-sonnet-4-5-20250929"-"omniparser+openai/gpt-4o"-"huggingface-local/ByteDance-Seed/UI-TARS-1.5-7B+openai/gpt-4o"-```--## Cua VLM Router--Instead of managing multiple API keys, use Cua VLM Router for unified access:--```python-agent = ComputerAgent(- model="cua/anthropic/claude-sonnet-4.5",- tools=[computer]-)-```--```bash-export CUA_API_KEY="your-cua-key"-```--The router provides:--- Single API key for all supported providers-- Automatic fallback between providers-- Unified usage tracking and billing--See [Cua VLM Router](/docs/guide/model-providers/cua-vlm-router) for details.+Ollama handles model downloading and serves inference locally.## Model Capabilitiesdiff --git a/docs/content/docs/guide/get-started/what-is-computer-use-agent.mdx b/docs/content/docs/guide/get-started/what-is-computer-use-agent.mdxindex e4f8e3eaef..a90812ca85 100644--- a/docs/content/docs/guide/get-started/what-is-computer-use-agent.mdx+++ b/docs/content/docs/guide/get-started/what-is-computer-use-agent.mdx@@ -5,6 +5,10 @@ description: Understanding AI agents that can see and interact with computer intA **computer-use agent** is an AI system that can perceive, understand, and interact with graphical user interfaces (GUIs) just like a human user would. Instead of using APIs or scripted automation, these agents "see" the screen and perform actions through simulated mouse and keyboard inputs.+<div className="not-prose relative rounded-xl overflow-hidden my-8 w-full">+ <img src="/docs/img/what-is-cua.png" alt="How Computer-Use Agents work" className="w-full h-auto rounded-xl" />+</div>+## How Computer-Use Agents WorkComputer-use agents operate through a continuous loop:diff --git a/docs/content/docs/guide/get-started/what-is-desktop-sandbox.mdx b/docs/content/docs/guide/get-started/what-is-desktop-sandbox.mdxindex b2279268b7..5f22cd69df 100644--- a/docs/content/docs/guide/get-started/what-is-desktop-sandbox.mdx+++ b/docs/content/docs/guide/get-started/what-is-desktop-sandbox.mdx@@ -5,6 +5,10 @@ description: Understanding isolated environments for safe computer-use agent exeA **desktop sandbox** is an isolated virtual environment that provides a complete desktop operating system where computer-use agents can safely execute tasks. Think of it as a disposable computer that your agent can control without risk to your real system.+<div className="not-prose relative rounded-xl overflow-hidden my-8 w-full">+ <img src="/docs/img/what-is-sandbox.png" alt="What is a Desktop Sandbox" className="w-full h-auto rounded-xl" />+</div>+## Why Use Sandboxes?Running AI agents directly on your computer poses risks:@@ -20,6 +24,7 @@ Sandboxes solve these problems by providing:- **Reset capability** - Start fresh for each task- **Safety** - Experiment freely without consequences- **Consistency** - Identical environment every time+- **Reproducibility** - Define dependencies and configurations that create baseline environments your agents can rely on## Sandbox Options in Cuadiff --git a/docs/content/docs/guide/integrations/hud.mdx b/docs/content/docs/guide/integrations/hud.mdxindex 7bfcbdea35..fee8bd47df 100644--- a/docs/content/docs/guide/integrations/hud.mdx+++ b/docs/content/docs/guide/integrations/hud.mdx@@ -1,14 +1,10 @@----title: HUD Evals+title: HUDdescription: Use ComputerAgent with HUD for benchmarking and evaluation---<Callout>- A corresponding{' '}- <a href="https://github.com/trycua/cua/blob/main/notebooks/eval_osworld.ipynb" target="_blank">- Jupyter Notebook- </a>{' '}- is available for this documentation.+ A corresponding <a href="https://github.com/trycua/cua/blob/main/notebooks/eval_osworld.ipynb" target="_blank">Jupyter Notebook</a> is available for this documentation.</Callout>The HUD integration allows an agent to be benchmarked using the [HUD framework](https://www.hud.so/). Through the HUD integration, the agent controls a computer inside HUD, where tests are run to evaluate the success of each task.diff --git a/docs/content/docs/guide/integrations/observability.mdx b/docs/content/docs/guide/integrations/laminar.mdxsimilarity index 81%rename from docs/content/docs/guide/integrations/observability.mdxrename to docs/content/docs/guide/integrations/laminar.mdxindex 44db0ea461..6571c1afe8 100644--- a/docs/content/docs/guide/integrations/observability.mdx+++ b/docs/content/docs/guide/integrations/laminar.mdx@@ -1,11 +1,9 @@----title: Observability-description: Trace CUA execution steps and sessions+title: Laminar+description: Trace Cua execution steps and sessions----## Observability--CUA has a native integration with [Laminar](https://laminar.sh/) – open-source platform for tracing, evals, and labeling of autonomous AI agents. Read more about Laminar in the [Laminar docs](https://docs.lmnr.ai/).+Cua has a native integration with [Laminar](https://laminar.sh/) – an open-source platform for tracing, evals, and labeling of autonomous AI agents. Read more about Laminar in the [Laminar docs](https://docs.lmnr.ai/).## Setup@@ -18,7 +16,7 @@ export LMNR_PROJECT_API_KEY=your-key## Usage-Then, initialize Laminar at the entry point of your application, register Laminar LiteLLM callback, and all steps of CUA will be automatically traced.+Then, initialize Laminar at the entry point of your application, register Laminar LiteLLM callback, and all steps of Cua will be automatically traced.```pythonimport osdiff --git a/docs/content/docs/guide/integrations/meta.json b/docs/content/docs/guide/integrations/meta.jsonindex 080015651b..bcb628fa92 100644--- a/docs/content/docs/guide/integrations/meta.json+++ b/docs/content/docs/guide/integrations/meta.json@@ -3,8 +3,7 @@"description": "Third-party tools and integrations","icon": "Plug","pages": [- "mcp-server",- "observability",+ "laminar","hud","benchmarks"]diff --git a/docs/content/docs/guide/meta.json b/docs/content/docs/guide/meta.jsonindex fe7e181380..fc797e5063 100644--- a/docs/content/docs/guide/meta.json+++ b/docs/content/docs/guide/meta.json@@ -6,9 +6,7 @@"pages": ["get-started","fundamentals",- "model-providers",- "agents",- "computers",+ "advanced","integrations"]}diff --git a/docs/content/docs/guide/model-providers/cua-vlm-router.mdx b/docs/content/docs/guide/model-providers/cua-vlm-router.mdxdeleted file mode 100644index d09cfe9f92..0000000000--- a/docs/content/docs/guide/model-providers/cua-vlm-router.mdx+++ /dev/null@@ -1,441 +0,0 @@-----title: Cua VLM Router-description: Intelligent vision-language model routing with cost optimization and unified access------# Cua VLM Router--The **Cua VLM Router** is an intelligent inference API that provides unified access to multiple vision-language model providers through a single API key. It offers cost optimization and detailed observability for production AI applications.--## Overview--Instead of managing multiple API keys and provider-specific code, Cua VLM Router acts as a smart cloud gateway that:--- **Unifies access** to multiple model providers-- **Optimizes costs** through intelligent routing and provider selection-- **Tracks usage** and costs with detailed metadata-- **Provides observability** with routing decisions and attempt logs-- **Managed infrastructure** - no need to manage provider API keys yourself--## Quick Start--### 1. Get Your API Key--Sign up at [cua.ai](https://cua.ai/signin) and get your Cua API key from the dashboard.--### 2. Set Environment Variable--```bash-export CUA_API_KEY="sk_cua-api01_..."-```--### 3. Use with Agent SDK--```python-from agent import ComputerAgent-from computer import Computer--computer = Computer(os_type="linux", provider_type="docker")--agent = ComputerAgent(- model="cua/anthropic/claude-sonnet-4.5",- tools=[computer],- max_trajectory_budget=5.0-)--messages = [{"role": "user", "content": "Take a screenshot and tell me what's on screen"}]--async for result in agent.run(messages):- for item in result["output"]:- if item["type"] == "message":- print(item["content"][0]["text"])-```--## Available Models--The Cua VLM Router currently supports these models:--| Model ID | Provider | Description | Best For |-| --------------------------------- | --------- | ----------------- | --------------------------------------- |-| `cua/anthropic/claude-sonnet-4.5` | Anthropic | Claude Sonnet 4.5 | General-purpose tasks, recommended |-| `cua/anthropic/claude-opus-4.5` | Anthropic | Claude Opus 4.5 | Enhanced agentic and computer-use tasks |-| `cua/anthropic/claude-haiku-4.5` | Anthropic | Claude Haiku 4.5 | Fast responses, cost-effective |-| `cua/qwen/qwen3-vl-235b` | Qwen | Qwen3 VL 235B | Large-scale vision-language tasks |--## How It Works--### Intelligent Routing--When you make a request to Cua VLM Router:--1. **Model Resolution**: Your model ID (e.g., `cua/anthropic/claude-sonnet-4.5`) is resolved to the appropriate provider-2. **Provider Selection**: Cua routes your request to the appropriate model provider-3. **Response**: You receive an OpenAI-compatible response with metadata--## API Reference--### Base URL--```-https://inference.cua.ai/v1-```--### Authentication--All requests require an API key in the Authorization header:--```bash-Authorization: Bearer sk_cua-api01_...-```--### Endpoints--#### List Available Models--```bash-GET /v1/models-```--**Response:**--```json-{- "data": [- {- "id": "anthropic/claude-sonnet-4.5",- "name": "Claude Sonnet 4.5",- "object": "model",- "owned_by": "cua"- }- ],- "object": "list"-}-```--#### Chat Completions--```bash-POST /v1/chat/completions-Content-Type: application/json-```--**Request:**--```json-{- "model": "anthropic/claude-sonnet-4.5",- "messages": [{ "role": "user", "content": "Hello!" }],- "max_tokens": 100,- "temperature": 0.7,- "stream": false-}-```--**Response:**--```json-{- "id": "gen_...",- "object": "chat.completion",- "created": 1763554838,- "model": "anthropic/claude-sonnet-4.5",- "choices": [- {- "index": 0,- "message": {- "role": "assistant",- "content": "Hello! How can I help you today?"- },- "finish_reason": "stop"- }- ],- "usage": {- "prompt_tokens": 10,- "completion_tokens": 12,- "total_tokens": 22,- "cost": 0.01,- "is_byok": true- }-}-```--#### Streaming--Set `"stream": true` to receive server-sent events:--```bash-curl -X POST https://inference.cua.ai/v1/chat/completions \- -H "Authorization: Bearer sk_cua-api01_..." \- -H "Content-Type: application/json" \- -d '{- "model": "anthropic/claude-sonnet-4.5",- "messages": [{"role": "user", "content": "Count to 5"}],- "stream": true- }'-```--**Response (SSE format):**--```-data: {"id":"gen_...","choices":[{"delta":{"content":"1"}}],"object":"chat.completion.chunk"}--data: {"id":"gen_...","choices":[{"delta":{"content":"\n2"}}],"object":"chat.completion.chunk"}--data: {"id":"gen_...","choices":[{"delta":{"content":"\n3\n4\n5"}}],"object":"chat.completion.chunk"}--data: {"id":"gen_...","choices":[{"delta":{},"finish_reason":"stop"}],"usage":{...}}-```--#### Check Balance--```bash-GET /v1/balance-```--**Response:**--```json-{- "balance": 211689.85,- "currency": "credits"-}-```--## Cost Tracking--CUA VLM Router provides detailed cost information in every response:--### Credit System--Requests are billed in **credits**:--- Credits are deducted from your CUA account balance-- Prices vary by model and usage-- CUA manages all provider API keys and infrastructure--### Response Cost Fields--```json-{- "usage": {- "cost": 0.01, // CUA gateway cost in credits- "market_cost": 0.000065 // Actual upstream API cost- }-}-```--**Note:** Cua VLM Router is a fully managed cloud service. If you want to use your own provider API keys directly (BYOK), see the [Supported Model Providers](/agent-sdk/supported-model-providers/) page for direct provider access via the agent SDK.--## Response Metadata--Cua VLM Router includes metadata about routing decisions and costs in the response. This information helps with debugging and monitoring your application's model usage.--## Configuration--### Environment Variables--```bash-# Required: Your Cua API key-export CUA_API_KEY="sk_cua-api01_..."--# Optional: Custom endpoint (defaults to https://inference.cua.ai/v1)-export CUA_BASE_URL="https://custom-endpoint.cua.ai/v1"-```--### Python SDK Configuration--```python-from agent import ComputerAgent--# Using environment variables (recommended)-agent = ComputerAgent(model="cua/anthropic/claude-sonnet-4.5")--# Or explicit configuration-agent = ComputerAgent(- model="cua/anthropic/claude-sonnet-4.5",- # CUA adapter automatically loads from CUA_API_KEY-)-```--## Benefits Over Direct Provider Access--| Feature | Cua VLM Router | Direct Provider (BYOK) |-| -------------------------- | ---------------------------- | --------------------------------- |-| **Single API Key** | ✅ One key for all providers | ❌ Multiple keys to manage |-| **Managed Infrastructure** | ✅ No API key management | ❌ Manage multiple provider keys |-| **Usage Tracking** | ✅ Unified dashboard | ❌ Per-provider tracking |-| **Model Switching** | ✅ Change model string only | ❌ Change code + keys |-| **Setup Complexity** | ✅ One environment variable | ❌ Multiple environment variables |--## Error Handling--### Common Error Responses--#### Invalid API Key--```json-{- "detail": "Insufficient credits. Current balance: 0.00 credits"-}-```--#### Missing Authorization--```json-{- "detail": "Missing Authorization: Bearer token"-}-```--#### Invalid Model--```json-{- "detail": "Invalid or unavailable model"-}-```--### Best Practices--1. **Check balance periodically** using `/v1/balance`-2. **Handle rate limits** with exponential backoff-3. **Log generation IDs** for debugging-4. **Set up usage alerts** in your CUA dashboard--## Examples--### Basic Usage--```python-from agent import ComputerAgent-from computer import Computer--computer = Computer(os_type="linux", provider_type="docker")--agent = ComputerAgent(- model="cua/anthropic/claude-sonnet-4.5",- tools=[computer]-)--messages = [{"role": "user", "content": "Open Firefox"}]--async for result in agent.run(messages):- print(result)-```--### Direct API Call (curl)--```bash-curl -X POST https://inference.cua.ai/v1/chat/completions \- -H "Authorization: Bearer ${CUA_API_KEY}" \- -H "Content-Type: application/json" \- -d '{- "model": "anthropic/claude-sonnet-4.5",- "messages": [- {"role": "user", "content": "Explain quantum computing"}- ],- "max_tokens": 200- }'-```--### With Custom Parameters--```python-agent = ComputerAgent(- model="cua/anthropic/claude-haiku-4.5",- tools=[computer],- max_trajectory_budget=10.0,- temperature=0.7-)-```--### Using Qwen3 VL 235B--```python-from agent import ComputerAgent-from computer import Computer--computer = Computer(os_type="linux", provider_type="docker")--agent = ComputerAgent(- model="cua/qwen/qwen3-vl-235b",- tools=[computer],- only_n_most_recent_images=3-)--messages = [{"role": "user", "content": "Open a browser and search for Python tutorials"}]--async for result in agent.run(messages):- print(result)-```--### Using Claude Opus 4.5--```python-from agent import ComputerAgent-from computer import Computer--computer = Computer(- os_type="linux",- provider_type="cloud",- name="your-container-name",- api_key="your-cua-api-key"-)--agent = ComputerAgent(- model="cua/anthropic/claude-opus-4.5",- tools=[computer],- instructions="You are a helpful assistant that can control computers",- only_n_most_recent_images=3-)--messages = [{"role": "user", "content": "Open a browser and search for Python tutorials"}]--async for result in agent.run(messages):- print(result)-```--## Migration from Direct Provider Access--Switching from direct provider access (BYOK) to Cua VLM Router is simple:--**Before (Direct Provider Access with BYOK):**--```python-import os-# Required: Provider-specific API key-os.environ["ANTHROPIC_API_KEY"] = "sk-ant-..."--agent = ComputerAgent(- model="anthropic/claude-sonnet-4-5-20250929",- tools=[computer]-)-```--**After (Cua VLM Router - Cloud Service):**--```python-import os-# Required: Cua API key only (no provider keys needed)-os.environ["CUA_API_KEY"] = "sk_cua-api01_..."--agent = ComputerAgent(- model="cua/anthropic/claude-sonnet-4.5", # Add "cua/" prefix- tools=[computer]-)-```--That's it! Same code structure, just different model format. Cua manages all provider infrastructure and credentials for you.--## Support--- **Documentation**: [cua.ai/docs](https://cua.ai/docs)-- **Discord**: [Join our community](https://discord.com/invite/mVnXXpdE85)-- **Issues**: [GitHub Issues](https://github.com/trycua/cua/issues)--## Next Steps--- Explore [Agent Loops](/agent-sdk/agent-loops) to customize agent behavior-- Learn about [Cost Saving Callbacks](/agent-sdk/callbacks/cost-saving)-- Try [Example Use Cases](/example-usecases/form-filling)-- Review [Supported Model Providers](/agent-sdk/supported-model-providers/) for all optionsdiff --git a/docs/content/docs/guide/model-providers/index.mdx b/docs/content/docs/guide/model-providers/index.mdxdeleted file mode 100644index d27aab31dd..0000000000--- a/docs/content/docs/guide/model-providers/index.mdx+++ /dev/null@@ -1,118 +0,0 @@-----title: Supported Model Providers------## Supported Models--### Cua VLM Router (Recommended)--Use Cua's cloud inference API for intelligent routing and cost optimization with a single API key. Cua manages all provider infrastructure and credentials for you.--```python-# Anthropic Claude models-model="cua/anthropic/claude-sonnet-4.5" # Claude Sonnet 4.5 (recommended)-model="cua/anthropic/claude-haiku-4.5" # Claude Haiku 4.5 (faster)--# Google Gemini models-model="cua/google/gemini-3-pro-preview" # Gemini 3 Pro Preview (most powerful)-model="cua/google/gemini-3-flash-preview" # Gemini 3 Flash Preview (fastest and cheapest, recommended for balance)-```--**Benefits:**--- Single API key for multiple providers-- Cost tracking and optimization-- Fully managed infrastructure (no provider keys to manage)--[Learn more about Cua VLM Router →](/agent-sdk/supported-model-providers/cua-vlm-router)-------### Anthropic Claude (Computer Use API - BYOK)--Access Anthropic's computer use models directly or through Azure AI Foundry using your own API key (BYOK).--#### Via Anthropic API--```python-model="anthropic/claude-haiku-4-5-20251001" # Claude Haiku 4.5 (fastest, cost-effective)-model="anthropic/claude-sonnet-4-5-20250929" # Claude Sonnet 4.5 (recommended)-model="anthropic/claude-opus-4-5-20251101" # Claude Opus 4.5 (most advanced)-```--**Setup:** Set `ANTHROPIC_API_KEY` environment variable with your Anthropic API key.--#### Via Azure AI Foundry--```python-model="anthropic/claude-haiku-4-5"-model="anthropic/claude-sonnet-4-5"-model="anthropic/claude-opus-4-5"-```--**Setup:**--- Set `ANTHROPIC_API_KEY` environment variable with your Azure AI Foundry key-- Set `ANTHROPIC_API_BASE` to your Azure endpoint (e.g., `https://<your-resource>.services.ai.azure.com/anthropic`)--### OpenAI Computer Use Preview (BYOK)--Direct access to OpenAI's computer use models using your own OpenAI API key (BYOK).--```python-model="openai/computer-use-preview"-```--**Setup:** Set `OPENAI_API_KEY` environment variable with your OpenAI API key.--### Google Gemini (BYOK)--Access Google's Gemini models with native computer use capabilities using your own credentials (BYOK).--```python-model="gemini-3-flash-preview" # Gemini 3 Flash (fastest, cheapest)-model="gemini-2.5-computer-use-preview" # Computer Use Specific Gemini and general computer use-model="gemini-3-pro-preview" # Gemini 3 Pro (most advanced)-```--**Setup Options:**--#### Option 1: Google AI Studio (Recommended for quick start)--Set the `GOOGLE_API_KEY` environment variable with your Google AI Studio API key.--```bash-export GOOGLE_API_KEY="your-google-ai-studio-key"-```--#### Option 2: Google Cloud Vertex AI--For production deployments or enterprise use, configure Vertex AI credentials:--```bash-export GOOGLE_CLOUD_PROJECT="your-gcp-project-id"-export GOOGLE_APPLICATION_CREDENTIALS="/path/to/service-account.json"-export GOOGLE_CLOUD_LOCATION="us-central1" # or your preferred region-```--**Note:** When `GOOGLE_API_KEY` is set, it takes precedence. If not set, the SDK will automatically use Vertex AI with the configured Google Cloud credentials.--### UI-TARS (Local or Huggingface Inference)--Run UI-TARS models locally for privacy and offline use.--```python-model="huggingface-local/ByteDance-Seed/UI-TARS-1.5-7B"-model="ollama_chat/0000/ui-tars-1.5-7b"-```--### Omniparser + Any LLM--Combine Omniparser for UI understanding with any LLM provider.--```python-model="omniparser+ollama_chat/mistral-small3.2"-model="omniparser+vertex_ai/gemini-pro"-model="omniparser+anthropic/claude-sonnet-4-5-20250929"-model="omniparser+openai/gpt-4o"-```diff --git a/docs/content/docs/guide/model-providers/local-models.mdx b/docs/content/docs/guide/model-providers/local-models.mdxdeleted file mode 100644index b147a538f5..0000000000--- a/docs/content/docs/guide/model-providers/local-models.mdx+++ /dev/null@@ -1,35 +0,0 @@-----title: Running Models Locally------You can run open-source LLMs and vision models on your own machine using Cua, without relying on cloud APIs. This is ideal for development, privacy, or running on air-gapped systems.--## Hugging Face (transformers)--Use the `huggingface-local/` prefix to run any Hugging Face model locally via the `transformers` library. This supports most text and vision models from the Hugging Face Hub.--**Example:**--```python-model = "huggingface-local/ByteDance-Seed/UI-TARS-1.5-7B"-```--## MLX (Apple Silicon)--Use the `mlx/` prefix to run models using the `mlx-vlm` library, optimized for Apple Silicon (M1/M2/M3). This allows fast, local inference for many open-source models.--**Example:**--```python-model = "mlx/mlx-community/UI-TARS-1.5-7B-6bit"-```--## Ollama--Use the `ollama_chat/` prefix to run models using the `ollama` library. This allows fast, local inference for many open-source models.--**Example:**--```python-model = "omniparser+ollama_chat/llama3.2:latest"-```diff --git a/docs/content/docs/guide/model-providers/meta.json b/docs/content/docs/guide/model-providers/meta.jsondeleted file mode 100644index 303c6bce13..0000000000--- a/docs/content/docs/guide/model-providers/meta.json+++ /dev/null@@ -1,10 +0,0 @@-{- "title": "Model Providers",- "description": "Supported LLM providers and models",- "icon": "Cpu",- "pages": [- "index",- "cua-vlm-router",- "local-models"- ]-}diff --git a/docs/content/docs/reference/computer-sdk/index.mdx b/docs/content/docs/reference/computer-sdk/index.mdxindex 807ef276d6..07ecfc6402 100644--- a/docs/content/docs/reference/computer-sdk/index.mdx+++ b/docs/content/docs/reference/computer-sdk/index.mdx@@ -266,7 +266,7 @@ await computer.interface.set_clipboard("Text to copy")#### Shell Methods-##### `run_shell(command)`+##### `run_shell(command)` / `run_command(command)`Execute a shell command in the computer.@@ -286,6 +286,114 @@ print(result.exit_code)- `stderr` - Standard error- `exit_code` - Exit code (0 = success)+#### Window Management++##### `launch(application)`++Launch an application.++```python+await computer.interface.launch("xfce4-terminal")+await computer.interface.launch("libreoffice --writer")+```++##### `open(uri)`++Open a URL or file with the default application.++```python+await computer.interface.open("https://www.google.com")+await computer.interface.open("/home/user/document.pdf")+```++##### `get_application_windows(app_name)`++Get window IDs for an application.++```python+windows = await computer.interface.get_application_windows("xfce4-terminal")+window_id = windows[0]+```++##### `activate_window(window_id)`++Bring a window to focus.++```python+await computer.interface.activate_window(window_id)+```++##### `get_current_window_id()`++Get the active window ID.++```python+window_id = await computer.interface.get_current_window_id()+```++##### `window_size(window_id)` / `set_window_size(window_id, width, height)`++Get or set window dimensions.++```python+size = await computer.interface.window_size(window_id)+await computer.interface.set_window_size(window_id, 1200, 800)+```++##### `maximize_window(window_id)` / `minimize_window(window_id)` / `close_window(window_id)`++Window state controls.++```python+await computer.interface.maximize_window(window_id)+await computer.interface.minimize_window(window_id)+await computer.interface.close_window(window_id)+```++#### Accessibility++##### `get_accessibility_tree()`++Get the accessibility tree for the current screen.++```python+tree = await computer.interface.get_accessibility_tree()+```++**Returns:** Accessibility tree structure with UI element information.++#### Virtual Environment++##### `venv_install(venv_name, packages)`++Install packages in a virtual environment.++```python+await computer.venv_install("my_env", ["requests", "pandas"])+```++##### `venv_cmd(venv_name, command)`++Run a shell command in a virtual environment.++```python+result = await computer.venv_cmd("my_env", "pip list")+```++##### `venv_exec(venv_name, function, *args, **kwargs)`++Execute a Python function in a virtual environment.++```python+def process_data(x):+ import pandas as pd+ return pd.DataFrame(x).to_dict()++result = await computer.venv_exec("my_env", process_data, [1, 2, 3])+```++See [Sandboxed Python](/docs/guide/fundamentals/sandboxed-python) for detailed usage.+#### File Methods##### `file_read(path)`@@ -466,12 +574,13 @@ Directly controls the host machine. Use with caution.The `CloudProvider` class enables programmatic management of cloud sandboxes.```python-from computer.providers import CloudProvider+from computer.providers.cloud.provider import CloudProvider-provider = CloudProvider(- api_key="your-api-key",- region="north-america"-)+# Automatically reads CUA_API_KEY from environment+provider = CloudProvider(verbose=False)++async with provider:+ vms = await provider.list_vms()```### Constructor Parameters@@ -479,52 +588,86 @@ provider = CloudProvider(| Parameter | Type | Default | Description ||-----------|------|---------|-------------|| `api_key` | `str` | `CUA_API_KEY` env var | API key for authentication |-| `region` | `str` | `"north-america"` | Region: `"north-america"`, `"europe"`, `"asia-pacific"` |+| `verbose` | `bool` | `False` | Enable verbose logging |### Methods-##### `create_sandbox(options)`+##### `list_vms()`-Create a new cloud sandbox.+List all sandboxes.```python-sandbox = await provider.create_sandbox({- "os": "linux",- "size": "medium",- "image": "trycua/cua-xfce:latest"-})+async with provider:+ vms = await provider.list_vms()+ for vm in vms:+ print(f"{vm['name']}: {vm['status']}")```-| Option | Type | Default | Description |-|--------|------|---------|-------------|-| `os` | `str` | `"linux"` | Operating system |-| `size` | `str` | `"small"` | Size: `"small"`, `"medium"`, `"large"` |-| `image` | `str` | Default image | Container image to use |+##### `get_vm(name)`-##### `list_sandboxes()`+Get details for a specific sandbox.-List all sandboxes.+```python+info = await provider.get_vm("my-vm-name")+```++##### `run_vm(name)`++Start a sandbox.```python-sandboxes = await provider.list_sandboxes()-for sandbox in sandboxes:- print(f"{sandbox.id}: {sandbox.status}")+resp = await provider.run_vm("my-vm-name")+# {"name": "my-vm-name", "status": "starting"}```-##### `get_sandbox(sandbox_id)`+##### `stop_vm(name)`-Get details for a specific sandbox.+Stop a sandbox.```python-sandbox = await provider.get_sandbox("sandbox-abc123")+resp = await provider.stop_vm("my-vm-name")+# {"name": "my-vm-name", "status": "stopping"}```-##### `delete_sandbox(sandbox_id)`+##### `restart_vm(name)`-Delete a sandbox.+Restart a sandbox.```python-await provider.delete_sandbox("sandbox-abc123")+resp = await provider.restart_vm("my-vm-name")+# {"name": "my-vm-name", "status": "restarting"}+```++### Sandbox Status Values++| Status | Description |+|--------|-------------|+| `pending` | Deployment in progress |+| `running` | Active and accessible |+| `stopped` | Stopped but not terminated |+| `terminated` | Permanently destroyed |+| `failed` | Deployment or operation failed |++### HTTP API++You can also manage sandboxes via HTTP:++```bash+# List sandboxes+curl -H "Authorization: Bearer $CUA_API_KEY" \+ "https://api.cua.ai/v1/vms"++# Start sandbox+curl -X POST -H "Authorization: Bearer $CUA_API_KEY" \+ "https://api.cua.ai/v1/vms/my-vm-name/start"++# Stop sandbox+curl -X POST -H "Authorization: Bearer $CUA_API_KEY" \+ "https://api.cua.ai/v1/vms/my-vm-name/stop"++# Restart sandbox+curl -X POST -H "Authorization: Bearer $CUA_API_KEY" \+ "https://api.cua.ai/v1/vms/my-vm-name/restart"```---diff --git a/docs/content/docs/guide/integrations/mcp-server/client-integrations.mdx b/docs/content/docs/reference/mcp-server/client-integrations.mdxsimilarity index 100%rename from docs/content/docs/guide/integrations/mcp-server/client-integrations.mdxrename to docs/content/docs/reference/mcp-server/client-integrations.mdxdiff --git a/docs/content/docs/guide/integrations/mcp-server/configuration.mdx b/docs/content/docs/reference/mcp-server/configuration.mdxsimilarity index 100%rename from docs/content/docs/guide/integrations/mcp-server/configuration.mdxrename to docs/content/docs/reference/mcp-server/configuration.mdxdiff --git a/docs/content/docs/guide/integrations/mcp-server/index.mdx b/docs/content/docs/reference/mcp-server/index.mdxsimilarity index 100%rename from docs/content/docs/guide/integrations/mcp-server/index.mdxrename to docs/content/docs/reference/mcp-server/index.mdxdiff --git a/docs/content/docs/guide/integrations/mcp-server/installation.mdx b/docs/content/docs/reference/mcp-server/installation.mdxsimilarity index 100%rename from docs/content/docs/guide/integrations/mcp-server/installation.mdxrename to docs/content/docs/reference/mcp-server/installation.mdxdiff --git a/docs/content/docs/guide/integrations/mcp-server/llm-integrations.mdx b/docs/content/docs/reference/mcp-server/llm-integrations.mdxsimilarity index 100%rename from docs/content/docs/guide/integrations/mcp-server/llm-integrations.mdxrename to docs/content/docs/reference/mcp-server/llm-integrations.mdxdiff --git a/docs/content/docs/guide/integrations/mcp-server/meta.json b/docs/content/docs/reference/mcp-server/meta.jsonsimilarity index 75%rename from docs/content/docs/guide/integrations/mcp-server/meta.jsonrename to docs/content/docs/reference/mcp-server/meta.jsonindex f5ccb9baee..4cbb6aa1b1 100644--- a/docs/content/docs/guide/integrations/mcp-server/meta.json+++ b/docs/content/docs/reference/mcp-server/meta.json@@ -1,4 +1,6 @@{+ "title": "MCP Server",+ "icon": "Server","pages": ["installation","configuration",diff --git a/docs/content/docs/guide/integrations/mcp-server/tools.mdx b/docs/content/docs/reference/mcp-server/tools.mdxsimilarity index 100%rename from docs/content/docs/guide/integrations/mcp-server/tools.mdxrename to docs/content/docs/reference/mcp-server/tools.mdxdiff --git a/docs/content/docs/guide/integrations/mcp-server/usage.mdx b/docs/content/docs/reference/mcp-server/usage.mdxsimilarity index 100%rename from docs/content/docs/guide/integrations/mcp-server/usage.mdxrename to docs/content/docs/reference/mcp-server/usage.mdxdiff --git a/docs/content/docs/reference/meta.json b/docs/content/docs/reference/meta.jsonindex 6c2d7f2179..2fc3378284 100644--- a/docs/content/docs/reference/meta.json+++ b/docs/content/docs/reference/meta.json@@ -6,6 +6,7 @@"pages": ["computer-sdk","agent-sdk",+ "mcp-server","cli-playbook","macos-vm-cli-playbook"]diff --git a/docs/public/img/what-is-cua.png b/docs/public/img/what-is-cua.pngnew file mode 100644index 0000000000..3083dc02fbBinary files /dev/null and b/docs/public/img/what-is-cua.png differdiff --git a/docs/public/img/what-is-sandbox.png b/docs/public/img/what-is-sandbox.pngnew file mode 100644index 0000000000..41885c1139Binary files /dev/null and b/docs/public/img/what-is-sandbox.png differdiff --git a/docs/src/app/(docs)/layout.tsx b/docs/src/app/(docs)/layout.tsxindex 71c6824c46..0e3cc99a89 100644--- a/docs/src/app/(docs)/layout.tsx+++ b/docs/src/app/(docs)/layout.tsx@@ -1,50 +1,30 @@-import { baseOptions } from '@/app/layout.config';+import { CustomHeader } from '@/components/custom-header';import { source } from '@/lib/source';import { DocsLayout } from 'fumadocs-ui/layouts/docs';-import { Compass, Blocks, BookOpen } from 'lucide-react';import type { ReactNode } from 'react';export default function Layout({ children }: { children: ReactNode }) {return (- <DocsLayout- tree={source.pageTree}- {...baseOptions}- sidebar={{- tabs: [- {- title: 'Guide',- description: 'Learn how to build with Cua',- url: '/guide/get-started/what-is-cua',- icon: (- <span className="flex items-center justify-center">- <Compass className="size-4" />- </span>- ),- },- {- title: 'Examples',- description: 'Real-world examples',- url: '/examples',- icon: (- <span className="flex items-center justify-center">- <Blocks className="size-4" />- </span>- ),- },- {- title: 'Reference',- description: 'CLI tools and API reference',- url: '/reference/computer-sdk',- icon: (- <span className="flex items-center justify-center">- <BookOpen className="size-4" />- </span>- ),- },- ],- }}- >- {children}- </DocsLayout>+ <>+ <CustomHeader />+ <div className="pt-10">+ <DocsLayout+ tree={source.pageTree}+ nav={{ enabled: false }}+ searchToggle={{ enabled: false }}+ themeSwitch={{ enabled: false }}+ sidebar={{+ // Disable automatic tabs - we use header navigation instead+ tabs: false,+ // Disable collapse/expand button+ collapsible: false,+ // Add top spacing in sidebar+ banner: <div className="h-6" />,+ }}+ >+ {children}+ </DocsLayout>+ </div>+ </>);}diff --git a/docs/src/app/(landing)/layout.tsx b/docs/src/app/(landing)/layout.tsxindex 1062deb2b6..dec46c4379 100644--- a/docs/src/app/(landing)/layout.tsx+++ b/docs/src/app/(landing)/layout.tsx@@ -1,7 +1,12 @@import type { ReactNode } from 'react';import { HomeLayout } from 'fumadocs-ui/layouts/home';-import { baseOptions } from '@/app/layout.config';+import { CustomHeader } from '@/components/custom-header';export default function LandingLayout({ children }: { children: ReactNode }) {- return <HomeLayout {...baseOptions}>{children}</HomeLayout>;+ return (+ <>+ <CustomHeader />+ <HomeLayout nav={{ enabled: false }}>{children}</HomeLayout>+ </>+ );}diff --git a/docs/src/app/(landing)/page.tsx b/docs/src/app/(landing)/page.tsxindex f56ddebf34..1634c0ed16 100644--- a/docs/src/app/(landing)/page.tsx+++ b/docs/src/app/(landing)/page.tsx@@ -1,6 +1,6 @@import Link from 'next/link';import Image from 'next/image';-import { BookOpen, Code2, FileCode, Play, ArrowRight, ChevronRight } from 'lucide-react';+import { BookOpen, Code2, FileCode, Cloud, ArrowRight, ChevronRight } from 'lucide-react';import type { Metadata } from 'next';export const metadata: Metadata = {@@ -16,28 +16,28 @@ const navCards = [title: 'Guide',description:'Everything you need to know to use Cua. Dive deep into all of our features and best practices.',- href: '/guide',+ href: '/guide/get-started/what-is-cua',},{icon: Code2,title: 'Examples',description:'Practical examples built with Cua. Explore guided starting points for your use case.',- href: '/examples',+ href: '/examples/automation/form-filling',},{icon: FileCode,- title: 'Reference',+ title: 'API Reference',description:'Technical information about the Cua APIs. Quickly refer to basic descriptions of various programming functionalities.',- href: '/reference',+ href: '/reference/computer-sdk',},{- icon: Play,- title: 'Playground',+ icon: Cloud,+ title: 'Cloud',description:- 'Interactive tutorials to learn how to use Cua. Run serverless cloud functions from your browser.',- href: '/guide/get-started/quickstart',+ 'Managed cloud sandboxes for production workloads. Deploy agents at scale with our hosted infrastructure.',+ href: 'https://cua.ai',},];@@ -46,22 +46,22 @@ const featuredExamples = [{title: 'Windows App Behind VPN',description: 'Automate legacy Windows applications securely behind VPN',- href: '/examples/example-usecases/windows-app-behind-vpn',+ href: '/examples/platform-specific/windows-app-behind-vpn',},{title: 'PDF to Form Automation',description: 'Enhance interactions between form filling and local file systems',- href: '/examples/example-usecases/form-filling',+ href: '/examples/automation/form-filling',},{title: 'Contact Export',description: 'Export contacts from post-event platforms automatically',- href: '/examples/example-usecases/post-event-contact-export',+ href: '/examples/automation/post-event-contact-export',},{title: 'Complex UI Navigation',description: 'Navigate complex UIs with Gemini vision capabilities',- href: '/examples/example-usecases/gemini-complex-ui-navigation',+ href: '/examples/ai-models/gemini-complex-ui-navigation',},];@@ -98,7 +98,7 @@ export default function LandingPage() {{/* Badge */}<div className="mb-6 inline-flex items-center gap-2 rounded-lg border border-fd-border bg-fd-card/50 px-3 py-1.5 text-sm backdrop-blur-sm"><span className="h-2 w-2 rounded-full bg-emerald-500" />- <span className="text-fd-muted-foreground">Open Source Documentation</span>+ <span className="text-fd-muted-foreground">Open Source</span></div><h1@@ -208,7 +208,7 @@ export default function LandingPage() {</p></div><Link- href="/examples"+ href="/examples/automation/form-filling"className="hidden items-center gap-1 text-sm font-medium text-fd-muted-foreground transition-colors hover:text-fd-foreground sm:inline-flex">View all@@ -257,7 +257,7 @@ export default function LandingPage() {{/* Mobile "View all" link */}<div className="mt-6 text-center sm:hidden"><Link- href="/examples"+ href="/examples/automation/form-filling"className="inline-flex items-center gap-1 text-sm font-medium text-fd-muted-foreground transition-colors hover:text-fd-foreground">View all examples@@ -281,23 +281,17 @@ export default function LandingPage() {</p><div className="mt-6 flex flex-wrap items-center justify-center gap-3"><Link- href="/guide/get-started/quickstart"+ href="/guide/get-started/what-is-cua"className="inline-flex items-center gap-2 rounded-xl bg-fd-foreground px-6 py-2.5 text-sm font-medium text-fd-background transition-colors hover:bg-fd-foreground/90">- Quickstart Guide+ Get Started<ArrowRight className="h-4 w-4" /></Link><Link- href="/reference/agent-sdk/agent-loops"+ href="/reference/computer-sdk"className="inline-flex items-center gap-2 rounded-xl border border-fd-border px-6 py-2.5 text-sm font-medium transition-colors hover:bg-fd-accent">- Agent Loops- </Link>- <Link- href="/reference/computer-sdk/computers"- className="inline-flex items-center gap-2 rounded-xl border border-fd-border px-6 py-2.5 text-sm font-medium transition-colors hover:bg-fd-accent"- >- Computer SDK+ API Reference</Link></div></div>diff --git a/docs/src/app/layout.config.tsx b/docs/src/app/layout.config.tsxindex 87414d2c17..1a58efd41f 100644--- a/docs/src/app/layout.config.tsx+++ b/docs/src/app/layout.config.tsx@@ -1,50 +1,7 @@import type { BaseLayoutProps } from 'fumadocs-ui/layouts/shared';-import Image from 'next/image';-import LogoBlack from '@/assets/logo-black.svg';-import LogoWhite from '@/assets/logo-white.svg';/**- * Shared layout configurations using Fumadocs native navigation+ * Shared layout configurations+ * Note: We use a custom header component directly in layouts*/-export const baseOptions: BaseLayoutProps = {- nav: {- title: (- <div className="flex items-center gap-2">- <Image- width={24}- height={24}- src={LogoBlack}- aria-label="Logo"- className="block dark:hidden"- alt="Logo"- />- <Image- width={24}- height={24}- src={LogoWhite}- aria-label="Logo"- className="hidden dark:block"- alt="Logo"- />- <span className="font-semibold" style={{ fontFamily: 'var(--font-urbanist)' }}>- Cua- </span>- <span className="text-sky-500 font-medium">Docs</span>- </div>- ),- },- links: [- {- type: 'icon',- url: 'https://discord.com/invite/mVnXXpdE85',- text: 'Discord',- icon: (- <svg viewBox="0 0 24 24" fill="currentColor" className="w-5 h-5">- <path d="M20.317 4.3698a19.7913 19.7913 0 00-4.8851-1.5152.0741.0741 0 00-.0785.0371c-.211.3753-.4447.8648-.6083 1.2495-1.8447-.2762-3.68-.2762-5.4868 0-.1636-.3933-.4058-.8742-.6177-1.2495a.077.077 0 00-.0785-.037 19.7363 19.7363 0 00-4.8852 1.515.0699.0699 0 00-.0321.0277C.5334 9.0458-.319 13.5799.0992 18.0578a.0824.0824 0 00.0312.0561c2.0528 1.5076 4.0413 2.4228 5.9929 3.0294a.0777.0777 0 00.0842-.0276c.4616-.6304.8731-1.2952 1.226-1.9942a.076.076 0 00-.0416-.1057c-.6528-.2476-1.2743-.5495-1.8722-.8923a.077.077 0 01-.0076-.1277c.1258-.0943.2517-.1923.3718-.2914a.0743.0743 0 01.0776-.0105c3.9278 1.7933 8.18 1.7933 12.0614 0a.0739.0739 0 01.0785.0095c.1202.099.246.1981.3728.2924a.077.077 0 01-.0066.1276 12.2986 12.2986 0 01-1.873.8914.0766.0766 0 00-.0407.1067c.3604.698.7719 1.3628 1.225 1.9932a.076.076 0 00.0842.0286c1.961-.6067 3.9495-1.5219 6.0023-3.0294a.077.077 0 00.0313-.0552c.5004-5.177-.8382-9.6739-3.5485-13.6604a.061.061 0 00-.0312-.0286zM8.02 15.3312c-1.1825 0-2.1569-1.0857-2.1569-2.419 0-1.3332.9555-2.4189 2.157-2.4189 1.2108 0 2.1757 1.0952 2.1568 2.419 0 1.3332-.9555 2.4189-2.1569 2.4189zm7.9748 0c-1.1825 0-2.1569-1.0857-2.1569-2.419 0-1.3332.9554-2.4189 2.1569-2.4189 1.2108 0 2.1757 1.0952 2.1568 2.419 0 1.3332-.946 2.4189-2.1568 2.4189Z" />- </svg>- ),- external: true,- },- ],- githubUrl: 'https://github.com/trycua/cua',-};+export const baseOptions: BaseLayoutProps = {};diff --git a/docs/src/components/custom-header.tsx b/docs/src/components/custom-header.tsxnew file mode 100644index 0000000000..cd79b9aac5--- /dev/null+++ b/docs/src/components/custom-header.tsx@@ -0,0 +1,104 @@+'use client';++import Link from 'next/link';+import Image from 'next/image';+import { usePathname } from 'next/navigation';+import { cn } from 'fumadocs-ui/utils/cn';+import { SearchToggle } from 'fumadocs-ui/components/layout/search-toggle';+import { ThemeToggle } from 'fumadocs-ui/components/layout/theme-toggle';+import LogoBlack from '@/assets/logo-black.svg';+import LogoWhite from '@/assets/logo-white.svg';++const navTabs = [+ { name: 'Guide', href: '/guide/get-started/what-is-cua', prefix: '/docs/guide' },+ { name: 'Examples', href: '/examples/automation/form-filling', prefix: '/docs/examples' },+ { name: 'API Reference', href: '/reference/computer-sdk', prefix: '/docs/reference' },+];++export function CustomHeader() {+ const pathname = usePathname();++ return (+ <header className="fixed top-0 left-0 right-0 z-50 border-b border-fd-border bg-fd-background/80 backdrop-blur-sm">+ <div className="container mx-auto flex h-14 items-center justify-between px-4">+ {/* Left: Logo and Nav */}+ <div className="flex items-center gap-6">+ {/* Logo */}+ <Link href="/" className="flex items-center gap-2">+ <Image+ width={24}+ height={24}+ src={LogoBlack}+ aria-label="Logo"+ className="block dark:hidden"+ alt="Logo"+ />+ <Image+ width={24}+ height={24}+ src={LogoWhite}+ aria-label="Logo"+ className="hidden dark:block"+ alt="Logo"+ />+ <span className="font-semibold" style={{ fontFamily: 'var(--font-urbanist)' }}>+ Cua+ </span>+ <span className="text-sky-500 font-medium">Docs</span>+ </Link>++ {/* Navigation */}+ <nav className="hidden items-center gap-4 md:flex">+ {navTabs.map((tab) => {+ const isActive = pathname.startsWith(tab.prefix);+ return (+ <Link+ key={tab.name}+ href={tab.href}+ className={cn(+ 'text-sm font-medium transition-colors',+ isActive+ ? 'text-fd-foreground'+ : 'text-fd-muted-foreground hover:text-fd-foreground'+ )}+ >+ {tab.name}+ </Link>+ );+ })}+ </nav>+ </div>++ {/* Right: Search, Theme, Icons */}+ <div className="flex items-center gap-2">+ <SearchToggle />+ <ThemeToggle />++ {/* Discord */}+ <a+ href="https://discord.com/invite/mVnXXpdE85"+ target="_blank"+ rel="noreferrer"+ className="inline-flex h-9 w-9 items-center justify-center rounded-md text-fd-muted-foreground transition-colors hover:bg-fd-accent hover:text-fd-foreground"+ >+ <svg viewBox="0 0 24 24" fill="currentColor" className="h-5 w-5">+ <path d="M20.317 4.3698a19.7913 19.7913 0 00-4.8851-1.5152.0741.0741 0 00-.0785.0371c-.211.3753-.4447.8648-.6083 1.2495-1.8447-.2762-3.68-.2762-5.4868 0-.1636-.3933-.4058-.8742-.6177-1.2495a.077.077 0 00-.0785-.037 19.7363 19.7363 0 00-4.8852 1.515.0699.0699 0 00-.0321.0277C.5334 9.0458-.319 13.5799.0992 18.0578a.0824.0824 0 00.0312.0561c2.0528 1.5076 4.0413 2.4228 5.9929 3.0294a.0777.0777 0 00.0842-.0276c.4616-.6304.8731-1.2952 1.226-1.9942a.076.076 0 00-.0416-.1057c-.6528-.2476-1.2743-.5495-1.8722-.8923a.077.077 0 01-.0076-.1277c.1258-.0943.2517-.1923.3718-.2914a.0743.0743 0 01.0776-.0105c3.9278 1.7933 8.18 1.7933 12.0614 0a.0739.0739 0 01.0785.0095c.1202.099.246.1981.3728.2924a.077.077 0 01-.0066.1276 12.2986 12.2986 0 01-1.873.8914.0766.0766 0 00-.0407.1067c.3604.698.7719 1.3628 1.225 1.9932a.076.076 0 00.0842.0286c1.961-.6067 3.9495-1.5219 6.0023-3.0294a.077.077 0 00.0313-.0552c.5004-5.177-.8382-9.6739-3.5485-13.6604a.061.061 0 00-.0312-.0286zM8.02 15.3312c-1.1825 0-2.1569-1.0857-2.1569-2.419 0-1.3332.9555-2.4189 2.157-2.4189 1.2108 0 2.1757 1.0952 2.1568 2.419 0 1.3332-.9555 2.4189-2.1569 2.4189zm7.9748 0c-1.1825 0-2.1569-1.0857-2.1569-2.419 0-1.3332.9554-2.4189 2.1569-2.4189 1.2108 0 2.1757 1.0952 2.1568 2.419 0 1.3332-.946 2.4189-2.1568 2.4189Z" />+ </svg>+ </a>++ {/* GitHub */}+ <a+ href="https://github.com/trycua/cua"+ target="_blank"+ rel="noreferrer"+ className="inline-flex h-9 w-9 items-center justify-center rounded-md text-fd-muted-foreground transition-colors hover:bg-fd-accent hover:text-fd-foreground"+ >+ <svg viewBox="0 0 24 24" fill="currentColor" className="h-5 w-5">+ <path d="M12 .297c-6.63 0-12 5.373-12 12 0 5.303 3.438 9.8 8.205 11.385.6.113.82-.258.82-.577 0-.285-.01-1.04-.015-2.04-3.338.724-4.042-1.61-4.042-1.61C4.422 18.07 3.633 17.7 3.633 17.7c-1.087-.744.084-.729.084-.729 1.205.084 1.838 1.236 1.838 1.236 1.07 1.835 2.809 1.305 3.495.998.108-.776.417-1.305.76-1.605-2.665-.3-5.466-1.332-5.466-5.93 0-1.31.465-2.38 1.235-3.22-.135-.303-.54-1.523.105-3.176 0 0 1.005-.322 3.3 1.23.96-.267 1.98-.399 3-.405 1.02.006 2.04.138 3 .405 2.28-1.552 3.285-1.23 3.285-1.23.645 1.653.24 2.873.12 3.176.765.84 1.23 1.91 1.23 3.22 0 4.61-2.805 5.625-5.475 5.92.42.36.81 1.096.81 2.22 0 1.606-.015 2.896-.015 3.286 0 .315.21.69.825.57C20.565 22.092 24 17.592 24 12.297c0-6.627-5.373-12-12-12" />+ </svg>+ </a>+ </div>+ </div>+ </header>+ );+}diff --git a/docs/src/components/docs-nav.tsx b/docs/src/components/docs-nav.tsxnew file mode 100644index 0000000000..f6cc3edc65--- /dev/null+++ b/docs/src/components/docs-nav.tsx@@ -0,0 +1,37 @@+'use client';++import Link from 'next/link';+import { usePathname } from 'next/navigation';+import { cn } from 'fumadocs-ui/utils/cn';++const tabs = [+ { name: 'Guide', href: '/guide/get-started/what-is-cua', prefix: '/guide' },+ { name: 'Examples', href: '/examples', prefix: '/examples' },+ { name: 'Reference', href: '/reference/computer-sdk', prefix: '/reference' },+];++export function DocsNav() {+ const pathname = usePathname();++ return (+ <nav className="flex items-center gap-4">+ {tabs.map((tab) => {+ const isActive = pathname.startsWith(tab.prefix);+ return (+ <Link+ key={tab.name}+ href={tab.href}+ className={cn(+ 'text-sm font-medium transition-colors',+ isActive+ ? 'text-fd-foreground'+ : 'text-fd-muted-foreground hover:text-fd-foreground'+ )}+ >+ {tab.name}+ </Link>+ );+ })}+ </nav>+ );+}diff --git a/docs/src/components/footer.tsx b/docs/src/components/footer.tsxindex 02f3a9eaf1..89d94d4fb2 100644--- a/docs/src/components/footer.tsx+++ b/docs/src/components/footer.tsx@@ -1,156 +1,23 @@export function Footer() {return (- <footer className="mt-auto border-t border-fd-border py-8">+ <footer className="mt-auto border-t border-fd-border py-6"><div className="container mx-auto px-4">- <div className="grid grid-cols-1 md:grid-cols-4 gap-8 mb-6">- {/* Product Links */}- <div>- <h3 className="font-semibold text-sm mb-3 text-fd-foreground">Product</h3>- <ul className="space-y-2">- <li>- <a- href="https://cua.ai"- className="text-sm text-fd-muted-foreground hover:text-fd-foreground transition-colors"- >- Home- </a>- </li>- <li>- <a- href="https://cua.ai/pricing"- className="text-sm text-fd-muted-foreground hover:text-fd-foreground transition-colors"- >- Pricing- </a>- </li>- <li>- <a- href="https://cua.ai/#features"- className="text-sm text-fd-muted-foreground hover:text-fd-foreground transition-colors"- >- Features- </a>- </li>- </ul>- </div>-- {/* Documentation Links */}- <div>- <h3 className="font-semibold text-sm mb-3 text-fd-foreground">Documentation</h3>- <ul className="space-y-2">- <li>- <a- href="/docs"- className="text-sm text-fd-muted-foreground hover:text-fd-foreground transition-colors"- >- Getting Started- </a>- </li>- <li>- <a- href="/docs/agent-sdk/agent-loops"- className="text-sm text-fd-muted-foreground hover:text-fd-foreground transition-colors"- >- Agent Loops- </a>- </li>- <li>- <a- href="/docs/get-started/quickstart"- className="text-sm text-fd-muted-foreground hover:text-fd-foreground transition-colors"- >- Quick Start- </a>- </li>- </ul>- </div>-- {/* Resources Links */}- <div>- <h3 className="font-semibold text-sm mb-3 text-fd-foreground">Resources</h3>- <ul className="space-y-2">- <li>- <a- href="https://cua.ai/blog"- className="text-sm text-fd-muted-foreground hover:text-fd-foreground transition-colors"- >- Blog- </a>- </li>- <li>- <a- href="https://github.com/trycua/cua"- target="_blank"- rel="noopener noreferrer"- className="text-sm text-fd-muted-foreground hover:text-fd-foreground transition-colors"- >- GitHub- </a>- </li>- <li>- <a- href="https://discord.com/invite/mVnXXpdE85"- target="_blank"- rel="noopener noreferrer"- className="text-sm text-fd-muted-foreground hover:text-fd-foreground transition-colors"- >- Discord Community- </a>- </li>- </ul>- </div>-- {/* Company Links */}- <div>- <h3 className="font-semibold text-sm mb-3 text-fd-foreground">Company</h3>- <ul className="space-y-2">- <li>- <a- href="https://cua.ai/about"- className="text-sm text-fd-muted-foreground hover:text-fd-foreground transition-colors"- >- About- </a>- </li>- <li>- <a- href="mailto:[email protected]"- className="text-sm text-fd-muted-foreground hover:text-fd-foreground transition-colors"- >- Contact- </a>- </li>- <li>- <a- href="https://cua.ai/cookie-policy"- target="_blank"- rel="noopener noreferrer"- className="text-sm text-fd-muted-foreground hover:text-fd-foreground transition-colors"- >- Cookie Policy- </a>- </li>- </ul>- </div>- </div>-- {/* Bottom Bar */}- <div className="pt-6 border-t border-fd-border flex flex-col md:flex-row justify-between items-center gap-4">+ <div className="flex flex-col md:flex-row justify-between items-center gap-4"><p className="text-sm text-fd-muted-foreground">- © {new Date().getFullYear()} Cua. All rights reserved.+ © {new Date().getFullYear()} Cua AI, Inc.</p><div className="flex gap-4"><ahref="https://cua.ai/privacy-policy"className="text-sm text-fd-muted-foreground hover:text-fd-foreground transition-colors">- Privacy Policy+ Privacy</a><ahref="https://cua.ai/cookie-policy"className="text-sm text-fd-muted-foreground hover:text-fd-foreground transition-colors">- Cookie Policy+ Cookies</a></div></div>diff --git a/docs/src/middleware.ts b/docs/src/middleware.tsindex 6a35451c9a..f5c5f6d427 100644--- a/docs/src/middleware.ts+++ b/docs/src/middleware.ts@@ -1,9 +1,24 @@import { NextResponse } from 'next/server';import type { NextRequest } from 'next/server';+// Redirect section roots to their first content page+// These paths don't include basePath because middleware receives paths without it+const redirects: Record<string, string> = {+ '/guide': '/docs/guide/get-started/what-is-cua',+ '/examples': '/docs/examples/automation/form-filling',+ '/reference': '/docs/reference/computer-sdk',+};+export function middleware(request: NextRequest) {+ const { pathname } = request.nextUrl;++ // Handle section root redirects+ if (redirects[pathname]) {+ return NextResponse.redirect(new URL(redirects[pathname], request.url));+ }+const requestHeaders = new Headers(request.headers);- requestHeaders.set('x-pathname', request.nextUrl.pathname);+ requestHeaders.set('x-pathname', pathname);return NextResponse.next({request: {