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
Replace Native Task example w/ more specific macOS & Windows Native Task examples (#868)
ddupontb8af518b88e6
diff --git a/docs/content/docs/cuabench/examples/macos-native-task.mdx b/docs/content/docs/cuabench/examples/macos-native-task.mdxnew file mode 100644index 0000000000..fbd55bb261--- /dev/null+++ b/docs/content/docs/cuabench/examples/macos-native-task.mdx@@ -0,0 +1,78 @@+---+title: macOS Native Task+description: Build a Reminders task using osascript-based app helpers on macOS+---++Create a task where agents must add a reminder using the Reminders app. This shows how to use macOS app helpers that leverage `osascript` for evaluation.++## Prerequisites++macOS native provider configured (runs on actual Mac hardware).++## Create the Task++Create `tasks/add_reminder/main.py`:++```python+import cua_bench as cb++[email protected]_config(split="train")+def load():+ return [+ cb.Task(+ description="Open Reminders and create a new reminder called 'Buy groceries' in the default list.",+ metadata={"reminder_name": "Buy groceries"},+ computer={+ "provider": "native",+ "setup_config": {"os_type": "macos", "width": 1440, "height": 900},+ },+ )+ ]++[email protected]_task(split="train")+async def start(task_cfg: cb.Task, session: cb.DesktopSession):+ """Launch Reminders app."""+ await session.apps.reminders.launch()++[email protected]_task(split="train")+async def evaluate(task_cfg: cb.Task, session: cb.DesktopSession) -> list[float]:+ """Check if the reminder was created using osascript getter."""+ target_name = task_cfg.metadata["reminder_name"]++ # App helper uses osascript internally to query Reminders+ reminders = await session.apps.reminders.get_incomplete_reminders()++ for reminder in reminders:+ if reminder["name"] == target_name:+ return [1.0]+ return [0.0]+++if __name__ == "__main__":+ cb.interact(__file__)+```++## How It Works++The macOS app helpers use AppleScript via `osascript` to interact with first-party apps:++```python+# These methods run osascript commands under the hood+notes = await session.apps.notes.get_all_notes()+events = await session.apps.calendar.get_events_today()+reminders = await session.apps.reminders.get_incomplete_reminders()+```++## Run It++```bash+cb interact tasks/add_reminder+```++## Next Steps++- [Windows Native Task](/cuabench/examples/windows-native-task) - File system-based evaluation+- [App Helpers](/cuabench/guide/fundamentals/app-helpers) - Full API referencediff --git a/docs/content/docs/cuabench/examples/meta.json b/docs/content/docs/cuabench/examples/meta.jsonindex 546cc85da5..a3831e93de 100644--- a/docs/content/docs/cuabench/examples/meta.json+++ b/docs/content/docs/cuabench/examples/meta.json@@ -2,5 +2,11 @@"title": "Examples","description": "Step-by-step tutorials for common workflows","icon": "Blocks",- "pages": ["universal-task", "native-task", "genai-task-generation", "custom-agent"]+ "pages": [+ "universal-task",+ "windows-native-task",+ "macos-native-task",+ "genai-task-generation",+ "custom-agent"+ ]}diff --git a/docs/content/docs/cuabench/examples/native-task.mdx b/docs/content/docs/cuabench/examples/native-task.mdxdeleted file mode 100644index b401db79e3..0000000000--- a/docs/content/docs/cuabench/examples/native-task.mdx+++ /dev/null@@ -1,364 +0,0 @@-----title: Create a Native Task-description: Build a file-based question-answering task using native OS commands and file manipulation------In this tutorial, you'll create a task that uses native OS capabilities to set up files and evaluate completion. This task uses **native provider** - it runs on real Docker/QEMU environments with full shell access.--**Time:** ~10 minutes-**Prerequisites:** cua-bench installed, Docker running--## What You'll Build--A question-answering task where agents must:--1. Read a question from a text file on the Desktop-2. Write their answer to another text file-3. Get evaluated based on file contents--You'll learn:--- Using `run_command()` for OS-level operations-- Setting up files and directories-- Evaluating tasks by reading files-- Working with native Linux/Windows environments--## When to Use Native Tasks--**Use native tasks when:**--- You need to test real OS interactions (file system, registry, processes)-- The task requires installing or using real applications-- You need shell access for complex setup-- You're building WinArena-style tasks--**Use Universal GUI instead when:**--- You're building custom interfaces or games-- You want cross-platform compatibility-- You don't need real OS features-- You want faster, lightweight environments--## Step 1: Create Task Directory--```bash-mkdir -p tasks/question_answer-cd tasks/question_answer-```--## Step 2: Create the Task Configuration--Create `main.py`:--```python-import cua_bench as cb-from pathlib import Path--[email protected]_config(split="train")-def load():- """Define task variants with different questions."""- qa_pairs = [- {- "question": "What is the capital of France?",- "answer": "Paris"- },- {- "question": "What is 2 + 2?",- "answer": "4"- },- {- "question": "What color is the sky on a clear day?",- "answer": "blue"- },- {- "question": "What is the largest planet in our solar system?",- "answer": "Jupiter"- }- ]-- return [- cb.Task(- description=f'Open the question.txt file on the Desktop, read the question, and write your answer in answer.txt on the Desktop. Question: {qa["question"]}',- metadata={- "question": qa["question"],- "answer": qa["answer"]- },- computer={- "provider": "native", # Requires Docker/QEMU- "setup_config": {- "os_type": "linux", # or "windows"- "width": 1024,- "height": 768- }- }- )- for qa in qa_pairs- ]--[email protected]_task(split="train")-async def start(task_cfg: cb.Task, session: cb.DesktopSession):- """Initialize the task environment with files."""- # Get the question from metadata- question = task_cfg.metadata["question"]-- # Create Desktop directory if it doesn't exist- await session.run_command("mkdir -p ~/Desktop")-- # Write the question to a text file on the Desktop- await session.run_command(f'echo "{question}" > ~/Desktop/question.txt')-- # Ensure answer.txt doesn't exist yet- await session.run_command("rm -f ~/Desktop/answer.txt")--[email protected]_task(split="train")-async def evaluate(task_cfg: cb.Task, session: cb.DesktopSession) -> list[float]:- """Return reward based on task completion."""- expected_answer = task_cfg.metadata["answer"].strip().lower()-- # Check if answer.txt exists and read it- result = await session.run_command("cat ~/Desktop/answer.txt 2>/dev/null || echo ''")-- # Extract the actual answer from the command result- user_answer = result["stdout"].strip().lower() if result else ""-- # Check if the answer matches (case-insensitive, stripped)- if user_answer == expected_answer:- return [1.0]- else:- return [0.0]--[email protected]_task(split="train")-async def solve(task_cfg: cb.Task, session: cb.DesktopSession):- """Demonstrate the solution."""- answer = task_cfg.metadata["answer"]-- # Open the question file to read it (demonstration)- await session.run_command("cat ~/Desktop/question.txt")-- # Write the answer to answer.txt- await session.run_command(f'echo "{answer}" > ~/Desktop/answer.txt')-```--## Step 3: Understanding run_command()--The `run_command()` method executes shell commands and returns a dict:--```python-result = await session.run_command("cat ~/Desktop/answer.txt")--# Result structure:-{- "stdout": str, # Command output- "stderr": str, # Error output- "return_code": int, # Exit code (0 = success)- "success": bool # True if return_code == 0-}--# Access the output:-output = result["stdout"]-errors = result["stderr"]-exit_code = result["return_code"]-succeeded = result["success"]-```--### Common Patterns--**Create directories:**--```python-await session.run_command("mkdir -p ~/Desktop/MyFolder")-```--**Write files:**--```python-await session.run_command('echo "content" > ~/Desktop/file.txt')-```--**Read files:**--```python-result = await session.run_command("cat ~/Desktop/file.txt")-content = result["stdout"]-```--**Check if file exists:**--```python-result = await session.run_command("test -f ~/Desktop/file.txt && echo 'yes' || echo 'no'")-exists = result["stdout"].strip() == "yes"-```--**Install applications (Linux):**--```python-await session.run_command("sudo apt update && sudo apt install -y firefox")-```--**Launch applications:**--```python-await session.run_command("firefox &") # Background process-```--## Step 4: Run the Task--### Preview Interactively--```bash-cb interact tasks/question_answer --variant-id 0-```--A VNC viewer will open showing the native Linux desktop environment.--### Run with Oracle--```bash-cb interact tasks/question_answer --oracle --variant-id 0-```--### Run with Agent--```bash-export ANTHROPIC_API_KEY=sk-...-cb run task tasks/question_answer --agent cua-agent --model anthropic/claude-sonnet-4-20250514-```--## Advanced: Windows Tasks--For Windows-specific tasks, use `os_type: "windows"`:--```python[email protected]_config(split="train")-def load():- return [- cb.Task(- description='Open Notepad and write "Hello World" to a file',- computer={- "provider": "native",- "setup_config": {- "os_type": "windows", # Windows VM- "width": 1920,- "height": 1080- }- }- )- ]-[email protected]_task(split="train")-async def start(task_cfg: cb.Task, session: cb.DesktopSession):- # Windows commands use PowerShell/CMD syntax- await session.run_command('powershell -Command "New-Item -Path C:\\Users\\Public\\Desktop -ItemType Directory -Force"')-- # Launch Notepad- await session.run_command("notepad.exe")-```--### Windows Command Patterns--**PowerShell commands:**--```python-result = await session.run_command('powershell -Command "Get-ChildItem C:\\Users"')-```--**Registry operations:**--```python-await session.run_command('reg add "HKCU\\Software\\MyApp" /v Setting /t REG_SZ /d "value"')-```--**File operations:**--```python-await session.run_command('powershell -Command "Get-Content C:\\path\\file.txt"')-```--## File API Alternative--For simple file operations, use the dedicated file methods instead of `run_command()`:--```python-# Read file-content = await session.read_file("/path/to/file.txt")--# Write file-await session.write_file("/path/to/file.txt", "content")--# Check if file exists-exists = await session.file_exists("/path/to/file.txt")--# List directory-files = await session.list_dir("/path/to/dir")-```--These methods are cleaner than shell commands for basic file operations.--## Key Concepts--**Native Provider**: Runs on real Docker (Linux) or QEMU (Windows) environments--**Shell Commands**: Use `run_command()` for OS-level operations--**Return Type**: Always returns a dict with `stdout`, `stderr`, `return_code`, `success`--**File Setup**: Use setup to prepare the environment before agents interact--**Evaluation**: Read files/check state to determine task completion--## Performance Considerations--Native tasks are **slower** than Universal GUI tasks because they:--- Require Docker/QEMU startup time-- Run full OS environments-- Execute real shell commands--**Optimization tips:**--- Use Universal GUI when possible-- Batch multiple commands with `&&`-- Avoid unnecessary file operations-- Use file API methods for simple reads/writes--## Troubleshooting--**Docker not running:**--```-Error: Cannot connect to Docker daemon-```--Solution: Start Docker Desktop--**Permission denied:**--```python-# Add sudo for operations requiring permissions-await session.run_command("sudo apt install -y package")-```--**Command not found:**--```python-# Install the package first-await session.run_command("sudo apt update && sudo apt install -y package-name")-```--**Windows path escaping:**--```python-# Use raw strings or double backslashes-await session.run_command('powershell -Command "Get-Item C:\\\\Users"')-```--## Next Steps--- Learn about [Native Provider](/cuabench/guide/fundamentals/native-provider) for advanced OS features-- See [Session API Reference](/cuabench/reference/session-api) for all available methods-- Build a [Custom Agent](/cuabench/guide/examples/custom-agent) to solve tasks-- Compare with [Universal Tasks](/cuabench/guide/examples/universal-task) to choose the right approachdiff --git a/docs/content/docs/cuabench/examples/windows-native-task.mdx b/docs/content/docs/cuabench/examples/windows-native-task.mdxnew file mode 100644index 0000000000..80ea199e26--- /dev/null+++ b/docs/content/docs/cuabench/examples/windows-native-task.mdx@@ -0,0 +1,72 @@+---+title: Windows Native Task+description: Build a Unity project creation task using app helpers on Windows+---++Create a task where agents must create a Unity project on Windows. This shows how to use app helpers for installation and file system checks for evaluation.++## Prerequisites++Create a Windows VM image:++```bash+cb image create windows-qemu --download-iso+```++## Create the Task++Create `tasks/unity_project/main.py`:++```python+import cua_bench as cb++[email protected]_config(split="train")+def load():+ return [+ cb.Task(+ description="Create a new Unity 3D project called 'MyGame' and save it to Desktop/UnityProjects/",+ metadata={"project_name": "MyGame"},+ computer={+ "provider": "native",+ "setup_config": {"os_type": "windows", "width": 1920, "height": 1080},+ },+ )+ ]++[email protected]_task(split="train")+async def start(task_cfg: cb.Task, session: cb.DesktopSession):+ """Install Unity using the app helper."""+ await session.apps.unity.install(with_shortcut=True)++[email protected]_task(split="train")+async def evaluate(task_cfg: cb.Task, session: cb.DesktopSession) -> list[float]:+ """Check if the Unity project was created."""+ project_name = task_cfg.metadata["project_name"]++ result = await session.run_command(+ f'if exist "%USERPROFILE%\\Desktop\\UnityProjects\\{project_name}\\Assets" (echo FOUND) else (echo NOT_FOUND)',+ check=False,+ )++ if "FOUND" in result["stdout"]:+ return [1.0]+ return [0.0]+++if __name__ == "__main__":+ cb.interact(__file__)+```++## Run It++```bash+cb interact tasks/unity_project+```++## Next Steps++- [macOS Native Task](/cuabench/examples/macos-native-task) - Use osascript-based app helpers+- [App Helpers](/cuabench/guide/fundamentals/app-helpers) - Full API referencediff --git a/docs/content/docs/cuabench/guide/fundamentals/app-helpers.mdx b/docs/content/docs/cuabench/guide/fundamentals/app-helpers.mdxindex 576215b5b4..91b7051d70 100644--- a/docs/content/docs/cuabench/guide/fundamentals/app-helpers.mdx+++ b/docs/content/docs/cuabench/guide/fundamentals/app-helpers.mdx@@ -27,11 +27,14 @@ async def evaluate(task_cfg: cb.Task, session: cb.DesktopSession) -> list[float]## Available Apps-| App | Name | Platforms |-|-----|------|-----------|-| Godot | `godot` | Linux, Windows, macOS |-| Unity | `unity` | Linux, Windows, macOS |+| App | Name | Platforms |+| --------------- | ----------------- | --------------------- |+| Godot | `godot` | Linux, Windows, macOS |+| Unity | `unity` | Linux, Windows, macOS || Adobe Photoshop | `adobe_photoshop` | Linux (WINE), Windows |+| Notes | `notes` | macOS |+| Reminders | `reminders` | macOS |+| Calendar | `calendar` | macOS |## Contributing Apps@@ -83,10 +86,10 @@ from . import chrome # noqa: F401## Platform Matrix-| Method | Linux | Windows | macOS |-|--------|-------|---------|-------|-| `install` | ✅ | ✅ | ✅ |-| `launch` | ✅ | ✅ | ✅ |-| `uninstall` | ✅ | ⚠️ | ⚠️ |+| Method | Linux | Windows | macOS |+| ----------- | ----- | ------- | ----- |+| `install` | ✅ | ✅ | ✅ |+| `launch` | ✅ | ✅ | ✅ |+| `uninstall` | ✅ | ⚠️ | ⚠️ |✅ = Supported, ⚠️ = Partial supportdiff --git a/libs/cua-bench/cua_bench/apps/__init__.py b/libs/cua-bench/cua_bench/apps/__init__.pyindex 7733102f74..ecfdc9614d 100644--- a/libs/cua-bench/cua_bench/apps/__init__.py+++ b/libs/cua-bench/cua_bench/apps/__init__.py@@ -46,21 +46,24 @@ Example - Using in a task:await session.launch_app("godot", project_path="~/project")"""+# macOS first-party apps (use osascript for getters)+# Import app modules to trigger auto-registration via AppMeta metaclass+from . import adobe_photoshop # noqa: F401+from . import calendar # noqa: F401+from . import godot # noqa: F401+from . import notes # noqa: F401+from . import reminders # noqa: F401+from . import unity # noqa: F401from .registry import (App,+ AppRegistry,+ get_app,install,launch,- uninstall,- get_app,list_apps,- AppRegistry,+ uninstall,)-# Import app modules to trigger auto-registration via AppMeta metaclass-from . import godot # noqa: F401-from . import adobe_photoshop # noqa: F401-from . import unity # noqa: F401-__all__ = ["App","install",diff --git a/libs/cua-bench/cua_bench/apps/calendar.py b/libs/cua-bench/cua_bench/apps/calendar.pynew file mode 100644index 0000000000..7cae841dce--- /dev/null+++ b/libs/cua-bench/cua_bench/apps/calendar.py@@ -0,0 +1,338 @@+"""Apple Calendar app definition for macOS."""++from __future__ import annotations++from typing import TYPE_CHECKING, List, Optional++from .registry import App, launch++if TYPE_CHECKING:+ from .registry import BoundApp+++class Calendar(App):+ """Apple Calendar - macOS first-party calendar application.++ Provides getters for retrieving calendar data via AppleScript/osascript.+ Calendar is pre-installed on macOS, so no install method is needed.++ Launch options:+ - None (just opens the app)++ Custom getters (macOS only):+ - get_calendars(): Get list of calendar names+ - get_events_today(): Get events for today+ - get_events_in_calendar(calendar): Get events in a specific calendar+ - get_event_by_title(title): Get a specific event by title+ """++ name = "calendar"+ description = "Apple Calendar - macOS calendar application"++ @launch("macos")+ async def launch_macos(self: "BoundApp") -> None:+ """Launch Calendar on macOS."""+ await self.session.run_command('open -a "Calendar"', check=False)++ async def get_calendars(self: "BoundApp") -> List[str]:+ """Get list of calendar names.++ Returns:+ List of calendar names.+ """+ script = """+tell application "Calendar"+ set calNames to {}+ repeat with c in calendars+ set end of calNames to name of c+ end repeat+ return calNames+end tell+"""+ result = await self.session.run_command(+ f"osascript -e '{script}'",+ check=False,+ )+ return _parse_list_output(result.get("stdout", ""))++ async def get_events_today(self: "BoundApp") -> List[dict]:+ """Get all events for today.++ Returns:+ List of dicts with 'summary', 'start_date', 'end_date', 'calendar' keys.+ """+ script = """+tell application "Calendar"+ set todayStart to current date+ set hours of todayStart to 0+ set minutes of todayStart to 0+ set seconds of todayStart to 0+ set todayEnd to todayStart + (1 * days)++ set eventList to {}+ repeat with c in calendars+ set calName to name of c+ set todayEvents to (events of c whose start date >= todayStart and start date < todayEnd)+ repeat with e in todayEvents+ set eventSummary to summary of e+ set eventStart to start date of e as string+ set eventEnd to end date of e as string+ set end of eventList to {summary:eventSummary, start_date:eventStart, end_date:eventEnd, calendar:calName}+ end repeat+ end repeat+ return eventList+end tell+"""+ result = await self.session.run_command(+ f"osascript -e '{script}'",+ check=False,+ )+ return _parse_event_output(result.get("stdout", ""))++ async def get_events_in_calendar(self: "BoundApp", *, calendar_name: str) -> List[dict]:+ """Get all events in a specific calendar.++ Args:+ calendar_name: Name of the calendar.++ Returns:+ List of dicts with 'summary', 'start_date', 'end_date' keys.+ """+ escaped_name = calendar_name.replace('"', '\\"')+ script = f"""+tell application "Calendar"+ set eventList to {{}}+ set targetCal to calendar "{escaped_name}"+ repeat with e in events of targetCal+ set eventSummary to summary of e+ set eventStart to start date of e as string+ set eventEnd to end date of e as string+ set end of eventList to {{summary:eventSummary, start_date:eventStart, end_date:eventEnd}}+ end repeat+ return eventList+end tell+"""+ result = await self.session.run_command(+ f"osascript -e '{script}'",+ check=False,+ )+ return _parse_event_output(result.get("stdout", ""))++ async def get_event_by_title(self: "BoundApp", *, title: str) -> Optional[dict]:+ """Get a specific event by its title/summary.++ Args:+ title: The title/summary of the event to find.++ Returns:+ Dict with 'summary', 'start_date', 'end_date', 'calendar' or None if not found.+ """+ escaped_title = title.replace('"', '\\"')+ script = f"""+tell application "Calendar"+ repeat with c in calendars+ set calName to name of c+ set matchingEvents to (events of c whose summary is "{escaped_title}")+ if (count of matchingEvents) > 0 then+ set e to item 1 of matchingEvents+ return {{summary:summary of e, start_date:(start date of e as string), end_date:(end date of e as string), calendar:calName}}+ end if+ end repeat+ return missing value+end tell+"""+ result = await self.session.run_command(+ f"osascript -e '{script}'",+ check=False,+ )+ stdout = result.get("stdout", "").strip()+ if not stdout or stdout == "missing value":+ return None+ records = _parse_event_output(stdout)+ return records[0] if records else None++ async def get_events_in_range(+ self: "BoundApp",+ *,+ start_date: str,+ end_date: str,+ ) -> List[dict]:+ """Get events within a date range.++ Args:+ start_date: Start date string (e.g., "January 1, 2025").+ end_date: End date string (e.g., "January 31, 2025").++ Returns:+ List of dicts with 'summary', 'start_date', 'end_date', 'calendar' keys.+ """+ escaped_start = start_date.replace('"', '\\"')+ escaped_end = end_date.replace('"', '\\"')+ script = f"""+tell application "Calendar"+ set rangeStart to date "{escaped_start}"+ set rangeEnd to date "{escaped_end}"++ set eventList to {{}}+ repeat with c in calendars+ set calName to name of c+ set rangeEvents to (events of c whose start date >= rangeStart and start date <= rangeEnd)+ repeat with e in rangeEvents+ set eventSummary to summary of e+ set eventStart to start date of e as string+ set eventEnd to end date of e as string+ set end of eventList to {{summary:eventSummary, start_date:eventStart, end_date:eventEnd, calendar:calName}}+ end repeat+ end repeat+ return eventList+end tell+"""+ result = await self.session.run_command(+ f"osascript -e '{script}'",+ check=False,+ )+ return _parse_event_output(result.get("stdout", ""))++ async def create_event(+ self: "BoundApp",+ *,+ summary: str,+ start_date: str,+ end_date: str,+ calendar_name: str = "Calendar",+ ) -> bool:+ """Create a new calendar event.++ Args:+ summary: Title of the event.+ start_date: Start date/time string (e.g., "January 15, 2025 at 2:00 PM").+ end_date: End date/time string (e.g., "January 15, 2025 at 3:00 PM").+ calendar_name: Name of the calendar to add to.++ Returns:+ True if created successfully.+ """+ escaped_summary = summary.replace('"', '\\"')+ escaped_start = start_date.replace('"', '\\"')+ escaped_end = end_date.replace('"', '\\"')+ escaped_cal = calendar_name.replace('"', '\\"')+ script = f"""+tell application "Calendar"+ tell calendar "{escaped_cal}"+ make new event with properties {{summary:"{escaped_summary}", start date:date "{escaped_start}", end date:date "{escaped_end}"}}+ end tell+end tell+"""+ result = await self.session.run_command(+ f"osascript -e '{script}'",+ check=False,+ )+ return result.get("return_code", 1) == 0++ async def delete_event(+ self: "BoundApp", *, title: str, calendar_name: Optional[str] = None+ ) -> bool:+ """Delete an event by title.++ Args:+ title: Title of the event to delete.+ calendar_name: Optional calendar name (searches all if not specified).++ Returns:+ True if deleted successfully.+ """+ escaped_title = title.replace('"', '\\"')+ if calendar_name:+ escaped_cal = calendar_name.replace('"', '\\"')+ script = f"""+tell application "Calendar"+ tell calendar "{escaped_cal}"+ delete (first event whose summary is "{escaped_title}")+ end tell+end tell+"""+ else:+ script = f"""+tell application "Calendar"+ repeat with c in calendars+ try+ delete (first event of c whose summary is "{escaped_title}")+ return true+ end try+ end repeat+ return false+end tell+"""+ result = await self.session.run_command(+ f"osascript -e '{script}'",+ check=False,+ )+ return result.get("return_code", 1) == 0+++def _parse_list_output(output: str) -> List[str]:+ """Parse AppleScript list output."""+ if not output.strip():+ return []+ items = [item.strip() for item in output.strip().split(",")]+ return [item for item in items if item]+++def _parse_event_output(output: str) -> List[dict]:+ """Parse AppleScript event records output."""+ if not output.strip():+ return []++ records = []+ output = output.strip()++ # Handle list of records: {{...}, {...}}+ if output.startswith("{{"):+ output = output[1:-1]+ parts = output.split("}, {")+ for i, part in enumerate(parts):+ if i == 0:+ part = part[1:]+ if i == len(parts) - 1:+ part = part[:-1]+ record = _parse_single_record(part)+ if record:+ records.append(record)+ elif output.startswith("{"):+ record = _parse_single_record(output[1:-1])+ if record:+ records.append(record)++ return records+++def _parse_single_record(record_str: str) -> Optional[dict]:+ """Parse a single AppleScript record string."""+ if not record_str:+ return None++ result = {}+ parts = []+ current = ""+ in_quotes = False++ for char in record_str:+ if char == '"' and (not current or current[-1] != "\\"):+ in_quotes = not in_quotes+ elif char == "," and not in_quotes:+ parts.append(current.strip())+ current = ""+ continue+ current += char++ if current.strip():+ parts.append(current.strip())++ for part in parts:+ if ":" in part:+ key, value = part.split(":", 1)+ key = key.strip()+ value = value.strip().strip('"')+ result[key] = value++ return result if result else Nonediff --git a/libs/cua-bench/cua_bench/apps/notes.py b/libs/cua-bench/cua_bench/apps/notes.pynew file mode 100644index 0000000000..a27e91537a--- /dev/null+++ b/libs/cua-bench/cua_bench/apps/notes.py@@ -0,0 +1,254 @@+"""Apple Notes app definition for macOS."""++from __future__ import annotations++from typing import TYPE_CHECKING, List, Optional++from .registry import App, launch++if TYPE_CHECKING:+ from .registry import BoundApp+++class Notes(App):+ """Apple Notes - macOS first-party notes application.++ Provides getters for retrieving notes data via AppleScript/osascript.+ Notes is pre-installed on macOS, so no install method is needed.++ Launch options:+ - None (just opens the app)++ Custom getters (macOS only):+ - get_all_notes(): Get all notes with titles and bodies+ - get_note_by_title(title): Get a specific note by title+ - get_folders(): Get list of note folders+ - get_notes_in_folder(folder): Get notes in a specific folder+ """++ name = "notes"+ description = "Apple Notes - macOS notes application"++ @launch("macos")+ async def launch_macos(self: "BoundApp") -> None:+ """Launch Notes on macOS."""+ await self.session.run_command('open -a "Notes"', check=False)++ async def get_all_notes(self: "BoundApp") -> List[dict]:+ """Get all notes with their titles and bodies.++ Returns:+ List of dicts with 'title', 'body', and 'folder' keys.+ """+ script = """+tell application "Notes"+ set noteList to {}+ repeat with f in folders+ set folderName to name of f+ repeat with n in notes of f+ set noteTitle to name of n+ set noteBody to plaintext of n+ set end of noteList to {title:noteTitle, body:noteBody, folder:folderName}+ end repeat+ end repeat+ return noteList+end tell+"""+ result = await self.session.run_command(+ f"osascript -e '{script}'",+ check=False,+ )+ return _parse_applescript_records(result.get("stdout", ""))++ async def get_note_by_title(self: "BoundApp", *, title: str) -> Optional[dict]:+ """Get a specific note by its title.++ Args:+ title: The title of the note to find.++ Returns:+ Dict with 'title', 'body', 'folder' or None if not found.+ """+ # Escape single quotes in title+ escaped_title = title.replace("'", "'\\''")+ script = f"""+tell application "Notes"+ repeat with f in folders+ set folderName to name of f+ repeat with n in notes of f+ if name of n is "{escaped_title}" then+ return {{title:name of n, body:plaintext of n, folder:folderName}}+ end if+ end repeat+ end repeat+ return missing value+end tell+"""+ result = await self.session.run_command(+ f"osascript -e '{script}'",+ check=False,+ )+ stdout = result.get("stdout", "").strip()+ if not stdout or stdout == "missing value":+ return None+ records = _parse_applescript_records(stdout)+ return records[0] if records else None++ async def get_folders(self: "BoundApp") -> List[str]:+ """Get list of note folder names.++ Returns:+ List of folder names.+ """+ script = """+tell application "Notes"+ set folderNames to {}+ repeat with f in folders+ set end of folderNames to name of f+ end repeat+ return folderNames+end tell+"""+ result = await self.session.run_command(+ f"osascript -e '{script}'",+ check=False,+ )+ return _parse_applescript_list(result.get("stdout", ""))++ async def get_notes_in_folder(self: "BoundApp", *, folder: str) -> List[dict]:+ """Get all notes in a specific folder.++ Args:+ folder: Name of the folder.++ Returns:+ List of dicts with 'title' and 'body' keys.+ """+ escaped_folder = folder.replace("'", "'\\''")+ script = f"""+tell application "Notes"+ set noteList to {{}}+ set targetFolder to folder "{escaped_folder}"+ repeat with n in notes of targetFolder+ set end of noteList to {{title:name of n, body:plaintext of n}}+ end repeat+ return noteList+end tell+"""+ result = await self.session.run_command(+ f"osascript -e '{script}'",+ check=False,+ )+ return _parse_applescript_records(result.get("stdout", ""))++ async def create_note(+ self: "BoundApp",+ *,+ title: str,+ body: str,+ folder: str = "Notes",+ ) -> bool:+ """Create a new note.++ Args:+ title: Title of the note.+ body: Body content of the note.+ folder: Folder to create the note in (default "Notes").++ Returns:+ True if created successfully.+ """+ escaped_title = title.replace('"', '\\"')+ escaped_body = body.replace('"', '\\"')+ escaped_folder = folder.replace('"', '\\"')+ script = f"""+tell application "Notes"+ tell folder "{escaped_folder}"+ make new note with properties {{name:"{escaped_title}", body:"{escaped_body}"}}+ end tell+end tell+"""+ result = await self.session.run_command(+ f"osascript -e '{script}'",+ check=False,+ )+ return result.get("return_code", 1) == 0+++def _parse_applescript_list(output: str) -> List[str]:+ """Parse AppleScript list output like 'item1, item2, item3'."""+ if not output.strip():+ return []+ # AppleScript returns comma-separated values+ items = [item.strip() for item in output.strip().split(",")]+ return [item for item in items if item]+++def _parse_applescript_records(output: str) -> List[dict]:+ """Parse AppleScript record output.++ AppleScript records look like: {title:"foo", body:"bar"}+ """+ if not output.strip():+ return []++ records = []+ # Simple parsing - AppleScript returns records in a specific format+ # For complex parsing, we'd need a proper parser+ # This handles the basic case of {key:value, key:value}+ output = output.strip()++ # Handle list of records: {{...}, {...}}+ if output.startswith("{{"):+ # Remove outer braces+ output = output[1:-1]+ # Split on "}, {" to get individual records+ parts = output.split("}, {")+ for i, part in enumerate(parts):+ if i == 0:+ part = part[1:] # Remove leading {+ if i == len(parts) - 1:+ part = part[:-1] # Remove trailing }+ record = _parse_single_record(part)+ if record:+ records.append(record)+ elif output.startswith("{"):+ # Single record+ record = _parse_single_record(output[1:-1])+ if record:+ records.append(record)++ return records+++def _parse_single_record(record_str: str) -> Optional[dict]:+ """Parse a single AppleScript record string."""+ if not record_str:+ return None++ result = {}+ # Split on comma, but be careful of commas in values+ parts = []+ current = ""+ in_quotes = False++ for char in record_str:+ if char == '"' and (not current or current[-1] != "\\"):+ in_quotes = not in_quotes+ elif char == "," and not in_quotes:+ parts.append(current.strip())+ current = ""+ continue+ current += char++ if current.strip():+ parts.append(current.strip())++ for part in parts:+ if ":" in part:+ key, value = part.split(":", 1)+ key = key.strip()+ value = value.strip().strip('"')+ result[key] = value++ return result if result else Nonediff --git a/libs/cua-bench/cua_bench/apps/reminders.py b/libs/cua-bench/cua_bench/apps/reminders.pynew file mode 100644index 0000000000..5c773f8b54--- /dev/null+++ b/libs/cua-bench/cua_bench/apps/reminders.py@@ -0,0 +1,319 @@+"""Apple Reminders app definition for macOS."""++from __future__ import annotations++from typing import TYPE_CHECKING, List, Optional++from .registry import App, launch++if TYPE_CHECKING:+ from .registry import BoundApp+++class Reminders(App):+ """Apple Reminders - macOS first-party reminders application.++ Provides getters for retrieving reminders data via AppleScript/osascript.+ Reminders is pre-installed on macOS, so no install method is needed.++ Launch options:+ - None (just opens the app)++ Custom getters (macOS only):+ - get_all_reminders(): Get all reminders+ - get_lists(): Get list of reminder lists+ - get_reminders_in_list(list_name): Get reminders in a specific list+ - get_completed_reminders(): Get completed reminders+ - get_incomplete_reminders(): Get incomplete reminders+ """++ name = "reminders"+ description = "Apple Reminders - macOS reminders application"++ @launch("macos")+ async def launch_macos(self: "BoundApp") -> None:+ """Launch Reminders on macOS."""+ await self.session.run_command('open -a "Reminders"', check=False)++ async def get_all_reminders(self: "BoundApp") -> List[dict]:+ """Get all reminders with their details.++ Returns:+ List of dicts with 'name', 'completed', 'list', 'due_date' keys.+ """+ script = """+tell application "Reminders"+ set reminderList to {}+ repeat with l in lists+ set listName to name of l+ repeat with r in reminders of l+ set reminderName to name of r+ set isCompleted to completed of r+ try+ set dueDate to due date of r as string+ on error+ set dueDate to ""+ end try+ set end of reminderList to {name:reminderName, completed:isCompleted, list:listName, due_date:dueDate}+ end repeat+ end repeat+ return reminderList+end tell+"""+ result = await self.session.run_command(+ f"osascript -e '{script}'",+ check=False,+ )+ return _parse_reminder_output(result.get("stdout", ""))++ async def get_lists(self: "BoundApp") -> List[str]:+ """Get list of reminder list names.++ Returns:+ List of list names.+ """+ script = """+tell application "Reminders"+ set listNames to {}+ repeat with l in lists+ set end of listNames to name of l+ end repeat+ return listNames+end tell+"""+ result = await self.session.run_command(+ f"osascript -e '{script}'",+ check=False,+ )+ return _parse_list_output(result.get("stdout", ""))++ async def get_reminders_in_list(self: "BoundApp", *, list_name: str) -> List[dict]:+ """Get all reminders in a specific list.++ Args:+ list_name: Name of the reminder list.++ Returns:+ List of dicts with 'name', 'completed', 'due_date' keys.+ """+ escaped_name = list_name.replace('"', '\\"')+ script = f"""+tell application "Reminders"+ set reminderList to {{}}+ set targetList to list "{escaped_name}"+ repeat with r in reminders of targetList+ set reminderName to name of r+ set isCompleted to completed of r+ try+ set dueDate to due date of r as string+ on error+ set dueDate to ""+ end try+ set end of reminderList to {{name:reminderName, completed:isCompleted, due_date:dueDate}}+ end repeat+ return reminderList+end tell+"""+ result = await self.session.run_command(+ f"osascript -e '{script}'",+ check=False,+ )+ return _parse_reminder_output(result.get("stdout", ""))++ async def get_completed_reminders(self: "BoundApp") -> List[dict]:+ """Get all completed reminders.++ Returns:+ List of dicts with 'name', 'list' keys.+ """+ script = """+tell application "Reminders"+ set reminderList to {}+ repeat with l in lists+ set listName to name of l+ repeat with r in (reminders of l whose completed is true)+ set end of reminderList to {name:name of r, list:listName}+ end repeat+ end repeat+ return reminderList+end tell+"""+ result = await self.session.run_command(+ f"osascript -e '{script}'",+ check=False,+ )+ return _parse_reminder_output(result.get("stdout", ""))++ async def get_incomplete_reminders(self: "BoundApp") -> List[dict]:+ """Get all incomplete reminders.++ Returns:+ List of dicts with 'name', 'list', 'due_date' keys.+ """+ script = """+tell application "Reminders"+ set reminderList to {}+ repeat with l in lists+ set listName to name of l+ repeat with r in (reminders of l whose completed is false)+ set reminderName to name of r+ try+ set dueDate to due date of r as string+ on error+ set dueDate to ""+ end try+ set end of reminderList to {name:reminderName, list:listName, due_date:dueDate}+ end repeat+ end repeat+ return reminderList+end tell+"""+ result = await self.session.run_command(+ f"osascript -e '{script}'",+ check=False,+ )+ return _parse_reminder_output(result.get("stdout", ""))++ async def create_reminder(+ self: "BoundApp",+ *,+ name: str,+ list_name: str = "Reminders",+ due_date: Optional[str] = None,+ ) -> bool:+ """Create a new reminder.++ Args:+ name: Name of the reminder.+ list_name: Name of the list to add to (default "Reminders").+ due_date: Optional due date string (e.g., "January 1, 2025 at 9:00 AM").++ Returns:+ True if created successfully.+ """+ escaped_name = name.replace('"', '\\"')+ escaped_list = list_name.replace('"', '\\"')++ if due_date:+ escaped_due = due_date.replace('"', '\\"')+ script = f"""+tell application "Reminders"+ tell list "{escaped_list}"+ make new reminder with properties {{name:"{escaped_name}", due date:date "{escaped_due}"}}+ end tell+end tell+"""+ else:+ script = f"""+tell application "Reminders"+ tell list "{escaped_list}"+ make new reminder with properties {{name:"{escaped_name}"}}+ end tell+end tell+"""+ result = await self.session.run_command(+ f"osascript -e '{script}'",+ check=False,+ )+ return result.get("return_code", 1) == 0++ async def complete_reminder(+ self: "BoundApp", *, name: str, list_name: str = "Reminders"+ ) -> bool:+ """Mark a reminder as completed.++ Args:+ name: Name of the reminder.+ list_name: Name of the list containing the reminder.++ Returns:+ True if completed successfully.+ """+ escaped_name = name.replace('"', '\\"')+ escaped_list = list_name.replace('"', '\\"')+ script = f"""+tell application "Reminders"+ tell list "{escaped_list}"+ set completed of (first reminder whose name is "{escaped_name}") to true+ end tell+end tell+"""+ result = await self.session.run_command(+ f"osascript -e '{script}'",+ check=False,+ )+ return result.get("return_code", 1) == 0+++def _parse_list_output(output: str) -> List[str]:+ """Parse AppleScript list output."""+ if not output.strip():+ return []+ items = [item.strip() for item in output.strip().split(",")]+ return [item for item in items if item]+++def _parse_reminder_output(output: str) -> List[dict]:+ """Parse AppleScript reminder records output."""+ if not output.strip():+ return []++ records = []+ output = output.strip()++ # Handle list of records: {{...}, {...}}+ if output.startswith("{{"):+ output = output[1:-1]+ parts = output.split("}, {")+ for i, part in enumerate(parts):+ if i == 0:+ part = part[1:]+ if i == len(parts) - 1:+ part = part[:-1]+ record = _parse_single_record(part)+ if record:+ records.append(record)+ elif output.startswith("{"):+ record = _parse_single_record(output[1:-1])+ if record:+ records.append(record)++ return records+++def _parse_single_record(record_str: str) -> Optional[dict]:+ """Parse a single AppleScript record string."""+ if not record_str:+ return None++ result = {}+ parts = []+ current = ""+ in_quotes = False++ for char in record_str:+ if char == '"' and (not current or current[-1] != "\\"):+ in_quotes = not in_quotes+ elif char == "," and not in_quotes:+ parts.append(current.strip())+ current = ""+ continue+ current += char++ if current.strip():+ parts.append(current.strip())++ for part in parts:+ if ":" in part:+ key, value = part.split(":", 1)+ key = key.strip()+ value = value.strip()+ # Handle boolean values+ if value == "true":+ result[key] = True+ elif value == "false":+ result[key] = False+ else:+ result[key] = value.strip('"')++ return result if result else Nonediff --git a/libs/cua-bench/datasets/cua-bench-workflows/README.md b/libs/cua-bench/datasets/cua-bench-workflows/README.mdnew file mode 100644index 0000000000..8f5dbbba51--- /dev/null+++ b/libs/cua-bench/datasets/cua-bench-workflows/README.md@@ -0,0 +1,55 @@+# CUA-Bench Workflows++Workflow-based computer-use tasks that involve real desktop applications and multi-step interactions.++## Tasks++### Creative Applications++- **photoshop-tasks** - Adobe Photoshop document creation and manipulation tasks+ - Create new documents with text layers+ - Open PSD files and analyze layer structure+ - Save and export documents++### Game Development++- **unity-tasks** - Unity game engine workflow tasks+ - Create new projects+ - Add GameObjects and scripts+ - Build projects and configure settings++## Task Structure++Each task folder contains:++- `main.py` - Task configuration, setup, evaluation, and solution+- `assets/` - Required files for the task (PSD files, images, etc.)++## Requirements++These tasks require native application support:++- **Windows**: Adobe Photoshop (native installation)+- **Linux**: Adobe Photoshop via WINE (see adobe_photoshop.py app definition)++## Running Tasks++```bash+# Run a specific task interactively+cb interact datasets/cua-bench-workflows/photoshop-tasks --variant-id 0++# Run with specific variant+cb interact datasets/cua-bench-workflows/photoshop-tasks --variant-id 2+```++## Task Variants++### photoshop-tasks++| Variant | Description |+|---------|-------------|+| 0 | Create document with "Hello World" text layer |+| 1 | Create document with "Welcome to CUA" text layer |+| 2 | Open PSD and count layers |+| 3 | Open PSD and describe layers |+| 4 | Create and save document as specific filename |diff --git a/libs/cua-bench/datasets/cua-bench-workflows/unity-tasks/assets/README.txt b/libs/cua-bench/datasets/cua-bench-workflows/unity-tasks/assets/README.txtnew file mode 100644index 0000000000..2137cb7913--- /dev/null+++ b/libs/cua-bench/datasets/cua-bench-workflows/unity-tasks/assets/README.txt@@ -0,0 +1,12 @@+Unity Task Assets+=================++This directory should contain assets for testing Unity import tasks.++Optional files:+- sample_texture.png: A PNG texture for the "import_asset" task (any 256x256 or similar image)++To create sample_texture.png:+1. Create or download any PNG image+2. Rename it to sample_texture.png+3. Place it in this directorydiff --git a/libs/cua-bench/datasets/cua-bench-workflows/unity-tasks/main.py b/libs/cua-bench/datasets/cua-bench-workflows/unity-tasks/main.pynew file mode 100644index 0000000000..28013f23b6--- /dev/null+++ b/libs/cua-bench/datasets/cua-bench-workflows/unity-tasks/main.py@@ -0,0 +1,202 @@+"""Unity game engine workflow tasks for cua-bench."""++import cua_bench as cb++[email protected]_config(split="train")+def load():+ """Define Unity workflow task variants."""+ tasks = [+ {+ "task_type": "create_project",+ "project_name": "MyFirstGame",+ "template": "3D",+ "description": "Create a new Unity 3D project called 'MyFirstGame' and save it to ~/Desktop/UnityProjects/",+ },+ {+ "task_type": "create_cube",+ "project_name": "CubeDemo",+ "object_name": "Player",+ "description": "Create a new Unity project called 'CubeDemo', add a Cube GameObject renamed to 'Player', and save it to ~/Desktop/UnityProjects/",+ },+ {+ "task_type": "create_script",+ "project_name": "ScriptDemo",+ "script_name": "PlayerController",+ "description": "Create a new Unity project called 'ScriptDemo', create a C# script named 'PlayerController', and save it to ~/Desktop/UnityProjects/",+ },+ {+ "task_type": "create_scene",+ "project_name": "SceneDemo",+ "scene_name": "MainMenu",+ "description": "Create a new Unity project called 'SceneDemo', create a new scene called 'MainMenu', and save it to ~/Desktop/UnityProjects/",+ },+ {+ "task_type": "create_ui",+ "project_name": "UIDemo",+ "text_content": "Hello World",+ "description": "Create a new Unity project called 'UIDemo', add a UI Canvas with a Text element saying 'Hello World', and save it to ~/Desktop/UnityProjects/",+ },+ {+ "task_type": "create_scene_objects",+ "project_name": "GameWorld",+ "objects": ["Cube", "Sphere", "Plane"],+ "description": "Create a new Unity project called 'GameWorld', add a Cube, Sphere, and Plane to the scene, and save it to ~/Desktop/UnityProjects/",+ },+ {+ "task_type": "create_project_2d",+ "project_name": "My2DGame",+ "template": "2D",+ "description": "Create a new Unity 2D project called 'My2DGame' and save it to ~/Desktop/UnityProjects/",+ },+ {+ "task_type": "create_with_settings",+ "project_name": "CUAGame",+ "company_name": "CUA Games",+ "description": "Create a new Unity project called 'CUAGame', set the Company Name to 'CUA Games' in Project Settings, and save it to ~/Desktop/UnityProjects/",+ },+ ]++ return [+ cb.Task(+ description=task["description"],+ metadata=task,+ computer={+ "provider": "native",+ "setup_config": {+ "os_type": "windows",+ "width": 1920,+ "height": 1080,+ },+ },+ )+ for task in tasks+ ]++[email protected]_task(split="train")+async def start(task_cfg: cb.Task, session: cb.DesktopSession):+ """Set up Unity environment by installing Unity Hub."""+ await session.apps.unity.install(with_shortcut=True)++[email protected]_task(split="train")+async def evaluate(task_cfg: cb.Task, session: cb.DesktopSession) -> list[float]:+ """Evaluate if the Unity task was completed correctly."""+ task_type = task_cfg.metadata.get("task_type", "")+ project_name = task_cfg.metadata.get("project_name", "")+ score = 0.0++ # Check if project directory exists+ result = await session.run_command(+ f'if exist "%USERPROFILE%\\Desktop\\UnityProjects\\{project_name}\\Assets" (echo FOUND) else (echo NOT_FOUND)',+ check=False,+ )+ if "FOUND" not in result["stdout"]:+ return [0.0]++ # Base score for having the project created+ score = 0.5++ if task_type == "create_project":+ score = 1.0++ elif task_type == "create_project_2d":+ result = await session.run_command(+ f'findstr /C:"m_ActiveInputHandler" "%USERPROFILE%\\Desktop\\UnityProjects\\{project_name}\\ProjectSettings\\ProjectSettings.asset" 2>nul || echo "NOT_FOUND"',+ check=False,+ )+ if "NOT_FOUND" not in result["stdout"]:+ score = 1.0++ elif task_type == "create_cube":+ result = await session.run_command(+ f'dir /S /B "%USERPROFILE%\\Desktop\\UnityProjects\\{project_name}\\Assets\\*.unity" 2>nul || echo "NO_SCENES"',+ check=False,+ )+ if "NO_SCENES" not in result["stdout"] and ".unity" in result["stdout"]:+ score = 0.75+ object_name = task_cfg.metadata.get("object_name", "Player")+ result = await session.run_command(+ f'findstr /S /C:"{object_name}" "%USERPROFILE%\\Desktop\\UnityProjects\\{project_name}\\Assets\\*.unity" 2>nul || echo "NOT_FOUND"',+ check=False,+ )+ if "NOT_FOUND" not in result["stdout"]:+ score = 1.0++ elif task_type == "create_script":+ script_name = task_cfg.metadata.get("script_name", "PlayerController")+ result = await session.run_command(+ f'if exist "%USERPROFILE%\\Desktop\\UnityProjects\\{project_name}\\Assets\\{script_name}.cs" (echo FOUND) else (echo NOT_FOUND)',+ check=False,+ )+ if "FOUND" in result["stdout"]:+ score = 1.0+ else:+ result = await session.run_command(+ f'dir /S /B "%USERPROFILE%\\Desktop\\UnityProjects\\{project_name}\\Assets\\*.cs" 2>nul || echo "NO_SCRIPTS"',+ check=False,+ )+ if "NO_SCRIPTS" not in result["stdout"]:+ score = 0.75++ elif task_type == "create_scene":+ scene_name = task_cfg.metadata.get("scene_name", "MainMenu")+ result = await session.run_command(+ f'dir /S /B "%USERPROFILE%\\Desktop\\UnityProjects\\{project_name}\\Assets\\*{scene_name}*.unity" 2>nul || echo "NOT_FOUND"',+ check=False,+ )+ if "NOT_FOUND" not in result["stdout"] and ".unity" in result["stdout"]:+ score = 1.0++ elif task_type == "create_ui":+ result = await session.run_command(+ f'findstr /S /C:"Canvas" "%USERPROFILE%\\Desktop\\UnityProjects\\{project_name}\\Assets\\*.unity" 2>nul || echo "NOT_FOUND"',+ check=False,+ )+ if "NOT_FOUND" not in result["stdout"]:+ score = 0.85+ text_content = task_cfg.metadata.get("text_content", "Hello World")+ result = await session.run_command(+ f'findstr /S /C:"{text_content}" "%USERPROFILE%\\Desktop\\UnityProjects\\{project_name}\\Assets\\*.unity" 2>nul || echo "NOT_FOUND"',+ check=False,+ )+ if "NOT_FOUND" not in result["stdout"]:+ score = 1.0++ elif task_type == "create_scene_objects":+ objects = task_cfg.metadata.get("objects", [])+ found_count = 0+ for obj in objects:+ result = await session.run_command(+ f'findstr /S /C:"{obj}" "%USERPROFILE%\\Desktop\\UnityProjects\\{project_name}\\Assets\\*.unity" 2>nul || echo "NOT_FOUND"',+ check=False,+ )+ if "NOT_FOUND" not in result["stdout"]:+ found_count += 1+ if objects:+ score = 0.5 + (0.5 * found_count / len(objects))++ elif task_type == "create_with_settings":+ company_name = task_cfg.metadata.get("company_name", "CUA Games")+ result = await session.run_command(+ f'findstr /C:"{company_name}" "%USERPROFILE%\\Desktop\\UnityProjects\\{project_name}\\ProjectSettings\\ProjectSettings.asset" 2>nul || echo "NOT_FOUND"',+ check=False,+ )+ if "NOT_FOUND" not in result["stdout"]:+ score = 1.0++ return [min(score, 1.0)]++[email protected]_task(split="train")+async def solve(task_cfg: cb.Task, session: cb.DesktopSession):+ """Oracle solution for Unity tasks."""+ raise NotImplementedError(+ "Unity tasks require complex UI interaction. "+ "Use this task for agent evaluation rather than oracle solving."+ )+++if __name__ == "__main__":+ cb.interact(__file__)