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
Added @sandboxed decorator
Dillon DuPonta7e56ce64a43
diff --git a/examples/eval_examples.py b/examples/eval_examples.pyindex a476e1047e..48da31bee0 100644--- a/examples/eval_examples.py+++ b/examples/eval_examples.py@@ -24,40 +24,12 @@ for path in pythonpath.split(":"):from computer.computer import Computerfrom computer.providers.base import VMProviderTypefrom computer.logger import LogLevel+from computer.helpers import sandboxed# Assuming these exist based on your requestfrom agent import ComputerAgent, LLM, AgentLoop, LLMProvider-# Global reference to computer instance (will be set in main)-_computer = None---def remote(venv_name="eval_env", max_retries=3):- """- Decorator that wraps a function to be executed remotely via computer.venv_exec-- Args:- venv_name: Name of the virtual environment to execute in- """- def decorator(func):- @wraps(func)- async def wrapper(*args, **kwargs):- if _computer is None:- raise RuntimeError("Computer instance not initialized. Call this after computer.run()")- for i in range(max_retries):- try:- return await _computer.venv_exec(venv_name, func, *args, **kwargs)- except Exception as e:- print(f"Attempt {i+1} failed: {e}")- await asyncio.sleep(1)- if i == max_retries - 1:- raise e- return wrapper- return decorator--async def main():- global _computer, remote-+async def main():try:print("\n=== Using cloud container ===")# # Create a remote Linux computer with CUA@@ -70,7 +42,6 @@ async def main():# Connect to local macOS computercomputer = Computer()- _computer = computer # Set global referencetry:# Run the computer with default parameters@@ -84,8 +55,8 @@ async def main():await computer.interface.run_command(f"open https://en.wikipedia.org/wiki/{page.replace(' ', '_')} &")await asyncio.sleep(2) # Wait for page to load- # Remote functions for wikirace - using @remote decorator- @remote("eval_env")+ # Remote functions for wikirace - using @sandboxed decorator+ @sandboxed("eval_env")def close_all_windows():import pywinctlwindows = pywinctl.getAllWindows()@@ -96,7 +67,7 @@ async def main():# Some windows might not be closeable or may have already closedpass- @remote("eval_env")+ @sandboxed("eval_env")def get_current_wiki_page():import pywinctltitles = pywinctl.getAllTitles()diff --git a/libs/computer/computer/computer.py b/libs/computer/computer/computer.pyindex 2057215e89..191c611dcc 100644--- a/libs/computer/computer/computer.py+++ b/libs/computer/computer/computer.py@@ -11,6 +11,7 @@ import jsonimport loggingfrom .telemetry import record_computer_initializationimport os+from . import helpers# Import provider related modulesfrom .providers.base import VMProviderType@@ -460,6 +461,10 @@ class Computer:# Set the initialization flag and clear the initializing flagself._initialized = True++ # Set this instance as the default computer for remote decorators+ helpers.set_default_computer(self)+self.logger.info("Computer successfully initialized")except Exception as e:raisediff --git a/libs/computer/computer/helpers.py b/libs/computer/computer/helpers.pynew file mode 100644index 0000000000..b472c0478e--- /dev/null+++ b/libs/computer/computer/helpers.py@@ -0,0 +1,49 @@+"""+Helper functions and decorators for the Computer module.+"""+import asyncio+from functools import wraps+from typing import Any, Callable, Optional, TypeVar, cast++# Global reference to the default computer instance+_default_computer = None++def set_default_computer(computer):+ """+ Set the default computer instance to be used by the remote decorator.++ Args:+ computer: The computer instance to use as default+ """+ global _default_computer+ _default_computer = computer+++def sandboxed(venv_name: str = "default", computer: str = "default", max_retries: int = 3):+ """+ Decorator that wraps a function to be executed remotely via computer.venv_exec++ Args:+ venv_name: Name of the virtual environment to execute in+ computer: The computer instance to use, or "default" to use the globally set default+ max_retries: Maximum number of retries for the remote execution+ """+ def decorator(func):+ @wraps(func)+ async def wrapper(*args, **kwargs):+ # Determine which computer instance to use+ comp = computer if computer != "default" else _default_computer++ if comp is None:+ raise RuntimeError("No computer instance available. Either specify a computer instance or call set_default_computer() first.")++ for i in range(max_retries):+ try:+ return await comp.venv_exec(venv_name, func, *args, **kwargs)+ except Exception as e:+ print(f"Attempt {i+1} failed: {e}")+ await asyncio.sleep(1)+ if i == max_retries - 1:+ raise e+ return wrapper+ return decoratordiff --git a/tests/venv.py b/tests/venv.pyindex 4f9e320670..8b78a78f99 100644--- a/tests/venv.py+++ b/tests/venv.py@@ -31,24 +31,29 @@ for path in pythonpath.split(":"):from computer.computer import Computerfrom computer.providers.base import VMProviderType+from computer.helpers import remote, set_default_computer@pytest.fixture(scope="session")async def computer():"""Shared Computer instance for all test cases."""- # Create a remote Linux computer with C/ua- computer = Computer(- os_type="linux",- api_key=os.getenv("CUA_API_KEY"),- name=str(os.getenv("CUA_CONTAINER_NAME")),- provider_type=VMProviderType.CLOUD,- )+ # # Create a remote Linux computer with C/ua+ # computer = Computer(+ # os_type="linux",+ # api_key=os.getenv("CUA_API_KEY"),+ # name=str(os.getenv("CUA_CONTAINER_NAME")),+ # provider_type=VMProviderType.CLOUD,+ # )++ # Create a local macOS computer with C/ua+ computer = Computer()try:await computer.run()yield computerfinally:- await computer.stop()+ # await computer.stop()+ pass# Sample test cases@@ -146,6 +151,56 @@ async def test_venv_exec_stdout_capture(computer, capfd):assert out == "Hello World!\n\n"assert result == "Function completed"[email protected](loop_scope="session")+async def test_remote_decorator(computer):+ """Test the remote decorator from computer.helpers module."""+ # Set the computer as default for the remote decorator+ set_default_computer(computer)++ # Define a function with the remote decorator+ @sandboxed("test_env")+ def get_package_version():+ import sys+ import platform+ return {+ "python_version": sys.version,+ "platform": platform.platform(),+ "success": True+ }++ # Call the decorated function+ result = await get_package_version()++ # Verify the function executed in the virtual environment+ assert "python_version" in result+ assert "platform" in result+ assert result["success"] == True+[email protected](loop_scope="session")+async def test_remote_decorator_with_custom_computer(computer):+ """Test the remote decorator with explicitly specified computer instance."""+ # Define a function with the remote decorator that explicitly specifies the computer+ @sandboxed("test_env", computer=computer)+ def get_system_info():+ import os+ import sys+ return {+ "python_version": sys.version,+ "environment_vars": dict(os.environ),+ "working_directory": os.getcwd()+ }++ # Call the decorated function+ result = await get_system_info()++ # Verify the function executed in the virtual environment+ assert "python_version" in result+ assert "environment_vars" in result+ assert "working_directory" in result+ # The virtual environment should have a different working directory+ # than the current test process+ assert result["working_directory"] != os.getcwd()+if __name__ == "__main__":# Run tests directlypytest.main([__file__, "-v"])