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
Format codebase with `uv run pre-commit run --all-files`
James Murdzaddc5a5de9140
diff --git a/.github/scripts/get_pyproject_version.py b/.github/scripts/get_pyproject_version.pyindex a00ea22c5a..74bf09dd04 100755--- a/.github/scripts/get_pyproject_version.py+++ b/.github/scripts/get_pyproject_version.py@@ -11,6 +11,7 @@ Exit codes:"""import sys+try:import tomllibexcept ImportError:@@ -20,7 +21,10 @@ except ImportError:def main():if len(sys.argv) != 3:- print("Usage: python get_pyproject_version.py <pyproject_path> <expected_version>", file=sys.stderr)+ print(+ "Usage: python get_pyproject_version.py <pyproject_path> <expected_version>",+ file=sys.stderr,+ )sys.exit(1)pyproject_path = sys.argv[1]@@ -28,7 +32,7 @@ def main():# tomllib requires binary modetry:- with open(pyproject_path, 'rb') as f:+ with open(pyproject_path, "rb") as f:data = tomllib.load(f)except FileNotFoundError:print(f"❌ ERROR: File not found: {pyproject_path}", file=sys.stderr)@@ -37,6 +41,7 @@ def main():# Fallback to toml if using the old library or handle other errorstry:import toml+data = toml.load(pyproject_path)except FileNotFoundError:print(f"❌ ERROR: File not found: {pyproject_path}", file=sys.stderr)@@ -45,7 +50,7 @@ def main():print(f"❌ ERROR: Failed to parse TOML file: {e}", file=sys.stderr)sys.exit(1)- actual_version = data.get('project', {}).get('version')+ actual_version = data.get("project", {}).get("version")if not actual_version:print("❌ ERROR: No version found in pyproject.toml", file=sys.stderr)@@ -56,13 +61,18 @@ def main():print(f" pyproject.toml version: {actual_version}", file=sys.stderr)print(f" Expected version: {expected_version}", file=sys.stderr)print("", file=sys.stderr)- print("The version in pyproject.toml must match the version being published.", file=sys.stderr)- print(f"Please update pyproject.toml to version {expected_version} or use the correct tag.", file=sys.stderr)+ print(+ "The version in pyproject.toml must match the version being published.", file=sys.stderr+ )+ print(+ f"Please update pyproject.toml to version {expected_version} or use the correct tag.",+ file=sys.stderr,+ )sys.exit(1)print(f"✅ Version consistency check passed: {actual_version}")sys.exit(0)-if __name__ == '__main__':+if __name__ == "__main__":main()diff --git a/.github/scripts/tests/README.md b/.github/scripts/tests/README.mdindex 2a44006502..a4fd28571c 100644--- a/.github/scripts/tests/README.md+++ b/.github/scripts/tests/README.md@@ -7,6 +7,7 @@ This directory contains comprehensive tests for the GitHub workflow scripts usin**No external dependencies required!**This test suite uses:+- `unittest` - Python's built-in testing framework- `tomllib` - Python 3.11+ built-in TOML parser@@ -15,27 +16,32 @@ For Python < 3.11, the `toml` package is used as a fallback.## Running Tests### Run all tests+```bashcd .github/scripts/testspython3 -m unittest discover -v```### Run a specific test file+```bashpython3 -m unittest test_get_pyproject_version -v```### Run a specific test class+```bashpython3 -m unittest test_get_pyproject_version.TestGetPyprojectVersion -v```### Run a specific test method+```bashpython3 -m unittest test_get_pyproject_version.TestGetPyprojectVersion.test_matching_versions -v```### Run tests directly from the test file+```bashpython3 test_get_pyproject_version.py```diff --git a/.github/scripts/tests/test_get_pyproject_version.py b/.github/scripts/tests/test_get_pyproject_version.pyindex 95c980a920..6b8fbd652a 100644--- a/.github/scripts/tests/test_get_pyproject_version.py+++ b/.github/scripts/tests/test_get_pyproject_version.py@@ -10,10 +10,10 @@ This test suite covers:"""import sys-import unittestimport tempfile-from pathlib import Path+import unittestfrom io import StringIO+from pathlib import Pathfrom unittest.mock import patch# Add parent directory to path to import the module@@ -36,46 +36,54 @@ class TestGetPyprojectVersion(unittest.TestCase):def create_pyproject_toml(self, version: str) -> Path:"""Helper to create a temporary pyproject.toml file with a given version."""- temp_file = tempfile.NamedTemporaryFile(mode='w', suffix='.toml', delete=False)- temp_file.write(f"""+ temp_file = tempfile.NamedTemporaryFile(mode="w", suffix=".toml", delete=False)+ temp_file.write(+ f"""[project]name = "test-project"version = "{version}"description = "A test project"-""")+"""+ )temp_file.close()return Path(temp_file.name)def create_pyproject_toml_no_version(self) -> Path:"""Helper to create a pyproject.toml without a version field."""- temp_file = tempfile.NamedTemporaryFile(mode='w', suffix='.toml', delete=False)- temp_file.write("""+ temp_file = tempfile.NamedTemporaryFile(mode="w", suffix=".toml", delete=False)+ temp_file.write(+ """[project]name = "test-project"description = "A test project without version"-""")+"""+ )temp_file.close()return Path(temp_file.name)def create_pyproject_toml_no_project(self) -> Path:"""Helper to create a pyproject.toml without a project section."""- temp_file = tempfile.NamedTemporaryFile(mode='w', suffix='.toml', delete=False)- temp_file.write("""+ temp_file = tempfile.NamedTemporaryFile(mode="w", suffix=".toml", delete=False)+ temp_file.write(+ """[tool.poetry]name = "test-project"version = "1.0.0"-""")+"""+ )temp_file.close()return Path(temp_file.name)def create_malformed_toml(self) -> Path:"""Helper to create a malformed TOML file."""- temp_file = tempfile.NamedTemporaryFile(mode='w', suffix='.toml', delete=False)- temp_file.write("""+ temp_file = tempfile.NamedTemporaryFile(mode="w", suffix=".toml", delete=False)+ temp_file.write(+ """[projectname = "test-projectversion = "1.0.0"-""")+"""+ )temp_file.close()return Path(temp_file.name)@@ -85,11 +93,11 @@ version = "1.0.0"pyproject_file = self.create_pyproject_toml("1.2.3")try:- sys.argv = ['get_pyproject_version.py', str(pyproject_file), '1.2.3']+ sys.argv = ["get_pyproject_version.py", str(pyproject_file), "1.2.3"]# Capture stdoutcaptured_output = StringIO()- with patch('sys.stdout', captured_output):+ with patch("sys.stdout", captured_output):with self.assertRaises(SystemExit) as cm:get_pyproject_version.main()@@ -104,11 +112,11 @@ version = "1.0.0"pyproject_file = self.create_pyproject_toml("1.2.3")try:- sys.argv = ['get_pyproject_version.py', str(pyproject_file), '1.2.4']+ sys.argv = ["get_pyproject_version.py", str(pyproject_file), "1.2.4"]# Capture stderrcaptured_error = StringIO()- with patch('sys.stderr', captured_error):+ with patch("sys.stderr", captured_error):with self.assertRaises(SystemExit) as cm:get_pyproject_version.main()@@ -127,10 +135,10 @@ version = "1.0.0"pyproject_file = self.create_pyproject_toml_no_version()try:- sys.argv = ['get_pyproject_version.py', str(pyproject_file), '1.0.0']+ sys.argv = ["get_pyproject_version.py", str(pyproject_file), "1.0.0"]captured_error = StringIO()- with patch('sys.stderr', captured_error):+ with patch("sys.stderr", captured_error):with self.assertRaises(SystemExit) as cm:get_pyproject_version.main()@@ -145,10 +153,10 @@ version = "1.0.0"pyproject_file = self.create_pyproject_toml_no_project()try:- sys.argv = ['get_pyproject_version.py', str(pyproject_file), '1.0.0']+ sys.argv = ["get_pyproject_version.py", str(pyproject_file), "1.0.0"]captured_error = StringIO()- with patch('sys.stderr', captured_error):+ with patch("sys.stderr", captured_error):with self.assertRaises(SystemExit) as cm:get_pyproject_version.main()@@ -160,7 +168,7 @@ version = "1.0.0"# Test: File not founddef test_file_not_found(self):"""Test handling of non-existent pyproject.toml file."""- sys.argv = ['get_pyproject_version.py', '/nonexistent/pyproject.toml', '1.0.0']+ sys.argv = ["get_pyproject_version.py", "/nonexistent/pyproject.toml", "1.0.0"]with self.assertRaises(SystemExit) as cm:get_pyproject_version.main()@@ -173,7 +181,7 @@ version = "1.0.0"pyproject_file = self.create_malformed_toml()try:- sys.argv = ['get_pyproject_version.py', str(pyproject_file), '1.0.0']+ sys.argv = ["get_pyproject_version.py", str(pyproject_file), "1.0.0"]with self.assertRaises(SystemExit) as cm:get_pyproject_version.main()@@ -185,44 +193,50 @@ version = "1.0.0"# Test: Incorrect number of arguments - too fewdef test_too_few_arguments(self):"""Test that providing too few arguments results in usage error."""- sys.argv = ['get_pyproject_version.py', 'pyproject.toml']+ sys.argv = ["get_pyproject_version.py", "pyproject.toml"]captured_error = StringIO()- with patch('sys.stderr', captured_error):+ with patch("sys.stderr", captured_error):with self.assertRaises(SystemExit) as cm:get_pyproject_version.main()self.assertEqual(cm.exception.code, 1)- self.assertIn("Usage: python get_pyproject_version.py <pyproject_path> <expected_version>",- captured_error.getvalue())+ self.assertIn(+ "Usage: python get_pyproject_version.py <pyproject_path> <expected_version>",+ captured_error.getvalue(),+ )# Test: Incorrect number of arguments - too manydef test_too_many_arguments(self):"""Test that providing too many arguments results in usage error."""- sys.argv = ['get_pyproject_version.py', 'pyproject.toml', '1.0.0', 'extra']+ sys.argv = ["get_pyproject_version.py", "pyproject.toml", "1.0.0", "extra"]captured_error = StringIO()- with patch('sys.stderr', captured_error):+ with patch("sys.stderr", captured_error):with self.assertRaises(SystemExit) as cm:get_pyproject_version.main()self.assertEqual(cm.exception.code, 1)- self.assertIn("Usage: python get_pyproject_version.py <pyproject_path> <expected_version>",- captured_error.getvalue())+ self.assertIn(+ "Usage: python get_pyproject_version.py <pyproject_path> <expected_version>",+ captured_error.getvalue(),+ )# Test: No argumentsdef test_no_arguments(self):"""Test that providing no arguments results in usage error."""- sys.argv = ['get_pyproject_version.py']+ sys.argv = ["get_pyproject_version.py"]captured_error = StringIO()- with patch('sys.stderr', captured_error):+ with patch("sys.stderr", captured_error):with self.assertRaises(SystemExit) as cm:get_pyproject_version.main()self.assertEqual(cm.exception.code, 1)- self.assertIn("Usage: python get_pyproject_version.py <pyproject_path> <expected_version>",- captured_error.getvalue())+ self.assertIn(+ "Usage: python get_pyproject_version.py <pyproject_path> <expected_version>",+ captured_error.getvalue(),+ )# Test: Version with pre-release tagsdef test_version_with_prerelease_tags(self):@@ -230,15 +244,17 @@ version = "1.0.0"pyproject_file = self.create_pyproject_toml("1.2.3-rc.1")try:- sys.argv = ['get_pyproject_version.py', str(pyproject_file), '1.2.3-rc.1']+ sys.argv = ["get_pyproject_version.py", str(pyproject_file), "1.2.3-rc.1"]captured_output = StringIO()- with patch('sys.stdout', captured_output):+ with patch("sys.stdout", captured_output):with self.assertRaises(SystemExit) as cm:get_pyproject_version.main()self.assertEqual(cm.exception.code, 0)- self.assertIn("✅ Version consistency check passed: 1.2.3-rc.1", captured_output.getvalue())+ self.assertIn(+ "✅ Version consistency check passed: 1.2.3-rc.1", captured_output.getvalue()+ )finally:pyproject_file.unlink()@@ -248,15 +264,17 @@ version = "1.0.0"pyproject_file = self.create_pyproject_toml("1.2.3+build.123")try:- sys.argv = ['get_pyproject_version.py', str(pyproject_file), '1.2.3+build.123']+ sys.argv = ["get_pyproject_version.py", str(pyproject_file), "1.2.3+build.123"]captured_output = StringIO()- with patch('sys.stdout', captured_output):+ with patch("sys.stdout", captured_output):with self.assertRaises(SystemExit) as cm:get_pyproject_version.main()self.assertEqual(cm.exception.code, 0)- self.assertIn("✅ Version consistency check passed: 1.2.3+build.123", captured_output.getvalue())+ self.assertIn(+ "✅ Version consistency check passed: 1.2.3+build.123", captured_output.getvalue()+ )finally:pyproject_file.unlink()@@ -290,15 +308,17 @@ version = "1.0.0"pyproject_file = self.create_pyproject_toml(version)try:- sys.argv = ['get_pyproject_version.py', str(pyproject_file), version]+ sys.argv = ["get_pyproject_version.py", str(pyproject_file), version]captured_output = StringIO()- with patch('sys.stdout', captured_output):+ with patch("sys.stdout", captured_output):with self.assertRaises(SystemExit) as cm:get_pyproject_version.main()self.assertEqual(cm.exception.code, 0)- self.assertIn(f"✅ Version consistency check passed: {version}", captured_output.getvalue())+ self.assertIn(+ f"✅ Version consistency check passed: {version}", captured_output.getvalue()+ )finally:pyproject_file.unlink()@@ -308,10 +328,10 @@ version = "1.0.0"pyproject_file = self.create_pyproject_toml("")try:- sys.argv = ['get_pyproject_version.py', str(pyproject_file), '1.0.0']+ sys.argv = ["get_pyproject_version.py", str(pyproject_file), "1.0.0"]captured_error = StringIO()- with patch('sys.stderr', captured_error):+ with patch("sys.stderr", captured_error):with self.assertRaises(SystemExit) as cm:get_pyproject_version.main()@@ -327,14 +347,14 @@ class TestSuiteInfo(unittest.TestCase):def test_suite_info(self):"""Display test suite information."""- print("\n" + "="*70)+ print("\n" + "=" * 70)print("Test Suite: get_pyproject_version.py")print("Framework: unittest (Python built-in)")print("TOML Library: tomllib (Python 3.11+ built-in)")- print("="*70)+ print("=" * 70)self.assertTrue(True)-if __name__ == '__main__':+if __name__ == "__main__":# Run tests with verbose outputunittest.main(verbosity=2)diff --git a/.github/workflows/test-validation-script.yml b/.github/workflows/test-validation-script.ymlindex cc11dda768..15f5b7ec3c 100644--- a/.github/workflows/test-validation-script.yml+++ b/.github/workflows/test-validation-script.yml@@ -3,14 +3,14 @@ name: Test valididation scripton:pull_request:paths:- - '.github/scripts/**'- - '.github/workflows/test-scripts.yml'+ - ".github/scripts/**"+ - ".github/workflows/test-scripts.yml"push:branches:- mainpaths:- - '.github/scripts/**'- - '.github/workflows/test-scripts.yml'+ - ".github/scripts/**"+ - ".github/workflows/test-scripts.yml"jobs:test:@@ -23,7 +23,7 @@ jobs:- name: Set up Pythonuses: actions/setup-python@v5with:- python-version: '3.11'+ python-version: "3.11"- name: Install dependenciesrun: |diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yamlindex bbc42d48c7..99b55c5b90 100644--- a/.pre-commit-config.yaml+++ b/.pre-commit-config.yaml@@ -20,7 +20,7 @@ repos:hooks:- id: isortname: isort code formatter- args: ['--profile', 'black']+ args: ["--profile", "black"]files: \.(py)$- repo: https://github.com/psf/black@@ -35,7 +35,7 @@ repos:hooks:- id: ruffname: ruff linter- args: ['--fix']+ args: ["--fix"]files: \.(py)$# Temporarily disabled due to untyped codebasediff --git a/LICENSE.md b/LICENSE.mdindex 207f26657c..b8b198ce3e 100644--- a/LICENSE.md+++ b/LICENSE.md@@ -18,4 +18,4 @@ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THEAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHERLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE-SOFTWARE.\ No newline at end of file+SOFTWARE.diff --git a/README.md b/README.mdindex 067656d222..2f9429ccbd 100644--- a/README.md+++ b/README.md@@ -5,18 +5,21 @@<img alt="Cua logo" height="150" src="img/logo_black.png"></picture>- [](#)- [](#)- [](#)- [](https://discord.com/invite/mVnXXpdE85)- <br>- <a href="https://trendshift.io/repositories/13685" target="_blank"><img src="https://trendshift.io/api/badge/repositories/13685" alt="trycua%2Fcua | Trendshift" style="width: 250px; height: 55px;" width="250" height="55"/></a>+[](#)+[](#)+[](#)+[](https://discord.com/invite/mVnXXpdE85)+<br>+<a href="https://trendshift.io/repositories/13685" target="_blank"><img src="https://trendshift.io/api/badge/repositories/13685" alt="trycua%2Fcua | Trendshift" style="width: 250px; height: 55px;" width="250" height="55"/></a>+</div>-> We're hosting **The Computer-Use Agents SOTA Challenge concluded** at [Hack the North](https://hackthenorth.com) and online!->> **Track A (On-site @ UWaterloo)**: 🏆 ~~Prize: **YC interview guaranteed**.~~ **Concluded**->> **Track B (Remote)**: 🏆 ~~Prize: **Cash award**.~~ **Concluded - Winners will be announced soon**->>> ~~👉 Sign up here: [trycua.com/hackathon](https://www.trycua.com/hackathon)~~+> We're hosting **The Computer-Use Agents SOTA Challenge concluded** at [Hack the North](https://hackthenorth.com) and online!+>+> > **Track A (On-site @ UWaterloo)**: 🏆 ~~Prize: **YC interview guaranteed**.~~ **Concluded**+> > **Track B (Remote)**: 🏆 ~~Prize: **Cash award**.~~ **Concluded - Winners will be announced soon**+> >+> > > ~~👉 Sign up here: [trycua.com/hackathon](https://www.trycua.com/hackathon)~~**Cua** ("koo-ah") is Docker for [Computer-Use Agents](https://www.oneusefulthing.org/p/when-you-give-a-claude-a-mouse) - it enables AI agents to control full operating systems in virtual containers and deploy them locally or to the cloud.@@ -25,10 +28,12 @@</div>With the Computer SDK, you can:+- automate Windows, Linux, and macOS VMs with a consistent, [pyautogui-like API](https://docs.trycua.com/docs/libraries/computer#interface-actions)- create & manage VMs [locally](https://docs.trycua.com/docs/computer-sdk/computers#cua-local-containers) or using [Cua cloud](https://www.trycua.com/)With the Agent SDK, you can:+- run computer-use models with a [consistent schema](https://docs.trycua.com/docs/agent-sdk/message-format)- benchmark on OSWorld-Verified, SheetBench-V2, and more [with a single line of code using HUD](https://docs.trycua.com/docs/agent-sdk/integrations/hud) ([Notebook](https://github.com/trycua/cua/blob/main/notebooks/eval_osworld.ipynb))- combine UI grounding models with any LLM using [composed agents](https://docs.trycua.com/docs/agent-sdk/supported-agents/composed-agents)@@ -38,16 +43,16 @@ With the Agent SDK, you can:### CUA Model Zoo 🐨| [All-in-one CUAs](https://docs.trycua.com/docs/agent-sdk/supported-agents/computer-use-agents) | [UI Grounding Models](https://docs.trycua.com/docs/agent-sdk/supported-agents/composed-agents) | [UI Planning Models](https://docs.trycua.com/docs/agent-sdk/supported-agents/composed-agents) |-|---|---|---|-| `anthropic/claude-sonnet-4-5-20250929`, `anthropic/claude-haiku-4-5-20251001` | `huggingface-local/xlangai/OpenCUA-{7B,32B}` | any all-in-one CUA |-| `openai/computer-use-preview` | `huggingface-local/HelloKKMe/GTA1-{7B,32B,72B}` | any VLM (using liteLLM, requires `tools` parameter) |-| `openrouter/z-ai/glm-4.5v` | `huggingface-local/Hcompany/Holo1.5-{3B,7B,72B}` | any LLM (using liteLLM, requires `moondream3+` prefix ) |-| `gemini-2.5-computer-use-preview-10-2025` | any-all-in-one CUA | |-| `huggingface-local/OpenGVLab/InternVL3_5-{1B,2B,4B,8B,...}` | | |-| `huggingface-local/ByteDance-Seed/UI-TARS-1.5-7B` | |-| `moondream3+{ui planning}` (supports text-only models) | |-| `omniparser+{ui planning}` | | |-| `{ui grounding}+{ui planning}` | | |+| ---------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------- |+| `anthropic/claude-sonnet-4-5-20250929`, `anthropic/claude-haiku-4-5-20251001` | `huggingface-local/xlangai/OpenCUA-{7B,32B}` | any all-in-one CUA |+| `openai/computer-use-preview` | `huggingface-local/HelloKKMe/GTA1-{7B,32B,72B}` | any VLM (using liteLLM, requires `tools` parameter) |+| `openrouter/z-ai/glm-4.5v` | `huggingface-local/Hcompany/Holo1.5-{3B,7B,72B}` | any LLM (using liteLLM, requires `moondream3+` prefix ) |+| `gemini-2.5-computer-use-preview-10-2025` | any-all-in-one CUA | |+| `huggingface-local/OpenGVLab/InternVL3_5-{1B,2B,4B,8B,...}` | | |+| `huggingface-local/ByteDance-Seed/UI-TARS-1.5-7B` | |+| `moondream3+{ui planning}` (supports text-only models) | |+| `omniparser+{ui planning}` | | |+| `{ui grounding}+{ui planning}` | | |- `human/human` → [Human-in-the-Loop](https://docs.trycua.com/docs/agent-sdk/supported-agents/human-in-the-loop)@@ -55,7 +60,7 @@ Missing a model? [Raise a feature request](https://github.com/trycua/cua/issues/<br/>-# Quick Start+# Quick Start- [Clone a starter template and run the code in <1 min](https://github.com/trycua/agent-template) (⭐️ Recommended!)- [Get started with the Computer-Use Agent CLI](https://docs.trycua.com/docs/quickstart-cli)@@ -68,6 +73,7 @@ Missing a model? [Raise a feature request](https://github.com/trycua/cua/issues/```bashpip install cua-agent[all]```+```pythonfrom agent import ComputerAgent@@ -86,8 +92,9 @@ async for result in agent.run(messages):```### Output format (OpenAI Agent Responses Format):+```json-{+{"output": [# user input{@@ -133,7 +140,7 @@ async for result in agent.run(messages):}]}- ],+ ],"usage": {"prompt_tokens": 150,"completion_tokens": 75,@@ -148,6 +155,7 @@ async for result in agent.run(messages):```bashpip install cua-computer[all]```+```pythonfrom computer import Computer@@ -174,18 +182,18 @@ async with Computer(## Modules-| Module | Description | Installation |-|--------|-------------|---------------|-| [**Lume**](./libs/lume/README.md) | VM management for macOS/Linux using Apple's Virtualization.Framework | `curl -fsSL https://raw.githubusercontent.com/trycua/cua/main/libs/lume/scripts/install.sh \| bash` |-| [**Lumier**](./libs/lumier/README.md) | Docker interface for macOS and Linux VMs | `docker pull trycua/lumier:latest` |-| [**Computer (Python)**](./libs/python/computer/README.md) | Python Interface for controlling virtual machines | `pip install "cua-computer[all]"` |-| [**Computer (Typescript)**](./libs/typescript/computer/README.md) | Typescript Interface for controlling virtual machines | `npm install @trycua/computer` |-| [**Agent**](./libs/python/agent/README.md) | AI agent framework for automating tasks | `pip install "cua-agent[all]"` |-| [**MCP Server**](./libs/python/mcp-server/README.md) | MCP server for using CUA with Claude Desktop | `pip install cua-mcp-server` |-| [**SOM**](./libs/python/som/README.md) | Self-of-Mark library for Agent | `pip install cua-som` |-| [**Computer Server**](./libs/python/computer-server/README.md) | Server component for Computer | `pip install cua-computer-server` |-| [**Core (Python)**](./libs/python/core/README.md) | Python Core utilities | `pip install cua-core` |-| [**Core (Typescript)**](./libs/typescript/core/README.md) | Typescript Core utilities | `npm install @trycua/core` |+| Module | Description | Installation |+| ----------------------------------------------------------------- | -------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------- |+| [**Lume**](./libs/lume/README.md) | VM management for macOS/Linux using Apple's Virtualization.Framework | `curl -fsSL https://raw.githubusercontent.com/trycua/cua/main/libs/lume/scripts/install.sh \| bash` |+| [**Lumier**](./libs/lumier/README.md) | Docker interface for macOS and Linux VMs | `docker pull trycua/lumier:latest` |+| [**Computer (Python)**](./libs/python/computer/README.md) | Python Interface for controlling virtual machines | `pip install "cua-computer[all]"` |+| [**Computer (Typescript)**](./libs/typescript/computer/README.md) | Typescript Interface for controlling virtual machines | `npm install @trycua/computer` |+| [**Agent**](./libs/python/agent/README.md) | AI agent framework for automating tasks | `pip install "cua-agent[all]"` |+| [**MCP Server**](./libs/python/mcp-server/README.md) | MCP server for using CUA with Claude Desktop | `pip install cua-mcp-server` |+| [**SOM**](./libs/python/som/README.md) | Self-of-Mark library for Agent | `pip install cua-som` |+| [**Computer Server**](./libs/python/computer-server/README.md) | Server component for Computer | `pip install cua-computer-server` |+| [**Core (Python)**](./libs/python/core/README.md) | Python Core utilities | `pip install cua-core` |+| [**Core (Typescript)**](./libs/typescript/core/README.md) | Typescript Core utilities | `npm install @trycua/core` |## Community@@ -193,7 +201,7 @@ Join our [Discord community](https://discord.com/invite/mVnXXpdE85) to discuss i## License-Cua is open-sourced under the MIT License - see the [LICENSE](LICENSE.md) file for details.+Cua is open-sourced under the MIT License - see the [LICENSE](LICENSE.md) file for details.Portions of this project, specifically components adapted from Kasm Technologies Inc., are also licensed under the MIT License. See [libs/kasm/LICENSE](libs/kasm/LICENSE) for details.@@ -211,16 +219,16 @@ When you choose to install and use such optional extras, your use, modification,Cua uses `bump2version` to manage package versions across all Python modules. A Makefile is provided to simplify the release process.-### Prerequisites+### Prerequisites#### install `bump2version`using brew+```brew install bumpversion```-### View Current Versions```bash@@ -282,7 +290,7 @@ We welcome contributions to Cua! Please refer to our [Contributing Guidelines](CApple, macOS, and Apple Silicon are trademarks of Apple Inc.Ubuntu and Canonical are registered trademarks of Canonical Ltd.-Microsoft is a registered trademark of Microsoft Corporation.+Microsoft is a registered trademark of Microsoft Corporation.This project is not affiliated with, endorsed by, or sponsored by Apple Inc., Canonical Ltd., Microsoft Corporation, or Kasm Technologies.diff --git a/blog/app-use.md b/blog/app-use.mdindex 2bd8e058ef..68cf9c9b8d 100644--- a/blog/app-use.md+++ b/blog/app-use.md@@ -1,6 +1,6 @@# App-Use: Control Individual Applications with Cua Agents-*Published on May 31, 2025 by The Cua Team*+_Published on May 31, 2025 by The Cua Team_Today, we are excited to introduce a new experimental feature landing in the [Cua GitHub repository](https://github.com/trycua/cua): **App-Use**. App-Use allows you to create lightweight virtual desktops that limit agent access to specific applications, improving precision of your agent's trajectory. Perfect for parallel workflows, and focused task execution.@@ -33,9 +33,11 @@ agent = ComputerAgent(## Key Benefits### 1. Lightweight and Fast+App-Use creates visual filters, not new processes. Your apps continue running normally - we just control what the agent can see and click on. The virtual desktops are composited views that require no additional compute resources beyond the existing window manager operations.### 2. Run Multiple Agents in Parallel+Deploy a team of specialized agents, each focused on their own apps:```python@@ -46,7 +48,7 @@ computer = Computer(experiments=["app-use"])research_desktop = computer.create_desktop_from_apps(["Safari"])research_agent = ComputerAgent(tools=[research_desktop], ...)-# Writing agent focuses on documents+# Writing agent focuses on documentswriting_desktop = computer.create_desktop_from_apps(["Pages", "Notes"])writing_agent = ComputerAgent(tools=[writing_desktop], ...)@@ -66,6 +68,7 @@ await asyncio.gather(### RequirementsTo get started with App-Use, you'll need:+- Python 3.11+- macOS Sequoia (15.0) or later@@ -85,21 +88,21 @@ from agent import ComputerAgentasync def main():computer = Computer()await computer.run()-+# Create app-specific desktop sessionsdesktop = computer.create_desktop_from_apps(["Notes"])-+# Initialize an agentagent = ComputerAgent(model="anthropic/claude-3-5-sonnet-20241022",tools=[desktop])-+# Take a screenshot (returns bytes by default)screenshot = await desktop.interface.screenshot()with open("app_screenshot.png", "wb") as f:f.write(screenshot)-+# Run an agent taskasync for result in agent.run("Create a new note titled 'Meeting Notes' and add today's agenda items"):print(f"Agent: {result.get('text', '')}")@@ -113,6 +116,7 @@ if __name__ == "__main__":### ⚠️ Important WarningComputer-use agents are powerful tools that can interact with your devices. This guide involves using your own macOS and iPhone instead of a VM. **Proceed at your own risk.** Always:+- Review agent actions before running- Start with non-critical tasks- Monitor agent behavior closely@@ -150,20 +154,20 @@ async def automate_iphone():# Connect to your local computer servermy_mac = Computer(use_host_computer_server=True, os_type="macos", experiments=["app-use"])await my_mac.run()-+# Create a desktop focused on iPhone Mirroringmy_iphone = my_mac.create_desktop_from_apps(["iPhone Mirroring"])-+# Initialize an agent for iPhone automationagent = ComputerAgent(model="anthropic/claude-3-5-sonnet-20241022",tools=[my_iphone])-+# Example: Send a messageasync for result in agent.run("Open Messages and send 'Hello from Cua!' to John"):print(f"Agent: {result.get('text', '')}")-+# Example: Set a reminderasync for result in agent.run("Create a reminder to call mom at 5 PM today"):print(f"Agent: {result.get('text', '')}")@@ -175,6 +179,7 @@ if __name__ == "__main__":### iPhone Automation Use CasesWith Cua's iPhone automation, you can:+- **Automate messaging**: Send texts, respond to messages, manage conversations- **Control apps**: Navigate any iPhone app using natural language- **Manage settings**: Adjust iPhone settings programmatically@@ -191,6 +196,7 @@ With Cua's iPhone automation, you can:## When to Use What: App-Use vs Multiple Cua Containers### Use App-Use within the same macOS Cua Container:+- ✅ You need lightweight, fast agent focusing (macOS only)- ✅ You want to run multiple agents on one desktop- ✅ You're automating personal devices like iPhones@@ -198,6 +204,7 @@ With Cua's iPhone automation, you can:- ✅ You want low computational overhead### Use Multiple Cua Containers:+- ✅ You need maximum isolation between agents- ✅ You require cross-platform support (Mac/Linux/Windows)- ✅ You need guaranteed resource allocation@@ -215,6 +222,7 @@ With Cua's iPhone automation, you can:### How It WorksWhen you create a desktop session with `create_desktop_from_apps()`, App Use:+- Filters the visual output to show only specified application windows- Routes input events only to those applications- Maintains window layout isolation between different sessionsdiff --git a/blog/bringing-computer-use-to-the-web.md b/blog/bringing-computer-use-to-the-web.mdindex 196af3d1d8..b753b4546e 100644--- a/blog/bringing-computer-use-to-the-web.md+++ b/blog/bringing-computer-use-to-the-web.md@@ -1,6 +1,6 @@# Bringing Computer-Use to the Web-*Published on August 5, 2025 by Morgan Dean*+_Published on August 5, 2025 by Morgan Dean_In one of our original posts, we explored building Computer-Use Operators on macOS - first with a [manual implementation](build-your-own-operator-on-macos-1.md) using OpenAI's `computer-use-preview` model, then with our [cua-agent framework](build-your-own-operator-on-macos-2.md) for Python developers. While these tutorials have been incredibly popular, we've received consistent feedback from our community: **"Can we use Cua with JavaScript and TypeScript?"**@@ -96,7 +96,7 @@ const res = await openai.responses.create({],},],- truncation: 'auto'+ truncation: 'auto',});```@@ -144,30 +144,30 @@ Each response contains:### Provision a Cua Cloud Container- 1. Visit [trycua.com](https://trycua.com), sign up, purchase [credits](https://trycua.com/pricing), and create a new container instance from the [dashboard](https://trycua.com/dashboard).- 2. Create an API key from the dashboard — be sure to save it in a secure location before continuing.- 3. Start the cloud container from the dashboard.+1. Visit [trycua.com](https://trycua.com), sign up, purchase [credits](https://trycua.com/pricing), and create a new container instance from the [dashboard](https://trycua.com/dashboard).+2. Create an API key from the dashboard — be sure to save it in a secure location before continuing.+3. Start the cloud container from the dashboard.### Environment Setup- 1. Install required packages with your preferred package manager:+1. Install required packages with your preferred package manager:- ```bash- npm install --save @trycua/computer # or yarn, pnpm, bun- npm install --save openai # or yarn, pnpm, bun- ```+ ```bash+ npm install --save @trycua/computer # or yarn, pnpm, bun+ npm install --save openai # or yarn, pnpm, bun+ ```- Works with any JavaScript/TypeScript project setup - whether you're using Create React App, Next.js, Vue, Angular, or plain JavaScript.+ Works with any JavaScript/TypeScript project setup - whether you're using Create React App, Next.js, Vue, Angular, or plain JavaScript.- 2. Save your OpenAI API key, Cua API key, and container name to a `.env` file:+2. Save your OpenAI API key, Cua API key, and container name to a `.env` file:- ```bash- OPENAI_API_KEY=openai-api-key- CUA_API_KEY=cua-api-key- CUA_CONTAINER_NAME=cua-cloud-container-name- ```+ ```bash+ OPENAI_API_KEY=openai-api-key+ CUA_API_KEY=cua-api-key+ CUA_CONTAINER_NAME=cua-cloud-container-name+ ```- These environment variables work the same whether you're using vanilla JavaScript, TypeScript, or any web framework.+ These environment variables work the same whether you're using vanilla JavaScript, TypeScript, or any web framework.## Building the Agentdiff --git a/blog/build-your-own-operator-on-macos-1.md b/blog/build-your-own-operator-on-macos-1.mdindex 1e15ae027d..7033677090 100644--- a/blog/build-your-own-operator-on-macos-1.md+++ b/blog/build-your-own-operator-on-macos-1.md@@ -1,6 +1,6 @@# Build Your Own Operator on macOS - Part 1-*Published on March 31, 2025 by Francesco Bonacci*+_Published on March 31, 2025 by Francesco Bonacci_In this first blogpost, we'll learn how to build our own Computer-Use Operator using OpenAI's `computer-use-preview` model. But first, let's understand what some common terms mean:@@ -19,6 +19,7 @@ Check out what it looks like to use your own Operator from a Gradio app:## What You'll LearnBy the end of this tutorial, you'll be able to:+- Set up a macOS virtual machine for AI automation- Connect OpenAI's computer-use model to your VM- Create a basic loop for the AI to interact with your VM@@ -26,6 +27,7 @@ By the end of this tutorial, you'll be able to:- Implement safety checks and error handling**Prerequisites:**+- macOS Sonoma (14.0) or later- 8GB RAM minimum (16GB recommended)- OpenAI API access (Tier 3+)@@ -41,15 +43,17 @@ Last March OpenAI released a fine-tuned version of GPT-4o, namely [CUA](https://Professor Ethan Mollick provides an excellent explanation of computer-use agents in this article: [When you give a Claude a mouse](https://www.oneusefulthing.org/p/when-you-give-a-claude-a-mouse).### ChatGPT Operator+OpenAI's computer-use model powers [ChatGPT Operator](https://openai.com/index/introducing-operator), a Chromium-based interface exclusively available to ChatGPT Pro subscribers. Users leverage this functionality to automate web-based tasks such as online shopping, expense report submission, and booking reservations by interacting with websites in a human-like manner.## Benefits of Custom Operators### Why Build Your Own?+While OpenAI's Operator uses a controlled Chromium VM instance, there are scenarios where you may want to use your own VM with full desktop capabilities. Here are some examples:- Automating native macOS apps like Finder, Xcode-- Managing files, changing settings, and running terminal commands+- Managing files, changing settings, and running terminal commands- Testing desktop software and applications- Creating workflows that combine web and desktop tasks- Automating media editing in apps like Final Cut Pro and Blender@@ -59,7 +63,9 @@ This gives you more control and flexibility to automate tasks beyond just web br## Access Requirements### Model Availability+As we speak, the **computer-use-preview** model has limited availability:+- Only accessible to OpenAI tier 3+ users- Additional application process may be required even for eligible users- Cannot be used in the OpenAI Playground@@ -68,15 +74,18 @@ As we speak, the **computer-use-preview** model has limited availability:## Understanding the OpenAI API### Responses API Overview+Let's start with the basics. In our case, we'll use OpenAI's Responses API to communicate with their computer-use model.Think of it like this:+1. We send the model a screenshot of our VM and tell it what we want it to do2. The model looks at the screenshot and decides what actions to take3. It sends back instructions (like "click here" or "type this")4. We execute those instructions in our VMThe [Responses API](https://platform.openai.com/docs/guides/responses) is OpenAI's newest way to interact with their AI models. It comes with several built-in tools:+- **Web search**: Let the AI search the internet- **File search**: Help the AI find documents- **Computer use**: Allow the AI to control a computer (what we'll be using)@@ -84,9 +93,11 @@ The [Responses API](https://platform.openai.com/docs/guides/responses) is OpenAIAs we speak, the computer-use model is only available through the Responses API.### Responses API Examples+Let's look at some simple examples. We'll start with the traditional way of using OpenAI's API with Chat Completions, then show the new Responses API primitive.Chat Completions:+```python# The old way required managing conversation history manuallymessages = [{"role": "user", "content": "Hello"}]@@ -98,13 +109,14 @@ messages.append(response.choices[0].message) # Manual message tracking```Responses API:+```python# Example 1: Simple web search# The API handles all the complexity for usresponse = client.responses.create(model="gpt-4",input=[{- "role": "user",+ "role": "user","content": "What's the latest news about AI?"}],tools=[{@@ -118,7 +130,7 @@ response = client.responses.create(response = client.responses.create(model="gpt-4",input=[{- "role": "user",+ "role": "user","content": "Find documents about project X"}],tools=[{@@ -130,6 +142,7 @@ response = client.responses.create(```### Computer-Use Model Setup+For our operator, we'll use the computer-use model. Here's how we set it up:```python@@ -144,7 +157,7 @@ response = client.responses.create(}],input=[{- "role": "user",+ "role": "user","content": [# What we want the AI to do{"type": "input_text", "text": "Open Safari and go to google.com"},@@ -158,6 +171,7 @@ response = client.responses.create(```### Understanding the Response+When we send a request, the API sends back a response that looks like this:```json@@ -189,6 +203,7 @@ When we send a request, the API sends back a response that looks like this:```Each response contains:+1. **Reasoning**: The AI's explanation of what it's doing2. **Action**: The specific computer action to perform3. **Safety Checks**: Any potential risks to review@@ -197,15 +212,18 @@ Each response contains:## CUA-Computer Interface### Architecture Overview+Let's break down the main components of our system and how they work together:1. **The Virtual Machine (VM)**+- Think of this as a safe playground for our AI- It's a complete macOS system running inside your computer- Anything the AI does stays inside this VM, keeping your main system safe- We use `lume` to create and manage this VM2. **The Computer Interface (CUI)**+- This is how we control the VM- It can move the mouse, type text, and take screenshots- Works like a remote control for the VM@@ -238,7 +256,7 @@ sequenceDiagramVM-->>CUI: Return current screenCUI->>AI: Send screenshot + instructionsAI-->>CUI: Return next action-+Note over CUI,VM: Execute the actionalt Mouse ClickCUI->>VM: Move and click mouse@@ -259,6 +277,7 @@ sequenceDiagram```The diagram above shows how information flows through our system:+1. You start the operator2. The Computer Interface creates a virtual macOS3. Then it enters a loop:@@ -284,23 +303,26 @@ This design keeps everything organized and safe. The AI can only interact with t```**Important Storage Notes:**+- Initial download requires 80GB of free space- After first run, space usage reduces to ~30GB due to macOS's sparse file system- VMs are stored in `~/.lume`- Cached images are stored in `~/.lume/cache`You can check your downloaded VM images anytime:+```bashlume ls```Example output:- | name | os | cpu | memory | disk | display | status | ip | vnc |- |--------------------------|---------|-------|---------|----------------|-----------|-----------|----------------|---------------------------------------------------|- | macos-sequoia-cua:latest | macOS | 12 | 16.00G | 64.5GB/80.0GB | 1024x768 | running | 192.168.64.78 | vnc://:[email protected]:56085 |+ | name | os | cpu | memory | disk | display | status | ip | vnc |+ | ------------------------ | ----- | --- | ------ | ------------- | -------- | ------- | ------------- | ---------------------------------------------- |+ | macos-sequoia-cua:latest | macOS | 12 | 16.00G | 64.5GB/80.0GB | 1024x768 | running | 192.168.64.78 | vnc://:[email protected]:56085 |After checking your available images, you can run the VM to ensure everything is working correctly:+```bashlume run macos-sequoia-cua:latest```@@ -309,12 +331,14 @@ This design keeps everything organized and safe. The AI can only interact with t**Note**: The `cua-computer` package requires Python 3.10 or later. We recommend creating a dedicated Python environment:**Using venv:**+```bashpython -m venv cua-envsource cua-env/bin/activate```**Using conda:**+```bashconda create -n cua-env python=3.10conda activate cua-env@@ -332,6 +356,7 @@ This design keeps everything organized and safe. The AI can only interact with t### Building the Operator#### Importing Required Modules+With the prerequisites installed and configured, we're ready to build our first operator.The following example uses asynchronous Python (async/await). You can run it either in a VS Code Notebook or as a standalone Python script.@@ -344,12 +369,13 @@ from computer import Computer```#### Mapping API Actions to CUA Methods+The following helper function converts a `computer_call` action from the OpenAI Responses API into corresponding commands on the CUI interface. For example, if the API instructs a `click` action, we move the cursor and perform a left click on the lume VM Sandbox. We will use the computer interface to execute the actions.```pythonasync def execute_action(computer, action):action_type = action.type-+if action_type == "click":x = action.xy = action.y@@ -360,12 +386,12 @@ async def execute_action(computer, action):await computer.interface.right_click()else:await computer.interface.left_click()-+elif action_type == "type":text = action.textprint(f"Typing text: {text}")await computer.interface.type_text(text)-+elif action_type == "scroll":x = action.xy = action.y@@ -374,7 +400,7 @@ async def execute_action(computer, action):print(f"Scrolling at ({x}, {y}) with offsets (scroll_x={scroll_x}, scroll_y={scroll_y})")await computer.interface.move_cursor(x, y)await computer.interface.scroll(scroll_y) # Using vertical scroll only-+elif action_type == "keypress":keys = action.keysfor key in keys:@@ -386,23 +412,24 @@ async def execute_action(computer, action):await computer.interface.press_key("space")else:await computer.interface.press_key(key)-+elif action_type == "wait":wait_time = action.timeprint(f"Waiting for {wait_time} seconds")await asyncio.sleep(wait_time)-+elif action_type == "screenshot":print("Taking screenshot")# This is handled automatically in the main loop, but we can take an extra one if requestedscreenshot = await computer.interface.screenshot()return screenshot-+else:print(f"Unrecognized action: {action_type}")```#### Implementing the Computer-Use Loop+This section defines a loop that:1. Initializes the cua-computer instance (connecting to a macOS sandbox).@@ -423,7 +450,7 @@ async def cua_openai_loop():os_type="macos") as computer:await computer.run() # Start the lume VM-+# Capture the initial screenshotscreenshot = await computer.interface.screenshot()screenshot_base64 = base64.b64encode(screenshot).decode('utf-8')@@ -438,8 +465,8 @@ async def cua_openai_loop():"environment": "mac"}],input=[- {- "role": "user",+ {+ "role": "user","content": [{"type": "input_text", "text": "Open Safari, download and install Cursor."},{"type": "input_image", "image_url": f"data:image/png;base64,{screenshot_base64}"}@@ -488,7 +515,7 @@ async def cua_openai_loop():"display_height": 768,"environment": "mac"}],- input=[{+ input=[{"type": "computer_call_output","call_id": last_call_id,"acknowledged_safety_checks": acknowledged_checks,@@ -511,12 +538,15 @@ if __name__ == "__main__":You can find the full code in our [notebook](https://github.com/trycua/cua/blob/main/notebooks/blog/build-your-own-operator-on-macos-1.ipynb).#### Request Handling Differences+The first request to the OpenAI Responses API is special in that it includes the initial screenshot and prompt. Subsequent requests are handled differently, using the `computer_call_output` type to provide feedback on the executed action.##### Initial Request Format+- We use `role: "user"` with `content` that contains both `input_text` (the prompt) and `input_image` (the screenshot)##### Subsequent Request Format+- We use `type: "computer_call_output"` instead of the user role- We include the `call_id` to link the output to the specific previous action that was executed- We provide any `acknowledged_safety_checks` that were approved@@ -529,6 +559,7 @@ This structured approach allows the API to maintain context and continuity throu## Conclusion### Summary+This blogpost demonstrates a single iteration of a OpenAI Computer-Use loop where:- A macOS sandbox is controlled using the CUA interface.@@ -538,9 +569,11 @@ This blogpost demonstrates a single iteration of a OpenAI Computer-Use loop wherIn a production setting, you would wrap the action-response cycle in a loop, handling multiple actions and safety checks as needed.### Next Steps+In the next blogpost, we'll introduce our Agent framework which abstracts away all these tedious implementation steps. This framework provides a higher-level API that handles the interaction loop between OpenAI's computer-use model and the macOS sandbox, allowing you to focus on building sophisticated applications rather than managing the low-level details we've explored here. Can't wait? Check out the [cua-agent](https://github.com/trycua/cua/tree/main/libs/agent) package!### Resources+- [OpenAI Computer-Use docs](https://platform.openai.com/docs/guides/tools-computer-use)- [cua-computer](https://github.com/trycua/cua/tree/main/libs/computer)- [lume](https://github.com/trycua/cua/tree/main/libs/lume)diff --git a/blog/build-your-own-operator-on-macos-2.md b/blog/build-your-own-operator-on-macos-2.mdindex 59844456e2..05b8835e1f 100644--- a/blog/build-your-own-operator-on-macos-2.md+++ b/blog/build-your-own-operator-on-macos-2.md@@ -1,6 +1,6 @@# Build Your Own Operator on macOS - Part 2-*Published on April 27, 2025 by Francesco Bonacci*+_Published on April 27, 2025 by Francesco Bonacci_In our [previous post](build-your-own-operator-on-macos-1.md), we built a basic Computer-Use Operator from scratch using OpenAI's `computer-use-preview` model and our [cua-computer](https://pypi.org/project/cua-computer) package. While educational, implementing the control loop manually can be tedious and error-prone.@@ -13,12 +13,14 @@ In this follow-up, we'll explore our [cua-agent](https://pypi.org/project/cua-ag## What You'll LearnBy the end of this tutorial, you'll be able to:+- Set up the `cua-agent` framework with various agent loop types and model providers- Understand the different agent loop types and their capabilities- Work with local models for cost-effective workflows- Use a simple UI for your operator**Prerequisites:**+- Completed setup from Part 1 ([lume CLI installed](https://github.com/trycua/cua?tab=readme-ov-file#option-2-full-computer-use-agent-capabilities), macOS CUA image already pulled)- Python 3.10+. We recommend using Conda (or Anaconda) to create an ad hoc Python environment.- API keys for OpenAI and/or Anthropic (optional for local models)@@ -58,6 +60,7 @@ pip install "cua-agent[ui]" # Gradio UIBefore running any code examples, let's set up a proper environment:1. **Create a new directory** for your project:+```bashmkdir cua-agent-tutorialcd cua-agent-tutorial@@ -66,13 +69,15 @@ Before running any code examples, let's set up a proper environment:2. **Set up a Python environment** using one of these methods:**Option A: Using conda command line**+```bash# Using condaconda create -n cua-agent python=3.10conda activate cua-agent```-+**Option B: Using Anaconda Navigator UI**+- Open Anaconda Navigator- Click on "Environments" in the left sidebar- Click the "Create" button at the bottom@@ -80,36 +85,41 @@ Before running any code examples, let's set up a proper environment:- Select Python 3.10- Click "Create"- Once created, select the environment and click "Open Terminal" to activate it-+**Option C: Using venv**+```bashpython -m venv cua-envsource cua-env/bin/activate # On macOS/Linux```3. **Install the cua-agent package**:+```bashpip install "cua-agent[all]"```4. **Set up your API keys as environment variables**:+```bash# For OpenAI modelsexport OPENAI_API_KEY=your_openai_key_here-+# For Anthropic models (if needed)export ANTHROPIC_API_KEY=your_anthropic_key_here```5. **Create a Python file or notebook**:-+**Option A: Create a Python script**+```bash# For a Python scripttouch cua_agent_example.py```-+**Option B: Use VS Code notebooks**+- Open VS Code- Install the Python extension if you haven't already- Create a new file with a `.ipynb` extension (e.g., `cua_agent_tutorial.ipynb`)@@ -120,9 +130,10 @@ Now you're ready to run the code examples!## Understanding Agent Loops-If you recall from Part 1, we had to implement a custom interaction loop to interact with the compute-use-preview model.+If you recall from Part 1, we had to implement a custom interaction loop to interact with the compute-use-preview model.In the `cua-agent` framework, an **Agent Loop** is the core abstraction that implements the continuous interaction cycle between an AI model and the computer environment. It manages the flow of:+1. Capturing screenshots of the computer's state2. Processing these screenshots (with or without UI element detection)3. Sending this visual context to an AI model along with the task instructions@@ -141,6 +152,7 @@ While the core concept remains the same across all agent loops, different AI mod| `AgentLoop.OMNI` | • `claude-3-5-sonnet-20240620`<br>• `claude-3-7-sonnet-20250219`<br>• `gpt-4.5-preview`<br>• `gpt-4o`<br>• `gpt-4`<br>• `phi4`<br>• `phi4-mini`<br>• `gemma3`<br>• `...`<br>• `Any Ollama or OpenAI-compatible model` | Use OmniParser for element pixel-detection (SoM) and any VLMs for UI Grounding and Reasoning | OmniParser |Each loop handles the same basic pattern we implemented manually in Part 1:+1. Take a screenshot of the VM2. Send the screenshot and task to the AI model3. Receive an action to perform@@ -169,13 +181,13 @@ Choosing the right agent loop depends not only on your API access and technicalThe performance of different Computer-Use models varies significantly across tasks. These benchmark evaluations measure an agent's ability to follow instructions and complete real-world tasks in different computing environments.-| Benchmark type | Benchmark | UI-TARS-1.5 | OpenAI CUA | Claude 3.7 | Previous SOTA | Human |-|----------------|--------------------------------------------------------------------------------------------------------------------------------------------------|-------------|-------------|-------------|----------------------|-------------|-| **Computer Use** | [OSworld](https://arxiv.org/abs/2404.07972) (100 steps) | **42.5** | 36.4 | 28 | 38.1 (200 step) | 72.4 |-| | [Windows Agent Arena](https://arxiv.org/abs/2409.08264) (50 steps) | **42.1** | - | - | 29.8 | - |-| **Browser Use** | [WebVoyager](https://arxiv.org/abs/2401.13919) | 84.8 | **87** | 84.1 | 87 | - |-| | [Online-Mind2web](https://arxiv.org/abs/2504.01382) | **75.8** | 71 | 62.9 | 71 | - |-| **Phone Use** | [Android World](https://arxiv.org/abs/2405.14573) | **64.2** | - | - | 59.5 | - |+| Benchmark type | Benchmark | UI-TARS-1.5 | OpenAI CUA | Claude 3.7 | Previous SOTA | Human |+| ---------------- | ------------------------------------------------------------------ | ----------- | ---------- | ---------- | --------------- | ----- |+| **Computer Use** | [OSworld](https://arxiv.org/abs/2404.07972) (100 steps) | **42.5** | 36.4 | 28 | 38.1 (200 step) | 72.4 |+| | [Windows Agent Arena](https://arxiv.org/abs/2409.08264) (50 steps) | **42.1** | - | - | 29.8 | - |+| **Browser Use** | [WebVoyager](https://arxiv.org/abs/2401.13919) | 84.8 | **87** | 84.1 | 87 | - |+| | [Online-Mind2web](https://arxiv.org/abs/2504.01382) | **75.8** | 71 | 62.9 | 71 | - |+| **Phone Use** | [Android World](https://arxiv.org/abs/2405.14573) | **64.2** | - | - | 59.5 | - |### When to Use Each Loop@@ -210,10 +222,10 @@ async def run_simple_task():model="openai/computer-use-preview",tools=[macos_computer])-+# Define a simple tasktask = "Open Safari and search for 'Python tutorials'"-+# Run the task and process responsesasync for result in agent.run(task):print(f"Action: {result.get('text')}")@@ -225,6 +237,7 @@ if __name__ == "__main__":3. Save the file4. Open a terminal, navigate to your project directory, and run:+```bashpython simple_task.py```@@ -232,6 +245,7 @@ if __name__ == "__main__":5. The code will initialize the macOS virtual machine, create an agent, and execute the task of opening Safari and searching for Python tutorials.You can also run this in a VS Code notebook:+1. Create a new notebook in VS Code (.ipynb file)2. Copy the code into a cell (without the `if __name__ == "__main__":` part)3. Run the cell to execute the code@@ -259,7 +273,7 @@ async def run_multi_task_workflow():model="anthropic/claude-3-5-sonnet-20241022",tools=[macos_computer])-+tasks = ["Open Safari and go to github.com","Search for 'trycua/cua'",@@ -267,7 +281,7 @@ async def run_multi_task_workflow():"Click on the 'Issues' tab","Read the first open issue"]-+for i, task in enumerate(tasks):print(f"\nTask {i+1}/{len(tasks)}: {task}")async for result in agent.run(task):@@ -301,13 +315,13 @@ async for result in agent.run(task):# Basic informationprint(f"Response ID: {result.get('id')}")print(f"Response Text: {result.get('text')}")-+# Detailed token usage statisticsusage = result.get('usage')if usage:print(f"Input Tokens: {usage.get('input_tokens')}")print(f"Output Tokens: {usage.get('output_tokens')}")-+# Reasoning and actionsfor output in result.get('output', []):if output.get('type') == 'reasoning':@@ -318,6 +332,7 @@ async for result in agent.run(task):```This structured format allows you to:+- Log detailed information about agent actions- Provide real-time feedback to users- Track token usage for cost monitoring@@ -330,6 +345,7 @@ One of the most powerful features of the framework is the ability to use local m**How to run this example:**1. First, you'll need to install Ollama for running local models:+- Visit [ollama.com](https://ollama.com) and download the installer for your OS- Follow the installation instructions- Pull the Gemma 3 model:@@ -350,9 +366,9 @@ async def run_with_local_model():model="omniparser+ollama_chat/gemma3",tools=[macos_computer])-+task = "Open the Calculator app and perform a simple calculation"-+async for result in agent.run(task):print(f"Action: {result.get('text')}")@@ -379,12 +395,14 @@ agent = ComputerAgent(```Common local endpoints include:+- LM Studio: `http://localhost:1234/v1`- vLLM: `http://localhost:8000/v1`- LocalAI: `http://localhost:8080/v1`- Ollama with OpenAI compat: `http://localhost:11434/v1`This approach is perfect for:+- Development and testing without incurring API costs- Offline or air-gapped environments where API access isn't possible- Privacy-sensitive applications where data can't leave your network@@ -406,8 +424,8 @@ UI-TARS is ByteDance's Computer-Use model designed for navigating OS-level inter```pythonagent = ComputerAgent(model=LLM(- provider=LLMProvider.OAICOMPAT,- name="tgi",+ provider=LLMProvider.OAICOMPAT,+ name="tgi",provider_base_url="https://**************.us-east-1.aws.endpoints.huggingface.cloud/v1"),tools=[macos_computer]@@ -475,11 +493,13 @@ if __name__ == "__main__":```2. Install the UI dependencies if you haven't already:+```bashpip install "cua-agent[ui]"```3. Run the script:+```bashpython launch_ui.py```@@ -498,12 +518,14 @@ if __name__ == "__main__":```When you run this, Gradio will display both a local URL and a public URL like:+```Running on local URL: http://127.0.0.1:7860Running on public URL: https://abcd1234.gradio.live```**Security Note:** Be cautious when sharing your Gradio UI publicly:+- The public URL gives anyone with the link full access to your agent- Consider using basic authentication for additional protection:```python@@ -513,6 +535,7 @@ Running on public URL: https://abcd1234.gradio.live- The temporary link expires when you stop the Gradio applicationThis provides:+- Model provider selection- Agent loop selection- Task input field@@ -566,7 +589,7 @@ async def github_workflow():verbosity=logging.INFO,tools=[macos_computer])-+tasks = ["Look for a repository named trycua/cua on GitHub.","Check the open issues, open the most recent one and read it.",@@ -575,7 +598,7 @@ async def github_workflow():"From Cursor, open Composer if not already open.","Focus on the Composer text area, then write and submit a task to help resolve the GitHub issue.",]-+for i, task in enumerate(tasks):print(f"\nExecuting task {i+1}/{len(tasks)}: {task}")async for result in agent.run(task):@@ -587,11 +610,13 @@ if __name__ == "__main__":```2. Make sure your OpenAI API key is set:+```bashexport OPENAI_API_KEY=your_openai_key_here```3. Run the script:+```bashpython github_workflow.py```@@ -604,6 +629,7 @@ if __name__ == "__main__":- Use Cursor's AI features to work on a solutionThis example:+1. Searches GitHub for a repository2. Reads an issue3. Clones the repository@@ -615,6 +641,7 @@ This example:Let's compare our manual implementation from Part 1 with the framework approach:### Manual Implementation (Part 1)+- Required writing custom code for the interaction loop- Needed explicit handling of different action types- Required direct management of the OpenAI API calls@@ -622,6 +649,7 @@ Let's compare our manual implementation from Part 1 with the framework approach:- Limited to OpenAI's computer-use model### Framework Implementation (Part 2)+- Abstracts the interaction loop- Handles all action types automatically- Manages API calls internally@@ -634,17 +662,21 @@ Let's compare our manual implementation from Part 1 with the framework approach:The `cua-agent` framework transforms what was a complex implementation task into a simple, high-level interface for building Computer-Use Agents. By abstracting away the technical details, it lets you focus on defining the tasks rather than the machinery.### When to Use Each Approach+- **Manual Implementation (Part 1)**: When you need complete control over the interaction loop or are implementing a custom solution- **Framework (Part 2)**: For most applications where you want to quickly build and deploy Computer-Use Agents### Next Steps+With the basics covered, you might want to explore:+- Customizing the agent's behavior with additional parameters- Building more complex workflows spanning multiple applications- Integrating your agent into other applications- Contributing to the open-source project on GitHub### Resources+- [cua-agent GitHub repository](https://github.com/trycua/cua/tree/main/libs/agent)- [Agent Notebook Examples](https://github.com/trycua/cua/blob/main/notebooks/agent_nb.ipynb)- [OpenAI Agent SDK Specification](https://platform.openai.com/docs/api-reference/responses)diff --git a/blog/composite-agents.md b/blog/composite-agents.mdindex 84d0efbf43..383fb035be 100644--- a/blog/composite-agents.md+++ b/blog/composite-agents.md@@ -1,6 +1,6 @@# Announcing Cua Agent framework 0.4 and Composite Agents-*Published on August 26, 2025 by Dillon DuPont*+_Published on August 26, 2025 by Dillon DuPont_<img src="./assets/composite-agents.png" alt="Composite Agents">@@ -12,7 +12,7 @@ This is the kind of problem that makes you wonder if we're building the future o## What we fixed-Agent framework 0.4 solves this by doing something radical: making all these different models speak the same language.+Agent framework 0.4 solves this by doing something radical: making all these different models speak the same language.Instead of writing separate code for each model's peculiarities, you now just pick a model with a string like `"anthropic/claude-3-5-sonnet-20241022"` or `"huggingface-local/ByteDance-Seed/UI-TARS-1.5-7B"`, and everything else Just Works™. Behind the scenes, we handle all the coordinate normalization, token parsing, and image preprocessing so you don't have to.@@ -42,7 +42,7 @@ agent = ComputerAgent(This creates a composite agent where one model (the "grounding" model) handles the visual understanding and precise UI interactions, while the other (the "planning" model) handles the high-level reasoning and task orchestration. It's like having a pilot and a navigator, except they're both AI models and they're trying to help you star a GitHub repository.- You can even take a model that was never designed for computer use—like GPT-4o—and give it GUI capabilities by pairing it with a specialized vision model:+You can even take a model that was never designed for computer use—like GPT-4o—and give it GUI capabilities by pairing it with a specialized vision model:```pythonagent = ComputerAgent(@@ -63,12 +63,11 @@ We're building integration with HUD evals, allowing us to curate and benchmark mIf you try out version 0.4.x, we'd love to hear how it goes. Join us on Discord to share your results and let us know what model combinations work best for your projects.----## Links-* **Composite Agent Docs:** [https://docs.trycua.com/docs/agent-sdk/supported-agents/composed-agents](https://docs.trycua.com/docs/agent-sdk/supported-agents/composed-agents)-* **Discord:** [https://discord.gg/cua-ai](https://discord.gg/cua-ai)+- **Composite Agent Docs:** [https://docs.trycua.com/docs/agent-sdk/supported-agents/composed-agents](https://docs.trycua.com/docs/agent-sdk/supported-agents/composed-agents)+- **Discord:** [https://discord.gg/cua-ai](https://discord.gg/cua-ai)-Questions or weird edge cases? Ping us on Discord—we’re curious to see what you build.\ No newline at end of file+Questions or weird edge cases? Ping us on Discord—we’re curious to see what you build.diff --git a/blog/cua-hackathon.md b/blog/cua-hackathon.mdindex ac40f48861..26e59cf7ba 100644--- a/blog/cua-hackathon.md+++ b/blog/cua-hackathon.md@@ -1,6 +1,6 @@# Computer-Use Agents SOTA Challenge: Hack the North + Global Online-*Published on August 25, 2025 by Francesco Bonacci*+_Published on August 25, 2025 by Francesco Bonacci_We’re bringing something new to [Hack the North](https://hackthenorth.com), Canada’s largest hackathon, this year: a head-to-head competition for **Computer-Use Agents** - on-site at Waterloo and a **Global online challenge**. From September 12–14, 2025, teams build on the **Cua Agent Framework** and are scored in **HUD’s OSWorld-Verified** environment to push past today’s SOTA on [OS-World](https://os-world.github.io).@@ -14,7 +14,8 @@ There’s one global leaderboard: **Cua - Best State-of-the-Art Computer-Use Age**Cua** and [**Ollama**](https://ollama.com) organize a global hackathon to find the **most creative uses of local and hybrid computer-use agents**. There are no geographic restrictions on who can join — this is a worldwide competition focused on **originality, impact, and inventive applications** that showcase what's possible with local and hybrid inference.-**Prizes:**+**Prizes:**+- 1st **MacBook Air M4 (or equivalent value)** + features in Cua & Ollama channels- 2nd **$500 CAD + swag**- 3rd **swag + public feature**@@ -26,36 +27,42 @@ There’s one global leaderboard: **Cua - Best State-of-the-Art Computer-Use AgeTwo different tracks, two different processes:### On-site (Track A)+Build during the weekend and submit a repo with a one-line start command. **HUD** executes your command in a clean environment and runs **OSWorld-Verified**. Scores come from official benchmark results; ties break by median, then wall-clock time, then earliest submission. Any model setup is allowed (cloud or local).**HUD** runs official evaluations immediately after submission. Winners are announced at the **closing ceremony**.### Rules+- Fork and star the [Cua repo](https://github.com/trycua/cua).- Add your agent and instructions in `samples/community/hack-the-north/<YOUR_TEAM_NAME>`.-- Include a README with details on the approach and any required notes.-- Submit a PR.+- Include a README with details on the approach and any required notes.+- Submit a PR.**Deadline: Sept 15, 8:00 AM EDT**### Global Online (Track B)+Open to anyone, anywhere. Build on your own timeline and submit through the **Cua Discord form** by the deadline.**Project Requirements:**+- Your agent must integrate **Cua and Ollama** in some way- Your agent must be **easily runnable by judges**-Judged by **Cua** and **Ollama** teams on:-- **Creativity (30%)** – originality, usefulness, surprise factor-- **Technical Depth (30%)** – quality of engineering and agent design-- **Use of Ollama (30%)** – effective integration of local/hybrid inference-- **Polish (10%)** – presentation, clarity, demo readiness+Judged by **Cua** and **Ollama** teams on:++- **Creativity (30%)** – originality, usefulness, surprise factor+- **Technical Depth (30%)** – quality of engineering and agent design+- **Use of Ollama (30%)** – effective integration of local/hybrid inference+- **Polish (10%)** – presentation, clarity, demo readiness### Submission Process+Submissions will be collected via a **form link provided in the Cua Discord**. Your submission must contain:- **GitHub repo** containing the agent source code and a clear README with instructions on how to use the agent-- **Explanation** of the models and tools used, and what's local or hybrid about your design+- **Explanation** of the models and tools used, and what's local or hybrid about your design- **Short demo video** (up to two minutes)A **commit freeze** will be used to ensure that no changes are made after the deadline. Winners will be announced after judging is complete.@@ -68,12 +75,13 @@ A **commit freeze** will be used to ensure that no changes are made after the deBring a team, pick a model stack, and push what agents can do on real computers. We can’t wait to see what you build at **Hack the North 2025**.-**Discord channels**+**Discord channels**+- Join the Discord first: https://discord.gg/cua-ai-- **#hack-the-north (on-site):** https://discord.com/channels/1328377437301641247/1409508526774157342-- **#global-online (Ollama × Cua):** https://discord.com/channels/1328377437301641247/1409518100491145226+- **#hack-the-north (on-site):** https://discord.com/channels/1328377437301641247/1409508526774157342+- **#global-online (Ollama × Cua):** https://discord.com/channels/1328377437301641247/1409518100491145226**Contact**Questions on Hack the North? Email **[email protected]**.-*P.S. If you’re planning ahead, start with the Cua Agent Framework and OSWorld-Verified docs at docs.trycua.com; we’ll share office-hour times in both Discord channels.*\ No newline at end of file+_P.S. If you’re planning ahead, start with the Cua Agent Framework and OSWorld-Verified docs at docs.trycua.com; we’ll share office-hour times in both Discord channels._diff --git a/blog/hack-the-north.md b/blog/hack-the-north.mdindex ae89ba4250..574af62cf0 100644--- a/blog/hack-the-north.md+++ b/blog/hack-the-north.md@@ -1,6 +1,6 @@# What happens when hackathon judging is a public benchmark (Hack the North edition)-*Written by Francesco Bonacci — Reviewed by Parth Patel (HUD W25) — Sept 25, 2025*+_Written by Francesco Bonacci — Reviewed by Parth Patel (HUD W25) — Sept 25, 2025_## Prologue@@ -16,7 +16,7 @@ The rest, as they say, was a 36h story worth telling—and a playbook worth shar## The sign-up problem we had to invent-We joined as a sponsor at the last minute, thanks to a push from our friend @Michael Chiang at Ollama—Waterloo alum, naturally. It’s kind of an open secret that UWaterloo turns out some of the sharpest hackers around (*no pun intended, HackMIT*). It was a bit of a scramble, but also great timing—our Agent framework had just finished a major refactor, with support for **100+ VLM configurations** now live. Naturally, we wanted to stress-test it at scale—and see whether teams could come up with SOTA-level setups. *This wasn’t a blank-slate, build-whatever-you-want kind of track.*+We joined as a sponsor at the last minute, thanks to a push from our friend @Michael Chiang at Ollama—Waterloo alum, naturally. It’s kind of an open secret that UWaterloo turns out some of the sharpest hackers around (_no pun intended, HackMIT_). It was a bit of a scramble, but also great timing—our Agent framework had just finished a major refactor, with support for **100+ VLM configurations** now live. Naturally, we wanted to stress-test it at scale—and see whether teams could come up with SOTA-level setups. _This wasn’t a blank-slate, build-whatever-you-want kind of track._From day one, though, we knew we’d have to fight for sign-ups. This was a niche track, and a guaranteed YC interview alone wouldn’t be enough to pull people in.@@ -24,7 +24,7 @@ Unfortunately, Hack the North (HTN) didn’t offer an interest form to help us eOn top of that, we were discouraged from external promotion on [lu.ma](http://lu.ma). So we spun up our own sign-up page at **trycua.com/hackathon** and built ad-hoc Discord channels to share track details. We emphasized—repeatedly—that only students already accepted to Hack the North should register.-*(Moral: the “measure-zero effect”—no matter how many times you say it, some people won’t see it. Plenty of invalid sign-ups still slipped through.)*+_(Moral: the “measure-zero effect”—no matter how many times you say it, some people won’t see it. Plenty of invalid sign-ups still slipped through.)_Even so, having your own form is absolutely worth it: it gives you an **early funnel**, surfaces demand signals ahead of time, and—crucially—**lets you require platform sign-up before kickoff**. In our case, Hack the North didn’t provide Devpost access until the very end, so our form was the only way to build a working roster.@@ -45,13 +45,13 @@ Day 0 on campus made the difference. We arrived a couple of hours early to colle-*(Our Founding Engineer, Morgan, hangs out with students at the stand, while Adam (runner-up) hacks on the side.)*+_(Our Founding Engineer, Morgan, hangs out with students at the stand, while Adam (runner-up) hacks on the side.)_## 02:30 a.m. is still prime time at a hackathonHack the North gives sponsors a 30-minute API Workshop during the early hours of the event—a perfect moment to shift from talking to building.-Our slot landed at **2:30 a.m.** (*perks of the cheapest sponsor tier*). Thirty students showed up, energy surprisingly high. James, our new Founding DevRel Engineer, led the session and nailed it.+Our slot landed at **2:30 a.m.** (_perks of the cheapest sponsor tier_). Thirty students showed up, energy surprisingly high. James, our new Founding DevRel Engineer, led the session and nailed it.**Our track rules were simple:**@@ -67,7 +67,7 @@ Our slot landed at **2:30 a.m.** (*perks of the cheapest sponsor tier*). Thirty-*(Our CUA Workshop at 2:30 AM.)*+_(Our CUA Workshop at 2:30 AM.)_## Making it possible to focus on the work@@ -87,7 +87,7 @@ We provided:**After the workshop buzz.** Morning interest was high, but Docker setup + requiring focus on a single track thinned the crowd. Most sponsor prizes are broad (“use our product and you qualify”), letting students stack tracks. Ours required commitment. Upside: those who stayed shipped sharper, higher-quality submissions.-**The bell curve of submissions.** Most entries used *claude-sonnet-4-20250514*—proof that docs and public leaderboards ([OSWorld](https://os-world.github.io/#benchmark)) guide choices. Results clustered around the safe pick, with fewer pushing boundaries.+**The bell curve of submissions.** Most entries used _claude-sonnet-4-20250514_—proof that docs and public leaderboards ([OSWorld](https://os-world.github.io/#benchmark)) guide choices. Results clustered around the safe pick, with fewer pushing boundaries.**Who went beyond the baseline.** A few tried multi-agent/tool graphs. One standout—[**cuala**](https://github.com/YeIIcw/cuala)—was a clean reference: deterministic actions, verifiable state changes, callbacks for saving images and trajectories.@@ -97,7 +97,7 @@ We provided:We skipped a full end-to-end **Cua × HUD** dry-run. It showed.-- Hackers ran out of inference credits. Desktop tasks are token-heavy. A full OSWorld run (200 max steps) for *computer-use-preview* (OpenAI Operator API) can cost >$600. Serious attempts: ~400k tokens × 14 tasks.+- Hackers ran out of inference credits. Desktop tasks are token-heavy. A full OSWorld run (200 max steps) for _computer-use-preview_ (OpenAI Operator API) can cost >$600. Serious attempts: ~400k tokens × 14 tasks.- Python version/build mismatches surfaced, requiring debug time across both OSS repos.- Our Cua framework lacked a **Response Agent** to complete evaluation loops. Some runs stalled until patched.@@ -112,28 +112,31 @@ We skipped a full end-to-end **Cua × HUD** dry-run. It showed.-*(Leaderboard on HUD)*+_(Leaderboard on HUD)_### Winners-**🥇 Winner — Ram**-- Devpost: https://devpost.com/software/sota-computer-use-agent-challenge-- Code: https://github.com/Ram-Raghav-S/cua/tree/ram+**🥇 Winner — Ram**++- Devpost: https://devpost.com/software/sota-computer-use-agent-challenge+- Code: https://github.com/Ram-Raghav-S/cua/tree/ram- Score: 68.3%-**🥈 Runner-up — Aryan**-- Devpost: https://devpost.com/software/loopdeloop-computer-use-agent-sota-attempt-- Code: https://github.com/Tumph/cua+**🥈 Runner-up — Aryan**++- Devpost: https://devpost.com/software/loopdeloop-computer-use-agent-sota-attempt+- Code: https://github.com/Tumph/cua- Score: 55.9%-**🥉 Special Mention — Adam**-- Devpost: https://devpost.com/software/cuala-- Code: https://github.com/YeIIcw/cuala+**🥉 Special Mention — Adam**++- Devpost: https://devpost.com/software/cuala+- Code: https://github.com/YeIIcw/cuala- Score: 42.1%-*(Our finalists before the award ceremony)*+_(Our finalists before the award ceremony)_## What We’d Keep@@ -163,4 +166,4 @@ Whether you’re a hacker who wants to participate, or a company looking to spon-*(HTN Closing Ceremony — Cua Track Winner Announcement)*\ No newline at end of file+_(HTN Closing Ceremony — Cua Track Winner Announcement)_diff --git a/blog/hud-agent-evals.md b/blog/hud-agent-evals.mdindex 93c8b38856..43a120e9b8 100644--- a/blog/hud-agent-evals.md+++ b/blog/hud-agent-evals.md@@ -1,6 +1,6 @@# Cua × HUD - Evaluate Any Computer-Use Agent-*Published on August 27, 2025 by Dillon DuPont*+_Published on August 27, 2025 by Dillon DuPont_You can now benchmark any GUI-capable agent on real computer-use tasks through our new integration with [HUD](https://hud.so), the evaluation platform for computer-use agents.@@ -70,9 +70,9 @@ Watch your agent work in real-time. Example output:```mdStarting full dataset run...╔═════════════════════════════════════════════════════════════════╗-║ 🚀 See your agent live at: ║+║ 🚀 See your agent live at: ║╟─────────────────────────────────────────────────────────────────╢-║ https://app.hud.so/jobs/fe05805d-4da9-4fc6-84b5-5c518528fd3c ║+║ https://app.hud.so/jobs/fe05805d-4da9-4fc6-84b5-5c518528fd3c ║╚═════════════════════════════════════════════════════════════════╝```@@ -90,4 +90,4 @@ Customize your evaluation with these options:- Notebook with end‑to‑end examples: https://github.com/trycua/cua/blob/main/notebooks/eval_osworld.ipynb- Docs: https://docs.trycua.com/docs/agent-sdk/integrations/hud-- Live traces: https://app.hud.so\ No newline at end of file+- Live traces: https://app.hud.sodiff --git a/blog/human-in-the-loop.md b/blog/human-in-the-loop.mdindex 055ad73ac1..dd14b27b08 100644--- a/blog/human-in-the-loop.md+++ b/blog/human-in-the-loop.md@@ -1,10 +1,10 @@# When Agents Need Human Wisdom - Introducing Human-In-The-Loop Support-*Published on August 29, 2025 by Francesco Bonacci*+_Published on August 29, 2025 by Francesco Bonacci_Sometimes the best AI agent is a human. Whether you're creating training demonstrations, evaluating complex scenarios, or need to intervene when automation hits a wall, our new Human-In-The-Loop integration puts you directly in control.-With yesterday's [HUD evaluation integration](hud-agent-evals.md), you could benchmark any agent at scale. Today's update lets you *become* the agent when it matters most—seamlessly switching between automated intelligence and human judgment.+With yesterday's [HUD evaluation integration](hud-agent-evals.md), you could benchmark any agent at scale. Today's update lets you _become_ the agent when it matters most—seamlessly switching between automated intelligence and human judgment.<div align="center"><video src="https://github.com/user-attachments/assets/9091b50f-26e7-4981-95ce-40e5d42a1260" width="600" controls></video>@@ -20,11 +20,12 @@ With yesterday's [HUD evaluation integration](hud-agent-evals.md), you could ben## Why Human-In-The-Loop?-Even the most sophisticated agents encounter edge cases, ambiguous interfaces, or tasks requiring human judgment. Rather than failing gracefully, they can now fail *intelligently*—by asking for human help.+Even the most sophisticated agents encounter edge cases, ambiguous interfaces, or tasks requiring human judgment. Rather than failing gracefully, they can now fail _intelligently_—by asking for human help.This approach bridges the gap between fully automated systems and pure manual control, letting you:+- **Demonstrate complex workflows** that agents can learn from-- **Evaluate tricky scenarios** where ground truth requires human assessment+- **Evaluate tricky scenarios** where ground truth requires human assessment- **Intervene selectively** when automated agents need guidance- **Test and debug** your tools and environments manually@@ -64,7 +65,7 @@ Combine model intelligence with human precision—let AI plan, then execute manu```pythonagent = ComputerAgent(- "huggingface-local/HelloKKMe/GTA1-7B+human/human",+ "huggingface-local/HelloKKMe/GTA1-7B+human/human",tools=[computer])@@ -81,7 +82,7 @@ Start automated, escalate to human when needed:# Primary automated agentprimary_agent = ComputerAgent("openai/computer-use-preview", tools=[computer])-# Human fallback agent+# Human fallback agentfallback_agent = ComputerAgent("human/human", tools=[computer])try:@@ -101,22 +102,26 @@ except Exception:The human-in-the-loop interface provides a rich, responsive experience:### **Visual Environment**+- **Screenshot display** with live updates as you work-- **Click handlers** for direct interaction with UI elements+- **Click handlers** for direct interaction with UI elements- **Zoom and pan** to see details clearly### **Action Controls**+- **Click actions** - precise cursor positioning and clicking- **Keyboard input** - type text naturally or send specific key combinations- **Action history** - see the sequence of actions taken- **Undo support** - step back when needed-### **Tool Integration**+### **Tool Integration**+- **Full OpenAI compatibility** - standard tool call format- **Custom tools** - integrate your own tools seamlessly- **Real-time feedback** - see tool responses immediately### **Smart Polling**+- **Responsive updates** - UI refreshes when new completions arrive- **Background processing** - continue working while waiting for tasks- **Session persistence** - resume interrupted sessions@@ -124,6 +129,7 @@ The human-in-the-loop interface provides a rich, responsive experience:## Real-World Use Cases### **Training Data Generation**+Create perfect demonstrations for fine-tuning:```python@@ -132,7 +138,7 @@ demo_agent = ComputerAgent("human/human", tools=[computer])tasks = ["Create a budget spreadsheet with income and expense categories",- "Apply conditional formatting to highlight overbudget items",+ "Apply conditional formatting to highlight overbudget items","Generate a pie chart showing expense distribution"]@@ -143,6 +149,7 @@ for task in tasks:```### **Evaluation and Ground Truth**+Validate agent performance on complex scenarios:```python@@ -154,6 +161,7 @@ async for _ in evaluator.run("Review this completed form and rate accuracy (1-10```### **Interactive Debugging**+Step through agent behavior manually:```python@@ -165,6 +173,7 @@ async for _ in debug_agent.run("Reproduce the agent's failed login sequence"):```### **Edge Case Handling**+Handle scenarios that break automated agents:```python@@ -180,26 +189,26 @@ async for _ in edge_case_agent.run("Navigate this CAPTCHA-protected form"):Customize the human agent experience:- **UI refresh rate**: Adjust polling frequency for your workflow-- **Image quality**: Balance detail vs. performance for screenshots+- **Image quality**: Balance detail vs. performance for screenshots- **Action logging**: Save detailed traces for analysis and training- **Session timeout**: Configure idle timeouts for security- **Tool permissions**: Restrict which tools humans can access## When to Use Human-In-The-Loop-| **Scenario** | **Why Human Control** |-|--------------|----------------------|-| **Creating training data** | Perfect demonstrations for model fine-tuning |-| **Evaluating complex tasks** | Human judgment for subjective or nuanced assessment |-| **Handling edge cases** | CAPTCHAs, unusual UIs, context-dependent decisions |-| **Debugging workflows** | Step through failures to identify breaking points |-| **High-stakes operations** | Critical tasks requiring human oversight and approval |-| **Testing new environments** | Validate tools and environments work as expected |+| **Scenario** | **Why Human Control** |+| ---------------------------- | ----------------------------------------------------- |+| **Creating training data** | Perfect demonstrations for model fine-tuning |+| **Evaluating complex tasks** | Human judgment for subjective or nuanced assessment |+| **Handling edge cases** | CAPTCHAs, unusual UIs, context-dependent decisions |+| **Debugging workflows** | Step through failures to identify breaking points |+| **High-stakes operations** | Critical tasks requiring human oversight and approval |+| **Testing new environments** | Validate tools and environments work as expected |## Learn More- **Interactive examples**: Try human-in-the-loop control with sample tasks-- **Training data pipelines**: Learn how to convert human demonstrations into model training data+- **Training data pipelines**: Learn how to convert human demonstrations into model training data- **Evaluation frameworks**: Build human-validated test suites for your agents- **API documentation**: Full reference for human agent configuration@@ -207,4 +216,4 @@ Ready to put humans back in the loop? The most sophisticated AI system knows whe----*Questions about human-in-the-loop agents? Join the conversation in our [Discord community](https://discord.gg/cua-ai) or check out our [documentation](https://docs.trycua.com/docs/agent-sdk/supported-agents/human-in-the-loop).*+_Questions about human-in-the-loop agents? Join the conversation in our [Discord community](https://discord.gg/cua-ai) or check out our [documentation](https://docs.trycua.com/docs/agent-sdk/supported-agents/human-in-the-loop)._diff --git a/blog/introducing-cua-cloud-containers.md b/blog/introducing-cua-cloud-containers.mdindex 1555da43ac..87ef62b04a 100644--- a/blog/introducing-cua-cloud-containers.md+++ b/blog/introducing-cua-cloud-containers.md@@ -1,6 +1,6 @@# Introducing Cua Cloud Sandbox: Computer-Use Agents in the Cloud-*Published on May 28, 2025 by Francesco Bonacci*+_Published on May 28, 2025 by Francesco Bonacci_Welcome to the next chapter in our Computer-Use Agent journey! In [Part 1](./build-your-own-operator-on-macos-1), we showed you how to build your own Operator on macOS. In [Part 2](./build-your-own-operator-on-macos-2), we explored the cua-agent framework. Today, we're excited to introduce **Cua Cloud Sandbox** – the easiest way to deploy Computer-Use Agents at scale.@@ -14,9 +14,9 @@ Think of Cua Cloud as **Docker for Computer-Use Agents**. Instead of managing VM## Why Cua Cloud Sandbox?-Four months ago, we launched [**Lume**](https://github.com/trycua/cua/tree/main/libs/lume) and [**Cua**](https://github.com/trycua/cua) with the goal to bring sandboxed VMs and Computer-Use Agents on Apple Silicon. The developer's community response was incredible 🎉+Four months ago, we launched [**Lume**](https://github.com/trycua/cua/tree/main/libs/lume) and [**Cua**](https://github.com/trycua/cua) with the goal to bring sandboxed VMs and Computer-Use Agents on Apple Silicon. The developer's community response was incredible 🎉-Going from prototype to production revealed a problem though: **local macOS VMs don't scale**, neither are they easily portable.+Going from prototype to production revealed a problem though: **local macOS VMs don't scale**, neither are they easily portable.Our Discord community, YC peers, and early pilot customers kept hitting the same issues. Storage constraints meant **20-40GB per VM** filled laptops fast. Different hardware architectures (Apple Silicon ARM vs Intel x86) prevented portability of local workflows. Every new user lost a day to setup and configuration.@@ -55,7 +55,7 @@ async def run_cloud_agent():name=os.getenv("CUA_CONTAINER_NAME"),provider_type=VMProviderType.CLOUD,)-+# Create an agent with your preferred loopagent = ComputerAgent(model="openai/gpt-4o",@@ -63,7 +63,7 @@ async def run_cloud_agent():verbosity=logging.INFO,tools=[computer])-+# Run a taskasync for result in agent.run("Open Chrome and search for AI news"):print(f"Response: {result.get('text')}")@@ -102,14 +102,14 @@ async def github_automation():name="github-automation",provider_type=VMProviderType.CLOUD,)-+agent = ComputerAgent(model="openai/gpt-4o",save_trajectory=True,verbosity=logging.INFO,tools=[computer])-+tasks = ["Look for a repository named trycua/cua on GitHub.","Check the open issues, open the most recent one and read it.",@@ -119,17 +119,17 @@ async def github_automation():"Commit the changes with a descriptive message.","Create a pull request."]-+for i, task in enumerate(tasks):print(f"\nExecuting task {i+1}/{len(tasks)}: {task}")async for result in agent.run(task):print(f"Response: {result.get('text')}")-+# Check if any tools were usedtools = result.get('tools')if tools:print(f"Tools used: {tools}")-+print(f"Task {i+1} completed")# Run the automation@@ -153,13 +153,13 @@ async def scrape_website(site_name, url):name=f"scraper-{site_name}",provider_type=VMProviderType.CLOUD,)-+agent = ComputerAgent(model="openai/gpt-4o",save_trajectory=True,tools=[computer])-+results = []tasks = [f"Navigate to {url}",@@ -167,7 +167,7 @@ async def scrape_website(site_name, url):"Take a screenshot of the page","Save the extracted data to a file"]-+for task in tasks:async for result in agent.run(task):results.append({@@ -175,7 +175,7 @@ async def scrape_website(site_name, url):'task': task,'response': result.get('text')})-+return resultsasync def parallel_scraping():@@ -185,11 +185,11 @@ async def parallel_scraping():("HackerNews", "https://news.ycombinator.com"),("TechCrunch", "https://techcrunch.com")]-+# Run all scraping tasks in paralleltasks = [scrape_website(name, url) for name, url in sites]results = await asyncio.gather(*tasks)-+# Process resultsfor site_results in results:print(f"\nResults from {site_results[0]['site']}:")diff --git a/blog/lume-to-containerization.md b/blog/lume-to-containerization.mdindex 7a77953613..ca74286d91 100644--- a/blog/lume-to-containerization.md+++ b/blog/lume-to-containerization.md@@ -1,6 +1,6 @@# From Lume to Containerization: Our Journey Meets Apple's Vision-*Published on June 10, 2025 by Francesco Bonacci*+_Published on June 10, 2025 by Francesco Bonacci_Yesterday, Apple announced their new [Containerization framework](https://github.com/apple/containerization) at WWDC. Since then, our Discord and X users have been asking what this means for Cua virtualization capabilities on Apple Silicon. We've been working in this space for months - from [Lume](https://github.com/trycua/cua/tree/main/libs/lume) to [Lumier](https://github.com/trycua/cua/tree/main/libs/lumier) to [Cua Cloud Sandbox](./introducing-cua-cloud-containers). Here's our take on Apple's announcement.@@ -40,6 +40,7 @@ How Apple's Framework Works:```Why is this better?+- **Better security**: Each container is completely separate- **Better performance**: Each container gets its own resources- **Real isolation**: If one container has problems, others aren't affected@@ -71,6 +72,7 @@ While Apple's new framework focuses on containers, we've been building VM manage[Lume](https://github.com/trycua/cua/tree/main/libs/lume) is our command-line tool for creating and managing VMs on Apple Silicon. We built it because setting up VMs on macOS was too complicated.What Lume does:+- **Direct control**: Works directly with Apple's Virtualization framework- **Ready-to-use images**: Start a macOS or Linux VM with one command- **API server**: Control VMs from other programs (runs on port 7777)@@ -91,6 +93,7 @@ lume run macos-sequoia-vanilla:latest[Lumier](https://github.com/trycua/lumier) works differently. It lets you use Docker commands to manage VMs. But here's the key: **Docker is just for packaging, not for isolation**.What makes Lumier useful:+- **Familiar commands**: If you know Docker, you know Lumier- **Web access**: Connect to your VM through a browser- **Save your work**: VMs remember their state@@ -127,6 +130,7 @@ Docker → Lume → Full VM → Mac Hardware### When to Use What**Apple's Containerization**+- ✅ Perfect for: Running containers with maximum security- ✅ Starts in under a second- ✅ Uses less memory and CPU@@ -134,6 +138,7 @@ Docker → Lume → Full VM → Mac Hardware- ❌ Only for containers, not full VMs**Lume**+- ✅ Perfect for: Development and testing- ✅ Full control over macOS/Linux VMs- ✅ Works on current macOS versions@@ -141,6 +146,7 @@ Docker → Lume → Full VM → Mac Hardware- ❌ Uses more resources than containers**Lumier**+- ✅ Perfect for: Teams already using Docker- ✅ Easy to share and deploy- ✅ Access through your browser@@ -173,4 +179,4 @@ Apple's announcement confirms we're on the right path. Here's what we're looking----*Questions about virtualization on Apple Silicon? Come chat with us on Discord!*\ No newline at end of file+_Questions about virtualization on Apple Silicon? Come chat with us on Discord!_diff --git a/blog/sandboxed-python-execution.md b/blog/sandboxed-python-execution.mdindex c7b115c428..e0eb8391e5 100644--- a/blog/sandboxed-python-execution.md+++ b/blog/sandboxed-python-execution.md@@ -1,6 +1,6 @@# Sandboxed Python Execution: Run Code Safely in Cua Containers-*Published on June 23, 2025 by Dillon DuPont*+_Published on June 23, 2025 by Dillon DuPont_Cua's computer-use capabilities that we touched on in [Building your own Operator on macOS - Part 2](build-your-own-operator-on-macos-2.md) – your AI agents can click, scroll, type, and interact with any desktop application. But what if your agent needs to do more than just UI automation? What if it needs to process data, make API calls, analyze images, or run complex logic alongside those UI interactions, within the same virtual environment?@@ -49,15 +49,19 @@ What's happening here? When you call `greet_and_print()`, Cua extracts the functCua's sandboxed execution system employs several key architectural components:### 1. Source Code Extraction+Cua uses Python's `inspect.getsource()` to extract your function's source code and reconstruct the function definition in the remote environment.### 2. Virtual Environment Isolation+Each sandboxed function runs in a named virtual environment within the container. This provides complete dependency isolation between different functions and their respective environments.### 3. Data Serialization and Transport+Arguments and return values are serialized as JSON and transported between the host and container. This ensures compatibility across different Python versions and execution environments.### 4. Comprehensive Error Handling+The system captures both successful results and exceptions, preserving stack traces and error information for debugging purposes.## Getting your sandbox ready@@ -73,10 +77,10 @@ async def main():# Fire up the computercomputer = Computer()await computer.run()-+# Make it the default for all sandboxed functionsset_default_computer(computer)-+# Install some packages in a virtual environmentawait computer.venv_install("demo_venv", ["requests", "beautifulsoup4"])```@@ -104,7 +108,7 @@ def automate_browser_with_playwright():import timeimport base64from datetime import datetime-+try:with sync_playwright() as p:# Launch browser (visible, because why not?)@@ -112,68 +116,68 @@ def automate_browser_with_playwright():headless=False,args=['--no-sandbox', '--disable-dev-shm-usage'])-+page = browser.new_page()page.set_viewport_size({"width": 1280, "height": 720})-+actions = []screenshots = {}-+# Let's visit example.com and poke aroundpage.goto("https://example.com")actions.append("Navigated to example.com")-+# Grab a screenshot because screenshots are coolscreenshot_bytes = page.screenshot(full_page=True)screenshots["initial"] = base64.b64encode(screenshot_bytes).decode()-+# Get some basic infotitle = page.title()actions.append(f"Page title: {title}")-+# Find links and headingstry:links = page.locator("a").all()link_texts = [link.text_content() for link in links[:5]]actions.append(f"Found {len(links)} links: {link_texts}")-+headings = page.locator("h1, h2, h3").all()heading_texts = [h.text_content() for h in headings[:3]]actions.append(f"Found headings: {heading_texts}")-+except Exception as e:actions.append(f"Element interaction error: {str(e)}")-+# Let's try a form for good measuretry:page.goto("https://httpbin.org/forms/post")actions.append("Navigated to form page")-+# Fill out the formpage.fill('input[name="custname"]', "Test User from Sandboxed Environment")page.fill('input[name="custtel"]', "555-0123")page.fill('input[name="custemail"]', "[email protected]")page.select_option('select[name="size"]', "large")-+actions.append("Filled out form fields")-+# Submit and see what happenspage.click('input[type="submit"]')page.wait_for_load_state("networkidle")-+actions.append("Submitted form")-+except Exception as e:actions.append(f"Form interaction error: {str(e)}")-+browser.close()-+return {"actions_performed": actions,"screenshots": screenshots,"success": True}-+except Exception as e:return {"error": f"Browser automation failed: {str(e)}"}@@ -196,9 +200,9 @@ def security_audit_tool(code_snippet):"""Analyze code for potential security issues"""import astimport re-+issues = []-+# Check for the usual suspectsdangerous_patterns = [(r'eval\s*\(', "Use of eval() function"),@@ -207,11 +211,11 @@ def security_audit_tool(code_snippet):(r'subprocess\.', "Subprocess usage"),(r'os\.system\s*\(', "OS system call"),]-+for pattern, description in dangerous_patterns:if re.search(pattern, code_snippet):issues.append(description)-+# Get fancy with AST analysistry:tree = ast.parse(code_snippet)@@ -222,7 +226,7 @@ def security_audit_tool(code_snippet):issues.append(f"Dangerous function call: {node.func.id}")except SyntaxError:issues.append("Syntax error in code")-+return {"security_issues": issues,"risk_level": "HIGH" if len(issues) > 2 else "MEDIUM" if issues else "LOW"@@ -245,34 +249,34 @@ def take_screenshot_and_analyze():import base64from PIL import ImageGrabfrom datetime import datetime-+try:# Grab the screenscreenshot = ImageGrab.grab()-+# Convert to base64 for easy transportbuffer = io.BytesIO()screenshot.save(buffer, format='PNG')screenshot_data = base64.b64encode(buffer.getvalue()).decode()-+# Get some basic infoscreen_info = {"size": screenshot.size,"mode": screenshot.mode,"timestamp": datetime.now().isoformat()}-+# Analyze the colors (because why not?)colors = screenshot.getcolors(maxcolors=256*256*256)dominant_color = max(colors, key=lambda x: x[0])[1] if colors else None-+return {"screenshot_base64": screenshot_data,"screen_info": screen_info,"dominant_color": dominant_color,"unique_colors": len(colors) if colors else 0}-+except Exception as e:return {"error": f"Screenshot failed: {str(e)}"}@@ -287,6 +291,7 @@ print("Desktop analysis complete!")## Pro tips for sandboxed success### Keep it self-contained+Always put your imports inside the function. Trust us on this one:```python@@ -294,12 +299,13 @@ Always put your imports inside the function. Trust us on this one:def good_function():import os # Import inside the functionimport json-+# Your code herereturn {"result": "success"}```### Install dependencies first+Don't forget to install packages before using them:```python@@ -314,13 +320,14 @@ def data_analysis():```### Use descriptive environment names+Future you will thank you:```python@sandboxed("data_processing_env")def process_data(): pass-@sandboxed("web_scraping_env")+@sandboxed("web_scraping_env")def scrape_site(): pass@sandboxed("ml_training_env")@@ -328,6 +335,7 @@ def train_model(): pass```### Always handle errors gracefully+Things break. Plan for it:```python@@ -345,6 +353,7 @@ def robust_function(data):Let's be honest – there's some overhead here. Code needs to be serialized, sent over the network, and executed remotely. But for most use cases, the benefits far outweigh the costs.If you're building something performance-critical, consider:+- Batching multiple operations into a single sandboxed function- Minimizing data transfer between host and container- Using persistent virtual environments@@ -369,4 +378,4 @@ Happy coding (safely)!----*Want to dive deeper? Check out our [sandboxed functions examples](https://github.com/trycua/cua/blob/main/examples/sandboxed_functions_examples.py) and [virtual environment tests](https://github.com/trycua/cua/blob/main/tests/venv.py) on GitHub. Questions? Come chat with us on Discord!*+_Want to dive deeper? Check out our [sandboxed functions examples](https://github.com/trycua/cua/blob/main/examples/sandboxed_functions_examples.py) and [virtual environment tests](https://github.com/trycua/cua/blob/main/tests/venv.py) on GitHub. Questions? Come chat with us on Discord!_diff --git a/blog/training-computer-use-models-trajectories-1.md b/blog/training-computer-use-models-trajectories-1.mdindex b5cafb6feb..040eaea4df 100644--- a/blog/training-computer-use-models-trajectories-1.md+++ b/blog/training-computer-use-models-trajectories-1.md@@ -1,6 +1,6 @@# Training Computer-Use Models: Creating Human Trajectories with Cua-*Published on May 1, 2025 by Dillon DuPont*+_Published on May 1, 2025 by Dillon DuPont_In our previous posts, we covered [building your own Computer-Use Operator](build-your-own-operator-on-macos-1) and [using the Agent framework](build-your-own-operator-on-macos-2) to simplify development. Today, we'll focus on a critical aspect of improving computer-use agents and models: gathering high-quality demonstration data using Cua's Computer-Use Interface (CUI) and its Gradio UI to create and share human-generated trajectories.@@ -8,10 +8,10 @@ Why is this important? Underlying models used by Computer-use agents need exampl<video src="https://github.com/user-attachments/assets/c586d460-3877-4b5f-a736-3248886d2134" controls width="600"></video>-## What You'll LearnBy the end of this tutorial, you'll be able to:+- Set up the Computer-Use Interface (CUI) with Gradio UI support- Record your own computer interaction trajectories- Organize and tag your demonstrations@@ -19,6 +19,7 @@ By the end of this tutorial, you'll be able to:- Contribute to improving computer-use AI for everyone**Prerequisites:**+- macOS Sonoma (14.0) or later- Python 3.10+- Basic familiarity with Python and terminal commands@@ -38,6 +39,7 @@ Human trajectories, in the context of Computer-use AI Agents, are recordings of- Time spent on different elementsThese trajectories serve as examples for AI models to learn from, helping them understand the relationship between:+1. The visual state of the screen2. The user's goal or task3. The most appropriate action to take@@ -59,17 +61,19 @@ By contributing high-quality demonstrations, you're helping to create more capabThe Computer-Use Interface includes an optional Gradio UI specifically designed to make recording and sharing demonstrations easy. Let's set it up:1. **Create a Python environment** (optional but recommended):+```bash# Using condaconda create -n cua-trajectories python=3.10conda activate cua-trajectories-+# Using venvpython -m venv cua-trajectoriessource cua-trajectories/bin/activate # On macOS/Linux```2. **Install the CUI package with UI support**:+```bashpip install "cua-computer[ui]"```@@ -145,6 +149,7 @@ Effective tagging and organization make your demonstrations more valuable to res### Task-Based TagsDescribe what the demonstration accomplishes:+- `web-browsing`- `document-editing`- `file-management`@@ -154,6 +159,7 @@ Describe what the demonstration accomplishes:### Application TagsIdentify the applications used:+- `finder`- `safari`- `notes`@@ -163,6 +169,7 @@ Identify the applications used:### Complexity TagsIndicate the difficulty level:+- `beginner`- `intermediate`- `advanced`@@ -171,6 +178,7 @@ Indicate the difficulty level:### UI Element TagsHighlight specific UI interactions:+- `drag-and-drop`- `menu-navigation`- `form-filling`@@ -229,11 +237,11 @@ from computer import Computercomputer = Computer(os_type="macos", display="1024x768", memory="8GB", cpu="4")try:await computer.run()-+screenshot = await computer.interface.screenshot()with open("screenshot.png", "wb") as f:f.write(screenshot)-+await computer.interface.move_cursor(100, 100)await computer.interface.left_click()await computer.interface.right_click(300, 300)@@ -280,6 +288,7 @@ You can also learn from existing trajectory datasets contributed by the communit### SummaryIn this guide, we've covered how to:+- Set up the Computer-Use Interface with Gradio UI- Record high-quality human demonstrations- Organize and tag your trajectoriesdiff --git a/blog/trajectory-viewer.md b/blog/trajectory-viewer.mdindex 697eda3ae4..20003708d5 100644--- a/blog/trajectory-viewer.md+++ b/blog/trajectory-viewer.md@@ -1,6 +1,6 @@# Trajectory Viewer for Cua-*Published on May 13, 2025 by Dillon DuPont*+_Published on May 13, 2025 by Dillon DuPont_Don’t forget to check out [Part 1: Building your own Computer-Use Operator](build-your-own-operator-on-macos-1) and [Part 2: Using the Agent framework](build-your-own-operator-on-macos-2) for setting up your Cua environment and basic tips and tricks!@@ -18,7 +18,7 @@ Think of a trajectory as a detailed video recording of your agent’s journey:- **Observations**: What did the agent see (the exact screen content) at each point in time?- **Actions**: What clicks, keystrokes, or commands did it perform in response?- **Decisions**: Which options did it choose, and why?-Especially for longer and more complex tasks, your agent will make multiple steps, take multiple actions, and make multiple observations. By examining this record, you can pinpoint where things go right, and more importantly, where they go wrong.+ Especially for longer and more complex tasks, your agent will make multiple steps, take multiple actions, and make multiple observations. By examining this record, you can pinpoint where things go right, and more importantly, where they go wrong.## So, what’s Cua’s Trajectory Viewer and why use it?diff --git a/blog/ubuntu-docker-support.md b/blog/ubuntu-docker-support.mdindex bd3c4a4d89..69b6b09ec2 100644--- a/blog/ubuntu-docker-support.md+++ b/blog/ubuntu-docker-support.md@@ -1,6 +1,6 @@# Ubuntu Docker Support in Cua with Kasm-*Published Aug 26, 2025 by Francesco Bonacci*+_Published Aug 26, 2025 by Francesco Bonacci_Today we’re shipping **Ubuntu Docker support** in Cua. You get a full Linux desktop inside a Docker container, viewable right in your browser—no VM spin-up, no extra clients. It behaves the same on macOS, Windows, and Linux.@@ -16,17 +16,17 @@ We wanted something lightweight, isolated, and identical across machines. So weShort answer: **portability, startup time, and ops friction.**-* **Runs everywhere, no hypervisor drama.** KVM needs Linux; Hyper-V/Virtualization.Framework setups vary by host and policy. Docker is ubiquitous across macOS/Windows/Linux and allowed in most CI runners—so your GUI env actually runs where your team works.-* **Faster boot & smaller footprints.** Containers cold-start in seconds and images are GB-scale; VMs tend to be minutes and tens of GB. That matters for parallel agents, CI, and local iteration.-* **Lower ops overhead.** No nested virt, kernel modules, or privileged host tweaks that many orgs (and cloud runners) block. Pull → run → browser.-* **Same image, everywhere.** One Docker image gives you an identical desktop on every dev laptop and in CI.-* **Web-first access out of the box.** KasmVNC serves the desktop over HTTP—no extra VNC/RDP clients or SPICE config.+- **Runs everywhere, no hypervisor drama.** KVM needs Linux; Hyper-V/Virtualization.Framework setups vary by host and policy. Docker is ubiquitous across macOS/Windows/Linux and allowed in most CI runners—so your GUI env actually runs where your team works.+- **Faster boot & smaller footprints.** Containers cold-start in seconds and images are GB-scale; VMs tend to be minutes and tens of GB. That matters for parallel agents, CI, and local iteration.+- **Lower ops overhead.** No nested virt, kernel modules, or privileged host tweaks that many orgs (and cloud runners) block. Pull → run → browser.+- **Same image, everywhere.** One Docker image gives you an identical desktop on every dev laptop and in CI.+- **Web-first access out of the box.** KasmVNC serves the desktop over HTTP—no extra VNC/RDP clients or SPICE config.-**When we *do* reach for QEMU/KVM:**+**When we _do_ reach for QEMU/KVM:**-* You need **true OS isolation** or to run **non-Linux** guests.-* You want **kernel-level features** or **device/GPU passthrough** (VFIO).-* You’re optimizing for **hardware realism** over startup speed and density.+- You need **true OS isolation** or to run **non-Linux** guests.+- You want **kernel-level features** or **device/GPU passthrough** (VFIO).+- You’re optimizing for **hardware realism** over startup speed and density.For this release, the goal was a **cross-platform Linux desktop that feels instant and identical** across local dev and CI. Containers + KasmVNC hit that sweet spot.@@ -174,10 +174,10 @@ await computer.run()## Links-* **Docker Provider Docs:** [https://docs.trycua.com/computers/docker](https://docs.trycua.com/computers/docker)-* **KasmVNC:** [https://github.com/kasmtech/KasmVNC](https://github.com/kasmtech/KasmVNC)-* **Container Source:** [https://github.com/trycua/cua/tree/main/libs/kasm](https://github.com/trycua/cua/tree/main/libs/kasm)-* **Computer SDK:** [https://docs.trycua.com/docs/computer-sdk/computers](https://docs.trycua.com/docs/computer-sdk/computers)-* **Discord:** [https://discord.gg/cua-ai](https://discord.gg/cua-ai)+- **Docker Provider Docs:** [https://docs.trycua.com/computers/docker](https://docs.trycua.com/computers/docker)+- **KasmVNC:** [https://github.com/kasmtech/KasmVNC](https://github.com/kasmtech/KasmVNC)+- **Container Source:** [https://github.com/trycua/cua/tree/main/libs/kasm](https://github.com/trycua/cua/tree/main/libs/kasm)+- **Computer SDK:** [https://docs.trycua.com/docs/computer-sdk/computers](https://docs.trycua.com/docs/computer-sdk/computers)+- **Discord:** [https://discord.gg/cua-ai](https://discord.gg/cua-ai)-Questions or weird edge cases? Ping us on Discord—we’re curious to see what you build.\ No newline at end of file+Questions or weird edge cases? Ping us on Discord—we’re curious to see what you build.diff --git a/blog/windows-sandbox.md b/blog/windows-sandbox.mdindex f892680495..ef5776113f 100644--- a/blog/windows-sandbox.md+++ b/blog/windows-sandbox.md@@ -1,10 +1,10 @@# Your Windows PC is Already the Perfect Development Environment for Computer-Use Agents-*Published on June 18, 2025 by Dillon DuPont*+_Published on June 18, 2025 by Dillon DuPont_-Over the last few months, our enterprise users kept asking the same type of question: *"When are you adding support for AutoCAD?"* *"What about SAP integration?"* *"Can you automate our MES system?"* - each request was for different enterprise applications we'd never heard of.+Over the last few months, our enterprise users kept asking the same type of question: _"When are you adding support for AutoCAD?"_ _"What about SAP integration?"_ _"Can you automate our MES system?"_ - each request was for different enterprise applications we'd never heard of.-At first, we deflected. We've been building Cua to work across different environments - from [Lume for macOS VMs](./lume-to-containerization) to cloud containers. But these requests kept piling up. AutoCAD automation. SAP integration. Specialized manufacturing systems.+At first, we deflected. We've been building Cua to work across different environments - from [Lume for macOS VMs](./lume-to-containerization) to cloud containers. But these requests kept piling up. AutoCAD automation. SAP integration. Specialized manufacturing systems.Then it hit us: **they all ran exclusively on Windows**.@@ -80,6 +80,7 @@ python -m agent.ui```**What you get**:+- Visual interface in your browser- Real-time agent action viewing- Natural language task instructions@@ -101,21 +102,21 @@ async def test_windows_agent():os_type="windows",memory="4GB",)-+# Start the VM (~35s)await computer.run()-+# Create agent with your preferred modelagent = ComputerAgent(model="openai/computer-use-preview",save_trajectory=True,tools=[computer])-+# Give it a taskasync for result in agent.run("Open Calculator and compute 15% tip on $47.50"):print(f"Agent action: {result}")-+# Shutdown the VMawait computer.stop()@@ -123,6 +124,7 @@ asyncio.run(test_windows_agent())```**What you get**:+- Full programmatic control- Custom agent workflows- Integration with your existing code@@ -141,6 +143,7 @@ asyncio.run(test_windows_agent())Let's see how different testing approaches stack up:### Windows Sandbox + Cua+- **Perfect for**: Quick testing and development- **Cost**: Free (built into Windows)- **Setup time**: Under 5 minutes@@ -149,6 +152,7 @@ Let's see how different testing approaches stack up:- **Requires**: Windows 10/11 with 4GB+ RAM### Traditional VMs+- **Perfect for**: Complex testing scenarios- **Full customization**: Any Windows version- **Heavy resource usage**: Slow to start/stop@@ -160,6 +164,7 @@ Let's see how different testing approaches stack up:Here's what our enterprise users are building with Windows Sandbox:### CAD and Engineering Automation+```python# Example: AutoCAD drawing automationtask = """@@ -172,6 +177,7 @@ task = """```### Manufacturing and ERP Integration+```python# Example: SAP workflow automationtask = """@@ -184,6 +190,7 @@ task = """```### Financial Software Automation+```python# Example: Trading platform automationtask = """@@ -196,6 +203,7 @@ task = """```### Legacy Windows Application Integration+```python# Example: Custom Windows application automationtask = """@@ -210,12 +218,14 @@ task = """## System Requirements and Performance### What You Need+- **Windows 10/11**: Any edition that supports Windows Sandbox- **Memory**: 4GB minimum (8GB recommended for CAD/professional software)- **CPU**: Virtualization support (enabled by default on modern systems)- **Storage**: A few GB free space### Performance Tips+- **Close unnecessary applications** before starting Windows Sandbox- **Allocate appropriate memory** based on your RPA workflow complexity- **Use SSD storage** for faster sandbox startup@@ -234,4 +244,4 @@ But for development, prototyping, and learning Windows RPA workflows, **Windows----*Ready to see AI agents control your Windows applications? Come share your testing experiences on Discord!*+_Ready to see AI agents control your Windows applications? Come share your testing experiences on Discord!_diff --git a/docs/content/docs/agent-sdk/benchmarks/meta.json b/docs/content/docs/agent-sdk/benchmarks/meta.jsonindex 3573a89226..8067bb0114 100644--- a/docs/content/docs/agent-sdk/benchmarks/meta.json+++ b/docs/content/docs/agent-sdk/benchmarks/meta.json@@ -1,9 +1,3 @@{- "pages": [- "introduction",- "screenspot-v2",- "screenspot-pro",- "interactive",- "osworld-verified"- ]-}\ No newline at end of file+ "pages": ["introduction", "screenspot-v2", "screenspot-pro", "interactive", "osworld-verified"]+}diff --git a/docs/content/docs/agent-sdk/callbacks/meta.json b/docs/content/docs/agent-sdk/callbacks/meta.jsonindex c9a072b08d..b1b7085aba 100644--- a/docs/content/docs/agent-sdk/callbacks/meta.json+++ b/docs/content/docs/agent-sdk/callbacks/meta.json@@ -1,11 +1,5 @@{- "title": "Callbacks",- "description": "Extending agents with callback hooks and built-in handlers",- "pages": [- "agent-lifecycle",- "trajectories",- "logging",- "cost-saving",- "pii-anonymization"- ]+ "title": "Callbacks",+ "description": "Extending agents with callback hooks and built-in handlers",+ "pages": ["agent-lifecycle", "trajectories", "logging", "cost-saving", "pii-anonymization"]}diff --git a/docs/content/docs/agent-sdk/meta.json b/docs/content/docs/agent-sdk/meta.jsonindex 1083fc25bd..b2b75fa3ec 100644--- a/docs/content/docs/agent-sdk/meta.json+++ b/docs/content/docs/agent-sdk/meta.json@@ -1,20 +1,20 @@{- "title": "Agent SDK",- "description": "Build computer-using agents with the Agent SDK",- "pages": [- "agent-loops",- "supported-agents",- "supported-model-providers",- "chat-history",- "message-format",- "customizing-computeragent",- "callbacks",- "custom-tools",- "custom-computer-handlers",- "prompt-caching",- "usage-tracking",- "benchmarks",- "migration-guide",- "integrations"- ]+ "title": "Agent SDK",+ "description": "Build computer-using agents with the Agent SDK",+ "pages": [+ "agent-loops",+ "supported-agents",+ "supported-model-providers",+ "chat-history",+ "message-format",+ "customizing-computeragent",+ "callbacks",+ "custom-tools",+ "custom-computer-handlers",+ "prompt-caching",+ "usage-tracking",+ "benchmarks",+ "migration-guide",+ "integrations"+ ]}diff --git a/docs/content/docs/agent-sdk/supported-agents/meta.json b/docs/content/docs/agent-sdk/supported-agents/meta.jsonindex 5d50b1242f..e812c4fbc1 100644--- a/docs/content/docs/agent-sdk/supported-agents/meta.json+++ b/docs/content/docs/agent-sdk/supported-agents/meta.json@@ -1,10 +1,5 @@{- "title": "Supported Agents",- "description": "Models and configurations supported by the Agent SDK",- "pages": [- "computer-use-agents",- "grounding-models",- "composed-agents",- "human-in-the-loop"- ]+ "title": "Supported Agents",+ "description": "Models and configurations supported by the Agent SDK",+ "pages": ["computer-use-agents", "grounding-models", "composed-agents", "human-in-the-loop"]}diff --git a/docs/content/docs/computer-sdk/meta.json b/docs/content/docs/computer-sdk/meta.jsonindex f09c60573e..ab69fa17f3 100644--- a/docs/content/docs/computer-sdk/meta.json+++ b/docs/content/docs/computer-sdk/meta.json@@ -1,11 +1,5 @@{- "title": "Computer SDK",- "description": "Build computer-using agents with the Computer SDK",- "pages": [- "computers",- "cloud-vm-management",- "commands",- "computer-ui",- "sandboxed-python"- ]+ "title": "Computer SDK",+ "description": "Build computer-using agents with the Computer SDK",+ "pages": ["computers", "cloud-vm-management", "commands", "computer-ui", "sandboxed-python"]}diff --git a/docs/content/docs/example-usecases/meta.json b/docs/content/docs/example-usecases/meta.jsonindex 13cbe81e27..60bba1c3d9 100644--- a/docs/content/docs/example-usecases/meta.json+++ b/docs/content/docs/example-usecases/meta.json@@ -1,7 +1,5 @@{- "title": "Example Use Cases",- "description": "Real-world examples of building with Cua",- "pages": [- "form-filling"- ]+ "title": "Example Use Cases",+ "description": "Real-world examples of building with Cua",+ "pages": ["form-filling"]}diff --git a/docs/content/docs/libraries/lume/faq.md b/docs/content/docs/libraries/lume/faq.mdindex 98d6b76674..4009a94ec2 100644--- a/docs/content/docs/libraries/lume/faq.md+++ b/docs/content/docs/libraries/lume/faq.md@@ -17,10 +17,12 @@ Lume follows the XDG Base Directory specification for the configuration file:- Configuration is stored in `$XDG_CONFIG_HOME/lume/config.yaml` (defaults to `~/.config/lume/config.yaml`)By default, other data is stored in:+- VM data: `~/.lume`- Cache files: `~/.lume/cache`The config file contains settings for:+- VM storage locations and the default location- Cache directory location- Whether caching is enabled@@ -88,6 +90,7 @@ lume delete <name>### How to Install macOS from an IPSW Image#### Create a new macOS VM using the latest supported IPSW image:+Run the following command to create a new macOS virtual machine using the latest available IPSW image:```bash@@ -95,6 +98,7 @@ lume create <name> --os macos --ipsw latest```#### Create a new macOS VM using a specific IPSW image:+To create a macOS virtual machine from an older or specific IPSW file, first download the desired IPSW (UniversalMac) from a trusted source.Then, use the downloaded IPSW path:diff --git a/docs/content/docs/libraries/lume/meta.json b/docs/content/docs/libraries/lume/meta.jsonindex 5f4d907a03..42aeac1d01 100644--- a/docs/content/docs/libraries/lume/meta.json+++ b/docs/content/docs/libraries/lume/meta.json@@ -1,9 +1,3 @@{- "pages": [- "installation",- "prebuilt-images",- "cli-reference",- "http-api",- "faq"- ]+ "pages": ["installation", "prebuilt-images", "cli-reference", "http-api", "faq"]}diff --git a/docs/content/docs/libraries/lumier/meta.json b/docs/content/docs/libraries/lumier/meta.jsonindex f6a8946cc1..bfe2572455 100644--- a/docs/content/docs/libraries/lumier/meta.json+++ b/docs/content/docs/libraries/lumier/meta.json@@ -1,8 +1,3 @@{- "pages": [- "installation",- "docker",- "docker-compose",- "building-lumier"- ]+ "pages": ["installation", "docker", "docker-compose", "building-lumier"]}diff --git a/docs/content/docs/libraries/mcp-server/meta.json b/docs/content/docs/libraries/mcp-server/meta.jsonindex 45fa4ba98e..f5ccb9baee 100644--- a/docs/content/docs/libraries/mcp-server/meta.json+++ b/docs/content/docs/libraries/mcp-server/meta.json@@ -1,10 +1,10 @@{- "pages": [- "installation",- "configuration",- "usage",- "tools",- "client-integrations",- "llm-integrations"- ]-}\ No newline at end of file+ "pages": [+ "installation",+ "configuration",+ "usage",+ "tools",+ "client-integrations",+ "llm-integrations"+ ]+}diff --git a/docs/content/docs/meta.json b/docs/content/docs/meta.jsonindex dc06cc5f79..c3517f0aad 100644--- a/docs/content/docs/meta.json+++ b/docs/content/docs/meta.json@@ -1,19 +1,19 @@{- "title": "Home",- "description": "Documentation Home",- "root": true,- "defaultOpen": true,- "pages": [- "index",- "quickstart-devs",- "quickstart-cli",- "telemetry",- "example-usecases",- "---[BookCopy]Computer Playbook---",- "...computer-sdk",- "---[BookCopy]Agent Playbook---",- "...agent-sdk",- "---[CodeXml]API Reference---",- "...libraries"- ]-}\ No newline at end of file+ "title": "Home",+ "description": "Documentation Home",+ "root": true,+ "defaultOpen": true,+ "pages": [+ "index",+ "quickstart-devs",+ "quickstart-cli",+ "telemetry",+ "example-usecases",+ "---[BookCopy]Computer Playbook---",+ "...computer-sdk",+ "---[BookCopy]Agent Playbook---",+ "...agent-sdk",+ "---[CodeXml]API Reference---",+ "...libraries"+ ]+}diff --git a/docs/package.json b/docs/package.jsonindex d94c168e7b..232e4f47f0 100644--- a/docs/package.json+++ b/docs/package.json@@ -43,4 +43,4 @@"sharp"]}-}\ No newline at end of file+}diff --git a/docs/source.config.ts b/docs/source.config.tsindex c3b9e719fe..dd019e8ff0 100644--- a/docs/source.config.ts+++ b/docs/source.config.ts@@ -1,9 +1,4 @@-import {- defineConfig,- defineDocs,- frontmatterSchema,- metaSchema,-} from 'fumadocs-mdx/config';+import { defineConfig, defineDocs, frontmatterSchema, metaSchema } from 'fumadocs-mdx/config';import { z } from 'zod';// You can customise Zod schemas for frontmatter and `meta.json` herediff --git a/docs/src/app/(home)/[[...slug]]/page.tsx b/docs/src/app/(home)/[[...slug]]/page.tsxindex 085238ef7c..5ea83484e2 100644--- a/docs/src/app/(home)/[[...slug]]/page.tsx+++ b/docs/src/app/(home)/[[...slug]]/page.tsx@@ -1,18 +1,9 @@import { getApiVersions, source } from '@/lib/source';import { getMDXComponents } from '@/mdx-components';import { buttonVariants } from 'fumadocs-ui/components/ui/button';-import {- Popover,- PopoverContent,- PopoverTrigger,-} from 'fumadocs-ui/components/ui/popover';+import { Popover, PopoverContent, PopoverTrigger } from 'fumadocs-ui/components/ui/popover';import { createRelativeLink } from 'fumadocs-ui/mdx';-import {- DocsBody,- DocsDescription,- DocsPage,- DocsTitle,-} from 'fumadocs-ui/page';+import { DocsBody, DocsDescription, DocsPage, DocsTitle } from 'fumadocs-ui/page';import { cn } from 'fumadocs-ui/utils/cn';import { ChevronDown, CodeXml, ExternalLink } from 'lucide-react';import type { Metadata } from 'next';@@ -20,9 +11,7 @@ import Link from 'next/link';import { notFound, redirect } from 'next/navigation';import { PageFeedback } from '@/components/page-feedback';-export default async function Page(props: {- params: Promise<{ slug?: string[] }>;-}) {+export default async function Page(props: { params: Promise<{ slug?: string[] }> }) {const params = await props.params;const slug = params.slug || [];const page = source.getPage(slug);@@ -66,7 +55,8 @@ export default async function Page(props: {xmlns="http://www.w3.org/2000/svg"fill="currentColor"className="h-5"- viewBox="0 0 448 512">+ viewBox="0 0 448 512"+ ><title>Windows</title><path d="M0 93.7l183.6-25.3v177.4H0V93.7zm0 324.6l183.6 25.3V268.4H0v149.9zm203.8 28L448 480V268.4H203.8v177.9zm0-380.6v180.1H448V32L203.8 65.7z" /></svg>@@ -76,7 +66,8 @@ export default async function Page(props: {xmlns="http://www.w3.org/2000/svg"fill="currentColor"className="h-5"- viewBox="0 0 384 512">+ viewBox="0 0 384 512"+ ><title>macOS</title><path d="M318.7 268.7c-.2-36.7 16.4-64.4 50-84.8-18.8-26.9-47.2-41.7-84.7-44.6-35.5-2.8-74.3 20.7-88.5 20.7-15 0-49.4-19.7-76.4-19.7C63.3 141.2 4 184.8 4 273.5q0 39.3 14.4 81.2c12.8 36.7 59 126.7 107.2 125.2 25.2-.6 43-17.9 75.8-17.9 31.8 0 48.3 17.9 76.4 17.9 48.6-.7 90.4-82.5 102.6-119.3-65.2-30.7-61.7-90-61.7-91.9zm-56.6-164.2c27.3-32.4 24.8-61.9 24-72.5-24.1 1.4-52 16.4-67.9 34.9-17.5 19.8-27.8 44.3-25.6 71.9 26.1 2 49.9-11.4 69.5-34.3z" /></svg>@@ -86,7 +77,8 @@ export default async function Page(props: {xmlns="http://www.w3.org/2000/svg"fill="currentColor"className="h-5"- viewBox="0 0 448 512">+ viewBox="0 0 448 512"+ ><title>Linux</title><path d="M220.8 123.3c1 .5 1.8 1.7 3 1.7 1.1 0 2.8-.4 2.9-1.5 .2-1.4-1.9-2.3-3.2-2.9-1.7-.7-3.9-1-5.5-.1-.4 .2-.8 .7-.6 1.1 .3 1.3 2.3 1.1 3.4 1.7zm-21.9 1.7c1.2 0 2-1.2 3-1.7 1.1-.6 3.1-.4 3.5-1.6 .2-.4-.2-.9-.6-1.1-1.6-.9-3.8-.6-5.5 .1-1.3 .6-3.4 1.5-3.2 2.9 .1 1 1.8 1.5 2.8 1.4zM420 403.8c-3.6-4-5.3-11.6-7.2-19.7-1.8-8.1-3.9-16.8-10.5-22.4-1.3-1.1-2.6-2.1-4-2.9-1.3-.8-2.7-1.5-4.1-2 9.2-27.3 5.6-54.5-3.7-79.1-11.4-30.1-31.3-56.4-46.5-74.4-17.1-21.5-33.7-41.9-33.4-72C311.1 85.4 315.7 .1 234.8 0 132.4-.2 158 103.4 156.9 135.2c-1.7 23.4-6.4 41.8-22.5 64.7-18.9 22.5-45.5 58.8-58.1 96.7-6 17.9-8.8 36.1-6.2 53.3-6.5 5.8-11.4 14.7-16.6 20.2-4.2 4.3-10.3 5.9-17 8.3s-14 6-18.5 14.5c-2.1 3.9-2.8 8.1-2.8 12.4 0 3.9 .6 7.9 1.2 11.8 1.2 8.1 2.5 15.7 .8 20.8-5.2 14.4-5.9 24.4-2.2 31.7 3.8 7.3 11.4 10.5 20.1 12.3 17.3 3.6 40.8 2.7 59.3 12.5 19.8 10.4 39.9 14.1 55.9 10.4 11.6-2.6 21.1-9.6 25.9-20.2 12.5-.1 26.3-5.4 48.3-6.6 14.9-1.2 33.6 5.3 55.1 4.1 .6 2.3 1.4 4.6 2.5 6.7v.1c8.3 16.7 23.8 24.3 40.3 23 16.6-1.3 34.1-11 48.3-27.9 13.6-16.4 36-23.2 50.9-32.2 7.4-4.5 13.4-10.1 13.9-18.3 .4-8.2-4.4-17.3-15.5-29.7zM223.7 87.3c9.8-22.2 34.2-21.8 44-.4 6.5 14.2 3.6 30.9-4.3 40.4-1.6-.8-5.9-2.6-12.6-4.9 1.1-1.2 3.1-2.7 3.9-4.6 4.8-11.8-.2-27-9.1-27.3-7.3-.5-13.9 10.8-11.8 23-4.1-2-9.4-3.5-13-4.4-1-6.9-.3-14.6 2.9-21.8zM183 75.8c10.1 0 20.8 14.2 19.1 33.5-3.5 1-7.1 2.5-10.2 4.6 1.2-8.9-3.3-20.1-9.6-19.6-8.4 .7-9.8 21.2-1.8 28.1 1 .8 1.9-.2-5.9 5.5-15.6-14.6-10.5-52.1 8.4-52.1zm-13.6 60.7c6.2-4.6 13.6-10 14.1-10.5 4.7-4.4 13.5-14.2 27.9-14.2 7.1 0 15.6 2.3 25.9 8.9 6.3 4.1 11.3 4.4 22.6 9.3 8.4 3.5 13.7 9.7 10.5 18.2-2.6 7.1-11 14.4-22.7 18.1-11.1 3.6-19.8 16-38.2 14.9-3.9-.2-7-1-9.6-2.1-8-3.5-12.2-10.4-20-15-8.6-4.8-13.2-10.4-14.7-15.3-1.4-4.9 0-9 4.2-12.3zm3.3 334c-2.7 35.1-43.9 34.4-75.3 18-29.9-15.8-68.6-6.5-76.5-21.9-2.4-4.7-2.4-12.7 2.6-26.4v-.2c2.4-7.6 .6-16-.6-23.9-1.2-7.8-1.8-15 .9-20 3.5-6.7 8.5-9.1 14.8-11.3 10.3-3.7 11.8-3.4 19.6-9.9 5.5-5.7 9.5-12.9 14.3-18 5.1-5.5 10-8.1 17.7-6.9 8.1 1.2 15.1 6.8 21.9 16l19.6 35.6c9.5 19.9 43.1 48.4 41 68.9zm-1.4-25.9c-4.1-6.6-9.6-13.6-14.4-19.6 7.1 0 14.2-2.2 16.7-8.9 2.3-6.2 0-14.9-7.4-24.9-13.5-18.2-38.3-32.5-38.3-32.5-13.5-8.4-21.1-18.7-24.6-29.9s-3-23.3-.3-35.2c5.2-22.9 18.6-45.2 27.2-59.2 2.3-1.7 .8 3.2-8.7 20.8-8.5 16.1-24.4 53.3-2.6 82.4 .6-20.7 5.5-41.8 13.8-61.5 12-27.4 37.3-74.9 39.3-112.7 1.1 .8 4.6 3.2 6.2 4.1 4.6 2.7 8.1 6.7 12.6 10.3 12.4 10 28.5 9.2 42.4 1.2 6.2-3.5 11.2-7.5 15.9-9 9.9-3.1 17.8-8.6 22.3-15 7.7 30.4 25.7 74.3 37.2 95.7 6.1 11.4 18.3 35.5 23.6 64.6 3.3-.1 7 .4 10.9 1.4 13.8-35.7-11.7-74.2-23.3-84.9-4.7-4.6-4.9-6.6-2.6-6.5 12.6 11.2 29.2 33.7 35.2 59 2.8 11.6 3.3 23.7 .4 35.7 16.4 6.8 35.9 17.9 30.7 34.8-2.2-.1-3.2 0-4.2 0 3.2-10.1-3.9-17.6-22.8-26.1-19.6-8.6-36-8.6-38.3 12.5-12.1 4.2-18.3 14.7-21.4 27.3-2.8 11.2-3.6 24.7-4.4 39.9-.5 7.7-3.6 18-6.8 29-32.1 22.9-76.7 32.9-114.3 7.2zm257.4-11.5c-.9 16.8-41.2 19.9-63.2 46.5-13.2 15.7-29.4 24.4-43.6 25.5s-26.5-4.8-33.7-19.3c-4.7-11.1-2.4-23.1 1.1-36.3 3.7-14.2 9.2-28.8 9.9-40.6 .8-15.2 1.7-28.5 4.2-38.7 2.6-10.3 6.6-17.2 13.7-21.1 .3-.2 .7-.3 1-.5 .8 13.2 7.3 26.6 18.8 29.5 12.6 3.3 30.7-7.5 38.4-16.3 9-.3 15.7-.9 22.6 5.1 9.9 8.5 7.1 30.3 17.1 41.6 10.6 11.6 14 19.5 13.7 24.6zM173.3 148.7c2 1.9 4.7 4.5 8 7.1 6.6 5.2 15.8 10.6 27.3 10.6 11.6 0 22.5-5.9 31.8-10.8 4.9-2.6 10.9-7 14.8-10.4s5.9-6.3 3.1-6.6-2.6 2.6-6 5.1c-4.4 3.2-9.7 7.4-13.9 9.8-7.4 4.2-19.5 10.2-29.9 10.2s-18.7-4.8-24.9-9.7c-3.1-2.5-5.7-5-7.7-6.9-1.5-1.4-1.9-4.6-4.3-4.9-1.4-.1-1.8 3.7 1.7 6.5z" /></svg>@@ -96,10 +88,7 @@ export default async function Page(props: {<div className="flex flex-row gap-2 items-left">{pypi && (- <a- target="_blank"- href={`https://pypi.org/project/${pypi}/`}- rel="noreferrer">+ <a target="_blank" href={`https://pypi.org/project/${pypi}/`} rel="noreferrer"><imgsrc={`https://img.shields.io/pypi/v/${pypi}?color=blue`}className="h-5"@@ -108,10 +97,7 @@ export default async function Page(props: {</a>)}{npm && (- <a- target="_blank"- href={`https://www.npmjs.com/package/${npm}`}- rel="noreferrer">+ <a target="_blank" href={`https://www.npmjs.com/package/${npm}`} rel="noreferrer"><imgsrc={`https://img.shields.io/npm/v/${npm}?color=bf4c4b`}className="h-5"@@ -138,7 +124,8 @@ export default async function Page(props: {target="_blank"className="inline-flex gap-2 w-fit items-center justify-center rounded-md text-sm font-medium transition-colors duration-100 disabled:pointer-events-none disabled:opacity-50 focus-visible:outline-none hover:bg-fd-accent hover:text-fd-accent-foreground p-1.5 [&_svg]:size-5 text-fd-muted-foreground md:[&_svg]:size-4.5"aria-label="Source"- data-active="false">+ data-active="false"+ ><svg role="img" viewBox="0 0 24 24" fill="currentColor"><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"></path></svg>@@ -162,12 +149,13 @@ export default async function Page(props: {href={link}rel="noreferrer noopener"target="_blank"- className="inline-flex gap-2 w-full items-center rounded-md p-2 text-sm hover:bg-fd-accent hover:text-fd-accent-foreground">+ className="inline-flex gap-2 w-full items-center rounded-md p-2 text-sm hover:bg-fd-accent hover:text-fd-accent-foreground"+ >{link.includes('python')? 'Python': link.includes('typescript')- ? 'TypeScript'- : `Source ${index + 1}`}+ ? 'TypeScript'+ : `Source ${index + 1}`}<ExternalLink className="w-4 h-4 ml-auto" /></a>))}@@ -190,10 +178,7 @@ export default async function Page(props: {};return (- <DocsPage- toc={page.data.toc}- tableOfContent={{ header: tocHeader() }}- full={page.data.full}>+ <DocsPage toc={page.data.toc} tableOfContent={{ header: tocHeader() }} full={page.data.full}><div className="flex flex-row w-full items-start"><div className="flex-1"><div className="flex flex-row w-full">@@ -209,15 +194,14 @@ export default async function Page(props: {size: 'sm',className: 'gap-2',})- )}>+ )}+ >{(() => {// Find the current version labellet currentLabel = 'Current';if (apiVersionSlug.length > 0) {const found = versionItems.find(- (item) =>- item.label !== 'Current' &&- apiVersionSlug[0] === item.label+ (item) => item.label !== 'Current' && apiVersionSlug[0] === item.label);if (found) currentLabel = found.label;}@@ -238,10 +222,8 @@ export default async function Page(props: {: `/api/${apiSection}/${item.label}`;// Highlight current versionconst isCurrent =- (item.label === 'Current' &&- apiVersionSlug.length === 0) ||- (item.label !== 'Current' &&- apiVersionSlug[0] === item.label);+ (item.label === 'Current' && apiVersionSlug.length === 0) ||+ (item.label !== 'Current' && apiVersionSlug[0] === item.label);return (<Linkkey={item.label}@@ -249,7 +231,8 @@ export default async function Page(props: {className={cn('px-3 py-1 rounded hover:bg-fd-muted',isCurrent && 'font-bold bg-fd-muted'- )}>+ )}+ >API version: {item.label}</Link>);@@ -259,9 +242,7 @@ export default async function Page(props: {)}</div></div>- <DocsDescription className="text-md mt-1">- {page.data.description}- </DocsDescription>+ <DocsDescription className="text-md mt-1">{page.data.description}</DocsDescription></div></div><DocsBody>@@ -290,8 +271,7 @@ export async function generateMetadata(props: {let title = `${page.data.title} | Cua Docs`;if (page.url.includes('api')) title = `${page.data.title} | Cua API Docs`;- if (page.url.includes('guide'))- title = ` Guide: ${page.data.title} | Cua Docs`;+ if (page.url.includes('guide')) title = ` Guide: ${page.data.title} | Cua Docs`;return {title,diff --git a/docs/src/app/layout.tsx b/docs/src/app/layout.tsxindex e821184e6e..97b6087067 100644--- a/docs/src/app/layout.tsx+++ b/docs/src/app/layout.tsx@@ -24,9 +24,7 @@ export default function Layout({ children }: { children: ReactNode }) {<PostHogPageView /></Suspense><AnalyticsTracker />- <RootProvider search={{ options: { api: '/docs/api/search' } }}>- {children}- </RootProvider>+ <RootProvider search={{ options: { api: '/docs/api/search' } }}>{children}</RootProvider><Footer /><CookieConsent /></PHProvider>diff --git a/docs/src/app/llms.mdx/[[...slug]]/route.ts b/docs/src/app/llms.mdx/[[...slug]]/route.tsindex 15b8e6784e..2a87ed97a4 100644--- a/docs/src/app/llms.mdx/[[...slug]]/route.ts+++ b/docs/src/app/llms.mdx/[[...slug]]/route.ts@@ -5,10 +5,7 @@ import { notFound } from 'next/navigation';export const revalidate = false;-export async function GET(- _req: NextRequest,- { params }: { params: Promise<{ slug?: string[] }> }-) {+export async function GET(_req: NextRequest, { params }: { params: Promise<{ slug?: string[] }> }) {const { slug } = await params;const page = source.getPage(slug);if (!page) notFound();diff --git a/docs/src/components/editable-code-block.tsx b/docs/src/components/editable-code-block.tsxindex e8cda746e6..6da1ded698 100644--- a/docs/src/components/editable-code-block.tsx+++ b/docs/src/components/editable-code-block.tsx@@ -55,14 +55,17 @@ export function EditableCodeBlock({const [values, setValues] = useState<Record<string, string>>(defaultValues);const updateValue = (key: string, value: string) => {- setValues(prev => ({ ...prev, [key]: value }));+ setValues((prev) => ({ ...prev, [key]: value }));};return (<EditableCodeContext.Provider value={{ values, updateValue }}><Base.CodeBlock title={title} className={cn('my-4', className)}>- <Base.Pre className={cn(`language-${lang}`, "px-3")}>- <code className={cn(`language-${lang}`)} style={{ display: 'block', whiteSpace: 'pre-wrap' }}>+ <Base.Pre className={cn(`language-${lang}`, 'px-3')}>+ <code+ className={cn(`language-${lang}`)}+ style={{ display: 'block', whiteSpace: 'pre-wrap' }}+ >{children}</code></Base.Pre>@@ -219,9 +222,7 @@ export function EditableValue({value={value}onChange={(e) => updateValue(placeholder, e.target.value)}placeholder={placeholder}- className={cn(- type === 'password' && value && 'text-security-disc'- )}+ className={cn(type === 'password' && value && 'text-security-disc')}style={{display: 'inline',width: inputWidth,diff --git a/docs/src/components/iou.tsx b/docs/src/components/iou.tsxindex ad34230479..05123f58fe 100644--- a/docs/src/components/iou.tsx+++ b/docs/src/components/iou.tsx@@ -34,7 +34,7 @@ interface IOUProps {}/**- * A React component that visualizes and calculates the Intersection over Union (IOU)+ * A React component that visualizes and calculates the Intersection over Union (IOU)* of two rectangles on a canvas* @param props - The component props* @returns The rendered IOU visualization component@@ -130,12 +130,7 @@ export default function IOU({ title, description, rect1, rect2 }: IOUProps) {<h3 className="text-sm font-semibold ">{title}</h3><div className="flex items-start gap-6"><div>- <canvas- ref={canvasRef}- width={200}- height={150}- className="border bg-white rounded-md"- />+ <canvas ref={canvasRef} width={200} height={150} className="border bg-white rounded-md" /><div className="mt-2 text-sm"><div className="font-mono mb-2">IOU = {actualIOU.toFixed(3)}</div><span className="">{description}</span>diff --git a/docs/src/components/mermaid.tsx b/docs/src/components/mermaid.tsxindex e22c31bdba..b4ec6a971b 100644--- a/docs/src/components/mermaid.tsx+++ b/docs/src/components/mermaid.tsx@@ -28,10 +28,7 @@ export function Mermaid({ chart }: { chart: string }) {theme: resolvedTheme === 'dark' ? 'dark' : 'default',});- const { svg, bindFunctions } = await mermaid.render(- id,- chart.replaceAll('\\n', '\n'),- );+ const { svg, bindFunctions } = await mermaid.render(id, chart.replaceAll('\\n', '\n'));bindFunctions?.(container);setSvg(svg);@@ -44,4 +41,4 @@ export function Mermaid({ chart }: { chart: string }) {}, [chart, id, resolvedTheme]);return <div ref={containerRef} dangerouslySetInnerHTML={{ __html: svg }} />;-}\ No newline at end of file+}diff --git a/docs/src/components/page-feedback.tsx b/docs/src/components/page-feedback.tsxindex f7067aeccd..02dda33684 100644--- a/docs/src/components/page-feedback.tsx+++ b/docs/src/components/page-feedback.tsx@@ -45,7 +45,7 @@ export function PageFeedback() {<p className="text-sm text-fd-muted-foreground text-left">{feedback === 'helpful'? 'Thanks for your feedback!'- : 'Thanks for your feedback. We\'ll work on improving this page.'}+ : "Thanks for your feedback. We'll work on improving this page."}</p>)}</div>diff --git a/docs/src/lib/source.ts b/docs/src/lib/source.tsindex a202cf802d..4841cf65a6 100644--- a/docs/src/lib/source.ts+++ b/docs/src/lib/source.ts@@ -34,9 +34,7 @@ export async function getApiVersions(...versions.filter((v) => v.label === 'Current'),...versions.filter((v) => v.label !== 'Current')- .sort((a, b) =>- b.label.localeCompare(a.label, undefined, { numeric: true })- ),+ .sort((a, b) => b.label.localeCompare(a.label, undefined, { numeric: true })),];}diff --git a/docs/tsconfig.json b/docs/tsconfig.jsonindex 504b29117f..8730cf8897 100644--- a/docs/tsconfig.json+++ b/docs/tsconfig.json@@ -2,11 +2,7 @@"compilerOptions": {"baseUrl": ".","target": "ESNext",- "lib": [- "dom",- "dom.iterable",- "esnext"- ],+ "lib": ["dom", "dom.iterable", "esnext"],"allowJs": true,"skipLibCheck": true,"strict": true,@@ -20,12 +16,8 @@"jsx": "preserve","incremental": true,"paths": {- "@/.source": [- "./.source/index.ts"- ],- "@/*": [- "./src/*"- ]+ "@/.source": ["./.source/index.ts"],+ "@/*": ["./src/*"]},"plugins": [{@@ -33,13 +25,6 @@}]},- "include": [- "next-env.d.ts",- "**/*.ts",- "**/*.tsx",- ".next/types/**/*.ts"- ],- "exclude": [- "node_modules"- ]-}\ No newline at end of file+ "include": ["next-env.d.ts", "**/*.ts", "**/*.tsx", ".next/types/**/*.ts"],+ "exclude": ["node_modules"]+}diff --git a/examples/agent_examples.py b/examples/agent_examples.pyindex 816c18510e..42fa5c7f75 100644--- a/examples/agent_examples.py+++ b/examples/agent_examples.py@@ -2,16 +2,15 @@import asyncioimport logging-import tracebackimport signal--from computer import Computer, VMProviderType+import traceback# Import the unified agent class and typesfrom agent import ComputerAgent+from computer import Computer, VMProviderType# Import utility functions-from utils import load_dotenv_files, handle_sigint+from utils import handle_sigint, load_dotenv_files# Set up logginglogging.basicConfig(level=logging.INFO)@@ -40,25 +39,20 @@ async def run_agent_example():# Create ComputerAgent with new APIagent = ComputerAgent(# Supported models:-# == OpenAI CUA (computer-use-preview) ==model="openai/computer-use-preview",-# == Anthropic CUA (Claude > 3.5) ==- # model="anthropic/claude-opus-4-20250514",+ # model="anthropic/claude-opus-4-20250514",# model="anthropic/claude-sonnet-4-20250514",# model="anthropic/claude-3-7-sonnet-20250219",# model="anthropic/claude-3-5-sonnet-20241022",-# == UI-TARS ==# model="huggingface-local/ByteDance-Seed/UI-TARS-1.5-7B",# model="mlx/mlx-community/UI-TARS-1.5-7B-6bit",# model="ollama_chat/0000/ui-tars-1.5-7b",-# == Omniparser + Any LLM ==# model="omniparser+anthropic/claude-opus-4-20250514",# model="omniparser+ollama_chat/gemma3:12b-it-q4_K_M",-tools=[computer],only_n_most_recent_images=3,verbosity=logging.DEBUG,@@ -79,18 +73,18 @@ async def run_agent_example():# Use message-based conversation historyhistory = []-+for i, task in enumerate(tasks):print(f"\nExecuting task {i+1}/{len(tasks)}: {task}")-+# Add user message to historyhistory.append({"role": "user", "content": task})-+# Run agent with conversation historyasync for result in agent.run(history, stream=False):# Add agent outputs to historyhistory += result.get("output", [])-+# Print output for debuggingfor item in result.get("output", []):if item.get("type") == "message":@@ -104,7 +98,7 @@ async def run_agent_example():print(f"Computer Action: {action_type}({action})")elif item.get("type") == "computer_call_output":print("Computer Output: [Screenshot/Result]")-+print(f"✅ Task {i+1}/{len(tasks)} completed: {task}")except Exception as e:diff --git a/examples/cloud_api_examples.py b/examples/cloud_api_examples.pyindex 88b1ea66ed..dd7d95ee99 100644--- a/examples/cloud_api_examples.py+++ b/examples/cloud_api_examples.py@@ -1,11 +1,13 @@import asyncioimport os+from utils import load_dotenv_filesload_dotenv_files()from computer.providers.cloud.provider import CloudProvider+async def main() -> None:api_key = os.getenv("CUA_API_KEY")if not api_key:@@ -13,7 +15,7 @@ async def main() -> None:api_base = os.getenv("CUA_API_BASE")if api_base:print(f"Using API base: {api_base}")-+provider = CloudProvider(api_key=api_key, verbose=True)async with provider:@@ -23,7 +25,7 @@ async def main() -> None:for vm in vms:print(f"name: {vm['name']}\n",- f"status: {vm['status']}\n", # pending, running, stopped, terminated, failed+ f"status: {vm['status']}\n", # pending, running, stopped, terminated, failedf"api_url: {vm.get('api_url')}\n",f"vnc_url: {vm.get('vnc_url')}\n",)@@ -59,12 +61,13 @@ async def main() -> None:# # To probe a VM's status via its public hostname (if you know the name):# name = "m-linux-96lcxd2c2k"# info = await provider.get_vm(name)- # print("get_vm info:\n",+ # print("get_vm info:\n",# f"name: {info['name']}\n",# f"status: {info['status']}\n", # running# f"api_url: {info.get('api_url')}\n",# f"os_type: {info.get('os_type')}\n",# )+if __name__ == "__main__":asyncio.run(main())diff --git a/examples/computer-example-ts/README.md b/examples/computer-example-ts/README.mdindex 7e7fc81ea7..2f6b6e9cc1 100644--- a/examples/computer-example-ts/README.md+++ b/examples/computer-example-ts/README.md@@ -19,6 +19,7 @@ This example demonstrates how to control a Cua Cloud Sandbox using the OpenAI `c2. **Set up environment variables:**Create a `.env` file with the following variables:+- `OPENAI_API_KEY` — your OpenAI API key- `CUA_API_KEY` — your Cua Cloud API key- `CUA_CONTAINER_NAME` — the name of your provisioned sandboxdiff --git a/examples/computer-example-ts/src/helpers.ts b/examples/computer-example-ts/src/helpers.tsindex adad234789..7f914f0d6d 100644--- a/examples/computer-example-ts/src/helpers.ts+++ b/examples/computer-example-ts/src/helpers.ts@@ -1,63 +1,63 @@-import type { Computer } from "@trycua/computer";-import type OpenAI from "openai";+import type { Computer } from '@trycua/computer';+import type OpenAI from 'openai';export async function executeAction(- computer: Computer,- action: OpenAI.Responses.ResponseComputerToolCall["action"],+ computer: Computer,+ action: OpenAI.Responses.ResponseComputerToolCall['action']) {- switch (action.type) {- case "click": {- const { x, y, button } = action;- console.log(`Executing click at (${x}, ${y}) with button '${button}'.`);- await computer.interface.moveCursor(x, y);- if (button === "right") await computer.interface.rightClick();- else await computer.interface.leftClick();- break;- }- case "type":- {- const { text } = action;- console.log(`Typing text: ${text}`);- await computer.interface.typeText(text);- }- break;- case "scroll": {- const { x: locX, y: locY, scroll_x, scroll_y } = action;- console.log(- `Scrolling at (${locX}, ${locY}) with offsets (scroll_x=${scroll_x}, scroll_y=${scroll_y}).`,- );- await computer.interface.moveCursor(locX, locY);- await computer.interface.scroll(scroll_x, scroll_y);- break;- }- case "keypress": {- const { keys } = action;- for (const key of keys) {- console.log(`Pressing key: ${key}.`);- // Map common key names to CUA equivalents- if (key.toLowerCase() === "enter") {- await computer.interface.pressKey("return");- } else if (key.toLowerCase() === "space") {- await computer.interface.pressKey("space");- } else {- await computer.interface.pressKey(key);- }- }- break;- }- case "wait": {- console.log(`Waiting for 3 seconds.`);- await new Promise((resolve) => setTimeout(resolve, 3 * 1000));- break;- }- case "screenshot": {- console.log("Taking screenshot.");- // This is handled automatically in the main loop, but we can take an extra one if requested- const screenshot = await computer.interface.screenshot();- return screenshot;- }- default:- console.log(`Unrecognized action: ${action.type}`);- break;- }+ switch (action.type) {+ case 'click': {+ const { x, y, button } = action;+ console.log(`Executing click at (${x}, ${y}) with button '${button}'.`);+ await computer.interface.moveCursor(x, y);+ if (button === 'right') await computer.interface.rightClick();+ else await computer.interface.leftClick();+ break;+ }+ case 'type':+ {+ const { text } = action;+ console.log(`Typing text: ${text}`);+ await computer.interface.typeText(text);+ }+ break;+ case 'scroll': {+ const { x: locX, y: locY, scroll_x, scroll_y } = action;+ console.log(+ `Scrolling at (${locX}, ${locY}) with offsets (scroll_x=${scroll_x}, scroll_y=${scroll_y}).`+ );+ await computer.interface.moveCursor(locX, locY);+ await computer.interface.scroll(scroll_x, scroll_y);+ break;+ }+ case 'keypress': {+ const { keys } = action;+ for (const key of keys) {+ console.log(`Pressing key: ${key}.`);+ // Map common key names to CUA equivalents+ if (key.toLowerCase() === 'enter') {+ await computer.interface.pressKey('return');+ } else if (key.toLowerCase() === 'space') {+ await computer.interface.pressKey('space');+ } else {+ await computer.interface.pressKey(key);+ }+ }+ break;+ }+ case 'wait': {+ console.log(`Waiting for 3 seconds.`);+ await new Promise((resolve) => setTimeout(resolve, 3 * 1000));+ break;+ }+ case 'screenshot': {+ console.log('Taking screenshot.');+ // This is handled automatically in the main loop, but we can take an extra one if requested+ const screenshot = await computer.interface.screenshot();+ return screenshot;+ }+ default:+ console.log(`Unrecognized action: ${action.type}`);+ break;+ }}diff --git a/examples/computer-example-ts/src/index.ts b/examples/computer-example-ts/src/index.tsindex d58a9843bf..29ff926da8 100644--- a/examples/computer-example-ts/src/index.ts+++ b/examples/computer-example-ts/src/index.ts@@ -1,104 +1,103 @@-import { Computer, OSType } from "@trycua/computer";-import OpenAI from "openai";-import { executeAction } from "./helpers";+import { Computer, OSType } from '@trycua/computer';+import OpenAI from 'openai';+import { executeAction } from './helpers';-import "dotenv/config";+import 'dotenv/config';const openai = new OpenAI({ apiKey: process.env.OPENAI_API_KEY });-const COMPUTER_USE_PROMPT = "Open firefox and go to trycua.com";+const COMPUTER_USE_PROMPT = 'Open firefox and go to trycua.com';// Initialize the Computer Connectionconst computer = new Computer({- apiKey: process.env.CUA_API_KEY!,- name: process.env.CUA_CONTAINER_NAME!,- osType: OSType.LINUX,+ apiKey: process.env.CUA_API_KEY!,+ name: process.env.CUA_CONTAINER_NAME!,+ osType: OSType.LINUX,});await computer.run();// Take the initial screenshotconst screenshot = await computer.interface.screenshot();-const screenshotBase64 = screenshot.toString("base64");+const screenshotBase64 = screenshot.toString('base64');// Setup openai config for computer useconst computerUseConfig: OpenAI.Responses.ResponseCreateParamsNonStreaming = {- model: "computer-use-preview",- tools: [- {- type: "computer_use_preview",- display_width: 1024,- display_height: 768,- environment: "linux", // we're using a linux vm- },- ],- truncation: "auto",+ model: 'computer-use-preview',+ tools: [+ {+ type: 'computer_use_preview',+ display_width: 1024,+ display_height: 768,+ environment: 'linux', // we're using a linux vm+ },+ ],+ truncation: 'auto',};// Send initial screenshot to the openai computer use modellet res = await openai.responses.create({- ...computerUseConfig,- input: [- {- role: "user",- content: [- // what we want the ai to do- { type: "input_text", text: COMPUTER_USE_PROMPT },- // current screenshot of the vm- {- type: "input_image",- image_url: `data:image/png;base64,${screenshotBase64}`,- detail: "auto",- },- ],- },- ],+ ...computerUseConfig,+ input: [+ {+ role: 'user',+ content: [+ // what we want the ai to do+ { type: 'input_text', text: COMPUTER_USE_PROMPT },+ // current screenshot of the vm+ {+ type: 'input_image',+ image_url: `data:image/png;base64,${screenshotBase64}`,+ detail: 'auto',+ },+ ],+ },+ ],});// Loop until there are no more computer use actions.while (true) {- const computerCalls = res.output.filter((o) => o.type === "computer_call");- if (computerCalls.length < 1) {- console.log("No more computer calls. Loop complete.");- break;- }- // Get the first call- const call = computerCalls[0];- const action = call.action;- console.log("Received action from OpenAI Responses API:", action);- let ackChecks: OpenAI.Responses.ResponseComputerToolCall.PendingSafetyCheck[] =- [];- if (call.pending_safety_checks.length > 0) {- console.log("Safety checks pending:", call.pending_safety_checks);- // In a real implementation, you would want to get user confirmation here- ackChecks = call.pending_safety_checks;- }+ const computerCalls = res.output.filter((o) => o.type === 'computer_call');+ if (computerCalls.length < 1) {+ console.log('No more computer calls. Loop complete.');+ break;+ }+ // Get the first call+ const call = computerCalls[0];+ const action = call.action;+ console.log('Received action from OpenAI Responses API:', action);+ let ackChecks: OpenAI.Responses.ResponseComputerToolCall.PendingSafetyCheck[] = [];+ if (call.pending_safety_checks.length > 0) {+ console.log('Safety checks pending:', call.pending_safety_checks);+ // In a real implementation, you would want to get user confirmation here+ ackChecks = call.pending_safety_checks;+ }- // Execute the action in the container- await executeAction(computer, action);- // Wait for changes to process within the container (1sec)- await new Promise((resolve) => setTimeout(resolve, 1000));+ // Execute the action in the container+ await executeAction(computer, action);+ // Wait for changes to process within the container (1sec)+ await new Promise((resolve) => setTimeout(resolve, 1000));- // Capture new screenshot- const newScreenshot = await computer.interface.screenshot();- const newScreenshotBase64 = newScreenshot.toString("base64");+ // Capture new screenshot+ const newScreenshot = await computer.interface.screenshot();+ const newScreenshotBase64 = newScreenshot.toString('base64');- // Screenshot back as computer_call_output+ // Screenshot back as computer_call_output- res = await openai.responses.create({- ...computerUseConfig,- previous_response_id: res.id,- input: [- {- type: "computer_call_output",- call_id: call.call_id,- acknowledged_safety_checks: ackChecks,- output: {- type: "computer_screenshot",- image_url: `data:image/png;base64,${newScreenshotBase64}`,- },- },- ],- });+ res = await openai.responses.create({+ ...computerUseConfig,+ previous_response_id: res.id,+ input: [+ {+ type: 'computer_call_output',+ call_id: call.call_id,+ acknowledged_safety_checks: ackChecks,+ output: {+ type: 'computer_screenshot',+ image_url: `data:image/png;base64,${newScreenshotBase64}`,+ },+ },+ ],+ });}process.exit();diff --git a/examples/computer-example-ts/tsconfig.json b/examples/computer-example-ts/tsconfig.jsonindex c606e279df..9d3e969add 100644--- a/examples/computer-example-ts/tsconfig.json+++ b/examples/computer-example-ts/tsconfig.json@@ -1,17 +1,13 @@{"compilerOptions": {"target": "esnext",- "lib": [- "es2023"- ],+ "lib": ["es2023"],"moduleDetection": "force","module": "preserve","moduleResolution": "bundler","allowImportingTsExtensions": true,"resolveJsonModule": true,- "types": [- "node"- ],+ "types": ["node"],"allowSyntheticDefaultImports": true,"strict": true,"noUnusedLocals": true,@@ -21,9 +17,7 @@"isolatedModules": true,"verbatimModuleSyntax": true,"skipLibCheck": true,- "outDir": "build",+ "outDir": "build"},- "include": [- "src"- ]-}\ No newline at end of file+ "include": ["src"]+}diff --git a/examples/computer_examples.py b/examples/computer_examples.pyindex bb9e7ad9db..7e990e8bc3 100644--- a/examples/computer_examples.py+++ b/examples/computer_examples.py@@ -1,8 +1,8 @@-import osimport asyncio-from pathlib import Path+import osimport sysimport traceback+from pathlib import Path# Load environment variables from .env fileproject_root = Path(__file__).parent.parent@@ -20,8 +20,9 @@ for path in pythonpath.split(":"):print(f"Added to sys.path: {path}")from computer.computer import Computer-from computer.providers.base import VMProviderTypefrom computer.logger import LogLevel+from computer.providers.base import VMProviderType+async def main():try:@@ -29,17 +30,15 @@ async def main():# Create a local macOS computercomputer = Computer(- display="1024x768",- memory="8GB",- cpu="4",+ display="1024x768",+ memory="8GB",+ cpu="4",os_type="macos",name="macos",verbosity=LogLevel.VERBOSE,provider_type=VMProviderType.LUME,storage="/Users/<USER>/repos/trycua/computer/examples/storage",- shared_directories=[- "/Users/<USER>/repos/trycua/computer/examples/shared"- ],+ shared_directories=["/Users/<USER>/repos/trycua/computer/examples/shared"],ephemeral=False,)@@ -50,22 +49,22 @@ async def main():# name=os.getenv("CONTAINER_NAME"),# provider_type=VMProviderType.CLOUD,# )-+try:# Run the computer with default parametersawait computer.run()-+screenshot = await computer.interface.screenshot()-+# Create output directory if it doesn't existoutput_dir = Path("./output")output_dir.mkdir(exist_ok=True)-+screenshot_path = output_dir / "screenshot.png"with open(screenshot_path, "wb") as f:f.write(screenshot)print(f"Screenshot saved to: {screenshot_path.absolute()}")-+# await computer.interface.hotkey("command", "space")# res = await computer.interface.run_command("touch ./Downloads/empty_file")diff --git a/examples/computer_examples_windows.py b/examples/computer_examples_windows.pyindex adcce8ae1b..19d228bf76 100644--- a/examples/computer_examples_windows.py+++ b/examples/computer_examples_windows.py@@ -1,8 +1,8 @@-import osimport asyncio-from pathlib import Path+import osimport sysimport traceback+from pathlib import Path# Load environment variables from .env fileproject_root = Path(__file__).parent.parent@@ -21,12 +21,13 @@ for path in pythonpath.split(":"):print(f"Added to sys.path: {path}")from computer.computer import Computer-from computer.providers.base import VMProviderTypefrom computer.logger import LogLevel+from computer.providers.base import VMProviderType# ANSI color codes-RED = '\033[91m'-RESET = '\033[0m'+RED = "\033[91m"+RESET = "\033[0m"+async def main():try:@@ -39,15 +40,15 @@ async def main():name=os.getenv("CONTAINER_NAME") or "",provider_type=VMProviderType.CLOUD,)-+try:# Run the computer with default parametersawait computer.run()-+# Create output directory if it doesn't existoutput_dir = Path("./output")output_dir.mkdir(exist_ok=True)-+# Keyboard Actions Examplesprint("\n=== Keyboard Actions ===")await computer.interface.type_text("Hello, World!")@@ -65,8 +66,10 @@ async def main():@sandboxed("demo_venv")def greet_and_print(name):- from mss import mssimport os++ from mss import mss+# get usernameusername = os.getlogin()print(f"Hello from inside the container, {name}!")@@ -75,9 +78,9 @@ async def main():# take a screenshotwith mss() as sct:- filename = sct.shot(mon=-1, output='C:/Users/azureuser/Desktop/fullscreen.png')+ filename = sct.shot(mon=-1, output="C:/Users/azureuser/Desktop/fullscreen.png")print(filename)-+return {"greeted": name, "username": username}# Call with args and kwargs@@ -94,33 +97,32 @@ async def main():with open(screenshot_path, "wb") as f:f.write(screenshot)print(f"Screenshot saved to: {screenshot_path.absolute()}")-+# Clipboard Actions Examplesprint("\n=== Clipboard Actions ===")await computer.interface.set_clipboard("Test clipboard")content = await computer.interface.copy_to_clipboard()print(f"Clipboard content: {content}")-# Simple REPL Loopprint("\n=== Command REPL ===")print("Enter commands to run on the remote computer.")print("Type 'exit' or 'quit' to leave the REPL.\n")-+while True:try:# Get command from usercommand = input("command> ").strip()-+# Check for exit commands- if command.lower() in ['exit', 'quit', '']:- if command.lower() in ['exit', 'quit']:+ if command.lower() in ["exit", "quit", ""]:+ if command.lower() in ["exit", "quit"]:print("Exiting REPL...")break-+# Run the commandresult = await computer.interface.run_command(command)-+print(result.stdout)if result.stderr:print(f"{RED}{result.stderr}{RESET}")@@ -130,7 +132,6 @@ async def main():except Exception as e:print(f"{RED}Error running command: {e}{RESET}")-finally:# Important to clean up resources# await computer.stop()diff --git a/examples/computer_ui_examples.py b/examples/computer_ui_examples.pyindex 0c1d0974d2..2151b9d88d 100644--- a/examples/computer_ui_examples.py+++ b/examples/computer_ui_examples.py@@ -23,9 +23,9 @@ if __name__ == "__main__":server_name="0.0.0.0",server_port=7860,)-+# Optional: Using the saved dataset# import datasets# from computer.ui.utils import convert_to_unsloth# ds = datasets.load_dataset("ddupont/highquality-cua-demonstrations")- # ds = convert_to_unsloth(ds)\ No newline at end of file+ # ds = convert_to_unsloth(ds)diff --git a/examples/docker_examples.py b/examples/docker_examples.pyindex 42dcf3ac7b..e84aa747a9 100644--- a/examples/docker_examples.py+++ b/examples/docker_examples.py@@ -1,8 +1,10 @@import asyncio-from computer.providers.factory import VMProviderFactory-from computer import Computer, VMProviderTypeimport os+from computer import Computer, VMProviderType+from computer.providers.factory import VMProviderFactory++async def main():# # Create docker provider# provider = VMProviderFactory.create_provider(@@ -39,5 +41,6 @@ async def main():with open("screenshot_docker.png", "wb") as f:f.write(screenshot)+if __name__ == "__main__":asyncio.run(main())diff --git a/examples/evals/hud_eval_examples.py b/examples/evals/hud_eval_examples.pyindex 86da50df8e..f49d7b8455 100644--- a/examples/evals/hud_eval_examples.py+++ b/examples/evals/hud_eval_examples.py@@ -6,7 +6,7 @@ hud_eval_examples.py — minimal HUD evaluation runner- No Docker/local computer usage"""-#imports+# importsimport asyncioimport loggingimport os@@ -14,13 +14,15 @@ import uuidfrom pathlib import Pathfrom pprint import pprint-from dotenv import load_dotenv, find_dotenvfrom agent import ComputerAgentfrom agent.integrations.hud import run_full_dataset+from dotenv import find_dotenv, load_dotenv"""Loading env"""++def load_env_or_fail() -> None:# Walk up from CWD / file dir to find nearest .envenv_path = find_dotenv(usecwd=False)@@ -32,17 +34,19 @@ def load_env_or_fail() -> None:if not os.getenv("HUD_API_KEY"):raise EnvironmentError("❌ HUD_API_KEY is missing in the loaded environment")+"""Build Agent Config- customize agent behavior, tool integration, callbacks, resource management, and more- https://docs.trycua.com/docs/agent-sdk/agent-loops#parameters- https://docs.trycua.com/docs/agent-sdk/supported-model-providers"""++def build_agent_config() -> dict:instruction = "You are a computer-using agent graded by deterministic checkers."-return {"model": "openai/computer-use-preview","trajectory_dir": str(Path("trajectories")),@@ -51,21 +55,25 @@ def build_agent_config() -> dict:"instruction": instruction,}+"""Hud Eval"""++async def run_hud_eval() -> None:- #load env and agent config+ # load env and agent configload_env_or_fail()agent_config = build_agent_config()# Initialize to ensure config is valid (tools, verbosity, etc.)_ = ComputerAgent(**agent_config)- job_name = f"osworld-test-{str(uuid.uuid4())[:4]}" #job name (each run of your task is a job on hud)+ job_name = (+ f"osworld-test-{str(uuid.uuid4())[:4]}" # job name (each run of your task is a job on hud)+ )print(f"🚀 Running HUD eval: {job_name}")-"""Customize your hud eval below, check the doc for additional params- https://docs.trycua.com/docs/agent-sdk/integrations/hud#parameters-1diff --git a/examples/pylume_examples.py b/examples/pylume_examples.pyindex 37dead889c..35e89ed62c 100644--- a/examples/pylume_examples.py+++ b/examples/pylume_examples.py@@ -1,5 +1,6 @@import asyncio-from pylume import PyLume, ImageRef, VMRunOpts, SharedDirectory, VMConfig, VMUpdateOpts++from pylume import ImageRef, PyLume, SharedDirectory, VMConfig, VMRunOpts, VMUpdateOptsasync def main():diff --git a/examples/sandboxed_functions_examples.py b/examples/sandboxed_functions_examples.pyindex 93d9302186..a983f95d9b 100644--- a/examples/sandboxed_functions_examples.py+++ b/examples/sandboxed_functions_examples.py@@ -1,6 +1,6 @@-from pathlib import Pathimport osimport sys+from pathlib import Path# Load environment variables from .env fileproject_root = Path(__file__).parent.parent@@ -18,14 +18,16 @@ for path in pythonpath.split(":"):print(f"Added to sys.path: {path}")import asyncio+from computer.computer import Computerfrom computer.helpers import sandboxed+async def main():# Initialize the computer in a Cua Containercomputer = Computer()await computer.run()-+# Install a package in a virtual environment in the containerawait computer.venv_install("demo_venv", ["requests", "macos-pyxa"])@@ -39,6 +41,7 @@ async def main():def greet_and_print(name):# get .html of the current Safari tabimport PyXA+safari = PyXA.Application("Safari")current_doc = safari.current_documenthtml = current_doc.source()@@ -50,5 +53,6 @@ async def main():result = await greet_and_print("Cua")print("Result from sandboxed function:", result)+if __name__ == "__main__":asyncio.run(main())diff --git a/examples/som_examples.py b/examples/som_examples.pyindex 4dc3e38bc4..5cb4567f5f 100644--- a/examples/som_examples.py+++ b/examples/som_examples.py@@ -9,17 +9,18 @@ This script shows how to:"""import argparse+import base64+import glob+import ioimport logging+import osimport sys-from pathlib import Pathimport time-from PIL import Image-from typing import Dict, Any, List, Optional+from pathlib import Path+from typing import Any, Dict, List, Optional+import numpy as np-import io-import base64-import glob-import os+from PIL import Image# Load environment variables from .env fileproject_root = Path(__file__).parent.parent@@ -42,8 +43,8 @@ if str(libs_path) not in sys.path:sys.path.append(str(libs_path))print(f"Added to sys.path: {libs_path}")-from som import OmniParser, ParseResult, IconElement, TextElement-from som.models import UIElement, ParserMetadata, BoundingBox+from som import IconElement, OmniParser, ParseResult, TextElement+from som.models import BoundingBox, ParserMetadata, UIElement# Configure logginglogging.basicConfig(@@ -361,7 +362,7 @@ def run_experiments(input_path: str, output_dir: Path, use_ocr: bool = False):# Update timing totalstotal_time += t.elapsed_time-+# Write summary for this combinationavg_time = total_time / len(image_files)f.write(diff --git a/examples/utils.py b/examples/utils.pyindex 759b0b6e09..7ad94e5cd1 100644--- a/examples/utils.py+++ b/examples/utils.py@@ -1,8 +1,8 @@"""Utility functions for example scripts."""import os-import sysimport signal+import sysfrom pathlib import Pathfrom typing import Optionaldiff --git a/examples/winsandbox_example.py b/examples/winsandbox_example.pyindex cd5ab5c190..98fa0f44a7 100644--- a/examples/winsandbox_example.py+++ b/examples/winsandbox_example.py@@ -4,11 +4,13 @@ Learn more at: https://learn.microsoft.com/en-us/windows/security/application-se"""import asyncio+from computer import Computer+async def main():"""Test the Windows Sandbox provider."""-+# Create a computer instance using Windows Sandboxcomputer = Computer(provider_type="winsandbox",@@ -16,19 +18,19 @@ async def main():memory="4GB",# ephemeral=True, # Always true for Windows Sandbox)-+try:print("Starting Windows Sandbox...")await computer.run()-+print("Windows Sandbox is ready!")print(f"IP Address: {await computer.get_ip()}")-+# Test basic functionalityprint("Testing basic functionality...")screenshot = await computer.interface.screenshot()print(f"Screenshot taken: {len(screenshot)} bytes")-+# Test running a commandprint("Testing command execution...")result = await computer.interface.run_command("echo Hello from Windows Sandbox!")@@ -36,16 +38,18 @@ async def main():print("Press any key to continue...")input()-+except Exception as e:print(f"Error: {e}")import traceback+traceback.print_exc()-+finally:print("Stopping Windows Sandbox...")await computer.stop()print("Windows Sandbox stopped.")+if __name__ == "__main__":asyncio.run(main())diff --git a/libs/kasm/README.md b/libs/kasm/README.mdindex 884f7ed73a..00c02019db 100644--- a/libs/kasm/README.md+++ b/libs/kasm/README.md@@ -70,14 +70,17 @@ async with provider:## Container Configuration### Ports+- **6901**: VNC web interface (noVNC)- **8080**: Computer-server API endpoint### Environment Variables+- `VNC_PW`: VNC password (default: "password")- `DISPLAY`: X11 display (set to ":0")### Volumes+- `/home/kasm-user/storage`: Persistent storage mount point- `/home/kasm-user/shared`: Shared folder mount pointdiff --git a/libs/lume/CONTRIBUTING.md b/libs/lume/CONTRIBUTING.mdindex 6c51a41610..edbe6c8a9b 100644--- a/libs/lume/CONTRIBUTING.md+++ b/libs/lume/CONTRIBUTING.md@@ -29,6 +29,7 @@ We're always looking for suggestions to make lume better. If you have an idea:## DocumentationDocumentation improvements are always welcome. You can:+- Fix typos or unclear explanations- Add examples and use cases- Improve API documentation@@ -36,4 +37,4 @@ Documentation improvements are always welcome. You can:For detailed instructions on setting up your development environment and submitting code contributions, please see our [Development.md](docs/Development.md) guide.-Feel free to join our [Discord community](https://discord.com/invite/mVnXXpdE85) to discuss ideas or get help with your contributions.\ No newline at end of file+Feel free to join our [Discord community](https://discord.com/invite/mVnXXpdE85) to discuss ideas or get help with your contributions.diff --git a/libs/lume/Development.md b/libs/lume/Development.mdindex 0ddf8c5e33..f991a49eea 100644--- a/libs/lume/Development.md+++ b/libs/lume/Development.md@@ -5,6 +5,7 @@ This guide will help you set up your development environment and understand the## Environment SetupLume development requires:+- Swift 6 or higher- Xcode 15 or higher- macOS Sequoia 15.2 or higher@@ -16,12 +17,13 @@ If you're working on Lume in the context of the Cua monorepo, we recommend using# Open VS Code workspace from the root of the monorepocode .vscode/lume.code-workspace```+This workspace is preconfigured with Swift language support, build tasks, and debug configurations.## Setting Up the Repository Locally1. **Fork the Repository**: Create your own fork of lume-2. **Clone the Repository**:+2. **Clone the Repository**:```bashgit clone https://github.com/trycua/lume.gitcd lumediff --git a/libs/lume/README.md b/libs/lume/README.mdindex c90c250a76..1ea563c9d3 100644--- a/libs/lume/README.md+++ b/libs/lume/README.md@@ -8,13 +8,13 @@</picture></div>- [](#)- [](#)- [](https://discord.com/invite/mVnXXpdE85)+[](#)+[](#)+[](https://discord.com/invite/mVnXXpdE85)+</h1></div>-**lume** is a lightweight Command Line Interface and local API server to create, run and manage macOS and Linux virtual machines (VMs) with near-native performance on Apple Silicon, using Apple's `Virtualization.Framework`.### Run prebuilt macOS images in just 1 step@@ -43,6 +43,7 @@ All prebuilt images use the default password `lume`. Change this immediately aft</Callout>**System Requirements**:+- Apple Silicon Mac (M1, M2, M3, etc.)- macOS 13.0 or later- At least 8GB of RAM (16GB recommended)diff --git a/libs/lumier/README.md b/libs/lumier/README.mdindex 92cfc5599a..61825867fc 100644--- a/libs/lumier/README.md+++ b/libs/lumier/README.md@@ -8,9 +8,10 @@</picture></div>- [](#)- [](#)- [](https://discord.com/invite/mVnXXpdE85)+[](#)+[](#)+[](https://discord.com/invite/mVnXXpdE85)+</h1></div>@@ -21,6 +22,7 @@ macOS and Linux virtual machines in a Docker container.</div>## What is Lumier?+**Lumier** is an interface for running macOS virtual machines with minimal setup. It uses Docker as a packaging system to deliver a pre-configured environment that connects to the `lume` virtualization service running on your host machine. With Lumier, you get:- A ready-to-use macOS or Linux virtual machine in minutes@@ -35,6 +37,7 @@ Before using Lumier, make sure you have:1. **Docker for Apple Silicon** - download it [here](https://desktop.docker.com/mac/main/arm64/Docker.dmg) and follow the installation instructions.2. **Lume** - This is the virtualization CLI that powers Lumier. Install it with this command:+```bash/bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/trycua/cua/main/libs/lume/scripts/install.sh)"```@@ -69,6 +72,7 @@ After running the command above, you can access your macOS VM through a web browThis project was inspired by [dockur/windows](https://github.com/dockur/windows) and [dockur/macos](https://github.com/dockur/macos), which pioneered the approach of running Windows and macOS VMs in Docker containers.Main differences with dockur/macos:+- Lumier is specifically designed for macOS virtualization- Lumier supports Apple Silicon (M1/M2/M3/M4) while dockur/macos only supports Intel- Lumier uses the Apple Virtualization Framework (Vz) through the `lume` CLI to create true virtual machines, while dockur relies on KVM.diff --git a/libs/python/agent/README.md b/libs/python/agent/README.mdindex ed90076be0..69adc24280 100644--- a/libs/python/agent/README.md+++ b/libs/python/agent/README.md@@ -8,10 +8,11 @@</picture></div>- [](#)- [](#)- [](https://discord.com/invite/mVnXXpdE85)- [](https://pypi.org/project/cua-computer/)+[](#)+[](#)+[](https://discord.com/invite/mVnXXpdE85)+[](https://pypi.org/project/cua-computer/)+</h1></div>@@ -47,7 +48,7 @@ async def main():name=os.getenv("CUA_CONTAINER_NAME"),api_key=os.getenv("CUA_API_KEY")) as computer:-+# Create agentagent = ComputerAgent(model="anthropic/claude-3-5-sonnet-20241022",@@ -56,10 +57,10 @@ async def main():trajectory_dir="trajectories",max_trajectory_budget=5.0 # $5 budget limit)-+# Run agentmessages = [{"role": "user", "content": "Take a screenshot and tell me what you see"}]-+async for result in agent.run(messages):for item in result["output"]:if item["type"] == "message":@@ -84,4 +85,4 @@ if __name__ == "__main__":## License-MIT License - see LICENSE file for details.\ No newline at end of file+MIT License - see LICENSE file for details.diff --git a/libs/python/agent/agent/__init__.py b/libs/python/agent/agent/__init__.pyindex f48297c4b4..124604583b 100644--- a/libs/python/agent/agent/__init__.py+++ b/libs/python/agent/agent/__init__.py@@ -5,19 +5,13 @@ agent - Decorator-based Computer Use Agent with liteLLM integrationimport loggingimport sys-from .decorators import register_agent-from .agent import ComputerAgent-from .types import Messages, AgentResponse-# Import loops to register themfrom . import loops+from .agent import ComputerAgent+from .decorators import register_agent+from .types import AgentResponse, Messages-__all__ = [- "register_agent",- "ComputerAgent",- "Messages",- "AgentResponse"-]+__all__ = ["register_agent", "ComputerAgent", "Messages", "AgentResponse"]__version__ = "0.4.0"diff --git a/libs/python/agent/agent/__main__.py b/libs/python/agent/agent/__main__.pyindex 1b4d669787..96ff779e95 100644--- a/libs/python/agent/agent/__main__.py+++ b/libs/python/agent/agent/__main__.py@@ -5,8 +5,9 @@ Usage:python -m agent.cli <model_string>"""-import sysimport asyncio+import sys+from .cli import mainif __name__ == "__main__":diff --git a/libs/python/agent/agent/adapters/huggingfacelocal_adapter.py b/libs/python/agent/agent/adapters/huggingfacelocal_adapter.pyindex 3ecba641b5..63e860e1ee 100644--- a/libs/python/agent/agent/adapters/huggingfacelocal_adapter.py+++ b/libs/python/agent/agent/adapters/huggingfacelocal_adapter.py@@ -2,27 +2,30 @@ import asyncioimport functoolsimport warningsfrom concurrent.futures import ThreadPoolExecutor-from typing import Iterator, AsyncIterator, Dict, List, Any, Optional-from litellm.types.utils import GenericStreamingChunk, ModelResponse+from typing import Any, AsyncIterator, Dict, Iterator, List, Optional++from litellm import acompletion, completionfrom litellm.llms.custom_llm import CustomLLM-from litellm import completion, acompletion+from litellm.types.utils import GenericStreamingChunk, ModelResponse# Try to import HuggingFace dependenciestry:import torchfrom transformers import AutoModelForImageTextToText, AutoProcessor+HF_AVAILABLE = Trueexcept ImportError:HF_AVAILABLE = Falsefrom .models import load_model as load_model_handler+class HuggingFaceLocalAdapter(CustomLLM):"""HuggingFace Local Adapter for running vision-language models locally."""-+def __init__(self, device: str = "auto", trust_remote_code: bool = False, **kwargs):"""Initialize the adapter.-+Args:device: Device to load model on ("auto", "cuda", "cpu", etc.)trust_remote_code: Whether to trust remote code@@ -34,129 +37,120 @@ class HuggingFaceLocalAdapter(CustomLLM):# Cache for model handlers keyed by model_nameself._handlers: Dict[str, Any] = {}self._executor = ThreadPoolExecutor(max_workers=1) # Single thread pool-+def _get_handler(self, model_name: str):"""Get or create a model handler for the given model name."""if model_name not in self._handlers:- self._handlers[model_name] = load_model_handler(model_name=model_name, device=self.device, trust_remote_code=self.trust_remote_code)+ self._handlers[model_name] = load_model_handler(+ model_name=model_name, device=self.device, trust_remote_code=self.trust_remote_code+ )return self._handlers[model_name]-+def _convert_messages(self, messages: List[Dict[str, Any]]) -> List[Dict[str, Any]]:"""Convert OpenAI format messages to HuggingFace format.-+Args:messages: Messages in OpenAI format-+Returns:Messages in HuggingFace format"""converted_messages = []-+for message in messages:- converted_message = {- "role": message["role"],- "content": []- }-+ converted_message = {"role": message["role"], "content": []}+content = message.get("content", [])if isinstance(content, str):# Simple text content- converted_message["content"].append({- "type": "text",- "text": content- })+ converted_message["content"].append({"type": "text", "text": content})elif isinstance(content, list):# Multi-modal contentfor item in content:if item.get("type") == "text":- converted_message["content"].append({- "type": "text",- "text": item.get("text", "")- })+ converted_message["content"].append(+ {"type": "text", "text": item.get("text", "")}+ )elif item.get("type") == "image_url":# Convert image_url format to image formatimage_url = item.get("image_url", {}).get("url", "")- converted_message["content"].append({- "type": "image",- "image": image_url- })-+ converted_message["content"].append({"type": "image", "image": image_url})+converted_messages.append(converted_message)-+return converted_messages-+def _generate(self, **kwargs) -> str:"""Generate response using the local HuggingFace model.-+Args:**kwargs: Keyword arguments containing messages and model info-+Returns:Generated text response"""if not HF_AVAILABLE:raise ImportError("HuggingFace transformers dependencies not found. "- "Please install with: pip install \"cua-agent[uitars-hf]\""+ 'Please install with: pip install "cua-agent[uitars-hf]"')-+# Extract messages and model from kwargs- messages = kwargs.get('messages', [])- model_name = kwargs.get('model', 'ByteDance-Seed/UI-TARS-1.5-7B')- max_new_tokens = kwargs.get('max_tokens', 128)-+ messages = kwargs.get("messages", [])+ model_name = kwargs.get("model", "ByteDance-Seed/UI-TARS-1.5-7B")+ max_new_tokens = kwargs.get("max_tokens", 128)+# Warn about ignored kwargs- ignored_kwargs = set(kwargs.keys()) - {'messages', 'model', 'max_tokens'}+ ignored_kwargs = set(kwargs.keys()) - {"messages", "model", "max_tokens"}if ignored_kwargs:warnings.warn(f"Ignoring unsupported kwargs: {ignored_kwargs}")-+# Convert messages to HuggingFace formathf_messages = self._convert_messages(messages)-+# Delegate to model handlerhandler = self._get_handler(model_name)generated_text = handler.generate(hf_messages, max_new_tokens=max_new_tokens)return generated_text-+def completion(self, *args, **kwargs) -> ModelResponse:"""Synchronous completion method.-+Returns:ModelResponse with generated text"""generated_text = self._generate(**kwargs)-+return completion(model=f"huggingface-local/{kwargs['model']}",mock_response=generated_text,)-+async def acompletion(self, *args, **kwargs) -> ModelResponse:"""Asynchronous completion method.-+Returns:ModelResponse with generated text"""# Run _generate in thread pool to avoid blockingloop = asyncio.get_event_loop()generated_text = await loop.run_in_executor(- self._executor,- functools.partial(self._generate, **kwargs)+ self._executor, functools.partial(self._generate, **kwargs))-+return await acompletion(model=f"huggingface-local/{kwargs['model']}",mock_response=generated_text,)-+def streaming(self, *args, **kwargs) -> Iterator[GenericStreamingChunk]:"""Synchronous streaming method.-+Returns:Iterator of GenericStreamingChunk"""generated_text = self._generate(**kwargs)-+generic_streaming_chunk: GenericStreamingChunk = {"finish_reason": "stop","index": 0,@@ -165,22 +159,21 @@ class HuggingFaceLocalAdapter(CustomLLM):"tool_use": None,"usage": {"completion_tokens": 0, "prompt_tokens": 0, "total_tokens": 0},}-+yield generic_streaming_chunk-+async def astreaming(self, *args, **kwargs) -> AsyncIterator[GenericStreamingChunk]:"""Asynchronous streaming method.-+Returns:AsyncIterator of GenericStreamingChunk"""# Run _generate in thread pool to avoid blockingloop = asyncio.get_event_loop()generated_text = await loop.run_in_executor(- self._executor,- functools.partial(self._generate, **kwargs)+ self._executor, functools.partial(self._generate, **kwargs))-+generic_streaming_chunk: GenericStreamingChunk = {"finish_reason": "stop","index": 0,@@ -189,5 +182,5 @@ class HuggingFaceLocalAdapter(CustomLLM):"tool_use": None,"usage": {"completion_tokens": 0, "prompt_tokens": 0, "total_tokens": 0},}-- yield generic_streaming_chunk\ No newline at end of file++ yield generic_streaming_chunkdiff --git a/libs/python/agent/agent/adapters/human_adapter.py b/libs/python/agent/agent/adapters/human_adapter.pyindex 0cd4fe025d..e5452acd46 100644--- a/libs/python/agent/agent/adapters/human_adapter.py+++ b/libs/python/agent/agent/adapters/human_adapter.py@@ -1,22 +1,23 @@-import osimport asyncio+import os+from typing import Any, AsyncIterator, Dict, Iterator, List+import requests-from typing import List, Dict, Any, Iterator, AsyncIterator-from litellm.types.utils import GenericStreamingChunk, ModelResponse+from litellm import acompletion, completionfrom litellm.llms.custom_llm import CustomLLM-from litellm import completion, acompletion+from litellm.types.utils import GenericStreamingChunk, ModelResponseclass HumanAdapter(CustomLLM):"""Human Adapter for human-in-the-loop completions.-+This adapter sends completion requests to a human completion serverwhere humans can review and respond to AI requests."""-+def __init__(self, base_url: str | None = None, timeout: float = 300.0, **kwargs):"""Initialize the human adapter.-+Args:base_url: Base URL for the human completion server.Defaults to HUMAN_BASE_URL environment variable or http://localhost:8002@@ -24,60 +25,58 @@ class HumanAdapter(CustomLLM):**kwargs: Additional arguments"""super().__init__()- self.base_url = base_url or os.getenv('HUMAN_BASE_URL', 'http://localhost:8002')+ self.base_url = base_url or os.getenv("HUMAN_BASE_URL", "http://localhost:8002")self.timeout = timeout-+# Ensure base_url doesn't end with slash- self.base_url = self.base_url.rstrip('/')-+ self.base_url = self.base_url.rstrip("/")+def _queue_completion(self, messages: List[Dict[str, Any]], model: str) -> str:"""Queue a completion request and return the call ID.-+Args:messages: Messages in OpenAI formatmodel: Model name-+Returns:Call ID for tracking the request-+Raises:Exception: If queueing fails"""try:response = requests.post(- f"{self.base_url}/queue",- json={"messages": messages, "model": model},- timeout=10+ f"{self.base_url}/queue", json={"messages": messages, "model": model}, timeout=10)response.raise_for_status()return response.json()["id"]except requests.RequestException as e:raise Exception(f"Failed to queue completion request: {e}")-+def _wait_for_completion(self, call_id: str) -> Dict[str, Any]:"""Wait for human to complete the call.-+Args:call_id: ID of the queued completion call-+Returns:Dict containing response and/or tool_calls-+Raises:TimeoutError: If timeout is exceededException: If completion fails"""import time-+start_time = time.time()-+while True:try:# Check statusstatus_response = requests.get(f"{self.base_url}/status/{call_id}")status_response.raise_for_status()status_data = status_response.json()-+if status_data["status"] == "completed":result = {}if "response" in status_data and status_data["response"]:@@ -88,38 +87,41 @@ class HumanAdapter(CustomLLM):elif status_data["status"] == "failed":error_msg = status_data.get("error", "Unknown error")raise Exception(f"Completion failed: {error_msg}")-+# Check timeoutif time.time() - start_time > self.timeout:- raise TimeoutError(f"Timeout waiting for human response after {self.timeout} seconds")-+ raise TimeoutError(+ f"Timeout waiting for human response after {self.timeout} seconds"+ )+# Wait before checking againtime.sleep(1.0)-+except requests.RequestException as e:if time.time() - start_time > self.timeout:raise TimeoutError(f"Timeout waiting for human response: {e}")# Continue trying if we haven't timed outtime.sleep(1.0)-+async def _async_wait_for_completion(self, call_id: str) -> Dict[str, Any]:"""Async version of wait_for_completion.-+Args:call_id: ID of the queued completion call-+Returns:Dict containing response and/or tool_calls-+Raises:TimeoutError: If timeout is exceededException: If completion fails"""- import aiohttpimport time-++ import aiohttp+start_time = time.time()-+async with aiohttp.ClientSession() as session:while True:try:@@ -127,7 +129,7 @@ class HumanAdapter(CustomLLM):async with session.get(f"{self.base_url}/status/{call_id}") as response:response.raise_for_status()status_data = await response.json()-+if status_data["status"] == "completed":result = {}if "response" in status_data and status_data["response"]:@@ -138,166 +140,158 @@ class HumanAdapter(CustomLLM):elif status_data["status"] == "failed":error_msg = status_data.get("error", "Unknown error")raise Exception(f"Completion failed: {error_msg}")-+# Check timeoutif time.time() - start_time > self.timeout:- raise TimeoutError(f"Timeout waiting for human response after {self.timeout} seconds")-+ raise TimeoutError(+ f"Timeout waiting for human response after {self.timeout} seconds"+ )+# Wait before checking againawait asyncio.sleep(1.0)-+except Exception as e:if time.time() - start_time > self.timeout:raise TimeoutError(f"Timeout waiting for human response: {e}")# Continue trying if we haven't timed outawait asyncio.sleep(1.0)-+def _generate_response(self, messages: List[Dict[str, Any]], model: str) -> Dict[str, Any]:"""Generate a human response for the given messages.-+Args:messages: Messages in OpenAI formatmodel: Model name-+Returns:Dict containing response and/or tool_calls"""# Queue the completion requestcall_id = self._queue_completion(messages, model)-+# Wait for human responseresponse = self._wait_for_completion(call_id)-+return response-- async def _async_generate_response(self, messages: List[Dict[str, Any]], model: str) -> Dict[str, Any]:++ async def _async_generate_response(+ self, messages: List[Dict[str, Any]], model: str+ ) -> Dict[str, Any]:"""Async version of _generate_response.-+Args:messages: Messages in OpenAI formatmodel: Model name-+Returns:Dict containing response and/or tool_calls"""# Queue the completion request (sync operation)call_id = self._queue_completion(messages, model)-+# Wait for human response (async)response = await self._async_wait_for_completion(call_id)-+return response-+def completion(self, *args, **kwargs) -> ModelResponse:"""Synchronous completion method.-+Returns:ModelResponse with human-generated text or tool calls"""- messages = kwargs.get('messages', [])- model = kwargs.get('model', 'human')-+ messages = kwargs.get("messages", [])+ model = kwargs.get("model", "human")+# Generate human responsehuman_response_data = self._generate_response(messages, model)-+# Create ModelResponse with proper structure- from litellm.types.utils import ModelResponse, Choices, Message- import uuidimport time-+ import uuid++ from litellm.types.utils import Choices, Message, ModelResponse+# Create message content based on response typeif "tool_calls" in human_response_data and human_response_data["tool_calls"]:# Tool calls responsemessage = Message(role="assistant",content=human_response_data.get("response", ""),- tool_calls=human_response_data["tool_calls"]+ tool_calls=human_response_data["tool_calls"],)else:# Text response- message = Message(- role="assistant",- content=human_response_data.get("response", "")- )-- choice = Choices(- finish_reason="stop",- index=0,- message=message- )-+ message = Message(role="assistant", content=human_response_data.get("response", ""))++ choice = Choices(finish_reason="stop", index=0, message=message)+result = ModelResponse(id=f"human-{uuid.uuid4()}",choices=[choice],created=int(time.time()),model=f"human/{model}",- object="chat.completion"+ object="chat.completion",)-+return result-+async def acompletion(self, *args, **kwargs) -> ModelResponse:"""Asynchronous completion method.-+Returns:ModelResponse with human-generated text or tool calls"""- messages = kwargs.get('messages', [])- model = kwargs.get('model', 'human')-+ messages = kwargs.get("messages", [])+ model = kwargs.get("model", "human")+# Generate human responsehuman_response_data = await self._async_generate_response(messages, model)-+# Create ModelResponse with proper structure- from litellm.types.utils import ModelResponse, Choices, Message- import uuidimport time-+ import uuid++ from litellm.types.utils import Choices, Message, ModelResponse+# Create message content based on response typeif "tool_calls" in human_response_data and human_response_data["tool_calls"]:# Tool calls responsemessage = Message(role="assistant",content=human_response_data.get("response", ""),- tool_calls=human_response_data["tool_calls"]+ tool_calls=human_response_data["tool_calls"],)else:# Text response- message = Message(- role="assistant",- content=human_response_data.get("response", "")- )-- choice = Choices(- finish_reason="stop",- index=0,- message=message- )-+ message = Message(role="assistant", content=human_response_data.get("response", ""))++ choice = Choices(finish_reason="stop", index=0, message=message)+result = ModelResponse(id=f"human-{uuid.uuid4()}",choices=[choice],created=int(time.time()),model=f"human/{model}",- object="chat.completion"+ object="chat.completion",)-+return result-+def streaming(self, *args, **kwargs) -> Iterator[GenericStreamingChunk]:"""Synchronous streaming method.-+Yields:Streaming chunks with human-generated text or tool calls"""- messages = kwargs.get('messages', [])- model = kwargs.get('model', 'human')-+ messages = kwargs.get("messages", [])+ model = kwargs.get("model", "human")+# Generate human responsehuman_response_data = self._generate_response(messages, model)-+import time-+# Handle tool calls vs text responseif "tool_calls" in human_response_data and human_response_data["tool_calls"]:# Stream tool calls as a single chunk@@ -319,22 +313,26 @@ class HumanAdapter(CustomLLM):"is_finished": True,"text": response_text,"tool_use": None,- "usage": {"completion_tokens": len(response_text.split()), "prompt_tokens": 0, "total_tokens": len(response_text.split())},+ "usage": {+ "completion_tokens": len(response_text.split()),+ "prompt_tokens": 0,+ "total_tokens": len(response_text.split()),+ },}yield generic_chunk-+async def astreaming(self, *args, **kwargs) -> AsyncIterator[GenericStreamingChunk]:"""Asynchronous streaming method.-+Yields:Streaming chunks with human-generated text or tool calls"""- messages = kwargs.get('messages', [])- model = kwargs.get('model', 'human')-+ messages = kwargs.get("messages", [])+ model = kwargs.get("model", "human")+# Generate human responsehuman_response = await self._async_generate_response(messages, model)-+# Return as single streaming chunkgeneric_streaming_chunk: GenericStreamingChunk = {"finish_reason": "stop",@@ -342,7 +340,11 @@ class HumanAdapter(CustomLLM):"is_finished": True,"text": human_response,"tool_use": None,- "usage": {"completion_tokens": len(human_response.split()), "prompt_tokens": 0, "total_tokens": len(human_response.split())},+ "usage": {+ "completion_tokens": len(human_response.split()),+ "prompt_tokens": 0,+ "total_tokens": len(human_response.split()),+ },}-- yield generic_streaming_chunk\ No newline at end of file++ yield generic_streaming_chunkdiff --git a/libs/python/agent/agent/adapters/mlxvlm_adapter.py b/libs/python/agent/agent/adapters/mlxvlm_adapter.pyindex 8255725b08..6caae27826 100644--- a/libs/python/agent/agent/adapters/mlxvlm_adapter.py+++ b/libs/python/agent/agent/adapters/mlxvlm_adapter.py@@ -1,24 +1,26 @@import asyncio+import base64import functools-import warningsimport io-import base64import mathimport re+import warningsfrom concurrent.futures import ThreadPoolExecutor-from typing import Iterator, AsyncIterator, Dict, List, Any, Optional, Tuple, cast-from PIL import Image-from litellm.types.utils import GenericStreamingChunk, ModelResponse+from typing import Any, AsyncIterator, Dict, Iterator, List, Optional, Tuple, cast++from litellm import acompletion, completionfrom litellm.llms.custom_llm import CustomLLM-from litellm import completion, acompletion+from litellm.types.utils import GenericStreamingChunk, ModelResponse+from PIL import Image# Try to import MLX dependenciestry:import mlx.core as mx- from mlx_vlm import load, generate+ from mlx_vlm import generate, loadfrom mlx_vlm.prompt_utils import apply_chat_templatefrom mlx_vlm.utils import load_configfrom transformers.tokenization_utils import PreTrainedTokenizer+MLX_AVAILABLE = Trueexcept ImportError:MLX_AVAILABLE = False@@ -29,20 +31,28 @@ MIN_PIXELS = 100 * 28 * 28MAX_PIXELS = 16384 * 28 * 28MAX_RATIO = 200+def round_by_factor(number: float, factor: int) -> int:"""Returns the closest integer to 'number' that is divisible by 'factor'."""return round(number / factor) * factor+def ceil_by_factor(number: float, factor: int) -> int:"""Returns the smallest integer greater than or equal to 'number' that is divisible by 'factor'."""return math.ceil(number / factor) * factor+def floor_by_factor(number: float, factor: int) -> int:"""Returns the largest integer less than or equal to 'number' that is divisible by 'factor'."""return math.floor(number / factor) * factor+def smart_resize(- height: int, width: int, factor: int = IMAGE_FACTOR, min_pixels: int = MIN_PIXELS, max_pixels: int = MAX_PIXELS+ height: int,+ width: int,+ factor: int = IMAGE_FACTOR,+ min_pixels: int = MIN_PIXELS,+ max_pixels: int = MAX_PIXELS,) -> tuple[int, int]:"""Rescales the image so that the following conditions are met:@@ -70,61 +80,62 @@ def smart_resize(class MLXVLMAdapter(CustomLLM):"""MLX VLM Adapter for running vision-language models locally using MLX."""-+def __init__(self, **kwargs):"""Initialize the adapter.-+Args:**kwargs: Additional arguments"""super().__init__()-+self.models = {} # Cache for loaded modelsself.processors = {} # Cache for loaded processorsself.configs = {} # Cache for loaded configsself._executor = ThreadPoolExecutor(max_workers=1) # Single thread pool-+def _load_model_and_processor(self, model_name: str):"""Load model and processor if not already cached.-+Args:model_name: Name of the model to load-+Returns:Tuple of (model, processor, config)"""if not MLX_AVAILABLE:raise ImportError("MLX VLM dependencies not available. Please install mlx-vlm.")-+if model_name not in self.models:# Load model and processormodel_obj, processor = load(- model_name,- processor_kwargs={"min_pixels": MIN_PIXELS, "max_pixels": MAX_PIXELS}+ model_name, processor_kwargs={"min_pixels": MIN_PIXELS, "max_pixels": MAX_PIXELS})config = load_config(model_name)-+# Cache themself.models[model_name] = model_objself.processors[model_name] = processorself.configs[model_name] = config-+return self.models[model_name], self.processors[model_name], self.configs[model_name]-- def _process_coordinates(self, text: str, original_size: Tuple[int, int], model_size: Tuple[int, int]) -> str:++ def _process_coordinates(+ self, text: str, original_size: Tuple[int, int], model_size: Tuple[int, int]+ ) -> str:"""Process coordinates in box tokens based on image resizing using smart_resize approach.-+Args:text: Text containing box tokensoriginal_size: Original image size (width, height)model_size: Model processed image size (width, height)-+Returns:Text with processed coordinates"""# Find all box tokensbox_pattern = r"<\|box_start\|>\((\d+),\s*(\d+)\)<\|box_end\|>"-+def process_coords(match):model_x, model_y = int(match.group(1)), int(match.group(2))# Scale coordinates from model space to original image space@@ -132,15 +143,20 @@ class MLXVLMAdapter(CustomLLM):new_x = int(model_x * original_size[0] / model_size[0]) # Widthnew_y = int(model_y * original_size[1] / model_size[1]) # Heightreturn f"<|box_start|>({new_x},{new_y})<|box_end|>"-+return re.sub(box_pattern, process_coords, text)-- def _convert_messages(self, messages: List[Dict[str, Any]]) -> Tuple[List[Dict[str, Any]], List[Image.Image], Dict[int, Tuple[int, int]], Dict[int, Tuple[int, int]]]:++ def _convert_messages(self, messages: List[Dict[str, Any]]) -> Tuple[+ List[Dict[str, Any]],+ List[Image.Image],+ Dict[int, Tuple[int, int]],+ Dict[int, Tuple[int, int]],+ ]:"""Convert OpenAI format messages to MLX VLM format and extract images.-+Args:messages: Messages in OpenAI format-+Returns:Tuple of (processed_messages, images, original_sizes, model_sizes)"""@@ -149,13 +165,10 @@ class MLXVLMAdapter(CustomLLM):original_sizes = {} # Track original sizes of images for coordinate mappingmodel_sizes = {} # Track model processed sizesimage_index = 0-+for message in messages:- processed_message = {- "role": message["role"],- "content": []- }-+ processed_message = {"role": message["role"], "content": []}+content = message.get("content", [])if isinstance(content, str):# Simple text content@@ -165,164 +178,163 @@ class MLXVLMAdapter(CustomLLM):processed_content = []for item in content:if item.get("type") == "text":- processed_content.append({- "type": "text",- "text": item.get("text", "")- })+ processed_content.append({"type": "text", "text": item.get("text", "")})elif item.get("type") == "image_url":image_url = item.get("image_url", {}).get("url", "")pil_image = None-+if image_url.startswith("data:image/"):# Extract base64 data- base64_data = image_url.split(',')[1]+ base64_data = image_url.split(",")[1]# Convert base64 to PIL Imageimage_data = base64.b64decode(base64_data)pil_image = Image.open(io.BytesIO(image_data))else:# Handle file path or URLpil_image = Image.open(image_url)-+# Store original image size for coordinate mappingoriginal_size = pil_image.sizeoriginal_sizes[image_index] = original_size-+# Use smart_resize to determine model size# Note: smart_resize expects (height, width) but PIL gives (width, height)height, width = original_size[1], original_size[0]new_height, new_width = smart_resize(height, width)# Store model size in (width, height) format for consistent coordinate processingmodel_sizes[image_index] = (new_width, new_height)-+# Resize the image using the calculated dimensions from smart_resizeresized_image = pil_image.resize((new_width, new_height))images.append(resized_image)-+# Add image placeholder to content- processed_content.append({- "type": "image"- })-+ processed_content.append({"type": "image"})+image_index += 1-+processed_message["content"] = processed_content-+processed_messages.append(processed_message)-+return processed_messages, images, original_sizes, model_sizes-+def _generate(self, **kwargs) -> str:"""Generate response using the local MLX VLM model.-+Args:**kwargs: Keyword arguments containing messages and model info-+Returns:Generated text response"""- messages = kwargs.get('messages', [])- model_name = kwargs.get('model', 'mlx-community/UI-TARS-1.5-7B-4bit')- max_tokens = kwargs.get('max_tokens', 128)-+ messages = kwargs.get("messages", [])+ model_name = kwargs.get("model", "mlx-community/UI-TARS-1.5-7B-4bit")+ max_tokens = kwargs.get("max_tokens", 128)+# Warn about ignored kwargs- ignored_kwargs = set(kwargs.keys()) - {'messages', 'model', 'max_tokens'}+ ignored_kwargs = set(kwargs.keys()) - {"messages", "model", "max_tokens"}if ignored_kwargs:warnings.warn(f"Ignoring unsupported kwargs: {ignored_kwargs}")-+# Load model and processormodel, processor, config = self._load_model_and_processor(model_name)-+# Convert messages and extract imagesprocessed_messages, images, original_sizes, model_sizes = self._convert_messages(messages)-+# Process user text input with box coordinates after image processing# Swap original_size and model_size arguments for inverse transformationfor msg_idx, msg in enumerate(processed_messages):if msg.get("role") == "user" and isinstance(msg.get("content"), str):content = msg.get("content", "")- if "<|box_start|>" in content and original_sizes and model_sizes and 0 in original_sizes and 0 in model_sizes:+ if (+ "<|box_start|>" in content+ and original_sizes+ and model_sizes+ and 0 in original_sizes+ and 0 in model_sizes+ ):orig_size = original_sizes[0]model_size = model_sizes[0]# Swap arguments to perform inverse transformation for user input- processed_messages[msg_idx]["content"] = self._process_coordinates(content, model_size, orig_size)-+ processed_messages[msg_idx]["content"] = self._process_coordinates(+ content, model_size, orig_size+ )+try:# Format prompt according to model requirements using the processor directlyprompt = processor.apply_chat_template(- processed_messages,- tokenize=False,- add_generation_prompt=True,- return_tensors='pt'+ processed_messages, tokenize=False, add_generation_prompt=True, return_tensors="pt")tokenizer = cast(PreTrainedTokenizer, processor)-+# Generate responsetext_content, usage = generate(- model,- tokenizer,- str(prompt),- images, # type: ignore+ model,+ tokenizer,+ str(prompt),+ images, # type: ignoreverbose=False,- max_tokens=max_tokens+ max_tokens=max_tokens,)-+except Exception as e:raise RuntimeError(f"Error generating response: {str(e)}") from e-+# Process coordinates in the response back to original image spaceif original_sizes and model_sizes and 0 in original_sizes and 0 in model_sizes:# Get original image size and model size (using the first image)orig_size = original_sizes[0]model_size = model_sizes[0]-+# Check if output contains box tokens that need processingif "<|box_start|>" in text_content:# Process coordinates from model space back to original image spacetext_content = self._process_coordinates(text_content, orig_size, model_size)-+return text_content-+def completion(self, *args, **kwargs) -> ModelResponse:"""Synchronous completion method.-+Returns:ModelResponse with generated text"""generated_text = self._generate(**kwargs)-+result = completion(model=f"mlx/{kwargs.get('model', 'mlx-community/UI-TARS-1.5-7B-4bit')}",mock_response=generated_text,)return cast(ModelResponse, result)-+async def acompletion(self, *args, **kwargs) -> ModelResponse:"""Asynchronous completion method.-+Returns:ModelResponse with generated text"""# Run _generate in thread pool to avoid blockingloop = asyncio.get_event_loop()generated_text = await loop.run_in_executor(- self._executor,- functools.partial(self._generate, **kwargs)+ self._executor, functools.partial(self._generate, **kwargs))-+result = await acompletion(model=f"mlx/{kwargs.get('model', 'mlx-community/UI-TARS-1.5-7B-4bit')}",mock_response=generated_text,)return cast(ModelResponse, result)-+def streaming(self, *args, **kwargs) -> Iterator[GenericStreamingChunk]:"""Synchronous streaming method.-+Returns:Iterator of GenericStreamingChunk"""generated_text = self._generate(**kwargs)-+generic_streaming_chunk: GenericStreamingChunk = {"finish_reason": "stop","index": 0,@@ -331,22 +343,21 @@ class MLXVLMAdapter(CustomLLM):"tool_use": None,"usage": {"completion_tokens": 0, "prompt_tokens": 0, "total_tokens": 0},}-+yield generic_streaming_chunk-+async def astreaming(self, *args, **kwargs) -> AsyncIterator[GenericStreamingChunk]:"""Asynchronous streaming method.-+Returns:AsyncIterator of GenericStreamingChunk"""# Run _generate in thread pool to avoid blockingloop = asyncio.get_event_loop()generated_text = await loop.run_in_executor(- self._executor,- functools.partial(self._generate, **kwargs)+ self._executor, functools.partial(self._generate, **kwargs))-+generic_streaming_chunk: GenericStreamingChunk = {"finish_reason": "stop","index": 0,@@ -355,5 +366,5 @@ class MLXVLMAdapter(CustomLLM):"tool_use": None,"usage": {"completion_tokens": 0, "prompt_tokens": 0, "total_tokens": 0},}-- yield generic_streaming_chunk\ No newline at end of file++ yield generic_streaming_chunkdiff --git a/libs/python/agent/agent/adapters/models/__init__.py b/libs/python/agent/agent/adapters/models/__init__.pyindex 3ed4840468..a7948d79d1 100644--- a/libs/python/agent/agent/adapters/models/__init__.py+++ b/libs/python/agent/agent/adapters/models/__init__.py@@ -2,32 +2,40 @@ from typing import Optionaltry:from transformers import AutoConfig+HF_AVAILABLE = Trueexcept ImportError:HF_AVAILABLE = Falsefrom .generic import GenericHFModel+from .internvl import InternVLModelfrom .opencua import OpenCUAModelfrom .qwen2_5_vl import Qwen2_5_VLModel-from .internvl import InternVLModel+def load_model(model_name: str, device: str = "auto", trust_remote_code: bool = False):"""Factory function to load and return the right model handler instance.-+- If the underlying transformers config class matches OpenCUA, return OpenCUAModel- Otherwise, return GenericHFModel"""if not HF_AVAILABLE:raise ImportError(- "HuggingFace transformers dependencies not found. Install with: pip install \"cua-agent[uitars-hf]\""+ 'HuggingFace transformers dependencies not found. Install with: pip install "cua-agent[uitars-hf]"')cfg = AutoConfig.from_pretrained(model_name, trust_remote_code=trust_remote_code)cls = cfg.__class__.__name__print(f"cls: {cls}")if "OpenCUA" in cls:- return OpenCUAModel(model_name=model_name, device=device, trust_remote_code=trust_remote_code)+ return OpenCUAModel(+ model_name=model_name, device=device, trust_remote_code=trust_remote_code+ )elif "Qwen2_5_VL" in cls:- return Qwen2_5_VLModel(model_name=model_name, device=device, trust_remote_code=trust_remote_code)+ return Qwen2_5_VLModel(+ model_name=model_name, device=device, trust_remote_code=trust_remote_code+ )elif "InternVL" in cls:- return InternVLModel(model_name=model_name, device=device, trust_remote_code=trust_remote_code)+ return InternVLModel(+ model_name=model_name, device=device, trust_remote_code=trust_remote_code+ )return GenericHFModel(model_name=model_name, device=device, trust_remote_code=trust_remote_code)diff --git a/libs/python/agent/agent/adapters/models/generic.py b/libs/python/agent/agent/adapters/models/generic.pyindex aefbaa7f2a..01c8c3bc68 100644--- a/libs/python/agent/agent/adapters/models/generic.py+++ b/libs/python/agent/agent/adapters/models/generic.py@@ -1,9 +1,10 @@-from typing import List, Dict, Any, Optional+from typing import Any, Dict, List, Optional# Hugging Face imports are local to avoid hard dependency at module importtry:import torch # type: ignorefrom transformers import AutoModel, AutoProcessor # type: ignore+HF_AVAILABLE = Trueexcept Exception:HF_AVAILABLE = False@@ -14,10 +15,12 @@ class GenericHFModel:Loads an AutoModelForImageTextToText and AutoProcessor and generates text."""- def __init__(self, model_name: str, device: str = "auto", trust_remote_code: bool = False) -> None:+ def __init__(+ self, model_name: str, device: str = "auto", trust_remote_code: bool = False+ ) -> None:if not HF_AVAILABLE:raise ImportError(- "HuggingFace transformers dependencies not found. Install with: pip install \"cua-agent[uitars-hf]\""+ 'HuggingFace transformers dependencies not found. Install with: pip install "cua-agent[uitars-hf]"')self.model_name = model_nameself.device = device@@ -64,7 +67,7 @@ class GenericHFModel:generated_ids = self.model.generate(**inputs, max_new_tokens=max_new_tokens)# Trim prompt tokens from outputgenerated_ids_trimmed = [- out_ids[len(in_ids):] for in_ids, out_ids in zip(inputs.input_ids, generated_ids)+ out_ids[len(in_ids) :] for in_ids, out_ids in zip(inputs.input_ids, generated_ids)]# Decodeoutput_text = self.processor.batch_decode(diff --git a/libs/python/agent/agent/adapters/models/internvl.py b/libs/python/agent/agent/adapters/models/internvl.pyindex b9aa424335..c0a7c84fe4 100644--- a/libs/python/agent/agent/adapters/models/internvl.py+++ b/libs/python/agent/agent/adapters/models/internvl.py@@ -1,19 +1,22 @@from __future__ import annotations-from typing import List, Dict, Any, Optional++from typing import Any, Dict, List, Optional# Hugging Face imports are local to avoid hard dependency at module importtry:- import torch # type: ignore- from transformers import AutoModel, AutoTokenizer # type: ignore+ import base64 # type: ignore+ from io import BytesIO # type: ignore+# Attempt to import InternVL's model dependenciesimport einops as _ # type: ignore+ import requests # type: ignoreimport timm as _ # type: ignore- from PIL import Image # type: ignore+ import torch # type: ignoreimport torchvision.transforms as T # type: ignore+ from PIL import Image # type: ignorefrom torchvision.transforms.functional import InterpolationMode # type: ignore- import base64 # type: ignore- from io import BytesIO # type: ignore- import requests # type: ignore+ from transformers import AutoModel, AutoTokenizer # type: ignore+HF_AVAILABLE = Trueexcept Exception:HF_AVAILABLE = False@@ -25,10 +28,12 @@ class InternVLModel:Provides preprocessing to support multi-turn conversations with multiple images."""- def __init__(self, model_name: str, device: str = "auto", trust_remote_code: bool = False) -> None:+ def __init__(+ self, model_name: str, device: str = "auto", trust_remote_code: bool = False+ ) -> None:if not HF_AVAILABLE:raise ImportError(- "InternVL dependencies not found. Install with: pip install \"cua-agent[internvl-hf]\""+ 'InternVL dependencies not found. Install with: pip install "cua-agent[internvl-hf]"')self.model_name = model_nameself.device = device@@ -60,16 +65,25 @@ class InternVLModel:def _build_transform(self, input_size: int) -> T.Compose:MEAN, STD = self.IMAGENET_MEAN, self.IMAGENET_STD- transform = T.Compose([- T.Lambda(lambda img: img.convert('RGB') if img.mode != 'RGB' else img),- T.Resize((input_size, input_size), interpolation=InterpolationMode.BICUBIC),- T.ToTensor(),- T.Normalize(mean=MEAN, std=STD)- ])+ transform = T.Compose(+ [+ T.Lambda(lambda img: img.convert("RGB") if img.mode != "RGB" else img),+ T.Resize((input_size, input_size), interpolation=InterpolationMode.BICUBIC),+ T.ToTensor(),+ T.Normalize(mean=MEAN, std=STD),+ ]+ )return transform- def _find_closest_aspect_ratio(self, aspect_ratio: float, target_ratios: List[tuple], width: int, height: int, image_size: int):- best_ratio_diff = float('inf')+ def _find_closest_aspect_ratio(+ self,+ aspect_ratio: float,+ target_ratios: List[tuple],+ width: int,+ height: int,+ image_size: int,+ ):+ best_ratio_diff = float("inf")best_ratio = (1, 1)area = width * heightfor ratio in target_ratios:@@ -83,17 +97,29 @@ class InternVLModel:best_ratio = ratioreturn best_ratio- def _dynamic_preprocess(self, image: Image.Image, min_num: int = 1, max_num: int = 12, image_size: int = 448, use_thumbnail: bool = True) -> List[Image.Image]:+ def _dynamic_preprocess(+ self,+ image: Image.Image,+ min_num: int = 1,+ max_num: int = 12,+ image_size: int = 448,+ use_thumbnail: bool = True,+ ) -> List[Image.Image]:orig_width, orig_height = image.sizeaspect_ratio = orig_width / orig_heighttarget_ratios = set(- (i, j) for n in range(min_num, max_num + 1) for i in range(1, n + 1) for j in range(1, n + 1) if- i * j <= max_num and i * j >= min_num)+ (i, j)+ for n in range(min_num, max_num + 1)+ for i in range(1, n + 1)+ for j in range(1, n + 1)+ if i * j <= max_num and i * j >= min_num+ )target_ratios = sorted(target_ratios, key=lambda x: x[0] * x[1])target_aspect_ratio = self._find_closest_aspect_ratio(- aspect_ratio, target_ratios, orig_width, orig_height, image_size)+ aspect_ratio, target_ratios, orig_width, orig_height, image_size+ )target_width = image_size * target_aspect_ratio[0]target_height = image_size * target_aspect_ratio[1]@@ -106,7 +132,7 @@ class InternVLModel:(i % (target_width // image_size)) * image_size,(i // (target_width // image_size)) * image_size,((i % (target_width // image_size)) + 1) * image_size,- ((i // (target_width // image_size)) + 1) * image_size+ ((i // (target_width // image_size)) + 1) * image_size,)split_img = resized_img.crop(box)processed_images.append(split_img)@@ -122,20 +148,24 @@ class InternVLModel:# data URL base64header, b64data = src.split(",", 1)img_bytes = base64.b64decode(b64data)- return Image.open(BytesIO(img_bytes)).convert('RGB')+ return Image.open(BytesIO(img_bytes)).convert("RGB")if src.startswith("http://") or src.startswith("https://"):resp = requests.get(src, timeout=10)resp.raise_for_status()- return Image.open(BytesIO(resp.content)).convert('RGB')+ return Image.open(BytesIO(resp.content)).convert("RGB")# Assume local file path- return Image.open(src).convert('RGB')+ return Image.open(src).convert("RGB")- def _images_to_pixel_values(self, images: List[Image.Image], input_size: int = 448, max_num: int = 12):+ def _images_to_pixel_values(+ self, images: List[Image.Image], input_size: int = 448, max_num: int = 12+ ):transform = self._build_transform(input_size=input_size)pixel_values_list = []num_patches_list: List[int] = []for img in images:- tiles = self._dynamic_preprocess(img, image_size=input_size, use_thumbnail=True, max_num=max_num)+ tiles = self._dynamic_preprocess(+ img, image_size=input_size, use_thumbnail=True, max_num=max_num+ )pv = [transform(tile) for tile in tiles]pv = torch.stack(pv)num_patches_list.append(pv.shape[0])@@ -191,7 +221,9 @@ class InternVLModel:last_user_text_parts = parts_text or last_user_text_partselif role == "assistant":# Only keep text content for history- parts_text = [item.get("text", "") for item in content_items if item.get("type") == "text"]+ parts_text = [+ item.get("text", "") for item in content_items if item.get("type") == "text"+ ]text = "\n".join(parts_text).strip()if text:context_lines.append(f"Assistant: {text}")@@ -200,7 +232,9 @@ class InternVLModel:pixel_values = Nonenum_patches_list: List[int] = []if all_images:- pixel_values, num_patches_list = self._images_to_pixel_values(all_images, input_size=448, max_num=12)+ pixel_values, num_patches_list = self._images_to_pixel_values(+ all_images, input_size=448, max_num=12+ )if pixel_values is not None:# Convert dtype/device as in docspixel_values = pixel_values.to(torch.bfloat16)@@ -246,7 +280,9 @@ class InternVLModel:num_patches_list=num_patches_list,)else:- response = self.model.chat(self.tokenizer, pixel_values, question, generation_config)+ response = self.model.chat(+ self.tokenizer, pixel_values, question, generation_config+ )except Exception as e:# Fallback: return empty string to avoid crashing the adapterreturn ""diff --git a/libs/python/agent/agent/adapters/models/opencua.py b/libs/python/agent/agent/adapters/models/opencua.pyindex 32c73134ad..a2831d4db4 100644--- a/libs/python/agent/agent/adapters/models/opencua.py+++ b/libs/python/agent/agent/adapters/models/opencua.py@@ -1,13 +1,18 @@-from typing import List, Dict, Any-import reimport base64+import refrom io import BytesIO+from typing import Any, Dict, Listtry:+ import blobfile as _ # assert blobfile is installedimport torch # type: ignore- from transformers import AutoTokenizer, AutoModel, AutoImageProcessor # type: ignorefrom PIL import Image # type: ignore- import blobfile as _ # assert blobfile is installed+ from transformers import ( # type: ignore+ AutoImageProcessor,+ AutoModel,+ AutoTokenizer,+ )+OPENCUA_AVAILABLE = Trueexcept Exception:OPENCUA_AVAILABLE = False@@ -16,10 +21,12 @@ except Exception:class OpenCUAModel:"""OpenCUA model handler using AutoTokenizer, AutoModel and AutoImageProcessor."""- def __init__(self, model_name: str, device: str = "auto", trust_remote_code: bool = False) -> None:+ def __init__(+ self, model_name: str, device: str = "auto", trust_remote_code: bool = False+ ) -> None:if not OPENCUA_AVAILABLE:raise ImportError(- "OpenCUA requirements not found. Install with: pip install \"cua-agent[opencua-hf]\""+ 'OpenCUA requirements not found. Install with: pip install "cua-agent[opencua-hf]"')self.model_name = model_nameself.device = device@@ -56,7 +63,11 @@ class OpenCUAModel:return ""def generate(self, messages: List[Dict[str, Any]], max_new_tokens: int = 512) -> str:- assert self.model is not None and self.tokenizer is not None and self.image_processor is not None+ assert (+ self.model is not None+ and self.tokenizer is not None+ and self.image_processor is not None+ )# Tokenize text side using chat templateinput_ids = self.tokenizer.apply_chat_template(@@ -74,7 +85,11 @@ class OpenCUAModel:pixel_values = torch.tensor(image_info["pixel_values"]).to(dtype=torch.bfloat16, device=self.model.device)- grid_thws = torch.tensor(image_info["image_grid_thw"]) if "image_grid_thw" in image_info else None+ grid_thws = (+ torch.tensor(image_info["image_grid_thw"])+ if "image_grid_thw" in image_info+ else None+ )gen_kwargs: Dict[str, Any] = {"max_new_tokens": max_new_tokens,diff --git a/libs/python/agent/agent/adapters/models/qwen2_5_vl.py b/libs/python/agent/agent/adapters/models/qwen2_5_vl.pyindex 17b25f8a9f..8c8045c04f 100644--- a/libs/python/agent/agent/adapters/models/qwen2_5_vl.py+++ b/libs/python/agent/agent/adapters/models/qwen2_5_vl.py@@ -1,9 +1,10 @@-from typing import List, Dict, Any, Optional+from typing import Any, Dict, List, Optional# Hugging Face imports are local to avoid hard dependency at module importtry:import torch # type: ignorefrom transformers import AutoModelForImageTextToText, AutoProcessor # type: ignore+HF_AVAILABLE = Trueexcept Exception:HF_AVAILABLE = False@@ -14,10 +15,12 @@ class Qwen2_5_VLModel:Loads an AutoModelForImageTextToText and AutoProcessor and generates text."""- def __init__(self, model_name: str, device: str = "auto", trust_remote_code: bool = False) -> None:+ def __init__(+ self, model_name: str, device: str = "auto", trust_remote_code: bool = False+ ) -> None:if not HF_AVAILABLE:raise ImportError(- "HuggingFace transformers dependencies not found. Install with: pip install \"cua-agent[uitars-hf]\""+ 'HuggingFace transformers dependencies not found. Install with: pip install "cua-agent[uitars-hf]"')self.model_name = model_nameself.device = device@@ -64,7 +67,7 @@ class Qwen2_5_VLModel:generated_ids = self.model.generate(**inputs, max_new_tokens=max_new_tokens)# Trim prompt tokens from outputgenerated_ids_trimmed = [- out_ids[len(in_ids):] for in_ids, out_ids in zip(inputs.input_ids, generated_ids)+ out_ids[len(in_ids) :] for in_ids, out_ids in zip(inputs.input_ids, generated_ids)]# Decodeoutput_text = self.processor.batch_decode(diff --git a/libs/python/agent/agent/agent.py b/libs/python/agent/agent/agent.pyindex fb119a68bf..370af99718 100644--- a/libs/python/agent/agent/agent.py+++ b/libs/python/agent/agent/agent.py@@ -3,76 +3,83 @@ ComputerAgent - Main agent class that selects and runs agent loops"""import asyncio+import inspect+import jsonfrom pathlib import Path-from typing import Dict, List, Any, Optional, AsyncGenerator, Union, cast, Callable, Set, Tuple--from litellm.responses.utils import Usage--from .types import (- Messages,- AgentCapability,- ToolError,- IllegalArgumentError+from typing import (+ Any,+ AsyncGenerator,+ Callable,+ Dict,+ List,+ Optional,+ Set,+ Tuple,+ Union,+ cast,)-from .responses import make_tool_error_item, replace_failed_computer_calls_with_function_calls-from .decorators import find_agent_config-import json+import litellmimport litellm.utils-import inspect+from litellm.responses.utils import Usage+from .adapters import (HuggingFaceLocalAdapter,HumanAdapter,MLXVLMAdapter,)from .callbacks import (- ImageRetentionCallback,- LoggingCallback,- TrajectorySaverCallback,BudgetManagerCallback,- TelemetryCallback,+ ImageRetentionCallback,+ LoggingCallback,OperatorNormalizerCallback,PromptInstructionsCallback,+ TelemetryCallback,+ TrajectorySaverCallback,)-from .computers import (- AsyncComputerHandler,- is_agent_computer,- make_computer_handler+from .computers import AsyncComputerHandler, is_agent_computer, make_computer_handler+from .decorators import find_agent_config+from .responses import (+ make_tool_error_item,+ replace_failed_computer_calls_with_function_calls,)+from .types import AgentCapability, IllegalArgumentError, Messages, ToolError+def assert_callable_with(f, *args, **kwargs):- """Check if function can be called with given arguments."""- try:- inspect.signature(f).bind(*args, **kwargs)- return True- except TypeError as e:- sig = inspect.signature(f)- raise IllegalArgumentError(f"Expected {sig}, got args={args} kwargs={kwargs}") from e+ """Check if function can be called with given arguments."""+ try:+ inspect.signature(f).bind(*args, **kwargs)+ return True+ except TypeError as e:+ sig = inspect.signature(f)+ raise IllegalArgumentError(f"Expected {sig}, got args={args} kwargs={kwargs}") from e+def get_json(obj: Any, max_depth: int = 10) -> Any:def custom_serializer(o: Any, depth: int = 0, seen: Optional[Set[int]] = None) -> Any:if seen is None:seen = set()-+# Use model_dump() if available- if hasattr(o, 'model_dump'):+ if hasattr(o, "model_dump"):return o.model_dump()-+# Check depth limitif depth > max_depth:return f"<max_depth_exceeded:{max_depth}>"-+# Check for circular references using object idobj_id = id(o)if obj_id in seen:return f"<circular_reference:{type(o).__name__}>"-+# Handle Computer objects- if hasattr(o, '__class__') and 'computer' in getattr(o, '__class__').__name__.lower():+ if hasattr(o, "__class__") and "computer" in o.__class__.__name__.lower():return f"<computer:{o.__class__.__name__}>"# Handle objects with __dict__- if hasattr(o, '__dict__'):+ if hasattr(o, "__dict__"):seen.add(obj_id)try:result = {}@@ -84,7 +91,7 @@ def get_json(obj: Any, max_depth: int = 10) -> Any:return resultfinally:seen.discard(obj_id)-+# Handle common types that might contain nested objectselif isinstance(o, dict):seen.add(obj_id)@@ -96,7 +103,7 @@ def get_json(obj: Any, max_depth: int = 10) -> Any:}finally:seen.discard(obj_id)-+elif isinstance(o, (list, tuple, set)):seen.add(obj_id)try:@@ -107,32 +114,33 @@ def get_json(obj: Any, max_depth: int = 10) -> Any:]finally:seen.discard(obj_id)-+# For basic types that json.dumps can handleelif isinstance(o, (str, int, float, bool)) or o is None:return o-+# Fallback to string representationelse:return str(o)-+def remove_nones(obj: Any) -> Any:if isinstance(obj, dict):return {k: remove_nones(v) for k, v in obj.items() if v is not None}elif isinstance(obj, list):return [remove_nones(item) for item in obj if item is not None]return obj-+# Serialize with circular reference and depth protectionserialized = custom_serializer(obj)-+# Convert to JSON string and back to ensure JSON compatibilityjson_str = json.dumps(serialized)parsed = json.loads(json_str)-+# Final cleanup of any remaining None valuesreturn remove_nones(parsed)+def sanitize_message(msg: Any) -> Any:"""Return a copy of the message with image_url omitted for computer_call_output messages."""if msg.get("type") == "computer_call_output":@@ -143,19 +151,24 @@ def sanitize_message(msg: Any) -> Any:return sanitizedreturn msg+def get_output_call_ids(messages: List[Dict[str, Any]]) -> List[str]:call_ids = []for message in messages:- if message.get("type") == "computer_call_output" or message.get("type") == "function_call_output":+ if (+ message.get("type") == "computer_call_output"+ or message.get("type") == "function_call_output"+ ):call_ids.append(message.get("call_id"))return call_ids+class ComputerAgent:"""Main agent class that automatically selects the appropriate agent loopbased on the model and executes tool calls."""-+def __init__(self,model: str,@@ -172,11 +185,11 @@ class ComputerAgent:max_trajectory_budget: Optional[float | dict] = None,telemetry_enabled: Optional[bool] = True,trust_remote_code: Optional[bool] = False,- **kwargs+ **kwargs,):"""Initialize ComputerAgent.-+Args:model: Model name (e.g., "claude-3-5-sonnet-20241022", "computer-use-preview", "omni+vertex_ai/gemini-pro")tools: List of tools (computer objects, decorated functions, etc.)@@ -193,11 +206,11 @@ class ComputerAgent:telemetry_enabled: If set, adds TelemetryCallback to track anonymized usage data. Enabled by default.trust_remote_code: If set, trust remote code when loading local models. Disabled by default.**kwargs: Additional arguments passed to the agent loop- """+ """# If the loop is "human/human", we need to prefix a grounding model fallbackif model in ["human/human", "human"]:model = "openai/computer-use-preview+human/human"-+self.model = modelself.tools = tools or []self.custom_loop = custom_loop@@ -236,34 +249,33 @@ class ComputerAgent:# Add image retention callback if only_n_most_recent_images is setif self.only_n_most_recent_images:self.callbacks.append(ImageRetentionCallback(self.only_n_most_recent_images))-+# Add trajectory saver callback if trajectory_dir is setif self.trajectory_dir:if isinstance(self.trajectory_dir, dict):self.callbacks.append(TrajectorySaverCallback(**self.trajectory_dir))elif isinstance(self.trajectory_dir, (str, Path)):self.callbacks.append(TrajectorySaverCallback(str(self.trajectory_dir)))-+# Add budget manager if max_trajectory_budget is setif max_trajectory_budget:if isinstance(max_trajectory_budget, dict):self.callbacks.append(BudgetManagerCallback(**max_trajectory_budget))else:self.callbacks.append(BudgetManagerCallback(max_trajectory_budget))-+# == Enable local model providers w/ LiteLLM ==# Register local model providershf_adapter = HuggingFaceLocalAdapter(- device="auto",- trust_remote_code=self.trust_remote_code or False+ device="auto", trust_remote_code=self.trust_remote_code or False)human_adapter = HumanAdapter()mlx_adapter = MLXVLMAdapter()litellm.custom_provider_map = [{"provider": "huggingface-local", "custom_handler": hf_adapter},{"provider": "human", "custom_handler": human_adapter},- {"provider": "mlx", "custom_handler": mlx_adapter}+ {"provider": "mlx", "custom_handler": mlx_adapter},]litellm.suppress_debug_info = True@@ -280,16 +292,16 @@ class ComputerAgent:# Instantiate the agent config classself.agent_loop = config_info.agent_class()self.agent_config_info = config_info-+self.tool_schemas = []self.computer_handler = None-+async def _initialize_computers(self):"""Initialize computer objects"""if not self.tool_schemas:# Process tools and create tool schemasself.tool_schemas = self._process_tools()-+# Find computer tool and create interface adaptercomputer_handler = Nonefor schema in self.tool_schemas:@@ -297,7 +309,7 @@ class ComputerAgent:computer_handler = await make_computer_handler(schema["computer"])breakself.computer_handler = computer_handler-+def _process_input(self, input: Messages) -> List[Dict[str, Any]]:"""Process input messages and create schemas for the agent loop"""if isinstance(input, str):@@ -307,69 +319,73 @@ class ComputerAgent:def _process_tools(self) -> List[Dict[str, Any]]:"""Process tools and create schemas for the agent loop"""schemas = []-+for tool in self.tools:# Check if it's a computer object (has interface attribute)if is_agent_computer(tool):# This is a computer tool - will be handled by agent loop- schemas.append({- "type": "computer",- "computer": tool- })+ schemas.append({"type": "computer", "computer": tool})elif callable(tool):# Use litellm.utils.function_to_dict to extract schema from docstringtry:function_schema = litellm.utils.function_to_dict(tool)- schemas.append({- "type": "function",- "function": function_schema- })+ schemas.append({"type": "function", "function": function_schema})except Exception as e:print(f"Warning: Could not process tool {tool}: {e}")else:print(f"Warning: Unknown tool type: {tool}")-+return schemas-+def _get_tool(self, name: str) -> Optional[Callable]:"""Get a tool by name"""for tool in self.tools:- if hasattr(tool, '__name__') and tool.__name__ == name:+ if hasattr(tool, "__name__") and tool.__name__ == name:return tool- elif hasattr(tool, 'func') and tool.func.__name__ == name:+ elif hasattr(tool, "func") and tool.func.__name__ == name:return toolreturn None-+# ============================================================================# AGENT RUN LOOP LIFECYCLE HOOKS# ============================================================================-+async def _on_run_start(self, kwargs: Dict[str, Any], old_items: List[Dict[str, Any]]) -> None:"""Initialize run tracking by calling callbacks."""for callback in self.callbacks:- if hasattr(callback, 'on_run_start'):+ if hasattr(callback, "on_run_start"):await callback.on_run_start(kwargs, old_items)-- async def _on_run_end(self, kwargs: Dict[str, Any], old_items: List[Dict[str, Any]], new_items: List[Dict[str, Any]]) -> None:++ async def _on_run_end(+ self,+ kwargs: Dict[str, Any],+ old_items: List[Dict[str, Any]],+ new_items: List[Dict[str, Any]],+ ) -> None:"""Finalize run tracking by calling callbacks."""for callback in self.callbacks:- if hasattr(callback, 'on_run_end'):+ if hasattr(callback, "on_run_end"):await callback.on_run_end(kwargs, old_items, new_items)-- async def _on_run_continue(self, kwargs: Dict[str, Any], old_items: List[Dict[str, Any]], new_items: List[Dict[str, Any]]) -> bool:++ async def _on_run_continue(+ self,+ kwargs: Dict[str, Any],+ old_items: List[Dict[str, Any]],+ new_items: List[Dict[str, Any]],+ ) -> bool:"""Check if run should continue by calling callbacks."""for callback in self.callbacks:- if hasattr(callback, 'on_run_continue'):+ if hasattr(callback, "on_run_continue"):should_continue = await callback.on_run_continue(kwargs, old_items, new_items)if not should_continue:return Falsereturn True-+async def _on_llm_start(self, messages: List[Dict[str, Any]]) -> List[Dict[str, Any]]:"""Prepare messages for the LLM call by applying callbacks."""result = messagesfor callback in self.callbacks:- if hasattr(callback, 'on_llm_start'):+ if hasattr(callback, "on_llm_start"):result = await callback.on_llm_start(result)return result@@ -377,82 +393,91 @@ class ComputerAgent:"""Postprocess messages after the LLM call by applying callbacks."""result = messagesfor callback in self.callbacks:- if hasattr(callback, 'on_llm_end'):+ if hasattr(callback, "on_llm_end"):result = await callback.on_llm_end(result)return resultasync def _on_responses(self, kwargs: Dict[str, Any], responses: Dict[str, Any]) -> None:"""Called when responses are received."""for callback in self.callbacks:- if hasattr(callback, 'on_responses'):+ if hasattr(callback, "on_responses"):await callback.on_responses(get_json(kwargs), get_json(responses))-+async def _on_computer_call_start(self, item: Dict[str, Any]) -> None:"""Called when a computer call is about to start."""for callback in self.callbacks:- if hasattr(callback, 'on_computer_call_start'):+ if hasattr(callback, "on_computer_call_start"):await callback.on_computer_call_start(get_json(item))-- async def _on_computer_call_end(self, item: Dict[str, Any], result: List[Dict[str, Any]]) -> None:++ async def _on_computer_call_end(+ self, item: Dict[str, Any], result: List[Dict[str, Any]]+ ) -> None:"""Called when a computer call has completed."""for callback in self.callbacks:- if hasattr(callback, 'on_computer_call_end'):+ if hasattr(callback, "on_computer_call_end"):await callback.on_computer_call_end(get_json(item), get_json(result))-+async def _on_function_call_start(self, item: Dict[str, Any]) -> None:"""Called when a function call is about to start."""for callback in self.callbacks:- if hasattr(callback, 'on_function_call_start'):+ if hasattr(callback, "on_function_call_start"):await callback.on_function_call_start(get_json(item))-- async def _on_function_call_end(self, item: Dict[str, Any], result: List[Dict[str, Any]]) -> None:++ async def _on_function_call_end(+ self, item: Dict[str, Any], result: List[Dict[str, Any]]+ ) -> None:"""Called when a function call has completed."""for callback in self.callbacks:- if hasattr(callback, 'on_function_call_end'):+ if hasattr(callback, "on_function_call_end"):await callback.on_function_call_end(get_json(item), get_json(result))-+async def _on_text(self, item: Dict[str, Any]) -> None:"""Called when a text message is encountered."""for callback in self.callbacks:- if hasattr(callback, 'on_text'):+ if hasattr(callback, "on_text"):await callback.on_text(get_json(item))-+async def _on_api_start(self, kwargs: Dict[str, Any]) -> None:"""Called when an LLM API call is about to start."""for callback in self.callbacks:- if hasattr(callback, 'on_api_start'):+ if hasattr(callback, "on_api_start"):await callback.on_api_start(get_json(kwargs))-+async def _on_api_end(self, kwargs: Dict[str, Any], result: Any) -> None:"""Called when an LLM API call has completed."""for callback in self.callbacks:- if hasattr(callback, 'on_api_end'):+ if hasattr(callback, "on_api_end"):await callback.on_api_end(get_json(kwargs), get_json(result))async def _on_usage(self, usage: Dict[str, Any]) -> None:"""Called when usage information is received."""for callback in self.callbacks:- if hasattr(callback, 'on_usage'):+ if hasattr(callback, "on_usage"):await callback.on_usage(get_json(usage))async def _on_screenshot(self, screenshot: Union[str, bytes], name: str = "screenshot") -> None:"""Called when a screenshot is taken."""for callback in self.callbacks:- if hasattr(callback, 'on_screenshot'):+ if hasattr(callback, "on_screenshot"):await callback.on_screenshot(screenshot, name)# ============================================================================# AGENT OUTPUT PROCESSING# ============================================================================-- async def _handle_item(self, item: Any, computer: Optional[AsyncComputerHandler] = None, ignore_call_ids: Optional[List[str]] = None) -> List[Dict[str, Any]]:++ async def _handle_item(+ self,+ item: Any,+ computer: Optional[AsyncComputerHandler] = None,+ ignore_call_ids: Optional[List[str]] = None,+ ) -> List[Dict[str, Any]]:"""Handle each item; may cause a computer action + screenshot."""call_id = item.get("call_id")if ignore_call_ids and call_id and call_id in ignore_call_ids:return []-+item_type = item.get("type", None)-+if item_type == "message":await self._on_text(item)# # Print messages@@ -461,7 +486,7 @@ class ComputerAgent:# if content_item.get("text"):# print(content_item.get("text"))return []-+try:if item_type == "computer_call":await self._on_computer_call_start(item)@@ -472,14 +497,16 @@ class ComputerAgent:action = item.get("action")action_type = action.get("type")if action_type is None:- print(f"Action type cannot be `None`: action={action}, action_type={action_type}")+ print(+ f"Action type cannot be `None`: action={action}, action_type={action_type}"+ )return []-+# Extract action arguments (all fields except 'type')action_args = {k: v for k, v in action.items() if k != "type"}-+# print(f"{action_type}({action_args})")-+# Execute the computer actioncomputer_method = getattr(computer, action_type, None)if computer_method:@@ -487,13 +514,13 @@ class ComputerAgent:await computer_method(**action_args)else:raise ToolError(f"Unknown computer action: {action_type}")-+# Take screenshot after actionif self.screenshot_delay and self.screenshot_delay > 0:await asyncio.sleep(self.screenshot_delay)screenshot_base64 = await computer.screenshot()await self._on_screenshot(screenshot_base64, "screenshot_after")-+# Handle safety checkspending_checks = item.get("pending_safety_checks", [])acknowledged_checks = []@@ -505,7 +532,7 @@ class ComputerAgent:# acknowledged_checks.append(check)# else:# raise ValueError(f"Safety check failed: {check_message}")-+# Create call outputcall_output = {"type": "computer_call_output",@@ -516,25 +543,25 @@ class ComputerAgent:"image_url": f"data:image/png;base64,{screenshot_base64}",},}-+# # Additional URL safety checks for browser environments# if await computer.get_environment() == "browser":# current_url = await computer.get_current_url()# call_output["output"]["current_url"] = current_url# # TODO: implement a callback for URL safety checks# # check_blocklisted_url(current_url)-+result = [call_output]await self._on_computer_call_end(item, result)return result-+if item_type == "function_call":await self._on_function_call_start(item)# Perform function callfunction = self._get_tool(item.get("name"))if not function:raise ToolError(f"Function {item.get('name')} not found")-+args = json.loads(item.get("arguments"))# Validate arguments before execution@@ -545,14 +572,14 @@ class ComputerAgent:result = await function(**args)else:result = await asyncio.to_thread(function, **args)-+# Create function call outputcall_output = {"type": "function_call_output","call_id": item.get("call_id"),"output": str(result),}-+result = [call_output]await self._on_function_call_end(item, result)return result@@ -564,36 +591,35 @@ class ComputerAgent:# ============================================================================# MAIN AGENT LOOP# ============================================================================-+async def run(- self,- messages: Messages,- stream: bool = False,- **kwargs+ self, messages: Messages, stream: bool = False, **kwargs) -> AsyncGenerator[Dict[str, Any], None]:"""Run the agent with the given messages using Computer protocol handler pattern.-+Args:messages: List of message dictionariesstream: Whether to stream the response**kwargs: Additional arguments-+Returns:AsyncGenerator that yields response chunks"""if not self.agent_config_info:raise ValueError("Agent configuration not found")-+capabilities = self.get_capabilities()if "step" not in capabilities:- raise ValueError(f"Agent loop {self.agent_config_info.agent_class.__name__} does not support step predictions")+ raise ValueError(+ f"Agent loop {self.agent_config_info.agent_class.__name__} does not support step predictions"+ )await self._initialize_computers()-+# Merge kwargsmerged_kwargs = {**self.kwargs, **kwargs}-+old_items = self._process_input(messages)new_items = []@@ -603,7 +629,7 @@ class ComputerAgent:"stream": stream,"model": self.model,"agent_loop": self.agent_config_info.agent_class.__name__,- **merged_kwargs+ **merged_kwargs,}await self._on_run_start(run_kwargs, old_items)@@ -620,7 +646,7 @@ class ComputerAgent:combined_messages = old_items + new_itemscombined_messages = replace_failed_computer_calls_with_function_calls(combined_messages)preprocessed_messages = await self._on_llm_start(combined_messages)-+loop_kwargs = {"messages": preprocessed_messages,"model": self.model,@@ -629,7 +655,7 @@ class ComputerAgent:"computer_handler": self.computer_handler,"max_retries": self.max_retries,"use_prompt_caching": self.use_prompt_caching,- **merged_kwargs+ **merged_kwargs,}# Run agent loop iteration@@ -641,13 +667,13 @@ class ComputerAgent:_on_screenshot=self._on_screenshot,)result = get_json(result)-+# Lifecycle hook: Postprocess messages after the LLM call# Use cases:# - PII deanonymization (if you want tool calls to see PII)result["output"] = await self._on_llm_end(result.get("output", []))await self._on_responses(loop_kwargs, result)-+# Yield agent responseyield result@@ -659,7 +685,9 @@ class ComputerAgent:# Handle computer actionsfor item in result.get("output"):- partial_items = await self._handle_item(item, self.computer_handler, ignore_call_ids=output_call_ids)+ partial_items = await self._handle_item(+ item, self.computer_handler, ignore_call_ids=output_call_ids+ )new_items += partial_items# Yield partial response@@ -669,54 +697,52 @@ class ComputerAgent:prompt_tokens=0,completion_tokens=0,total_tokens=0,- )+ ),}-+await self._on_run_end(loop_kwargs, old_items, new_items)-+async def predict_click(- self,- instruction: str,- image_b64: Optional[str] = None+ self, instruction: str, image_b64: Optional[str] = None) -> Optional[Tuple[int, int]]:"""Predict click coordinates based on image and instruction.-+Args:instruction: Instruction for where to clickimage_b64: Base64 encoded image (optional, will take screenshot if not provided)-+Returns:None or tuple with (x, y) coordinates"""if not self.agent_config_info:raise ValueError("Agent configuration not found")-+capabilities = self.get_capabilities()if "click" not in capabilities:- raise ValueError(f"Agent loop {self.agent_config_info.agent_class.__name__} does not support click predictions")- if hasattr(self.agent_loop, 'predict_click'):+ raise ValueError(+ f"Agent loop {self.agent_config_info.agent_class.__name__} does not support click predictions"+ )+ if hasattr(self.agent_loop, "predict_click"):if not image_b64:if not self.computer_handler:raise ValueError("Computer tool or image_b64 is required for predict_click")image_b64 = await self.computer_handler.screenshot()return await self.agent_loop.predict_click(- model=self.model,- image_b64=image_b64,- instruction=instruction+ model=self.model, image_b64=image_b64, instruction=instruction)return None-+def get_capabilities(self) -> List[AgentCapability]:"""Get list of capabilities supported by the current agent config.-+Returns:List of capability strings (e.g., ["step", "click"])"""if not self.agent_config_info:raise ValueError("Agent configuration not found")-- if hasattr(self.agent_loop, 'get_capabilities'):++ if hasattr(self.agent_loop, "get_capabilities"):return self.agent_loop.get_capabilities()- return ["step"] # Default capability\ No newline at end of file+ return ["step"] # Default capabilitydiff --git a/libs/python/agent/agent/callbacks/__init__.py b/libs/python/agent/agent/callbacks/__init__.pyindex eca401736d..06987593f6 100644--- a/libs/python/agent/agent/callbacks/__init__.py+++ b/libs/python/agent/agent/callbacks/__init__.py@@ -3,17 +3,17 @@ Callback system for ComputerAgent preprocessing and postprocessing hooks."""from .base import AsyncCallbackHandler+from .budget_manager import BudgetManagerCallbackfrom .image_retention import ImageRetentionCallbackfrom .logging import LoggingCallback-from .trajectory_saver import TrajectorySaverCallback-from .budget_manager import BudgetManagerCallback-from .telemetry import TelemetryCallbackfrom .operator_validator import OperatorNormalizerCallbackfrom .prompt_instructions import PromptInstructionsCallback+from .telemetry import TelemetryCallback+from .trajectory_saver import TrajectorySaverCallback__all__ = ["AsyncCallbackHandler",- "ImageRetentionCallback",+ "ImageRetentionCallback","LoggingCallback","TrajectorySaverCallback","BudgetManagerCallback",diff --git a/libs/python/agent/agent/callbacks/base.py b/libs/python/agent/agent/callbacks/base.pyindex 0168807767..d7c2a56fb4 100644--- a/libs/python/agent/agent/callbacks/base.py+++ b/libs/python/agent/agent/callbacks/base.py@@ -3,7 +3,7 @@ Base callback handler interface for ComputerAgent preprocessing and postprocessi"""from abc import ABC, abstractmethod-from typing import List, Dict, Any, Optional, Union+from typing import Any, Dict, List, Optional, Unionclass AsyncCallbackHandler(ABC):@@ -16,42 +16,52 @@ class AsyncCallbackHandler(ABC):"""Called at the start of an agent run loop."""pass- async def on_run_end(self, kwargs: Dict[str, Any], old_items: List[Dict[str, Any]], new_items: List[Dict[str, Any]]) -> None:+ async def on_run_end(+ self,+ kwargs: Dict[str, Any],+ old_items: List[Dict[str, Any]],+ new_items: List[Dict[str, Any]],+ ) -> None:"""Called at the end of an agent run loop."""pass-- async def on_run_continue(self, kwargs: Dict[str, Any], old_items: List[Dict[str, Any]], new_items: List[Dict[str, Any]]) -> bool:++ async def on_run_continue(+ self,+ kwargs: Dict[str, Any],+ old_items: List[Dict[str, Any]],+ new_items: List[Dict[str, Any]],+ ) -> bool:"""Called during agent run loop to determine if execution should continue.-+Args:kwargs: Run argumentsold_items: Original messagesnew_items: New messages generated during run-+Returns:True to continue execution, False to stop"""return True-+async def on_llm_start(self, messages: List[Dict[str, Any]]) -> List[Dict[str, Any]]:"""Called before messages are sent to the agent loop.-+Args:messages: List of message dictionaries to preprocess-+Returns:List of preprocessed message dictionaries"""return messages-+async def on_llm_end(self, output: List[Dict[str, Any]]) -> List[Dict[str, Any]]:"""Called after the agent loop returns output.-+Args:output: List of output message dictionaries to postprocess-+Returns:List of postprocessed output dictionaries"""@@ -60,63 +70,67 @@ class AsyncCallbackHandler(ABC):async def on_computer_call_start(self, item: Dict[str, Any]) -> None:"""Called when a computer call is about to start.-+Args:item: The computer call item dictionary"""pass-- async def on_computer_call_end(self, item: Dict[str, Any], result: List[Dict[str, Any]]) -> None:++ async def on_computer_call_end(+ self, item: Dict[str, Any], result: List[Dict[str, Any]]+ ) -> None:"""Called when a computer call has completed.-+Args:item: The computer call item dictionaryresult: The result of the computer call"""pass-+async def on_function_call_start(self, item: Dict[str, Any]) -> None:"""Called when a function call is about to start.-+Args:item: The function call item dictionary"""pass-- async def on_function_call_end(self, item: Dict[str, Any], result: List[Dict[str, Any]]) -> None:++ async def on_function_call_end(+ self, item: Dict[str, Any], result: List[Dict[str, Any]]+ ) -> None:"""Called when a function call has completed.-+Args:item: The function call item dictionaryresult: The result of the function call"""pass-+async def on_text(self, item: Dict[str, Any]) -> None:"""Called when a text message is encountered.-+Args:item: The message item dictionary"""pass-+async def on_api_start(self, kwargs: Dict[str, Any]) -> None:"""Called when an API call is about to start.-+Args:kwargs: The kwargs being passed to the API call"""pass-+async def on_api_end(self, kwargs: Dict[str, Any], result: Any) -> None:"""Called when an API call has completed.-+Args:kwargs: The kwargs that were passed to the API callresult: The result of the API call@@ -126,7 +140,7 @@ class AsyncCallbackHandler(ABC):async def on_usage(self, usage: Dict[str, Any]) -> None:"""Called when usage information is received.-+Args:usage: The usage information"""@@ -135,7 +149,7 @@ class AsyncCallbackHandler(ABC):async def on_screenshot(self, screenshot: Union[str, bytes], name: str = "screenshot") -> None:"""Called when a screenshot is taken.-+Args:screenshot: The screenshot imagename: The name of the screenshot@@ -145,9 +159,9 @@ class AsyncCallbackHandler(ABC):async def on_responses(self, kwargs: Dict[str, Any], responses: Dict[str, Any]) -> None:"""Called when responses are received.-+Args:kwargs: The kwargs being passed to the agent loopresponses: The responses received"""- pass\ No newline at end of file+ passdiff --git a/libs/python/agent/agent/callbacks/budget_manager.py b/libs/python/agent/agent/callbacks/budget_manager.pyindex bc17c69526..ff45b3fd20 100644--- a/libs/python/agent/agent/callbacks/budget_manager.py+++ b/libs/python/agent/agent/callbacks/budget_manager.py@@ -1,17 +1,23 @@-from typing import Dict, List, Any+from typing import Any, Dict, List+from .base import AsyncCallbackHandler+class BudgetExceededError(Exception):"""Exception raised when budget is exceeded."""+pass+class BudgetManagerCallback(AsyncCallbackHandler):"""Budget manager callback that tracks usage costs and can stop execution when budget is exceeded."""-- def __init__(self, max_budget: float, reset_after_each_run: bool = True, raise_error: bool = False):++ def __init__(+ self, max_budget: float, reset_after_each_run: bool = True, raise_error: bool = False+ ):"""Initialize BudgetManagerCallback.-+Args:max_budget: Maximum budget allowedreset_after_each_run: Whether to reset budget after each run@@ -21,24 +27,30 @@ class BudgetManagerCallback(AsyncCallbackHandler):self.reset_after_each_run = reset_after_each_runself.raise_error = raise_errorself.total_cost = 0.0-+async def on_run_start(self, kwargs: Dict[str, Any], old_items: List[Dict[str, Any]]) -> None:"""Reset budget if configured to do so."""if self.reset_after_each_run:self.total_cost = 0.0-+async def on_usage(self, usage: Dict[str, Any]) -> None:"""Track usage costs."""if "response_cost" in usage:self.total_cost += usage["response_cost"]-- async def on_run_continue(self, kwargs: Dict[str, Any], old_items: List[Dict[str, Any]], new_items: List[Dict[str, Any]]) -> bool:++ async def on_run_continue(+ self,+ kwargs: Dict[str, Any],+ old_items: List[Dict[str, Any]],+ new_items: List[Dict[str, Any]],+ ) -> bool:"""Check if budget allows continuation."""if self.total_cost >= self.max_budget:if self.raise_error:- raise BudgetExceededError(f"Budget exceeded: ${self.total_cost} >= ${self.max_budget}")+ raise BudgetExceededError(+ f"Budget exceeded: ${self.total_cost} >= ${self.max_budget}"+ )else:print(f"Budget exceeded: ${self.total_cost} >= ${self.max_budget}")return Falsereturn True-\ No newline at end of filediff --git a/libs/python/agent/agent/callbacks/image_retention.py b/libs/python/agent/agent/callbacks/image_retention.pyindex 320a3f43ce..e95f17d386 100644--- a/libs/python/agent/agent/callbacks/image_retention.py+++ b/libs/python/agent/agent/callbacks/image_retention.py@@ -2,7 +2,8 @@Image retention callback handler that limits the number of recent images in message history."""-from typing import List, Dict, Any, Optional+from typing import Any, Dict, List, Optional+from .base import AsyncCallbackHandler@@ -11,40 +12,40 @@ class ImageRetentionCallback(AsyncCallbackHandler):Callback handler that applies image retention policy to limit the numberof recent images in message history to prevent context window overflow."""-+def __init__(self, only_n_most_recent_images: Optional[int] = None):"""Initialize the image retention callback.-+Args:only_n_most_recent_images: If set, only keep the N most recent images in message history"""self.only_n_most_recent_images = only_n_most_recent_images-+async def on_llm_start(self, messages: List[Dict[str, Any]]) -> List[Dict[str, Any]]:"""Apply image retention policy to messages before sending to agent loop.-+Args:messages: List of message dictionaries-+Returns:List of messages with image retention policy applied"""if self.only_n_most_recent_images is None:return messages-+return self._apply_image_retention(messages)-+def _apply_image_retention(self, messages: List[Dict[str, Any]]) -> List[Dict[str, Any]]:"""Apply image retention policy to keep only the N most recent images.-+Removes computer_call_output items with image_url and their corresponding computer_call items,keeping only the most recent N image pairs based on only_n_most_recent_images setting.-+Args:messages: List of message dictionaries-+Returns:Filtered list of messages with image retention applied"""@@ -78,7 +79,11 @@ class ImageRetentionCallback(AsyncCallbackHandler):# Remove the immediately preceding computer_call with matching call_id (if present)call_id = messages[idx].get("call_id")prev_idx = idx - 1- if prev_idx >= 0 and messages[prev_idx].get("type") == "computer_call" and messages[prev_idx].get("call_id") == call_id:+ if (+ prev_idx >= 0+ and messages[prev_idx].get("type") == "computer_call"+ and messages[prev_idx].get("call_id") == call_id+ ):to_remove.add(prev_idx)# Check a single reasoning immediately before that computer_callr_idx = prev_idx - 1@@ -87,4 +92,4 @@ class ImageRetentionCallback(AsyncCallbackHandler):# Construct filtered listfiltered = [m for i, m in enumerate(messages) if i not in to_remove]- return filtered\ No newline at end of file+ return filtereddiff --git a/libs/python/agent/agent/callbacks/logging.py b/libs/python/agent/agent/callbacks/logging.pyindex af17192586..c9674c7e4e 100644--- a/libs/python/agent/agent/callbacks/logging.py+++ b/libs/python/agent/agent/callbacks/logging.py@@ -4,17 +4,18 @@ Logging callback for ComputerAgent that provides configurable logging of agent limport jsonimport logging-from typing import Dict, List, Any, Optional, Union+from typing import Any, Dict, List, Optional, Union+from .base import AsyncCallbackHandlerdef sanitize_image_urls(data: Any) -> Any:"""Recursively search for 'image_url' keys and set their values to '[omitted]'.-+Args:data: Any data structure (dict, list, or primitive type)-+Returns:A deep copy of the data with all 'image_url' values replaced with '[omitted]'"""@@ -28,11 +29,11 @@ def sanitize_image_urls(data: Any) -> Any:# Recursively sanitize the valuesanitized[key] = sanitize_image_urls(value)return sanitized-+elif isinstance(data, list):# Recursively sanitize each item in the listreturn [sanitize_image_urls(item) for item in data]-+else:# For primitive types (str, int, bool, None, etc.), return as-isreturn data@@ -41,37 +42,36 @@ def sanitize_image_urls(data: Any) -> Any:class LoggingCallback(AsyncCallbackHandler):"""Callback handler that logs agent lifecycle events with configurable verbosity.-+Logging levels:- DEBUG: All events including API calls, message preprocessing, and detailed outputs- - INFO: Major lifecycle events (start/end, messages, outputs)+ - INFO: Major lifecycle events (start/end, messages, outputs)- WARNING: Only warnings and errors- ERROR: Only errors"""-+def __init__(self, logger: Optional[logging.Logger] = None, level: int = logging.INFO):"""Initialize the logging callback.-+Args:logger: Logger instance to use. If None, creates a logger named 'agent.ComputerAgent'level: Logging level (logging.DEBUG, logging.INFO, etc.)"""- self.logger = logger or logging.getLogger('agent.ComputerAgent')+ self.logger = logger or logging.getLogger("agent.ComputerAgent")self.level = level-+# Set up logger if it doesn't have handlersif not self.logger.handlers:handler = logging.StreamHandler()- formatter = logging.Formatter(- '%(asctime)s - %(name)s - %(levelname)s - %(message)s'- )+ formatter = logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s")handler.setFormatter(formatter)self.logger.addHandler(handler)self.logger.setLevel(level)-+def _update_usage(self, usage: Dict[str, Any]) -> None:"""Update total usage statistics."""+def add_dicts(target: Dict[str, Any], source: Dict[str, Any]) -> None:for key, value in source.items():if isinstance(value, dict):@@ -82,18 +82,25 @@ class LoggingCallback(AsyncCallbackHandler):if key not in target:target[key] = 0target[key] += value+add_dicts(self.total_usage, usage)-+async def on_run_start(self, kwargs: Dict[str, Any], old_items: List[Dict[str, Any]]) -> None:"""Called before the run starts."""self.total_usage = {}-+async def on_usage(self, usage: Dict[str, Any]) -> None:"""Called when usage information is received."""self._update_usage(usage)- async def on_run_end(self, kwargs: Dict[str, Any], old_items: List[Dict[str, Any]], new_items: List[Dict[str, Any]]) -> None:+ async def on_run_end(+ self,+ kwargs: Dict[str, Any],+ old_items: List[Dict[str, Any]],+ new_items: List[Dict[str, Any]],+ ) -> None:"""Called after the run ends."""+def format_dict(d, indent=0):lines = []prefix = f" - {' ' * indent}"@@ -106,10 +113,10 @@ class LoggingCallback(AsyncCallbackHandler):else:lines.append(f"{prefix}{key}: {value}")return lines-+formatted_output = "\n".join(format_dict(self.total_usage))self.logger.info(f"Total usage:\n{formatted_output}")-+async def on_llm_start(self, messages: List[Dict[str, Any]]) -> List[Dict[str, Any]]:"""Called before LLM processing starts."""if self.logger.isEnabledFor(logging.INFO):@@ -118,27 +125,27 @@ class LoggingCallback(AsyncCallbackHandler):sanitized_messages = [sanitize_image_urls(msg) for msg in messages]self.logger.debug(f"LLM input messages: {json.dumps(sanitized_messages, indent=2)}")return messages-+async def on_llm_end(self, messages: List[Dict[str, Any]]) -> List[Dict[str, Any]]:"""Called after LLM processing ends."""if self.logger.isEnabledFor(logging.DEBUG):sanitized_messages = [sanitize_image_urls(msg) for msg in messages]self.logger.debug(f"LLM output: {json.dumps(sanitized_messages, indent=2)}")return messages-+async def on_computer_call_start(self, item: Dict[str, Any]) -> None:"""Called when a computer call starts."""action = item.get("action", {})action_type = action.get("type", "unknown")action_args = {k: v for k, v in action.items() if k != "type"}-+# INFO level logging for the actionself.logger.info(f"Computer: {action_type}({action_args})")-+# DEBUG level logging for full detailsif self.logger.isEnabledFor(logging.DEBUG):self.logger.debug(f"Computer call started: {json.dumps(action, indent=2)}")-+async def on_computer_call_end(self, item: Dict[str, Any], result: Any) -> None:"""Called when a computer call ends."""if self.logger.isEnabledFor(logging.DEBUG):@@ -147,48 +154,52 @@ class LoggingCallback(AsyncCallbackHandler):if result:sanitized_result = sanitize_image_urls(result)self.logger.debug(f"Computer call result: {json.dumps(sanitized_result, indent=2)}")-+async def on_function_call_start(self, item: Dict[str, Any]) -> None:"""Called when a function call starts."""name = item.get("name", "unknown")arguments = item.get("arguments", "{}")-+# INFO level logging for the function callself.logger.info(f"Function: {name}({arguments})")-+# DEBUG level logging for full detailsif self.logger.isEnabledFor(logging.DEBUG):self.logger.debug(f"Function call started: {name}")-+async def on_function_call_end(self, item: Dict[str, Any], result: Any) -> None:"""Called when a function call ends."""# INFO level logging for function output (similar to function_call_output)if result:# Handle both list and direct result formatsif isinstance(result, list) and len(result) > 0:- output = result[0].get("output", str(result)) if isinstance(result[0], dict) else str(result[0])+ output = (+ result[0].get("output", str(result))+ if isinstance(result[0], dict)+ else str(result[0])+ )else:output = str(result)-+# Truncate long outputsif len(output) > 100:output = output[:100] + "..."-+self.logger.info(f"Output: {output}")-+# DEBUG level logging for full detailsif self.logger.isEnabledFor(logging.DEBUG):name = item.get("name", "unknown")self.logger.debug(f"Function call completed: {name}")if result:self.logger.debug(f"Function call result: {json.dumps(result, indent=2)}")-+async def on_text(self, item: Dict[str, Any]) -> None:"""Called when a text message is encountered."""# Get the role to determine if it's Agent or Userrole = item.get("role", "unknown")content_items = item.get("content", [])-+# Process content items to build display texttext_parts = []for content_item in content_items:@@ -206,10 +217,10 @@ class LoggingCallback(AsyncCallbackHandler):else:# Non-text content, show as [type]text_parts.append(f"[{content_type}]")-+# Join all text parts- display_text = ''.join(text_parts) if text_parts else "[empty]"-+ display_text = "".join(text_parts) if text_parts else "[empty]"+# Log with appropriate level and formatif role == "assistant":self.logger.info(f"Agent: {display_text}")@@ -219,7 +230,7 @@ class LoggingCallback(AsyncCallbackHandler):# Fallback for unknown roles, use debug levelif self.logger.isEnabledFor(logging.DEBUG):self.logger.debug(f"Text message ({role}): {display_text}")-+async def on_api_start(self, kwargs: Dict[str, Any]) -> None:"""Called when an API call is about to start."""if self.logger.isEnabledFor(logging.DEBUG):@@ -232,16 +243,18 @@ class LoggingCallback(AsyncCallbackHandler):elif "input" in kwargs:sanitized_input = sanitize_image_urls(kwargs["input"])self.logger.debug(f"API call input: {json.dumps(sanitized_input, indent=2)}")-+async def on_api_end(self, kwargs: Dict[str, Any], result: Any) -> None:"""Called when an API call has completed."""if self.logger.isEnabledFor(logging.DEBUG):model = kwargs.get("model", "unknown")self.logger.debug(f"API call completed for model: {model}")- self.logger.debug(f"API call result: {json.dumps(sanitize_image_urls(result), indent=2)}")+ self.logger.debug(+ f"API call result: {json.dumps(sanitize_image_urls(result), indent=2)}"+ )async def on_screenshot(self, item: Union[str, bytes], name: str = "screenshot") -> None:"""Called when a screenshot is taken."""if self.logger.isEnabledFor(logging.DEBUG):image_size = len(item) / 1024- self.logger.debug(f"Screenshot captured: {name} {image_size:.2f} KB")\ No newline at end of file+ self.logger.debug(f"Screenshot captured: {name} {image_size:.2f} KB")diff --git a/libs/python/agent/agent/callbacks/operator_validator.py b/libs/python/agent/agent/callbacks/operator_validator.pyindex 56a9c2806d..28a6fd3718 100644--- a/libs/python/agent/agent/callbacks/operator_validator.py+++ b/libs/python/agent/agent/callbacks/operator_validator.py@@ -9,6 +9,7 @@ Ensures agent output actions conform to expected schemas by fixing common issuesThis runs in on_llm_end, which receives the output array (AgentMessage[] as dicts).The purpose is to avoid spending another LLM call to fix broken computer call syntax when possible."""+from __future__ import annotationsfrom typing import Any, Dict, List@@ -48,6 +49,7 @@ class OperatorNormalizerCallback(AsyncCallbackHandler):action["type"] = "type"action_type = action.get("type")+def _keep_keys(action: Dict[str, Any], keys_to_keep: List[str]):"""Keep only the provided keys on action; delete everything else.Always ensures required 'type' is present if listed in keys_to_keep.@@ -55,6 +57,7 @@ class OperatorNormalizerCallback(AsyncCallbackHandler):for key in list(action.keys()):if key not in keys_to_keep:del action[key]+# rename "coordinate" to "x", "y"if "coordinate" in action:action["x"] = action["coordinate"][0]@@ -100,7 +103,6 @@ class OperatorNormalizerCallback(AsyncCallbackHandler):keep = required_keys_by_type.get(action_type or "")if keep:_keep_keys(action, keep)-# # Second pass: if an assistant message is immediately followed by a computer_call,# # replace the assistant message itself with a reasoning message with summary text.diff --git a/libs/python/agent/agent/callbacks/pii_anonymization.py b/libs/python/agent/agent/callbacks/pii_anonymization.pyindex 68f4b2fcaa..167f74f20e 100644--- a/libs/python/agent/agent/callbacks/pii_anonymization.py+++ b/libs/python/agent/agent/callbacks/pii_anonymization.py@@ -2,38 +2,41 @@PII anonymization callback handler using Microsoft Presidio for text and image redaction."""-from typing import List, Dict, Any, Optional, Tuple-from .base import AsyncCallbackHandlerimport base64import ioimport logging+from typing import Any, Dict, List, Optional, Tuple++from .base import AsyncCallbackHandlertry:# TODO: Add Presidio dependenciesfrom PIL import Image+PRESIDIO_AVAILABLE = Trueexcept ImportError:PRESIDIO_AVAILABLE = Falselogger = logging.getLogger(__name__)+class PIIAnonymizationCallback(AsyncCallbackHandler):"""Callback handler that anonymizes PII in text and images using Microsoft Presidio.-+This handler:1. Anonymizes PII in messages before sending to the agent loop2. Deanonymizes PII in tool calls and message outputs after the agent loop3. Redacts PII from images in computer_call_output messages"""-+def __init__(self,# TODO: Any extra kwargs if needed):"""Initialize the PII anonymization callback.-+Args:anonymize_text: Whether to anonymize text contentanonymize_images: Whether to redact images@@ -46,16 +49,16 @@ class PIIAnonymizationCallback(AsyncCallbackHandler):"Presidio is not available. Install with: ""pip install cua-agent[pii-anonymization]")-+# TODO: Implement __init__-+async def on_llm_start(self, messages: List[Dict[str, Any]]) -> List[Dict[str, Any]]:"""Anonymize PII in messages before sending to agent loop.-+Args:messages: List of message dictionaries-+Returns:List of messages with PII anonymized"""@@ -63,16 +66,16 @@ class PIIAnonymizationCallback(AsyncCallbackHandler):for msg in messages:anonymized_msg = await self._anonymize_message(msg)anonymized_messages.append(anonymized_msg)-+return anonymized_messages-+async def on_llm_end(self, output: List[Dict[str, Any]]) -> List[Dict[str, Any]]:"""Deanonymize PII in tool calls and message outputs after agent loop.-+Args:output: List of output dictionaries-+Returns:List of output with PII deanonymized for tool calls"""@@ -84,13 +87,13 @@ class PIIAnonymizationCallback(AsyncCallbackHandler):deanonymized_output.append(deanonymized_item)else:deanonymized_output.append(item)-+return deanonymized_output-+async def _anonymize_message(self, message: Dict[str, Any]) -> Dict[str, Any]:# TODO: Implement _anonymize_messagereturn message-+async def _deanonymize_item(self, item: Dict[str, Any]) -> Dict[str, Any]:# TODO: Implement _deanonymize_itemreturn itemdiff --git a/libs/python/agent/agent/callbacks/telemetry.py b/libs/python/agent/agent/callbacks/telemetry.pyindex bdb3fd4c64..d8e77e1d93 100644--- a/libs/python/agent/agent/callbacks/telemetry.py+++ b/libs/python/agent/agent/callbacks/telemetry.py@@ -2,17 +2,17 @@Telemetry callback handler for Computer-Use Agent (cua-agent)"""+import platformimport timeimport uuid-from typing import List, Dict, Any, Optional, Union+from typing import Any, Dict, List, Optional, Union-from .base import AsyncCallbackHandlerfrom core.telemetry import (- record_event,is_telemetry_enabled,+ record_event,)-import platform+from .base import AsyncCallbackHandlerSYSTEM_INFO = {"os": platform.system().lower(),@@ -20,32 +20,29 @@ SYSTEM_INFO = {"python_version": platform.python_version(),}+class TelemetryCallback(AsyncCallbackHandler):"""Telemetry callback handler for Computer-Use Agent (cua-agent)-+Tracks agent usage, performance metrics, and optionally trajectory data."""-- def __init__(- self,- agent,- log_trajectory: bool = False- ):++ def __init__(self, agent, log_trajectory: bool = False):"""Initialize telemetry callback.-+Args:agent: The ComputerAgent instancelog_trajectory: Whether to log full trajectory items (opt-in)"""self.agent = agentself.log_trajectory = log_trajectory-+# Generate session/run IDsself.session_id = str(uuid.uuid4())self.run_id = None-+# Track timing and metricsself.run_start_time = Noneself.step_count = 0@@ -54,126 +51,133 @@ class TelemetryCallback(AsyncCallbackHandler):"prompt_tokens": 0,"completion_tokens": 0,"total_tokens": 0,- "response_cost": 0.0+ "response_cost": 0.0,}-+# Record agent initializationif is_telemetry_enabled():self._record_agent_initialization()-+def _record_agent_initialization(self) -> None:"""Record agent type/model and session initialization."""agent_info = {"session_id": self.session_id,- "agent_type": self.agent.agent_loop.__name__ if hasattr(self.agent, 'agent_loop') else 'unknown',- "model": getattr(self.agent, 'model', 'unknown'),- **SYSTEM_INFO+ "agent_type": (+ self.agent.agent_loop.__name__ if hasattr(self.agent, "agent_loop") else "unknown"+ ),+ "model": getattr(self.agent, "model", "unknown"),+ **SYSTEM_INFO,}-+record_event("agent_session_start", agent_info)-+async def on_run_start(self, kwargs: Dict[str, Any], old_items: List[Dict[str, Any]]) -> None:"""Called at the start of an agent run loop."""if not is_telemetry_enabled():return-+self.run_id = str(uuid.uuid4())self.run_start_time = time.time()self.step_count = 0-+# Calculate input context sizeinput_context_size = self._calculate_context_size(old_items)-+run_data = {"session_id": self.session_id,"run_id": self.run_id,"start_time": self.run_start_time,"input_context_size": input_context_size,- "num_existing_messages": len(old_items)+ "num_existing_messages": len(old_items),}-+# Log trajectory if opted inif self.log_trajectory:trajectory = self._extract_trajectory(old_items)if trajectory:run_data["uploaded_trajectory"] = trajectory-+record_event("agent_run_start", run_data)-- async def on_run_end(self, kwargs: Dict[str, Any], old_items: List[Dict[str, Any]], new_items: List[Dict[str, Any]]) -> None:++ async def on_run_end(+ self,+ kwargs: Dict[str, Any],+ old_items: List[Dict[str, Any]],+ new_items: List[Dict[str, Any]],+ ) -> None:"""Called at the end of an agent run loop."""if not is_telemetry_enabled() or not self.run_start_time:return-+run_duration = time.time() - self.run_start_time-+run_data = {"session_id": self.session_id,"run_id": self.run_id,"end_time": time.time(),"duration_seconds": run_duration,"num_steps": self.step_count,- "total_usage": self.total_usage.copy()+ "total_usage": self.total_usage.copy(),}-+# Log trajectory if opted inif self.log_trajectory:trajectory = self._extract_trajectory(new_items)if trajectory:run_data["uploaded_trajectory"] = trajectory-+record_event("agent_run_end", run_data)-+async def on_usage(self, usage: Dict[str, Any]) -> None:"""Called when usage information is received."""if not is_telemetry_enabled():return-+# Accumulate usage statsself.total_usage["prompt_tokens"] += usage.get("prompt_tokens", 0)- self.total_usage["completion_tokens"] += usage.get("completion_tokens", 0)+ self.total_usage["completion_tokens"] += usage.get("completion_tokens", 0)self.total_usage["total_tokens"] += usage.get("total_tokens", 0)self.total_usage["response_cost"] += usage.get("response_cost", 0.0)-+# Record individual usage eventusage_data = {"session_id": self.session_id,"run_id": self.run_id,"step": self.step_count,- **usage+ **usage,}-+record_event("agent_usage", usage_data)-+async def on_responses(self, kwargs: Dict[str, Any], responses: Dict[str, Any]) -> None:"""Called when responses are received."""if not is_telemetry_enabled():return-+self.step_count += 1step_duration = None-+if self.step_start_time:step_duration = time.time() - self.step_start_time-+self.step_start_time = time.time()-+step_data = {"session_id": self.session_id,"run_id": self.run_id,"step": self.step_count,- "timestamp": self.step_start_time+ "timestamp": self.step_start_time,}-+if step_duration is not None:step_data["duration_seconds"] = step_duration-+record_event("agent_step", step_data)-+def _calculate_context_size(self, items: List[Dict[str, Any]]) -> int:"""Calculate approximate context size in tokens/characters."""total_size = 0-+for item in items:if item.get("type") == "message" and "content" in item:content = item["content"]@@ -185,25 +189,27 @@ class TelemetryCallback(AsyncCallbackHandler):total_size += len(part["text"])elif "content" in item and isinstance(item["content"], str):total_size += len(item["content"])-+return total_size-+def _extract_trajectory(self, items: List[Dict[str, Any]]) -> List[Dict[str, Any]]:"""Extract trajectory items that should be logged."""trajectory = []-+for item in items:# Include user messages, assistant messages, reasoning, computer calls, and computer outputsif (- item.get("role") == "user" or # User inputs- (item.get("type") == "message" and item.get("role") == "assistant") or # Model outputs- item.get("type") == "reasoning" or # Reasoning traces- item.get("type") == "computer_call" or # Computer actions- item.get("type") == "computer_call_output" # Computer outputs+ item.get("role") == "user" # User inputs+ or (+ item.get("type") == "message" and item.get("role") == "assistant"+ ) # Model outputs+ or item.get("type") == "reasoning" # Reasoning traces+ or item.get("type") == "computer_call" # Computer actions+ or item.get("type") == "computer_call_output" # Computer outputs):# Create a copy of the item with timestamptrajectory_item = item.copy()trajectory_item["logged_at"] = time.time()trajectory.append(trajectory_item)-- return trajectory\ No newline at end of file++ return trajectorydiff --git a/libs/python/agent/agent/callbacks/trajectory_saver.py b/libs/python/agent/agent/callbacks/trajectory_saver.pyindex 7ea708db15..cb08d1a8b1 100644--- a/libs/python/agent/agent/callbacks/trajectory_saver.py+++ b/libs/python/agent/agent/callbacks/trajectory_saver.py@@ -2,26 +2,28 @@Trajectory saving callback handler for ComputerAgent."""-import os+import base64+import ioimport json+import osimport uuid+from copy import deepcopyfrom datetime import datetime-import base64from pathlib import Path-from typing import List, Dict, Any, Optional, Union, override+from typing import Any, Dict, List, Optional, Union, override+from PIL import Image, ImageDraw-import io-from copy import deepcopyfrom .base import AsyncCallbackHandler+def sanitize_image_urls(data: Any) -> Any:"""Recursively search for 'image_url' keys and set their values to '[omitted]'.-+Args:data: Any data structure (dict, list, or primitive type)-+Returns:A deep copy of the data with all 'image_url' values replaced with '[omitted]'"""@@ -35,17 +37,19 @@ def sanitize_image_urls(data: Any) -> Any:# Recursively sanitize the valuesanitized[key] = sanitize_image_urls(value)return sanitized-+elif isinstance(data, list):# Recursively sanitize each item in the listreturn [sanitize_image_urls(item) for item in data]-+else:# For primitive types (str, int, bool, None, etc.), return as-isreturn data-def extract_computer_call_outputs(items: List[Dict[str, Any]], screenshot_dir: Optional[Path]) -> List[Dict[str, Any]]:+def extract_computer_call_outputs(+ items: List[Dict[str, Any]], screenshot_dir: Optional[Path]+) -> List[Dict[str, Any]]:"""Save any base64-encoded screenshots from computer_call_output entries to files andreplace their image_url with the saved file path when a call_id is present.@@ -103,18 +107,21 @@ def extract_computer_call_outputs(items: List[Dict[str, Any]], screenshot_dir: Oupdated.append(msg)return updated+class TrajectorySaverCallback(AsyncCallbackHandler):"""Callback handler that saves agent trajectories to disk.-+Saves each run as a separate trajectory with unique ID, and each turnwithin the trajectory gets its own folder with screenshots and responses."""-- def __init__(self, trajectory_dir: str, reset_on_run: bool = True, screenshot_dir: Optional[str] = None):++ def __init__(+ self, trajectory_dir: str, reset_on_run: bool = True, screenshot_dir: Optional[str] = None+ ):"""Initialize trajectory saver.-+Args:trajectory_dir: Base directory to save trajectoriesreset_on_run: If True, reset trajectory_id/turn/artifact on each run.@@ -129,7 +136,7 @@ class TrajectorySaverCallback(AsyncCallbackHandler):self.reset_on_run = reset_on_run# Optional directory to store extracted screenshots from metadata/new_itemsself.screenshot_dir: Optional[Path] = Path(screenshot_dir) if screenshot_dir else None-+# Ensure trajectory directory existsself.trajectory_dir.mkdir(parents=True, exist_ok=True)@@ -137,7 +144,7 @@ class TrajectorySaverCallback(AsyncCallbackHandler):"""Get the directory for the current turn."""if not self.trajectory_id:raise ValueError("Trajectory not initialized - call _on_run_start first")-+# format: trajectory_id/turn_000turn_dir = self.trajectory_dir / self.trajectory_id / f"turn_{self.current_turn:03d}"turn_dir.mkdir(parents=True, exist_ok=True)@@ -166,6 +173,7 @@ class TrajectorySaverCallback(AsyncCallbackHandler):def _update_usage(self, usage: Dict[str, Any]) -> None:"""Update total usage statistics."""+def add_dicts(target: Dict[str, Any], source: Dict[str, Any]) -> None:for key, value in source.items():if isinstance(value, dict):@@ -176,20 +184,21 @@ class TrajectorySaverCallback(AsyncCallbackHandler):if key not in target:target[key] = 0target[key] += value+add_dicts(self.total_usage, usage)-+@overrideasync def on_run_start(self, kwargs: Dict[str, Any], old_items: List[Dict[str, Any]]) -> None:"""Initialize trajectory tracking for a new run."""model = kwargs.get("model", "unknown")-+# Only reset trajectory state if reset_on_run is True or no trajectory existsif self.reset_on_run or not self.trajectory_id:model_name_short = model.split("+")[-1].split("/")[-1].lower()[:16]if "+" in model:model_name_short = model.split("+")[0].lower()[:4] + "_" + model_name_short# strip non-alphanumeric characters from model_name_short- model_name_short = ''.join(c for c in model_name_short if c.isalnum() or c == '_')+ model_name_short = "".join(c for c in model_name_short if c.isalnum() or c == "_")# id format: yyyy-mm-dd_model_hhmmss_uuid[:4]now = datetime.now()@@ -198,11 +207,11 @@ class TrajectorySaverCallback(AsyncCallbackHandler):self.current_artifact = 0self.model = modelself.total_usage = {}-+# Create trajectory directorytrajectory_path = self.trajectory_dir / self.trajectory_idtrajectory_path.mkdir(parents=True, exist_ok=True)-+# Save trajectory metadata (optionally extract screenshots to screenshot_dir)kwargs_to_save = kwargs.copy()try:@@ -219,7 +228,7 @@ class TrajectorySaverCallback(AsyncCallbackHandler):"status": "running","kwargs": kwargs_to_save,}-+with open(trajectory_path / "metadata.json", "w") as f:json.dump(metadata, f, indent=2)else:@@ -227,22 +236,27 @@ class TrajectorySaverCallback(AsyncCallbackHandler):self.model = model@override- async def on_run_end(self, kwargs: Dict[str, Any], old_items: List[Dict[str, Any]], new_items: List[Dict[str, Any]]) -> None:+ async def on_run_end(+ self,+ kwargs: Dict[str, Any],+ old_items: List[Dict[str, Any]],+ new_items: List[Dict[str, Any]],+ ) -> None:"""Finalize run tracking by updating metadata with completion status, usage, and new items."""if not self.trajectory_id:return-+# Update metadata with completion status, total usage, and new itemstrajectory_path = self.trajectory_dir / self.trajectory_idmetadata_path = trajectory_path / "metadata.json"-+# Read existing metadataif metadata_path.exists():with open(metadata_path, "r") as f:metadata = json.load(f)else:metadata = {}-+# Update metadata with completion info# Optionally extract screenshots from new_items before persistingnew_items_to_save = new_items@@ -251,32 +265,34 @@ class TrajectorySaverCallback(AsyncCallbackHandler):except Exception:pass- metadata.update({- "status": "completed",- "completed_at": str(uuid.uuid1().time),- "total_usage": self.total_usage,- "new_items": new_items_to_save,- "total_turns": self.current_turn- })-+ metadata.update(+ {+ "status": "completed",+ "completed_at": str(uuid.uuid1().time),+ "total_usage": self.total_usage,+ "new_items": new_items_to_save,+ "total_turns": self.current_turn,+ }+ )+# Save updated metadatawith open(metadata_path, "w") as f:json.dump(metadata, f, indent=2)-- @override++ @overrideasync def on_api_start(self, kwargs: Dict[str, Any]) -> None:if not self.trajectory_id:return-- self._save_artifact("api_start", { "kwargs": kwargs })-++ self._save_artifact("api_start", {"kwargs": kwargs})+@overrideasync def on_api_end(self, kwargs: Dict[str, Any], result: Any) -> None:"""Save API call result."""if not self.trajectory_id:return-- self._save_artifact("api_result", { "kwargs": kwargs, "result": result })++ self._save_artifact("api_result", {"kwargs": kwargs, "result": result})@overrideasync def on_screenshot(self, screenshot: Union[str, bytes], name: str = "screenshot") -> None:@@ -295,77 +311,83 @@ class TrajectorySaverCallback(AsyncCallbackHandler):"""Save responses to the current turn directory and update usage statistics."""if not self.trajectory_id:return-+# Save responsesturn_dir = self._get_turn_dir()response_data = {"timestamp": str(uuid.uuid1().time),"model": self.model,"kwargs": kwargs,- "response": responses+ "response": responses,}-+self._save_artifact("agent_response", response_data)-+# Increment turn counterself.current_turn += 1def _draw_crosshair_on_image(self, image_bytes: bytes, x: int, y: int) -> bytes:"""Draw a red dot and crosshair at the specified coordinates on the image.-+Args:image_bytes: The original image as bytesx: X coordinate for the crosshairy: Y coordinate for the crosshair-+Returns:Modified image as bytes with red dot and crosshair"""# Open the imageimage = Image.open(io.BytesIO(image_bytes))draw = ImageDraw.Draw(image)-+# Draw crosshair lines (red, 2px thick)crosshair_size = 20line_width = 2color = "red"-+# Horizontal linedraw.line([(x - crosshair_size, y), (x + crosshair_size, y)], fill=color, width=line_width)# Vertical linedraw.line([(x, y - crosshair_size), (x, y + crosshair_size)], fill=color, width=line_width)-+# Draw center dot (filled circle)dot_radius = 3- draw.ellipse([(x - dot_radius, y - dot_radius), (x + dot_radius, y + dot_radius)], fill=color)-+ draw.ellipse(+ [(x - dot_radius, y - dot_radius), (x + dot_radius, y + dot_radius)], fill=color+ )+# Convert back to bytesoutput = io.BytesIO()- image.save(output, format='PNG')+ image.save(output, format="PNG")return output.getvalue()@override- async def on_computer_call_end(self, item: Dict[str, Any], result: List[Dict[str, Any]]) -> None:+ async def on_computer_call_end(+ self, item: Dict[str, Any], result: List[Dict[str, Any]]+ ) -> None:"""Called when a computer call has completed.Saves screenshots and computer call output."""if not self.trajectory_id:return-- self._save_artifact("computer_call_result", { "item": item, "result": result })-++ self._save_artifact("computer_call_result", {"item": item, "result": result})+# Check if action has x/y coordinates and there's a screenshot in the resultaction = item.get("action", {})if "x" in action and "y" in action:# Look for screenshot in the resultfor result_item in result:- if (result_item.get("type") == "computer_call_output" and- result_item.get("output", {}).get("type") == "input_image"):-+ if (+ result_item.get("type") == "computer_call_output"+ and result_item.get("output", {}).get("type") == "input_image"+ ):+image_url = result_item["output"]["image_url"]-+# Extract base64 image dataif image_url.startswith("data:image/"):# Format: data:image/png;base64,<base64_data>@@ -373,26 +395,24 @@ class TrajectorySaverCallback(AsyncCallbackHandler):else:# Assume it's just base64 database64_data = image_url-+try:# Decode the imageimage_bytes = base64.b64decode(base64_data)-+# Draw crosshair at the action coordinatesannotated_image = self._draw_crosshair_on_image(- image_bytes,- int(action["x"]),- int(action["y"])+ image_bytes, int(action["x"]), int(action["y"]))-+# Save as screenshot_actionself._save_artifact("screenshot_action", annotated_image)-+except Exception as e:# If annotation fails, just log and continueprint(f"Failed to annotate screenshot: {e}")-+break # Only process the first screenshot found# Increment turn counter- self.current_turn += 1\ No newline at end of file+ self.current_turn += 1diff --git a/libs/python/agent/agent/cli.py b/libs/python/agent/agent/cli.pyindex 7edc99e1ca..7669b25586 100644--- a/libs/python/agent/agent/cli.py+++ b/libs/python/agent/agent/cli.py@@ -3,7 +3,7 @@ CLI chat interface for agent - Computer Use AgentUsage:python -m agent.cli <model_string>-+Examples:python -m agent.cli openai/computer-use-previewpython -m agent.cli anthropic/claude-3-5-sonnet-20241022@@ -11,19 +11,22 @@ Examples:"""try:- import asyncioimport argparse+ import asyncio+ import base64+ import jsonimport os+ import platformimport sys- import json- from typing import List, Dict, Any- import dotenv- import base64import time- import platformfrom pathlib import Path+ from typing import Any, Dict, List++ import dotenv+try:from PIL import Image, ImageDraw+PIL_AVAILABLE = Trueexcept Exception:PIL_AVAILABLE = False@@ -31,36 +34,44 @@ try:except ImportError:if __name__ == "__main__":raise ImportError(- "CLI dependencies not found. "- "Please install with: pip install \"cua-agent[cli]\""+ "CLI dependencies not found. " 'Please install with: pip install "cua-agent[cli]"')# Load environment variablesdotenv.load_dotenv()+# Color codes for terminal outputclass Colors:- RESET = '\033[0m'- BOLD = '\033[1m'- DIM = '\033[2m'-+ RESET = "\033[0m"+ BOLD = "\033[1m"+ DIM = "\033[2m"+# Text colors- RED = '\033[31m'- GREEN = '\033[32m'- YELLOW = '\033[33m'- BLUE = '\033[34m'- MAGENTA = '\033[35m'- CYAN = '\033[36m'- WHITE = '\033[37m'- GRAY = '\033[90m'-- # Background colors- BG_RED = '\033[41m'- BG_GREEN = '\033[42m'- BG_YELLOW = '\033[43m'- BG_BLUE = '\033[44m'+ RED = "\033[31m"+ GREEN = "\033[32m"+ YELLOW = "\033[33m"+ BLUE = "\033[34m"+ MAGENTA = "\033[35m"+ CYAN = "\033[36m"+ WHITE = "\033[37m"+ GRAY = "\033[90m"-def print_colored(text: str, color: str = "", bold: bool = False, dim: bool = False, end: str = "\n", right: str = ""):+ # Background colors+ BG_RED = "\033[41m"+ BG_GREEN = "\033[42m"+ BG_YELLOW = "\033[43m"+ BG_BLUE = "\033[44m"+++def print_colored(+ text: str,+ color: str = "",+ bold: bool = False,+ dim: bool = False,+ end: str = "\n",+ right: str = "",+):"""Print colored text to terminal with optional right-aligned text."""prefix = ""if bold:@@ -69,24 +80,25 @@ def print_colored(text: str, color: str = "", bold: bool = False, dim: bool = Faprefix += Colors.DIMif color:prefix += color-+if right:# Get terminal width (default to 80 if unable to determine)try:import shutil+terminal_width = shutil.get_terminal_size().columnsexcept:terminal_width = 80# Add right marginterminal_width -= 1-+# Calculate padding needed# Account for ANSI escape codes not taking visual spacevisible_left_len = len(text)visible_right_len = len(right)padding = terminal_width - visible_left_len - visible_right_len-+if padding > 0:output = f"{prefix}{text}{' ' * padding}{right}{Colors.RESET}"else:@@ -94,7 +106,7 @@ def print_colored(text: str, color: str = "", bold: bool = False, dim: bool = Faoutput = f"{prefix}{text} {right}{Colors.RESET}"else:output = f"{prefix}{text}{Colors.RESET}"-+print(output, end=end)@@ -113,29 +125,34 @@ def print_action(action_type: str, details: Dict[str, Any], total_cost: float):args_str = f"('{details['text']}')"elif action_type == "scroll" and "x" in details and "y" in details:args_str = f"({details['x']}, {details['y']})"-+if total_cost > 0:print_colored(f"🛠️ {action_type}{args_str}", dim=True, right=f"💸 ${total_cost:.2f}")else:print_colored(f"🛠️ {action_type}{args_str}", dim=True)+def print_welcome(model: str, agent_loop: str, container_name: str):"""Print welcome message."""print_colored(f"Connected to {container_name} ({model}, {agent_loop})")print_colored("Type 'exit' to quit.", dim=True)+async def ainput(prompt: str = ""):return await asyncio.to_thread(input, prompt)-async def chat_loop(agent, model: str, container_name: str, initial_prompt: str = "", show_usage: bool = True):++async def chat_loop(+ agent, model: str, container_name: str, initial_prompt: str = "", show_usage: bool = True+):"""Main chat loop with the agent."""print_welcome(model, agent.agent_config_info.agent_class.__name__, container_name)-+history = []-+if initial_prompt:history.append({"role": "user", "content": initial_prompt})-+total_cost = 0while True:@@ -143,28 +160,28 @@ async def chat_loop(agent, model: str, container_name: str, initial_prompt: str# Get user input with promptprint_colored("> ", end="")user_input = await ainput()-- if user_input.lower() in ['exit', 'quit', 'q']:++ if user_input.lower() in ["exit", "quit", "q"]:print_colored("\n👋 Goodbye!")break-+if not user_input:continue-+# Add user message to historyhistory.append({"role": "user", "content": user_input})-+# Stream responses from the agent with spinnerwith yaspin(text="Thinking...", spinner="line", attrs=["dark"]) as spinner:spinner.hide()-+async for result in agent.run(history):# Add agent responses to historyhistory.extend(result.get("output", []))if show_usage:total_cost += result.get("usage", {}).get("response_cost", 0)-+# Process and display the outputfor item in result.get("output", []):if item.get("type") == "message" and item.get("role") == "assistant":@@ -176,7 +193,7 @@ async def chat_loop(agent, model: str, container_name: str, initial_prompt: strif text:spinner.hide()print_colored(text)-+elif item.get("type") == "computer_call":# Display computer actionaction = item.get("action", {})@@ -186,7 +203,7 @@ async def chat_loop(agent, model: str, container_name: str, initial_prompt: strprint_action(action_type, action, total_cost)spinner.text = f"Performing {action_type}..."spinner.show()-+elif item.get("type") == "function_call":# Display function callfunction_name = item.get("name", "")@@ -194,18 +211,18 @@ async def chat_loop(agent, model: str, container_name: str, initial_prompt: strprint_colored(f"🔧 Calling function: {function_name}", dim=True)spinner.text = f"Calling {function_name}..."spinner.show()-+elif item.get("type") == "function_call_output":# Display function output (dimmed)output = item.get("output", "")if output and len(output.strip()) > 0:spinner.hide()print_colored(f"📤 {output}", dim=True)-+spinner.hide()if show_usage and total_cost > 0:print_colored(f"Total cost: ${total_cost:.2f}", dim=True)-+async def main():"""Main CLI function."""@@ -218,90 +235,74 @@ Examples:python -m agent.cli anthropic/claude-3-5-sonnet-20241022python -m agent.cli omniparser+anthropic/claude-3-5-sonnet-20241022python -m agent.cli huggingface-local/ByteDance-Seed/UI-TARS-1.5-7B- """+ """,)-+parser.add_argument("model",- help="Model string (e.g., 'openai/computer-use-preview', 'anthropic/claude-3-5-sonnet-20241022')"+ help="Model string (e.g., 'openai/computer-use-preview', 'anthropic/claude-3-5-sonnet-20241022')",)-+parser.add_argument("--provider",choices=["cloud", "lume", "winsandbox", "docker"],default="cloud",- help="Computer provider to use: cloud (default), lume, winsandbox, or docker"+ help="Computer provider to use: cloud (default), lume, winsandbox, or docker",)-+parser.add_argument("--images",type=int,default=3,- help="Number of recent images to keep in context (default: 3)"- )-- parser.add_argument(- "--trajectory",- action="store_true",- help="Save trajectory for debugging"- )-- parser.add_argument(- "--budget",- type=float,- help="Maximum budget for the session (in dollars)"- )-- parser.add_argument(- "--verbose",- action="store_true",- help="Enable verbose logging"+ help="Number of recent images to keep in context (default: 3)",)+ parser.add_argument("--trajectory", action="store_true", help="Save trajectory for debugging")++ parser.add_argument("--budget", type=float, help="Maximum budget for the session (in dollars)")++ parser.add_argument("--verbose", action="store_true", help="Enable verbose logging")+parser.add_argument(- "-p", "--prompt",+ "-p",+ "--prompt",type=str,- help="Initial prompt to send to the agent. Leave blank for interactive mode."+ help="Initial prompt to send to the agent. Leave blank for interactive mode.",)parser.add_argument("--prompt-file",type=Path,- help="Path to a UTF-8 text file whose contents will be used as the initial prompt. If provided, overrides --prompt."+ help="Path to a UTF-8 text file whose contents will be used as the initial prompt. If provided, overrides --prompt.",)parser.add_argument("--predict-click",dest="predict_click",type=str,- help="Instruction for click prediction. If set, runs predict_click, draws crosshair on a fresh screenshot, saves and opens it."+ help="Instruction for click prediction. If set, runs predict_click, draws crosshair on a fresh screenshot, saves and opens it.",)- parser.add_argument(- "-c", "--cache",- action="store_true",- help="Tell the API to enable caching"- )+ parser.add_argument("-c", "--cache", action="store_true", help="Tell the API to enable caching")parser.add_argument(- "-u", "--usage",- action="store_true",- help="Show total cost of the agent runs"+ "-u", "--usage", action="store_true", help="Show total cost of the agent runs")parser.add_argument(- "-r", "--max-retries",+ "-r",+ "--max-retries",type=int,default=3,- help="Maximum number of retries for the LLM API calls"+ help="Maximum number of retries for the LLM API calls",)-+args = parser.parse_args()-+# Check for required environment variablescontainer_name = os.getenv("CUA_CONTAINER_NAME")cua_api_key = os.getenv("CUA_API_KEY")-+# Prompt for missing environment variables (container name always required)if not container_name:if args.provider == "cloud":@@ -321,13 +322,13 @@ Examples:if not cua_api_key:print_colored("❌ API key is required for cloud provider.")sys.exit(1)-+# Check for provider-specific API keys based on modelprovider_api_keys = {"openai/": "OPENAI_API_KEY","anthropic/": "ANTHROPIC_API_KEY",}-+# Find matching provider and check for API keyfor prefix, env_var in provider_api_keys.items():if prefix in args.model:@@ -340,7 +341,7 @@ Examples:# Set the environment variable for the sessionos.environ[env_var] = api_keybreak-+# Import here to avoid import errors if dependencies are missingtry:from agent import ComputerAgent@@ -349,7 +350,7 @@ Examples:print_colored(f"❌ Import error: {e}", Colors.RED, bold=True)print_colored("Make sure agent and computer libraries are installed.", Colors.YELLOW)sys.exit(1)-+# Resolve provider -> os_type, provider_type, api key requirementprovider_map = {"cloud": ("linux", "cloud", True),@@ -365,42 +366,46 @@ Examples:"name": container_name,}if needs_api_key:- computer_kwargs["api_key"] = cua_api_key # type: ignore+ computer_kwargs["api_key"] = cua_api_key # type: ignore# Create computer instance- async with Computer(**computer_kwargs) as computer: # type: ignore-+ async with Computer(**computer_kwargs) as computer: # type: ignore+# Create agentagent_kwargs = {"model": args.model,"tools": [computer],- "trust_remote_code": True, # needed for some local models (e.g., InternVL, OpenCUA)+ "trust_remote_code": True, # needed for some local models (e.g., InternVL, OpenCUA)"verbosity": 20 if args.verbose else 30, # DEBUG vs WARNING- "max_retries": args.max_retries+ "max_retries": args.max_retries,}if args.images > 0:agent_kwargs["only_n_most_recent_images"] = args.images-+if args.trajectory:agent_kwargs["trajectory_dir"] = "trajectories"-+if args.budget:agent_kwargs["max_trajectory_budget"] = {"max_budget": args.budget,"raise_error": True,- "reset_after_each_run": False+ "reset_after_each_run": False,}if args.cache:agent_kwargs["use_prompt_caching"] = True-+agent = ComputerAgent(**agent_kwargs)-+# If predict-click mode is requested, run once and exitif args.predict_click:if not PIL_AVAILABLE:- print_colored("❌ Pillow (PIL) is required for --predict-click visualization. Install with: pip install pillow", Colors.RED, bold=True)+ print_colored(+ "❌ Pillow (PIL) is required for --predict-click visualization. Install with: pip install pillow",+ Colors.RED,+ bold=True,+ )sys.exit(1)instruction = args.predict_click@@ -435,6 +440,7 @@ Examples:try:from io import BytesIO+with Image.open(BytesIO(img_bytes)) as img:img = img.convert("RGB")draw = ImageDraw.Draw(img)@@ -457,9 +463,9 @@ Examples:if system == "windows":os.startfile(str(out_path)) # type: ignore[attr-defined]elif system == "darwin":- os.system(f"open \"{out_path}\"")+ os.system(f'open "{out_path}"')else:- os.system(f"xdg-open \"{out_path}\"")+ os.system(f'xdg-open "{out_path}"')except Exception:passexcept Exception as e:@@ -482,9 +488,8 @@ Examples:await chat_loop(agent, args.model, container_name, initial_prompt, args.usage)-if __name__ == "__main__":try:asyncio.run(main())except (KeyboardInterrupt, EOFError) as _:- print_colored("\n\n👋 Goodbye!")\ No newline at end of file+ print_colored("\n\n👋 Goodbye!")diff --git a/libs/python/agent/agent/computers/__init__.py b/libs/python/agent/agent/computers/__init__.pyindex 7c7194b693..d5628fae1e 100644--- a/libs/python/agent/agent/computers/__init__.py+++ b/libs/python/agent/agent/computers/__init__.py@@ -6,27 +6,32 @@ computer interface types, supporting both the ComputerHandler protocol and theComputer library interface."""+from computer import Computer as cuaComputer+from .base import AsyncComputerHandlerfrom .cua import cuaComputerHandlerfrom .custom import CustomComputerHandler-from computer import Computer as cuaComputer+def is_agent_computer(computer):"""Check if the given computer is a ComputerHandler or CUA Computer."""- return isinstance(computer, AsyncComputerHandler) or \- isinstance(computer, cuaComputer) or \- (isinstance(computer, dict)) #and "screenshot" in computer)+ return (+ isinstance(computer, AsyncComputerHandler)+ or isinstance(computer, cuaComputer)+ or (isinstance(computer, dict))+ ) # and "screenshot" in computer)+async def make_computer_handler(computer):"""Create a computer handler from a computer interface.-+Args:computer: Either a ComputerHandler instance, Computer instance, or dict of functions-+Returns:ComputerHandler: A computer handler instance-+Raises:ValueError: If the computer type is not supported"""@@ -38,4 +43,4 @@ async def make_computer_handler(computer):return computer_handlerif isinstance(computer, dict):return CustomComputerHandler(computer)- raise ValueError(f"Unsupported computer type: {type(computer)}")\ No newline at end of file+ raise ValueError(f"Unsupported computer type: {type(computer)}")diff --git a/libs/python/agent/agent/computers/base.py b/libs/python/agent/agent/computers/base.pyindex 7fbcb0f76f..51da978b41 100644--- a/libs/python/agent/agent/computers/base.py+++ b/libs/python/agent/agent/computers/base.py@@ -2,69 +2,78 @@Base computer interface protocol for agent interactions."""-from typing import Protocol, Literal, List, Dict, Any, Union, Optional, runtime_checkable+from typing import (+ Any,+ Dict,+ List,+ Literal,+ Optional,+ Protocol,+ Union,+ runtime_checkable,+)@runtime_checkableclass AsyncComputerHandler(Protocol):"""Protocol defining the interface for computer interactions."""-- # ==== Computer-Use-Preview Action Space ====++ # ==== 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 ====++ # ==== 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."""...diff --git a/libs/python/agent/agent/computers/cua.py b/libs/python/agent/agent/computers/cua.pyindex f935be5b4f..99723bda1e 100644--- a/libs/python/agent/agent/computers/cua.py+++ b/libs/python/agent/agent/computers/cua.py@@ -3,24 +3,27 @@ Computer handler implementation for OpenAI computer-use-preview protocol."""import base64-from typing import Dict, List, Any, Literal, Union, Optional-from .base import AsyncComputerHandler+from typing import Any, Dict, List, Literal, Optional, Union+from computer import Computer+from .base import AsyncComputerHandler++class cuaComputerHandler(AsyncComputerHandler):"""Computer handler that implements the Computer protocol using the computer interface."""-+def __init__(self, cua_computer: Computer):"""Initialize with a computer interface (from tool schema)."""self.cua_computer = cua_computerself.interface = Noneasync def _initialize(self):- if hasattr(self.cua_computer, '_initialized') and not self.cua_computer._initialized:+ if hasattr(self.cua_computer, "_initialized") and not self.cua_computer._initialized:await self.cua_computer.run()self.interface = self.cua_computer.interface-- # ==== Computer-Use-Preview Action Space ====++ # ==== Computer-Use-Preview Action Space ====async def get_environment(self) -> Literal["windows", "mac", "linux", "browser"]:"""Get the current environment type."""@@ -32,13 +35,13 @@ class cuaComputerHandler(AsyncComputerHandler):assert self.interface is not Nonescreen_size = await self.interface.get_screen_size()return screen_size["width"], screen_size["height"]-+async def screenshot(self) -> str:"""Take a screenshot and return as base64 string."""assert self.interface is not Nonescreenshot_bytes = await self.interface.screenshot()- return base64.b64encode(screenshot_bytes).decode('utf-8')-+ return base64.b64encode(screenshot_bytes).decode("utf-8")+async def click(self, x: int, y: int, button: str = "left") -> None:"""Click at coordinates with specified button."""assert self.interface is not None@@ -49,34 +52,35 @@ class cuaComputerHandler(AsyncComputerHandler):else:# Default to left click for unknown buttonsawait self.interface.left_click(x, y)-+async def double_click(self, x: int, y: int) -> None:"""Double click at coordinates."""assert self.interface is not Noneawait self.interface.double_click(x, y)-+async def scroll(self, x: int, y: int, scroll_x: int, scroll_y: int) -> None:"""Scroll at coordinates with specified scroll amounts."""assert self.interface is not Noneawait self.interface.move_cursor(x, y)await self.interface.scroll(scroll_x, scroll_y)-+async def type(self, text: str) -> None:"""Type text."""assert self.interface is not Noneawait self.interface.type_text(text)-+async def wait(self, ms: int = 1000) -> None:"""Wait for specified milliseconds."""assert self.interface is not Noneimport asyncio+await asyncio.sleep(ms / 1000.0)-+async def move(self, x: int, y: int) -> None:"""Move cursor to coordinates."""assert self.interface is not Noneawait self.interface.move_cursor(x, y)-+async def keypress(self, keys: Union[List[str], str]) -> None:"""Press key combination."""assert self.interface is not None@@ -87,38 +91,38 @@ class cuaComputerHandler(AsyncComputerHandler):else:# Handle key combinationsawait self.interface.hotkey(*keys)-+async def drag(self, path: List[Dict[str, int]]) -> None:"""Drag along specified path."""assert self.interface is not Noneif not path:return-+# Start drag from first pointstart = path[0]await self.interface.mouse_down(start["x"], start["y"])-+# Move through pathfor point in path[1:]:await self.interface.move_cursor(point["x"], point["y"])-+# End drag at last pointend = path[-1]await self.interface.mouse_up(end["x"], end["y"])-+async def get_current_url(self) -> str:"""Get current URL (for browser environments)."""# This would need to be implemented based on the specific browser interface# For now, return empty stringreturn ""- # ==== Anthropic Computer Action Space ====+ # ==== Anthropic Computer Action Space ====async def left_mouse_down(self, x: Optional[int] = None, y: Optional[int] = None) -> None:"""Left mouse down at coordinates."""assert self.interface is not Noneawait self.interface.mouse_down(x, y, button="left")-+async def left_mouse_up(self, x: Optional[int] = None, y: Optional[int] = None) -> None:"""Left mouse up at coordinates."""assert self.interface is not None- await self.interface.mouse_up(x, y, button="left")\ No newline at end of file+ await self.interface.mouse_up(x, y, button="left")diff --git a/libs/python/agent/agent/computers/custom.py b/libs/python/agent/agent/computers/custom.pyindex b5f801b69b..e87b151999 100644--- a/libs/python/agent/agent/computers/custom.py+++ b/libs/python/agent/agent/computers/custom.py@@ -3,47 +3,49 @@ Custom computer handler implementation that accepts a dictionary of functions."""import base64-from typing import Dict, List, Any, Literal, Union, Optional, Callable-from PIL import Imageimport io+from typing import Any, Callable, Dict, List, Literal, Optional, Union++from PIL import Image+from .base import AsyncComputerHandlerclass CustomComputerHandler(AsyncComputerHandler):"""Computer handler that implements the Computer protocol using a dictionary of custom functions."""-+def __init__(self, functions: Dict[str, Callable]):"""Initialize with a dictionary of functions.-+Args:functions: Dictionary where keys are method names and values are callable functions.Only 'screenshot' is required, all others are optional.-+Raises:ValueError: If required 'screenshot' function is not provided."""- if 'screenshot' not in functions:+ if "screenshot" not in functions:raise ValueError("'screenshot' function is required in functions dictionary")-+self.functions = functionsself._last_screenshot_size: Optional[tuple[int, int]] = None-+async def _call_function(self, func, *args, **kwargs):"""Call a function, handling both async and sync functions.-+Args:func: The function to call*args: Positional arguments to pass to the function**kwargs: Keyword arguments to pass to the function-+Returns:The result of the function call"""import asyncioimport inspect-+if callable(func):if inspect.iscoroutinefunction(func):return await func(*args, **kwargs)@@ -51,14 +53,14 @@ class CustomComputerHandler(AsyncComputerHandler):return func(*args, **kwargs)else:return func-+async def _get_value(self, attribute: str):"""Get value for an attribute, checking both 'get_{attribute}' and '{attribute}' keys.-+Args:attribute: The attribute name to look for-+Returns:The value from the functions dict, called if callable, returned directly if not"""@@ -66,20 +68,20 @@ class CustomComputerHandler(AsyncComputerHandler):get_key = f"get_{attribute}"if get_key in self.functions:return await self._call_function(self.functions[get_key])-- # Check for '{attribute}'++ # Check for '{attribute}'if attribute in self.functions:return await self._call_function(self.functions[attribute])-+return None-+def _to_b64_str(self, img: Union[bytes, Image.Image, str]) -> str:"""Convert image to base64 string.-+Args:img: Image as bytes, PIL Image, or base64 string-+Returns:str: Base64 encoded image string"""@@ -88,43 +90,43 @@ class CustomComputerHandler(AsyncComputerHandler):return imgelif isinstance(img, bytes):# Raw bytes- return base64.b64encode(img).decode('utf-8')+ return base64.b64encode(img).decode("utf-8")elif isinstance(img, Image.Image):# PIL Imagebuffer = io.BytesIO()- img.save(buffer, format='PNG')- return base64.b64encode(buffer.getvalue()).decode('utf-8')+ img.save(buffer, format="PNG")+ return base64.b64encode(buffer.getvalue()).decode("utf-8")else:raise ValueError(f"Unsupported image type: {type(img)}")-- # ==== Computer-Use-Preview Action Space ====++ # ==== Computer-Use-Preview Action Space ====async def get_environment(self) -> Literal["windows", "mac", "linux", "browser"]:"""Get the current environment type."""- result = await self._get_value('environment')+ result = await self._get_value("environment")if result is None:return "linux"assert result in ["windows", "mac", "linux", "browser"]- return result # type: ignore+ return result # type: ignoreasync def get_dimensions(self) -> tuple[int, int]:"""Get screen dimensions as (width, height)."""- result = await self._get_value('dimensions')+ result = await self._get_value("dimensions")if result is not None:- return result # type: ignore-+ return result # type: ignore+# Fallback: use last screenshot size if availableif not self._last_screenshot_size:await self.screenshot()assert self._last_screenshot_size is not None, "Failed to get screenshot size"-+return self._last_screenshot_size-+async def screenshot(self) -> str:"""Take a screenshot and return as base64 string."""- result = await self._call_function(self.functions['screenshot'])- b64_str = self._to_b64_str(result) # type: ignore-+ result = await self._call_function(self.functions["screenshot"])+ b64_str = self._to_b64_str(result) # type: ignore+# Try to extract dimensions for fallback usetry:if isinstance(result, Image.Image):@@ -136,74 +138,75 @@ class CustomComputerHandler(AsyncComputerHandler):except Exception:# If we can't get dimensions, that's okaypass-+return b64_str-+async def click(self, x: int, y: int, button: str = "left") -> None:"""Click at coordinates with specified button."""- if 'click' in self.functions:- await self._call_function(self.functions['click'], x, y, button)+ if "click" in self.functions:+ await self._call_function(self.functions["click"], x, y, button)# No-op if not implemented-+async def double_click(self, x: int, y: int) -> None:"""Double click at coordinates."""- if 'double_click' in self.functions:- await self._call_function(self.functions['double_click'], x, y)+ if "double_click" in self.functions:+ await self._call_function(self.functions["double_click"], x, y)# No-op if not implemented-+async def scroll(self, x: int, y: int, scroll_x: int, scroll_y: int) -> None:"""Scroll at coordinates with specified scroll amounts."""- if 'scroll' in self.functions:- await self._call_function(self.functions['scroll'], x, y, scroll_x, scroll_y)+ if "scroll" in self.functions:+ await self._call_function(self.functions["scroll"], x, y, scroll_x, scroll_y)# No-op if not implemented-+async def type(self, text: str) -> None:"""Type text."""- if 'type' in self.functions:- await self._call_function(self.functions['type'], text)+ if "type" in self.functions:+ await self._call_function(self.functions["type"], text)# No-op if not implemented-+async def wait(self, ms: int = 1000) -> None:"""Wait for specified milliseconds."""- if 'wait' in self.functions:- await self._call_function(self.functions['wait'], ms)+ if "wait" in self.functions:+ await self._call_function(self.functions["wait"], ms)else:# Default implementationimport asyncio+await asyncio.sleep(ms / 1000.0)-+async def move(self, x: int, y: int) -> None:"""Move cursor to coordinates."""- if 'move' in self.functions:- await self._call_function(self.functions['move'], x, y)+ if "move" in self.functions:+ await self._call_function(self.functions["move"], x, y)# No-op if not implemented-+async def keypress(self, keys: Union[List[str], str]) -> None:"""Press key combination."""- if 'keypress' in self.functions:- await self._call_function(self.functions['keypress'], keys)+ if "keypress" in self.functions:+ await self._call_function(self.functions["keypress"], keys)# No-op if not implemented-+async def drag(self, path: List[Dict[str, int]]) -> None:"""Drag along specified path."""- if 'drag' in self.functions:- await self._call_function(self.functions['drag'], path)+ if "drag" in self.functions:+ await self._call_function(self.functions["drag"], path)# No-op if not implemented-+async def get_current_url(self) -> str:"""Get current URL (for browser environments)."""- if 'get_current_url' in self.functions:- return await self._get_value('current_url') # type: ignore+ if "get_current_url" in self.functions:+ return await self._get_value("current_url") # type: ignorereturn "" # Default fallback-+async def left_mouse_down(self, x: Optional[int] = None, y: Optional[int] = None) -> None:"""Left mouse down at coordinates."""- if 'left_mouse_down' in self.functions:- await self._call_function(self.functions['left_mouse_down'], x, y)+ if "left_mouse_down" in self.functions:+ await self._call_function(self.functions["left_mouse_down"], x, y)# No-op if not implemented-+async def left_mouse_up(self, x: Optional[int] = None, y: Optional[int] = None) -> None:"""Left mouse up at coordinates."""- if 'left_mouse_up' in self.functions:- await self._call_function(self.functions['left_mouse_up'], x, y)+ if "left_mouse_up" in self.functions:+ await self._call_function(self.functions["left_mouse_up"], x, y)# No-op if not implementeddiff --git a/libs/python/agent/agent/decorators.py b/libs/python/agent/agent/decorators.pyindex 7fba044344..a4e5cd936e 100644--- a/libs/python/agent/agent/decorators.py+++ b/libs/python/agent/agent/decorators.py@@ -3,47 +3,56 @@ Decorators for agent - agent_loop decorator"""from typing import List, Optional+from .types import AgentConfigInfo# Global registry_agent_configs: List[AgentConfigInfo] = []+def register_agent(models: str, priority: int = 0):"""Decorator to register an AsyncAgentConfig class.-+Args:models: Regex pattern to match supported modelspriority: Priority for agent selection (higher = more priority)"""+def decorator(agent_class: type):# Validate that the class implements AsyncAgentConfig protocol- if not hasattr(agent_class, 'predict_step'):- raise ValueError(f"Agent class {agent_class.__name__} must implement predict_step method")- if not hasattr(agent_class, 'predict_click'):- raise ValueError(f"Agent class {agent_class.__name__} must implement predict_click method")- if not hasattr(agent_class, 'get_capabilities'):- raise ValueError(f"Agent class {agent_class.__name__} must implement get_capabilities method")-+ if not hasattr(agent_class, "predict_step"):+ raise ValueError(+ f"Agent class {agent_class.__name__} must implement predict_step method"+ )+ if not hasattr(agent_class, "predict_click"):+ raise ValueError(+ f"Agent class {agent_class.__name__} must implement predict_click method"+ )+ if not hasattr(agent_class, "get_capabilities"):+ raise ValueError(+ f"Agent class {agent_class.__name__} must implement get_capabilities method"+ )+# Register the agent configconfig_info = AgentConfigInfo(- agent_class=agent_class,- models_regex=models,- priority=priority+ agent_class=agent_class, models_regex=models, priority=priority)_agent_configs.append(config_info)-+# Sort by priority (highest first)_agent_configs.sort(key=lambda x: x.priority, reverse=True)-+return agent_class-+return decorator+def get_agent_configs() -> List[AgentConfigInfo]:"""Get all registered agent configs"""return _agent_configs.copy()+def find_agent_config(model: str) -> Optional[AgentConfigInfo]:"""Find the best matching agent config for a model"""for config_info in _agent_configs:diff --git a/libs/python/agent/agent/human_tool/__init__.py b/libs/python/agent/agent/human_tool/__init__.pyindex f57fb30507..9006433226 100644--- a/libs/python/agent/agent/human_tool/__init__.py+++ b/libs/python/agent/agent/human_tool/__init__.py@@ -12,7 +12,7 @@ Components:Usage:# Run the server and UIpython -m agent.human_tool-+# Or run components separatelypython -m agent.human_tool.server # API server onlypython -m agent.human_tool.ui # UI only@@ -21,9 +21,4 @@ Usage:from .server import CompletionQueue, completion_queuefrom .ui import HumanCompletionUI, create_ui-__all__ = [- "CompletionQueue",- "completion_queue",- "HumanCompletionUI",- "create_ui"-]+__all__ = ["CompletionQueue", "completion_queue", "HumanCompletionUI", "create_ui"]diff --git a/libs/python/agent/agent/human_tool/__main__.py b/libs/python/agent/agent/human_tool/__main__.pyindex e1ceed50ef..bca0b3f2dd 100644--- a/libs/python/agent/agent/human_tool/__main__.py+++ b/libs/python/agent/agent/human_tool/__main__.py@@ -8,6 +8,7 @@ with a Gradio UI for human interaction.import gradio as grfrom fastapi import FastAPI+from .server import app as fastapi_appfrom .ui import create_ui@@ -18,6 +19,7 @@ gradio_demo = create_ui()CUSTOM_PATH = "/gradio"app = gr.mount_gradio_app(fastapi_app, gradio_demo, path=CUSTOM_PATH)+# Add a redirect from root to Gradio UI@fastapi_app.get("/")async def redirect_to_ui():@@ -25,14 +27,16 @@ async def redirect_to_ui():return {"message": "Human Completion Server is running","ui_url": "/gradio",- "api_docs": "/docs"+ "api_docs": "/docs",}+if __name__ == "__main__":import uvicorn+print("🚀 Starting Human-in-the-Loop Completion Server...")print("📊 API Server: http://localhost:8002")print("🎨 Gradio UI: http://localhost:8002/gradio")print("📚 API Docs: http://localhost:8002/docs")-+uvicorn.run(app, host="0.0.0.0", port=8002)diff --git a/libs/python/agent/agent/human_tool/server.py b/libs/python/agent/agent/human_tool/server.pyindex c5d08cfef1..8c67f95a5d 100644--- a/libs/python/agent/agent/human_tool/server.py+++ b/libs/python/agent/agent/human_tool/server.py@@ -1,9 +1,9 @@import asyncioimport uuid+from dataclasses import asdict, dataclassfrom datetime import datetime-from typing import Dict, List, Any, Optional-from dataclasses import dataclass, asdictfrom enum import Enum+from typing import Any, Dict, List, Optionalfrom fastapi import FastAPI, HTTPExceptionfrom pydantic import BaseModel@@ -49,7 +49,7 @@ class CompletionQueue:self._queue: Dict[str, CompletionCall] = {}self._pending_order: List[str] = []self._lock = asyncio.Lock()-+async def add_completion(self, messages: List[Dict[str, Any]], model: str) -> str:"""Add a completion call to the queue."""async with self._lock:@@ -59,42 +59,47 @@ class CompletionQueue:messages=messages,model=model,status=CompletionStatus.PENDING,- created_at=datetime.now()+ created_at=datetime.now(),)self._queue[call_id] = completion_callself._pending_order.append(call_id)return call_id-+async def get_pending_calls(self) -> List[Dict[str, Any]]:"""Get all pending completion calls."""async with self._lock:pending_calls = []for call_id in self._pending_order:- if call_id in self._queue and self._queue[call_id].status == CompletionStatus.PENDING:+ if (+ call_id in self._queue+ and self._queue[call_id].status == CompletionStatus.PENDING+ ):call = self._queue[call_id]- pending_calls.append({- "id": call.id,- "model": call.model,- "created_at": call.created_at.isoformat(),- "messages": call.messages- })+ pending_calls.append(+ {+ "id": call.id,+ "model": call.model,+ "created_at": call.created_at.isoformat(),+ "messages": call.messages,+ }+ )return pending_calls-+async def get_call_status(self, call_id: str) -> Optional[Dict[str, Any]]:"""Get the status of a specific completion call."""async with self._lock:if call_id not in self._queue:return None-+call = self._queue[call_id]result = {"id": call.id,"status": call.status.value,"created_at": call.created_at.isoformat(),"model": call.model,- "messages": call.messages+ "messages": call.messages,}-+if call.completed_at:result["completed_at"] = call.completed_at.isoformat()if call.response:@@ -103,69 +108,74 @@ class CompletionQueue:result["tool_calls"] = call.tool_callsif call.error:result["error"] = call.error-+return result-- async def complete_call(self, call_id: str, response: Optional[str] = None, tool_calls: Optional[List[Dict[str, Any]]] = None) -> bool:++ async def complete_call(+ self,+ call_id: str,+ response: Optional[str] = None,+ tool_calls: Optional[List[Dict[str, Any]]] = None,+ ) -> bool:"""Mark a completion call as completed with a response or tool calls."""async with self._lock:if call_id not in self._queue:return False-+call = self._queue[call_id]if call.status != CompletionStatus.PENDING:return False-+call.status = CompletionStatus.COMPLETEDcall.completed_at = datetime.now()call.response = responsecall.tool_calls = tool_calls-+# Remove from pending orderif call_id in self._pending_order:self._pending_order.remove(call_id)-+return True-+async def fail_call(self, call_id: str, error: str) -> bool:"""Mark a completion call as failed with an error."""async with self._lock:if call_id not in self._queue:return False-+call = self._queue[call_id]if call.status != CompletionStatus.PENDING:return False-+call.status = CompletionStatus.FAILEDcall.completed_at = datetime.now()call.error = error-+# Remove from pending orderif call_id in self._pending_order:self._pending_order.remove(call_id)-+return True-+async def wait_for_completion(self, call_id: str, timeout: float = 300.0) -> Optional[str]:"""Wait for a completion call to be completed and return the response."""start_time = asyncio.get_event_loop().time()-+while True:status = await self.get_call_status(call_id)if not status:return None-+if status["status"] == CompletionStatus.COMPLETED.value:return status.get("response")elif status["status"] == CompletionStatus.FAILED.value:raise Exception(f"Completion failed: {status.get('error', 'Unknown error')}")-+# Check timeoutif asyncio.get_event_loop().time() - start_time > timeout:await self.fail_call(call_id, "Timeout waiting for human response")raise TimeoutError("Timeout waiting for human response")-+# Wait a bit before checking againawait asyncio.sleep(0.5)@@ -204,9 +214,7 @@ async def get_status(call_id: str):async def complete_call(call_id: str, response: CompletionResponse):"""Complete a call with a human response."""success = await completion_queue.complete_call(- call_id,- response=response.response,- tool_calls=response.tool_calls+ call_id, response=response.response, tool_calls=response.tool_calls)if success:return {"status": "success", "message": "Call completed"}@@ -219,7 +227,9 @@ async def fail_call(call_id: str, error: Dict[str, str]):"""Mark a call as failed."""success = await completion_queue.fail_call(call_id, error.get("error", "Unknown error"))if not success:- raise HTTPException(status_code=404, detail="Completion call not found or already completed")+ raise HTTPException(+ status_code=404, detail="Completion call not found or already completed"+ )return {"status": "failed"}@@ -231,4 +241,5 @@ async def root():if __name__ == "__main__":import uvicorn+uvicorn.run(app, host="0.0.0.0", port=8002)diff --git a/libs/python/agent/agent/human_tool/ui.py b/libs/python/agent/agent/human_tool/ui.pyindex 12366477a3..ae6b54050b 100644--- a/libs/python/agent/agent/human_tool/ui.py+++ b/libs/python/agent/agent/human_tool/ui.py@@ -1,14 +1,17 @@-import gradio as gr+import base64+import ioimport jsonimport time-from typing import List, Dict, Any, Optionalfrom datetime import datetime+from typing import Any, Dict, List, Optional++import gradio as grimport requests-from .server import completion_queue-import base64-import iofrom PIL import Image+from .server import completion_queue++class HumanCompletionUI:def __init__(self, server_url: str = "http://localhost:8002"):self.server_url = server_url@@ -20,7 +23,7 @@ class HumanCompletionUI:self.current_button: str = "left"self.current_scroll_x: int = 0self.current_scroll_y: int = -120-+def format_messages_for_chatbot(self, messages: List[Dict[str, Any]]) -> List[Dict[str, Any]]:"""Format messages for display in gr.Chatbot with type='messages'."""formatted = []@@ -28,7 +31,7 @@ class HumanCompletionUI:role = msg.get("role", "user")content = msg.get("content", "")tool_calls = msg.get("tool_calls", [])-+# Handle different content formatsif isinstance(content, list):# Multi-modal content - can include text and images@@ -55,7 +58,7 @@ class HumanCompletionUI:else:# For URL images, create gr.Image with URLformatted_content.append(gr.Image(value=image_url))-+# Determine final content formatif len(formatted_content) == 1:content = formatted_content[0]@@ -63,28 +66,28 @@ class HumanCompletionUI:content = formatted_contentelse:content = "[Empty content]"-+# Ensure role is valid for Gradio Chatbotif role not in ["user", "assistant"]:role = "assistant" if role == "system" else "user"-+# Invert roles for better display in human UI context# (what the AI says becomes "user", what human should respond becomes "assistant")if role == "user":role = "assistant"else:role = "user"-+# Add the main message if it has contentif content and str(content).strip():formatted.append({"role": role, "content": content})-+# Handle tool calls - create separate messages for each tool callif tool_calls:for tool_call in tool_calls:function_name = tool_call.get("function", {}).get("name", "unknown")arguments_str = tool_call.get("function", {}).get("arguments", "{}")-+try:# Parse arguments to format them nicelyarguments = json.loads(arguments_str)@@ -92,18 +95,20 @@ class HumanCompletionUI:except json.JSONDecodeError:# If parsing fails, use the raw stringformatted_args = arguments_str-+# Create a formatted message for the tool calltool_call_content = f"```json\n{formatted_args}\n```"-- formatted.append({- "role": role,- "content": tool_call_content,- "metadata": {"title": f"🛠️ Used {function_name}"}- })-++ formatted.append(+ {+ "role": role,+ "content": tool_call_content,+ "metadata": {"title": f"🛠️ Used {function_name}"},+ }+ )+return formatted-+def get_pending_calls(self) -> List[Dict[str, Any]]:"""Get pending calls from the server."""try:@@ -113,38 +118,39 @@ class HumanCompletionUI:except Exception as e:print(f"Error fetching pending calls: {e}")return []-+def complete_call_with_response(self, call_id: str, response: str) -> bool:"""Complete a call with a text response."""try:response_data = {"response": response}response_obj = requests.post(- f"{self.server_url}/complete/{call_id}",- json=response_data,- timeout=10+ f"{self.server_url}/complete/{call_id}", json=response_data, timeout=10)response_obj.raise_for_status()return Trueexcept requests.RequestException as e:print(f"Error completing call: {e}")return False-+def complete_call_with_tool_calls(self, call_id: str, tool_calls: List[Dict[str, Any]]) -> bool:"""Complete a call with tool calls."""try:response_data = {"tool_calls": tool_calls}response_obj = requests.post(- f"{self.server_url}/complete/{call_id}",- json=response_data,- timeout=10+ f"{self.server_url}/complete/{call_id}", json=response_data, timeout=10)response_obj.raise_for_status()return Trueexcept requests.RequestException as e:print(f"Error completing call: {e}")return False-- def complete_call(self, call_id: str, response: Optional[str] = None, tool_calls: Optional[List[Dict[str, Any]]] = None) -> bool:++ def complete_call(+ self,+ call_id: str,+ response: Optional[str] = None,+ tool_calls: Optional[List[Dict[str, Any]]] = None,+ ) -> bool:"""Complete a call with either a response or tool calls."""try:response_data = {}@@ -152,25 +158,23 @@ class HumanCompletionUI:response_data["response"] = responseif tool_calls:response_data["tool_calls"] = tool_calls-+response_obj = requests.post(- f"{self.server_url}/complete/{call_id}",- json=response_data,- timeout=10+ f"{self.server_url}/complete/{call_id}", json=response_data, timeout=10)response_obj.raise_for_status()return Trueexcept requests.RequestException as e:print(f"Error completing call: {e}")return False-+def get_last_image_from_messages(self, messages: List[Dict[str, Any]]) -> Optional[Any]:"""Extract the last image from the messages for display above conversation."""last_image = None-+for msg in reversed(messages): # Start from the last messagecontent = msg.get("content", "")-+if isinstance(content, list):for item in reversed(content): # Get the last image in the messageif item.get("type") == "image_url":@@ -189,13 +193,13 @@ class HumanCompletionUI:else:# For URL images, return the URLreturn image_url-+return last_image-+def refresh_pending_calls(self):"""Refresh the list of pending calls."""pending_calls = self.get_pending_calls()-+if not pending_calls:return (gr.update(choices=["latest"], value="latest"), # dropdown@@ -205,27 +209,27 @@ class HumanCompletionUI:gr.update(visible=False), # click_actions_group hiddengr.update(visible=False), # actions_group hidden)-+# Sort pending calls by created_at to get oldest firstsorted_calls = sorted(pending_calls, key=lambda x: x.get("created_at", ""))-+# Create choices for dropdownchoices = [("latest", "latest")] # Add "latest" option first-+for call in sorted_calls:call_id = call["id"]model = call.get("model", "unknown")created_at = call.get("created_at", "")# Format timestamptry:- dt = datetime.fromisoformat(created_at.replace('Z', '+00:00'))+ dt = datetime.fromisoformat(created_at.replace("Z", "+00:00"))time_str = dt.strftime("%H:%M:%S")except:time_str = created_at-+choice_label = f"{call_id[:8]}... ({model}) - {time_str}"choices.append((choice_label, call_id))-+# Default to "latest" which shows the oldest pending conversationselected_call_id = "latest"if selected_call_id == "latest" and sorted_calls:@@ -239,7 +243,7 @@ class HumanCompletionUI:conversation = []self.current_call_id = Noneself.last_image = None-+return (gr.update(choices=choices, value="latest"),gr.update(value=self.last_image),@@ -248,7 +252,7 @@ class HumanCompletionUI:gr.update(visible=True), # click_actions_group visible when there is a callgr.update(visible=True), # actions_group visible when there is a call)-+def on_call_selected(self, selected_choice):"""Handle when a call is selected from the dropdown."""if not selected_choice:@@ -259,7 +263,7 @@ class HumanCompletionUI:gr.update(visible=False), # click_actions_group hiddengr.update(visible=False), # actions_group hidden)-+pending_calls = self.get_pending_calls()if not pending_calls:return (@@ -269,7 +273,7 @@ class HumanCompletionUI:gr.update(visible=False), # click_actions_group hiddengr.update(visible=False), # actions_group hidden)-+# Handle "latest" optionif selected_choice == "latest":# Sort calls by created_at to get oldest first@@ -284,17 +288,17 @@ class HumanCompletionUI:if call_id_short in selected_choice:call_id = call["id"]break-+if not call_id:return (gr.update(value=None), # no imagegr.update(value=[]), # empty chatbot- gr.update(interactive=False)+ gr.update(interactive=False),)-+# Find the selected callselected_call = next((c for c in pending_calls if c["id"] == call_id), None)-+if not selected_call:return (gr.update(value=None), # no image@@ -303,12 +307,12 @@ class HumanCompletionUI:gr.update(visible=False), # click_actions_group hiddengr.update(visible=False), # actions_group hidden)-+conversation = self.format_messages_for_chatbot(selected_call.get("messages", []))self.current_call_id = call_id# Get the last image from messagesself.last_image = self.get_last_image_from_messages(selected_call.get("messages", []))-+return (gr.update(value=self.last_image),gr.update(value=conversation),@@ -316,110 +320,111 @@ class HumanCompletionUI:gr.update(visible=True), # click_actions_group visiblegr.update(visible=True), # actions_group visible)-+def submit_response(self, response_text: str):"""Submit a text response to the current call."""if not self.current_call_id:return (gr.update(value=response_text), # keep response text- gr.update(value="❌ No call selected") # status+ gr.update(value="❌ No call selected"), # status)-+if not response_text.strip():return (gr.update(value=response_text), # keep response text- gr.update(value="❌ Response cannot be empty") # status+ gr.update(value="❌ Response cannot be empty"), # status)-+success = self.complete_call_with_response(self.current_call_id, response_text)-+if success:status_msg = "✅ Response submitted successfully!"return (gr.update(value=""), # clear response text- gr.update(value=status_msg) # status+ gr.update(value=status_msg), # status)else:return (gr.update(value=response_text), # keep response text- gr.update(value="❌ Failed to submit response") # status+ gr.update(value="❌ Failed to submit response"), # status)-+def submit_action(self, action_type: str, **kwargs) -> str:"""Submit a computer action as a tool call."""if not self.current_call_id:return "❌ No call selected"-+import uuid-+# Create tool call structureaction_data = {"type": action_type, **kwargs}tool_call = {"id": f"call_{uuid.uuid4().hex[:24]}","type": "function",- "function": {- "name": "computer",- "arguments": json.dumps(action_data)- }+ "function": {"name": "computer", "arguments": json.dumps(action_data)},}-+success = self.complete_call_with_tool_calls(self.current_call_id, [tool_call])-+if success:return f"✅ {action_type.capitalize()} action submitted as tool call"else:return f"❌ Failed to submit {action_type} action"-- def submit_click_action(self, x: int, y: int, action_type: str = "click", button: str = "left") -> str:++ def submit_click_action(+ self, x: int, y: int, action_type: str = "click", button: str = "left"+ ) -> str:"""Submit a coordinate-based action."""if action_type == "click":return self.submit_action(action_type, x=x, y=y, button=button)else:return self.submit_action(action_type, x=x, y=y)-+def submit_type_action(self, text: str) -> str:"""Submit a type action."""return self.submit_action("type", text=text)-+def submit_hotkey_action(self, keys: str) -> str:"""Submit a hotkey action."""return self.submit_action("keypress", keys=keys)-+def submit_wait_action(self) -> str:"""Submit a wait action with no kwargs."""return self.submit_action("wait")-- def submit_description_click(self, description: str, action_type: str = "click", button: str = "left") -> str:++ def submit_description_click(+ self, description: str, action_type: str = "click", button: str = "left"+ ) -> str:"""Submit a description-based action."""if action_type == "click":return self.submit_action(action_type, element_description=description, button=button)else:return self.submit_action(action_type, element_description=description)-+def wait_for_pending_calls(self, max_seconds: float = 10.0, check_interval: float = 0.2):"""Wait for pending calls to appear or until max_seconds elapsed.-+This method loops and checks for pending calls at regular intervals,returning as soon as a pending call is found or the maximum wait time is reached.-+Args:max_seconds: Maximum number of seconds to waitcheck_interval: How often to check for pending calls (in seconds)"""import time-+start_time = time.time()-+while time.time() - start_time < max_seconds:# Check if there are any pending callspending_calls = self.get_pending_calls()if pending_calls:# Found pending calls, return immediatelyreturn self.refresh_pending_calls()-+# Wait before checking againtime.sleep(check_interval)-+# Max wait time reached, return current statereturn self.refresh_pending_calls()@@ -427,79 +432,73 @@ class HumanCompletionUI:def create_ui():"""Create the Gradio interface."""ui_handler = HumanCompletionUI()-+with gr.Blocks(title="Human-in-the-Loop Agent Tool", fill_width=True) as demo:gr.Markdown("# 🤖 Human-in-the-Loop Agent Tool")gr.Markdown("Review AI conversation requests and provide human responses.")-+with gr.Row():with gr.Column(scale=2):with gr.Group():screenshot_image = gr.Image(- label="Interactive Screenshot",- interactive=False,- height=600+ label="Interactive Screenshot", interactive=False, height=600)-+# Action type selection for image clicks (wrapped for visibility control)with gr.Group(visible=False) as click_actions_group:with gr.Row():action_type_radio = gr.Dropdown(label="Interactive Action",- choices=["click", "double_click", "move", "left_mouse_up", "left_mouse_down", "scroll"],+ choices=[+ "click",+ "double_click",+ "move",+ "left_mouse_up",+ "left_mouse_down",+ "scroll",+ ],value="click",- scale=2+ scale=2,)action_button_radio = gr.Dropdown(label="Button",choices=["left", "right", "wheel", "back", "forward"],value="left",visible=True,- scale=1+ scale=1,)scroll_x_input = gr.Number(- label="scroll_x",- value=0,- visible=False,- scale=1+ label="scroll_x", value=0, visible=False, scale=1)scroll_y_input = gr.Number(- label="scroll_y",- value=-120,- visible=False,- scale=1+ label="scroll_y", value=-120, visible=False, scale=1)-+conversation_chatbot = gr.Chatbot(- label="Conversation",- type="messages",- height=500,- show_copy_button=True+ label="Conversation", type="messages", height=500, show_copy_button=True)-+with gr.Column(scale=1):with gr.Group():call_dropdown = gr.Dropdown(label="Select a pending conversation request",choices=["latest"],interactive=True,- value="latest"+ value="latest",)refresh_btn = gr.Button("🔄 Refresh", variant="secondary")status_display = gr.Textbox(- label="Status",- interactive=False,- value="Ready to receive requests..."+ label="Status", interactive=False, value="Ready to receive requests...")with gr.Group():response_text = gr.Textbox(- label="Message",- lines=3,- placeholder="Enter your message here..."+ label="Message", lines=3, placeholder="Enter your message here...")- submit_btn = gr.Button("📤 Submit Message", variant="primary", interactive=False)-+ submit_btn = gr.Button(+ "📤 Submit Message", variant="primary", interactive=False+ )+# Action Accordions (wrapped for visibility control)with gr.Group(visible=False) as actions_group:with gr.Tabs():@@ -507,58 +506,73 @@ def create_ui():with gr.Group():description_text = gr.Textbox(label="Element Description",- placeholder="e.g., 'Privacy and security option in left sidebar'"+ placeholder="e.g., 'Privacy and security option in left sidebar'",)with gr.Row():description_action_type = gr.Dropdown(label="Action",- choices=["click", "double_click", "move", "left_mouse_up", "left_mouse_down"],- value="click"+ choices=[+ "click",+ "double_click",+ "move",+ "left_mouse_up",+ "left_mouse_down",+ ],+ value="click",)description_button = gr.Dropdown(label="Button",choices=["left", "right", "wheel", "back", "forward"],- value="left"+ value="left",)description_submit_btn = gr.Button("Submit Click Action")-+with gr.Tab("📝 Type Action"):with gr.Group():type_text = gr.Textbox(- label="Text to Type",- placeholder="Enter text to type..."+ label="Text to Type", placeholder="Enter text to type...")type_submit_btn = gr.Button("Submit Type")-+with gr.Tab("⌨️ Keypress Action"):with gr.Group():keypress_text = gr.Textbox(- label="Keys",- placeholder="e.g., ctrl+c, alt+tab"+ label="Keys", placeholder="e.g., ctrl+c, alt+tab")keypress_submit_btn = gr.Button("Submit Keypress")-+with gr.Tab("🧰 Misc Actions"):with gr.Group():misc_action_dropdown = gr.Dropdown(- label="Action",- choices=["wait"],- value="wait"+ label="Action", choices=["wait"], value="wait")misc_submit_btn = gr.Button("Submit Action")-+# Event handlersrefresh_btn.click(fn=ui_handler.refresh_pending_calls,- outputs=[call_dropdown, screenshot_image, conversation_chatbot, submit_btn, click_actions_group, actions_group]+ outputs=[+ call_dropdown,+ screenshot_image,+ conversation_chatbot,+ submit_btn,+ click_actions_group,+ actions_group,+ ],)-+call_dropdown.change(fn=ui_handler.on_call_selected,inputs=[call_dropdown],- outputs=[screenshot_image, conversation_chatbot, submit_btn, click_actions_group, actions_group]+ outputs=[+ screenshot_image,+ conversation_chatbot,+ submit_btn,+ click_actions_group,+ actions_group,+ ],)-+def handle_image_click(evt: gr.SelectData):if evt.index is not None:x, y = evt.index@@ -568,31 +582,44 @@ def create_ui():sx_i = int(ui_handler.current_scroll_x or 0)sy_i = int(ui_handler.current_scroll_y or 0)# Submit a scroll action with x,y position and scroll deltas- result = ui_handler.submit_action("scroll", x=x, y=y, scroll_x=sx_i, scroll_y=sy_i)+ result = ui_handler.submit_action(+ "scroll", x=x, y=y, scroll_x=sx_i, scroll_y=sy_i+ )else:result = ui_handler.submit_click_action(x, y, action_type, button)ui_handler.wait_for_pending_calls()return resultreturn "No coordinates selected"- screenshot_image.select(- fn=handle_image_click,- outputs=[status_display]- ).then(+ screenshot_image.select(fn=handle_image_click, outputs=[status_display]).then(fn=ui_handler.wait_for_pending_calls,- outputs=[call_dropdown, screenshot_image, conversation_chatbot, submit_btn, click_actions_group, actions_group]+ outputs=[+ call_dropdown,+ screenshot_image,+ conversation_chatbot,+ submit_btn,+ click_actions_group,+ actions_group,+ ],)# Response submissionsubmit_btn.click(fn=ui_handler.submit_response,inputs=[response_text],- outputs=[response_text, status_display]+ outputs=[response_text, status_display],).then(fn=ui_handler.refresh_pending_calls,- outputs=[call_dropdown, screenshot_image, conversation_chatbot, submit_btn, click_actions_group, actions_group]+ outputs=[+ call_dropdown,+ screenshot_image,+ conversation_chatbot,+ submit_btn,+ click_actions_group,+ actions_group,+ ],)-+# Toggle visibility of controls based on action typedef toggle_action_controls(action_type):# Button visible only for click@@ -603,59 +630,63 @@ def create_ui():# Update stateui_handler.current_action_type = action_type or "click"return button_vis, scroll_x_vis, scroll_y_vis-+action_type_radio.change(fn=toggle_action_controls,inputs=[action_type_radio],- outputs=[action_button_radio, scroll_x_input, scroll_y_input]+ outputs=[action_button_radio, scroll_x_input, scroll_y_input],)# Keep other control values in ui_handler statedef on_button_change(val):- ui_handler.current_button = (val or "left")- action_button_radio.change(- fn=on_button_change,- inputs=[action_button_radio]- )+ ui_handler.current_button = val or "left"++ action_button_radio.change(fn=on_button_change, inputs=[action_button_radio])def on_scroll_x_change(val):try:ui_handler.current_scroll_x = int(val) if val is not None else 0except Exception:ui_handler.current_scroll_x = 0- scroll_x_input.change(- fn=on_scroll_x_change,- inputs=[scroll_x_input]- )++ scroll_x_input.change(fn=on_scroll_x_change, inputs=[scroll_x_input])def on_scroll_y_change(val):try:ui_handler.current_scroll_y = int(val) if val is not None else 0except Exception:ui_handler.current_scroll_y = 0- scroll_y_input.change(- fn=on_scroll_y_change,- inputs=[scroll_y_input]- )-++ scroll_y_input.change(fn=on_scroll_y_change, inputs=[scroll_y_input])+type_submit_btn.click(- fn=ui_handler.submit_type_action,- inputs=[type_text],- outputs=[status_display]+ fn=ui_handler.submit_type_action, inputs=[type_text], outputs=[status_display]).then(fn=ui_handler.wait_for_pending_calls,- outputs=[call_dropdown, screenshot_image, conversation_chatbot, submit_btn, click_actions_group, actions_group]+ outputs=[+ call_dropdown,+ screenshot_image,+ conversation_chatbot,+ submit_btn,+ click_actions_group,+ actions_group,+ ],)-+keypress_submit_btn.click(- fn=ui_handler.submit_hotkey_action,- inputs=[keypress_text],- outputs=[status_display]+ fn=ui_handler.submit_hotkey_action, inputs=[keypress_text], outputs=[status_display]).then(fn=ui_handler.wait_for_pending_calls,- outputs=[call_dropdown, screenshot_image, conversation_chatbot, submit_btn, click_actions_group, actions_group]+ outputs=[+ call_dropdown,+ screenshot_image,+ conversation_chatbot,+ submit_btn,+ click_actions_group,+ actions_group,+ ],)-+def handle_description_submit(description, action_type, button):if description:result = ui_handler.submit_description_click(description, action_type, button)@@ -666,12 +697,19 @@ def create_ui():description_submit_btn.click(fn=handle_description_submit,inputs=[description_text, description_action_type, description_button],- outputs=[status_display]+ outputs=[status_display],).then(fn=ui_handler.wait_for_pending_calls,- outputs=[call_dropdown, screenshot_image, conversation_chatbot, submit_btn, click_actions_group, actions_group]+ outputs=[+ call_dropdown,+ screenshot_image,+ conversation_chatbot,+ submit_btn,+ click_actions_group,+ actions_group,+ ],)-+# Misc action handlerdef handle_misc_submit(selected_action):if selected_action == "wait":@@ -681,20 +719,32 @@ def create_ui():return f"Unsupported misc action: {selected_action}"misc_submit_btn.click(- fn=handle_misc_submit,- inputs=[misc_action_dropdown],- outputs=[status_display]+ fn=handle_misc_submit, inputs=[misc_action_dropdown], outputs=[status_display]).then(fn=ui_handler.wait_for_pending_calls,- outputs=[call_dropdown, screenshot_image, conversation_chatbot, submit_btn, click_actions_group, actions_group]+ outputs=[+ call_dropdown,+ screenshot_image,+ conversation_chatbot,+ submit_btn,+ click_actions_group,+ actions_group,+ ],)-+# Load initial datademo.load(fn=ui_handler.refresh_pending_calls,- outputs=[call_dropdown, screenshot_image, conversation_chatbot, submit_btn, click_actions_group, actions_group]+ outputs=[+ call_dropdown,+ screenshot_image,+ conversation_chatbot,+ submit_btn,+ click_actions_group,+ actions_group,+ ],)-+return demodiff --git a/libs/python/agent/agent/integrations/hud/__init__.py b/libs/python/agent/agent/integrations/hud/__init__.pyindex e27060ff03..2dd64ac4c0 100644--- a/libs/python/agent/agent/integrations/hud/__init__.py+++ b/libs/python/agent/agent/integrations/hud/__init__.py@@ -8,21 +8,22 @@ Exports:- run_full_dataset(dataset, ...)- MCPComputerAgent"""+import timefrom typing import Any, Optionalfrom agent.computers import is_agent_computer-from datasets import load_dataset, Dataset-from hud.datasets import Task, run_dataset+from datasets import Dataset, load_datasetfrom hud import trace+from hud.datasets import Task, run_datasetfrom .agent import MCPComputerAgent-# ---------------------------------------------------------------------------# Single-task runner# ---------------------------------------------------------------------------+async def run_single_task(dataset: str | Dataset | list[dict[str, Any]],*,@@ -47,24 +48,20 @@ async def run_single_task(# Load dataset and pick a sampleif isinstance(dataset, str):- dataset = load_dataset(dataset, split="train") # type: ignore[arg-type]+ dataset = load_dataset(dataset, split="train") # type: ignore[arg-type]elif isinstance(dataset, list):dataset = datasetelse:dataset = dataset["train"]-+sample_task = dataset[task_id] # type: ignore[index]task_prompt = sample_task.get("prompt", f"Task {sample_task.get('id', 0)}") # type: ignore[attr-defined]# Filter any existing Computer tools# The eval framework will add its own Computer tool per taskif tools:- tools = [- tool- for tool in tools- if not is_agent_computer(tool)- ]-+ tools = [tool for tool in tools if not is_agent_computer(tool)]+with trace(name=task_prompt):task = Task(**sample_task) # type: ignore[arg-type]@@ -87,13 +84,14 @@ async def run_single_task()print(f"Running: {task_prompt}")result = await agent.run(task, max_steps=10)- print(f"✅ Reward: {getattr(result, 'reward')}")+ print(f"✅ Reward: {result.reward}")# ---------------------------------------------------------------------------# Full-dataset runner# ---------------------------------------------------------------------------+async def run_full_dataset(dataset: str | Dataset | list[dict[str, Any]],*,@@ -121,9 +119,9 @@ async def run_full_dataset(# Run with our MCP-based agent class.if isinstance(dataset, str):- dataset_name = dataset.split('/')[-1]+ dataset_name = dataset.split("/")[-1]job_name = job_name or f"Evaluation {dataset_name}"- dataset = load_dataset(dataset, split=split) # type: ignore[arg-type]+ dataset = load_dataset(dataset, split=split) # type: ignore[arg-type]else:dataset_name = "custom"job_name = job_name or f"Evaluation {time.strftime('%H:%M %Y-%m-%d')}"@@ -131,12 +129,8 @@ async def run_full_dataset(# Filter any existing Computer tools# The eval framework will add its own Computer tool per taskif tools:- tools = [- tool- for tool in tools- if not is_agent_computer(tool)- ]-+ tools = [tool for tool in tools if not is_agent_computer(tool)]+# Execute evaluationreturn await run_dataset(name=job_name,@@ -170,4 +164,4 @@ __all__ = ["run_single_task","run_full_dataset","MCPComputerAgent",-]\ No newline at end of file+]diff --git a/libs/python/agent/agent/integrations/hud/agent.py b/libs/python/agent/agent/integrations/hud/agent.pyindex c1465ee61a..e830d53cfe 100644--- a/libs/python/agent/agent/integrations/hud/agent.py+++ b/libs/python/agent/agent/integrations/hud/agent.py@@ -9,26 +9,26 @@ Key differences from the OpenAI OperatorAgent variant:- Planning is executed via `ComputerAgent.run(messages)`.- The first yielded result per step is returned as the agent response."""+from __future__ import annotations+import base64import io+import uuid+from pathlib import Pathfrom typing import Any, ClassVar, Optional+import hud+import mcp.types as typesfrom agent.agent import ComputerAgent as BaseComputerAgentfrom agent.callbacks import PromptInstructionsCallbackfrom agent.callbacks.trajectory_saver import TrajectorySaverCallback+from agent.computers import is_agent_computer+from agent.responses import make_failed_tool_call_itemsfrom hud.agents import MCPAgentfrom hud.tools.computer.settings import computer_settingsfrom hud.types import AgentResponse, MCPToolCall, MCPToolResult, Trace--from agent.responses import make_failed_tool_call_items-from agent.computers import is_agent_computerfrom PIL import Image-import mcp.types as types-import hud-import uuid-import base64-from pathlib import Pathclass MCPComputerAgent(MCPAgent):@@ -114,8 +114,10 @@ class MCPComputerAgent(MCPAgent):self.last_screenshot_b64 = Nonebuffer = io.BytesIO()- Image.new('RGB', (self.metadata["display_width"], self.metadata["display_height"])).save(buffer, format='PNG')- self.last_screenshot_b64 = base64.b64encode(buffer.getvalue()).decode('utf-8')+ Image.new("RGB", (self.metadata["display_width"], self.metadata["display_height"])).save(+ buffer, format="PNG"+ )+ self.last_screenshot_b64 = base64.b64encode(buffer.getvalue()).decode("utf-8")# Ensure a computer shim is present so width/height/environment are knowncomputer_shim = {@@ -128,12 +130,8 @@ class MCPComputerAgent(MCPAgent):}agent_tools: list[Any] = [computer_shim]if tools:- agent_tools.extend([- tool- for tool in tools- if not is_agent_computer(tool)- ])-+ agent_tools.extend([tool for tool in tools if not is_agent_computer(tool)])+agent_kwargs = {"model": self.model,"trajectory_dir": trajectory_dir,@@ -150,9 +148,7 @@ class MCPComputerAgent(MCPAgent):"telemetry_enabled": telemetry_enabled,}- self.computer_agent = BaseComputerAgent(- **agent_kwargs- )+ self.computer_agent = BaseComputerAgent(**agent_kwargs)async def get_system_messages(self) -> list[Any]:"""Create initial messages.@@ -161,9 +157,7 @@ class MCPComputerAgent(MCPAgent):"""return []- async def format_blocks(- self, blocks: list[types.ContentBlock]- ) -> list[dict[str, Any]]:+ async def format_blocks(self, blocks: list[types.ContentBlock]) -> list[dict[str, Any]]:"""Format blocks for OpenAI input format.@@ -200,42 +194,49 @@ class MCPComputerAgent(MCPAgent):# Call the ComputerAgent LLM APIasync for result in self.computer_agent.run(messages): # type: ignore[arg-type]- items = result['output']+ items = result["output"]if not items or tool_calls:breakfor item in items:- if item['type'] in ['reasoning', 'message', 'computer_call', 'function_call', 'function_call_output']:+ if item["type"] in [+ "reasoning",+ "message",+ "computer_call",+ "function_call",+ "function_call_output",+ ]:agent_result.append(item)-+# Add messages to output text- if item['type'] == 'reasoning':+ if item["type"] == "reasoning":output_text.extend(- f"Reasoning: {summary['text']}"- for summary in item['summary']+ f"Reasoning: {summary['text']}" for summary in item["summary"])- elif item['type'] == 'message':- if isinstance(item['content'], list):+ elif item["type"] == "message":+ if isinstance(item["content"], list):output_text.extend(- item['text']- for item in item['content']- if item['type'] == 'output_text'+ item["text"]+ for item in item["content"]+ if item["type"] == "output_text")- elif isinstance(item['content'], str):- output_text.append(item['content'])-+ elif isinstance(item["content"], str):+ output_text.append(item["content"])+# If we get a tool call, we're not done- if item['type'] == 'computer_call':+ if item["type"] == "computer_call":id = item["call_id"]- tool_calls.append(MCPToolCall(- name="openai_computer",- arguments=item["action"],- id=id,- ))+ tool_calls.append(+ MCPToolCall(+ name="openai_computer",+ arguments=item["action"],+ id=id,+ )+ )is_done = Falseself.tool_call_inputs[id] = agent_resultbreak-+# if we have tool calls, we should exit the loopif tool_calls:break@@ -247,7 +248,7 @@ class MCPComputerAgent(MCPAgent):tool_calls=tool_calls,done=is_done,)-+def _log_image(self, image_b64: str):callbacks = self.computer_agent.callbacksfor callback in callbacks:@@ -257,9 +258,7 @@ class MCPComputerAgent(MCPAgent):callback._save_artifact("screenshot_after", image_bytes)async def format_tool_results(- self,- tool_calls: list[MCPToolCall],- tool_results: list[MCPToolResult]+ self, tool_calls: list[MCPToolCall], tool_results: list[MCPToolResult]) -> list[dict[str, Any]]:"""Extract latest screenshot from tool results in dict form.@@ -274,45 +273,60 @@ class MCPComputerAgent(MCPAgent):previous_output = self.previous_output.copy() or []# First we need to remove any pending computer_calls from the end of previous_output- while previous_output and previous_output[-1]['type'] == 'computer_call':+ while previous_output and previous_output[-1]["type"] == "computer_call":previous_output.pop()messages.extend(previous_output)# If the call is a 'response', don't add the result- if call.name == 'response':+ if call.name == "response":continue# Otherwise, if we have a result, we should add it to the messagescontent = [- { "type": "input_text", "text": content.text } if isinstance(content, types.TextContent)- else { "type": "input_image", "image_url": f"data:image/png;base64,{content.data}" } if isinstance(content, types.ImageContent)- else { "type": "input_text", "text": "" }+ (+ {"type": "input_text", "text": content.text}+ if isinstance(content, types.TextContent)+ else (+ {+ "type": "input_image",+ "image_url": f"data:image/png;base64,{content.data}",+ }+ if isinstance(content, types.ImageContent)+ else {"type": "input_text", "text": ""}+ )+ )for content in result.content]- messages.append({- "role": "user",- "content": content,- })+ messages.append(+ {+ "role": "user",+ "content": content,+ }+ )continue-+# Add the assistant's computer callmessages.extend(self.tool_call_inputs[call.id])-+if result.isError:- error_text = "".join([- content.text- for content in result.content- if isinstance(content, types.TextContent)- ])+ error_text = "".join(+ [+ content.text+ for content in result.content+ if isinstance(content, types.TextContent)+ ]+ )# Replace computer call with failed tool callmessages.pop()- messages.extend(make_failed_tool_call_items(- tool_name=call.name,- tool_kwargs=call.arguments or {},- error_message=error_text,- call_id=call.id,- ))+ messages.extend(+ make_failed_tool_call_items(+ tool_name=call.name,+ tool_kwargs=call.arguments or {},+ error_message=error_text,+ call_id=call.id,+ )+ )else:# Get the latest screenshotscreenshots = [@@ -325,23 +339,27 @@ class MCPComputerAgent(MCPAgent):if screenshots:self._log_image(screenshots[0])self.last_screenshot_b64 = screenshots[0]- messages.append({- "type": "computer_call_output",- "call_id": call.id,- "output": {- "type": "input_image",- "image_url": f"data:image/png;base64,{screenshots[0]}"- },- })+ messages.append(+ {+ "type": "computer_call_output",+ "call_id": call.id,+ "output": {+ "type": "input_image",+ "image_url": f"data:image/png;base64,{screenshots[0]}",+ },+ }+ )else:# Otherwise, replace computer call with failed tool callmessages.pop()- messages.extend(make_failed_tool_call_items(- tool_name=call.name,- tool_kwargs=call.arguments or {},- error_message="No screenshots returned.",- call_id=call.id,- ))+ messages.extend(+ make_failed_tool_call_items(+ tool_name=call.name,+ tool_kwargs=call.arguments or {},+ error_message="No screenshots returned.",+ call_id=call.id,+ )+ )return messagesdiff --git a/libs/python/agent/agent/integrations/hud/proxy.py b/libs/python/agent/agent/integrations/hud/proxy.pyindex 9087d1c96f..3b06219678 100644--- a/libs/python/agent/agent/integrations/hud/proxy.py+++ b/libs/python/agent/agent/integrations/hud/proxy.py@@ -7,30 +7,33 @@ OpenAI-like response blocks. We intentionally only support a single-step callby consuming the first yielded result from `ComputerAgent.run()`."""-import tracebackimport time+import tracebackimport uuidfrom typing import Any, Dict, List, Optionalfrom agent.agent import ComputerAgent as BaseComputerAgentfrom agent.callbacks import PromptInstructionsCallback-from hud.tools.computer.settings import computer_settings-from PIL import Imagefrom hud.agents import OperatorAgent+from hud.tools.computer.settings import computer_settings# OpenAI Responses typed models (required)from openai.types.responses import (Response,+ ResponseComputerToolCall,ResponseInputParam,ResponseOutputItem,- ResponseComputerToolCall,ResponseOutputMessage,ResponseOutputText,ResponseReasoningItem,ResponseUsage,)+from PIL import Image-def _map_agent_output_to_openai_blocks(output_items: List[Dict[str, Any]]) -> List[ResponseOutputItem]:++def _map_agent_output_to_openai_blocks(+ output_items: List[Dict[str, Any]],+) -> List[ResponseOutputItem]:"""Map our agent output items to OpenAI ResponseOutputItem typed models.Only a subset is supported: computer_call, assistant message (text), and reasoning.@@ -40,14 +43,16 @@ def _map_agent_output_to_openai_blocks(output_items: List[Dict[str, Any]]) -> Lifor item in output_items or []:t = item.get("type")if t == "computer_call":- comp = ResponseComputerToolCall.model_validate({- "id": item.get("id") or f"cu_{uuid.uuid4().hex}",- "type": "computer_call",- "call_id": item["call_id"],- "action": item["action"],- "pending_safety_checks": item.get("pending_safety_checks", []),- "status": "completed",- })+ comp = ResponseComputerToolCall.model_validate(+ {+ "id": item.get("id") or f"cu_{uuid.uuid4().hex}",+ "type": "computer_call",+ "call_id": item["call_id"],+ "action": item["action"],+ "pending_safety_checks": item.get("pending_safety_checks", []),+ "status": "completed",+ }+ )blocks.append(comp)# we will exit early here as the responses api only supports a single stepbreak@@ -55,31 +60,38 @@ def _map_agent_output_to_openai_blocks(output_items: List[Dict[str, Any]]) -> Licontent_blocks: List[ResponseOutputText] = []for c in item.get("content", []) or []:content_blocks.append(- ResponseOutputText.model_validate({- "type": "output_text",- "text": c["text"],- "annotations": [],- })+ ResponseOutputText.model_validate(+ {+ "type": "output_text",+ "text": c["text"],+ "annotations": [],+ }+ ))if content_blocks:- msg = ResponseOutputMessage.model_validate({- "id": item.get("id") or f"msg_{uuid.uuid4()}",- "type": "message",- "role": "assistant",- "status": "completed",- "content": [ct.model_dump() for ct in content_blocks],- })+ msg = ResponseOutputMessage.model_validate(+ {+ "id": item.get("id") or f"msg_{uuid.uuid4()}",+ "type": "message",+ "role": "assistant",+ "status": "completed",+ "content": [ct.model_dump() for ct in content_blocks],+ }+ )blocks.append(msg)elif t == "reasoning":- reasoning = ResponseReasoningItem.model_validate({- "id": item.get("id") or f"rsn_{uuid.uuid4()}",- "type": "reasoning",- "summary": item["summary"],- })+ reasoning = ResponseReasoningItem.model_validate(+ {+ "id": item.get("id") or f"rsn_{uuid.uuid4()}",+ "type": "reasoning",+ "summary": item["summary"],+ }+ )blocks.append(reasoning)# Unhandled types are ignoredreturn blocks+def _to_plain_dict_list(items: Any) -> List[Dict[str, Any]]:out: List[Dict[str, Any]] = []for it in list(items):@@ -92,6 +104,7 @@ def _to_plain_dict_list(items: Any) -> List[Dict[str, Any]]:out.append(dict(it)) # may raise if not mappingreturn out+class FakeAsyncOpenAI:"""Minimal fake OpenAI client with only `responses.create` implemented.@@ -132,10 +145,12 @@ class FakeAsyncOpenAI:# Pre-pend instructions messageeffective_input = full_inputif instructions:- effective_input = [{- "role": "user",- "content": instructions,- }] + full_input+ effective_input = [+ {+ "role": "user",+ "content": instructions,+ }+ ] + full_input# Run a single iteration of the ComputerAgentagent_result: Optional[Dict[str, Any]] = None@@ -152,32 +167,43 @@ class FakeAsyncOpenAI:blocks_to_cache = full_input + outputfor b in blocks_to_cache:bid = getattr(b, "id", None) or f"tmp-{hash(repr(b))}"- self.blocks_cache[bid] = b # type: ignore[assignment]+ self.blocks_cache[bid] = b # type: ignore[assignment]block_ids.append(bid)response_id = agent_result.get("id") or f"fake-{int(time.time()*1000)}"self.context_cache[response_id] = block_idstry:- return Response.model_validate({- "id": response_id,- "created_at": time.time(),- "object": "response",- "model": model,- "output": output,- "parallel_tool_calls": False,- "tool_choice": "auto",- "tools": [],- "previous_response_id": previous_response_id,- "usage": ResponseUsage.model_validate({- "input_tokens": usage.get("input_tokens", 0),- "output_tokens": usage.get("output_tokens", 0),- "total_tokens": usage.get("total_tokens", 0),- "input_tokens_details": usage.get("input_tokens_details", { "cached_tokens": 0 }),- "output_tokens_details": usage.get("output_tokens_details", { "reasoning_tokens": 0 }),- }),- })+ return Response.model_validate(+ {+ "id": response_id,+ "created_at": time.time(),+ "object": "response",+ "model": model,+ "output": output,+ "parallel_tool_calls": False,+ "tool_choice": "auto",+ "tools": [],+ "previous_response_id": previous_response_id,+ "usage": ResponseUsage.model_validate(+ {+ "input_tokens": usage.get("input_tokens", 0),+ "output_tokens": usage.get("output_tokens", 0),+ "total_tokens": usage.get("total_tokens", 0),+ "input_tokens_details": usage.get(+ "input_tokens_details", {"cached_tokens": 0}+ ),+ "output_tokens_details": usage.get(+ "output_tokens_details", {"reasoning_tokens": 0}+ ),+ }+ ),+ }+ )except Exception as e:- print(f"Error while validating agent response (attempt {attempt + 1}/{max_retries}): ", e)+ print(+ f"Error while validating agent response (attempt {attempt + 1}/{max_retries}): ",+ e,+ )if attempt == max_retries - 1:print(traceback.format_exc())raise e@@ -221,9 +247,15 @@ class ProxyOperatorAgent(OperatorAgent):allowed_tools = allowed_tools or ["openai_computer"]computer_shim = {- 'screenshot': lambda: Image.new('RGB', (computer_settings.OPENAI_COMPUTER_WIDTH, computer_settings.OPENAI_COMPUTER_HEIGHT)),- 'environment': 'linux',- 'dimensions': (computer_settings.OPENAI_COMPUTER_WIDTH, computer_settings.OPENAI_COMPUTER_HEIGHT)+ "screenshot": lambda: Image.new(+ "RGB",+ (computer_settings.OPENAI_COMPUTER_WIDTH, computer_settings.OPENAI_COMPUTER_HEIGHT),+ ),+ "environment": "linux",+ "dimensions": (+ computer_settings.OPENAI_COMPUTER_WIDTH,+ computer_settings.OPENAI_COMPUTER_HEIGHT,+ ),}# Build tools ensuring the computer_shim is includedagent_tools: list[Any] = [computer_shim]@@ -258,6 +290,7 @@ class ProxyOperatorAgent(OperatorAgent):**kwargs,)+__all__ = ["FakeAsyncOpenAI","ProxyOperatorAgent",diff --git a/libs/python/agent/agent/loops/__init__.py b/libs/python/agent/agent/loops/__init__.pyindex bda16cf930..6fd20cde28 100644--- a/libs/python/agent/agent/loops/__init__.py+++ b/libs/python/agent/agent/loops/__init__.py@@ -3,30 +3,32 @@ Agent loops for agent"""# Import the loops to register them-from . import anthropic-from . import openai-from . import uitars-from . import omniparser-from . import gta1-from . import composed_grounded-from . import glm45v-from . import opencua-from . import internvl-from . import holo-from . import moondream3-from . import gemini+from . import (+ anthropic,+ composed_grounded,+ gemini,+ glm45v,+ gta1,+ holo,+ internvl,+ moondream3,+ omniparser,+ openai,+ opencua,+ uitars,+)__all__ = [- "anthropic",- "openai",- "uitars",- "omniparser",- "gta1",- "composed_grounded",- "glm45v",+ "anthropic",+ "openai",+ "uitars",+ "omniparser",+ "gta1",+ "composed_grounded",+ "glm45v","opencua","internvl","holo","moondream3",- "gemini"-]\ No newline at end of file+ "gemini",+]diff --git a/libs/python/agent/agent/loops/anthropic.py b/libs/python/agent/agent/loops/anthropic.pyindex 063776a80e..9dd77eb499 100644--- a/libs/python/agent/agent/loops/anthropic.py+++ b/libs/python/agent/agent/loops/anthropic.py@@ -4,30 +4,33 @@ Anthropic hosted tools agent loop implementation using liteLLMimport asyncioimport json-from typing import Dict, List, Any, AsyncGenerator, Union, Optional, Tuple+from typing import Any, AsyncGenerator, Dict, List, Optional, Tuple, Union+import litellm-from litellm.responses.litellm_completion_transformation.transformation import LiteLLMCompletionResponsesConfig+from litellm.responses.litellm_completion_transformation.transformation import (+ LiteLLMCompletionResponsesConfig,+)from ..decorators import register_agent-from ..types import Messages, AgentResponse, Tools, AgentCapabilityfrom ..loops.base import AsyncAgentConfigfrom ..responses import (- make_reasoning_item,- make_output_text_item,make_click_item,make_double_click_item,make_drag_item,+ make_failed_tool_call_items,+ make_input_image_item,make_keypress_item,+ make_left_mouse_down_item,+ make_left_mouse_up_item,make_move_item,+ make_output_text_item,+ make_reasoning_item,+ make_screenshot_item,make_scroll_item,make_type_item,make_wait_item,- make_input_image_item,- make_screenshot_item,- make_failed_tool_call_items,- make_left_mouse_down_item,- make_left_mouse_up_item)+from ..types import AgentCapability, AgentResponse, Messages, Tools# Model version mapping to tool version and beta flagMODEL_TOOL_MAPPING = [@@ -35,38 +38,34 @@ MODEL_TOOL_MAPPING = [{"pattern": r"claude-4|claude-opus-4|claude-sonnet-4|claude-haiku-4","tool_version": "computer_20250124",- "beta_flag": "computer-use-2025-01-24"+ "beta_flag": "computer-use-2025-01-24",},# Claude 3.7 models{"pattern": r"claude-3\.?7|claude-3-7","tool_version": "computer_20250124",- "beta_flag": "computer-use-2025-01-24"+ "beta_flag": "computer-use-2025-01-24",},# Claude 3.5 models (fallback){"pattern": r"claude-3\.?5|claude-3-5","tool_version": "computer_20241022",- "beta_flag": "computer-use-2024-10-22"- }+ "beta_flag": "computer-use-2024-10-22",+ },]+def _get_tool_config_for_model(model: str) -> Dict[str, str]:"""Get tool version and beta flag for the given model."""import re-+for mapping in MODEL_TOOL_MAPPING:if re.search(mapping["pattern"], model, re.IGNORECASE):- return {- "tool_version": mapping["tool_version"],- "beta_flag": mapping["beta_flag"]- }-+ return {"tool_version": mapping["tool_version"], "beta_flag": mapping["beta_flag"]}+# Default to Claude 3.5 configuration- return {- "tool_version": "computer_20241022",- "beta_flag": "computer-use-2024-10-22"- }+ return {"tool_version": "computer_20241022", "beta_flag": "computer-use-2024-10-22"}+async def _map_computer_tool_to_anthropic(computer_tool: Any, tool_version: str) -> Dict[str, Any]:"""Map a computer tool to Anthropic's hosted tool schema."""@@ -76,7 +75,7 @@ async def _map_computer_tool_to_anthropic(computer_tool: Any, tool_version: str)except Exception:# Fallback to default dimensions if method failswidth, height = 1024, 768-+return {"type": tool_version,"function": {@@ -89,32 +88,37 @@ async def _map_computer_tool_to_anthropic(computer_tool: Any, tool_version: str)},}+async def _prepare_tools_for_anthropic(tool_schemas: List[Dict[str, Any]], model: str) -> Tools:"""Prepare tools for Anthropic API format."""tool_config = _get_tool_config_for_model(model)anthropic_tools = []-+for schema in tool_schemas:if schema["type"] == "computer":# Map computer tool to Anthropic format- anthropic_tools.append(await _map_computer_tool_to_anthropic(- schema["computer"],- tool_config["tool_version"]- ))+ anthropic_tools.append(+ await _map_computer_tool_to_anthropic(+ schema["computer"], tool_config["tool_version"]+ )+ )elif schema["type"] == "function":# Function tools - convert to Anthropic formatfunction_schema = schema["function"]- anthropic_tools.append({- "type": "function",- "function": {- "name": function_schema["name"],- "description": function_schema.get("description", ""),- "parameters": function_schema.get("parameters", {})+ anthropic_tools.append(+ {+ "type": "function",+ "function": {+ "name": function_schema["name"],+ "description": function_schema.get("description", ""),+ "parameters": function_schema.get("parameters", {}),+ },}- })-+ )+return anthropic_tools+def _convert_responses_items_to_completion_messages(messages: Messages) -> List[Dict[str, Any]]:"""Convert responses_items message format to liteLLM completion format."""completion_messages = []@@ -123,7 +127,7 @@ def _convert_responses_items_to_completion_messages(messages: Messages) -> List[for message in messages:msg_type = message.get("type")role = message.get("role")-+# Handle user messages (both with and without explicit type)if role == "user" or msg_type == "user":content = message.get("content", "")@@ -135,51 +139,38 @@ def _convert_responses_items_to_completion_messages(messages: Messages) -> List[# Convert input_image to OpenAI image formatimage_url = item.get("image_url", "")if image_url and image_url != "[omitted]":- converted_content.append({- "type": "image_url",- "image_url": {- "url": image_url- }- })+ converted_content.append(+ {"type": "image_url", "image_url": {"url": image_url}}+ )elif isinstance(item, dict) and item.get("type") == "input_text":# Convert input_text to OpenAI text formattext = item.get("text", "")- converted_content.append({- "type": "text",- "text": text- })+ converted_content.append({"type": "text", "text": text})else:# Keep other content types as-isconverted_content.append(item)-- completion_messages.append({- "role": "user",- "content": converted_content if converted_content else content- })++ completion_messages.append(+ {"role": "user", "content": converted_content if converted_content else content}+ )else:# Text content- completion_messages.append({- "role": "user",- "content": content- })-+ completion_messages.append({"role": "user", "content": content})+# Handle assistant messageselif role == "assistant":content = message.get("content", [])if isinstance(content, str):- content = [{ "type": "output_text", "text": content }]-+ content = [{"type": "output_text", "text": content}]+content = "\n".join(item.get("text", "") for item in content)- completion_messages.append({- "role": "assistant",- "content": content- })-+ completion_messages.append({"role": "assistant", "content": content})+elif msg_type == "reasoning":# Reasoning becomes part of assistant messagesummary = message.get("summary", [])reasoning_text = ""-+if isinstance(summary, list) and summary:# Extract text from summary itemsfor item in summary:@@ -189,58 +180,54 @@ def _convert_responses_items_to_completion_messages(messages: Messages) -> List[else:# Fallback to direct reasoning fieldreasoning_text = message.get("reasoning", "")-+if reasoning_text:- completion_messages.append({- "role": "assistant",- "content": reasoning_text- })-+ completion_messages.append({"role": "assistant", "content": reasoning_text})+elif msg_type == "function_call":fn_name = message.get("name")fn_args = message.get("arguments", "{}")call_id = message.get("call_id", "call_1")call_id_to_fn_name[call_id] = fn_name- openai_tool_calls = [{- "id": call_id,- "type": "function",- "function": {- "name": fn_name,- "arguments": fn_args+ openai_tool_calls = [+ {+ "id": call_id,+ "type": "function",+ "function": {"name": fn_name, "arguments": fn_args},}- }] # If the last completion message is an assistant message, extend the tool_calls+ ] # If the last completion message is an assistant message, extend the tool_callsif completion_messages and completion_messages[-1].get("role") == "assistant":if "tool_calls" not in completion_messages[-1]:completion_messages[-1]["tool_calls"] = []completion_messages[-1]["tool_calls"].extend(openai_tool_calls)else:# Create new assistant message with tool calls- completion_messages.append({- "role": "assistant",- "content": None,- "tool_calls": openai_tool_calls- })-+ completion_messages.append(+ {"role": "assistant", "content": None, "tool_calls": openai_tool_calls}+ )+elif msg_type == "function_call_output":call_id = message.get("call_id", "call_1")fn_output = message.get("output", "")fn_name = call_id_to_fn_name.get(call_id, "computer")- completion_messages.append({- "role": "function",- "name": fn_name,- "tool_call_id": call_id,- "content": str(fn_output)- })-+ completion_messages.append(+ {+ "role": "function",+ "name": fn_name,+ "tool_call_id": call_id,+ "content": str(fn_output),+ }+ )+elif msg_type == "computer_call":# Computer call becomes tool use in assistant messageaction = message.get("action", {})action_type = action.get("type")call_id = message.get("call_id", "call_1")-+tool_use_content = []-+# Basic actions (all versions)if action_type == "click":# Input:@@ -253,7 +240,7 @@ def _convert_responses_items_to_completion_messages(messages: Messages) -> List[# "y": 200# }# }-+# Output:# {# "function": {@@ -267,16 +254,22 @@ def _convert_responses_items_to_completion_messages(messages: Messages) -> List[# "type": "function"# }button = action.get("button", "left")- action_name = "right_click" if button == "right" else "middle_click" if button == "wheel" else "left_click"- tool_use_content.append({- "type": "tool_use",- "id": call_id,- "name": "computer",- "input": {- "action": action_name,- "coordinate": [action.get("x", 0), action.get("y", 0)]+ action_name = (+ "right_click"+ if button == "right"+ else "middle_click" if button == "wheel" else "left_click"+ )+ tool_use_content.append(+ {+ "type": "tool_use",+ "id": call_id,+ "name": "computer",+ "input": {+ "action": action_name,+ "coordinate": [action.get("x", 0), action.get("y", 0)],+ },}- })+ )elif action_type == "double_click":# Input:# {@@ -288,7 +281,7 @@ def _convert_responses_items_to_completion_messages(messages: Messages) -> List[# "y": 240# }# }-+# Output:# {# "function": {@@ -301,15 +294,17 @@ def _convert_responses_items_to_completion_messages(messages: Messages) -> List[# "id": "call_1",# "type": "function"# }- tool_use_content.append({- "type": "tool_use",- "id": call_id,- "name": "computer",- "input": {- "action": "double_click",- "coordinate": [action.get("x", 0), action.get("y", 0)]+ tool_use_content.append(+ {+ "type": "tool_use",+ "id": call_id,+ "name": "computer",+ "input": {+ "action": "double_click",+ "coordinate": [action.get("x", 0), action.get("y", 0)],+ },}- })+ )elif action_type == "type":# Input:# {@@ -320,7 +315,7 @@ def _convert_responses_items_to_completion_messages(messages: Messages) -> List[# "text": "Hello World"# }# }-+# Output:# {# "function": {@@ -333,15 +328,14 @@ def _convert_responses_items_to_completion_messages(messages: Messages) -> List[# "id": "call_1",# "type": "function"# }- tool_use_content.append({- "type": "tool_use",- "id": call_id,- "name": "computer",- "input": {- "action": "type",- "text": action.get("text", "")+ tool_use_content.append(+ {+ "type": "tool_use",+ "id": call_id,+ "name": "computer",+ "input": {"action": "type", "text": action.get("text", "")},}- })+ )elif action_type == "keypress":# Input:# {@@ -352,7 +346,7 @@ def _convert_responses_items_to_completion_messages(messages: Messages) -> List[# "keys": ["ctrl", "c"]# }# }-+# Output:# {# "function": {@@ -365,15 +359,14 @@ def _convert_responses_items_to_completion_messages(messages: Messages) -> List[# "id": "call_1",# "type": "function"# }- tool_use_content.append({- "type": "tool_use",- "id": call_id,- "name": "computer",- "input": {- "action": "key",- "text": "+".join(action.get("keys", []))+ tool_use_content.append(+ {+ "type": "tool_use",+ "id": call_id,+ "name": "computer",+ "input": {"action": "key", "text": "+".join(action.get("keys", []))},}- })+ )elif action_type in ["mouse_move", "move"]:# Input:# {@@ -385,7 +378,7 @@ def _convert_responses_items_to_completion_messages(messages: Messages) -> List[# "y": 250# }# }-+# Output:# {# "function": {@@ -398,15 +391,17 @@ def _convert_responses_items_to_completion_messages(messages: Messages) -> List[# "id": "call_1",# "type": "function"# }- tool_use_content.append({- "type": "tool_use",- "id": call_id,- "name": "computer",- "input": {- "action": "mouse_move",- "coordinate": [action.get("x", 0), action.get("y", 0)]+ tool_use_content.append(+ {+ "type": "tool_use",+ "id": call_id,+ "name": "computer",+ "input": {+ "action": "mouse_move",+ "coordinate": [action.get("x", 0), action.get("y", 0)],+ },}- })+ )elif action_type == "scroll":# Input:# {@@ -420,7 +415,7 @@ def _convert_responses_items_to_completion_messages(messages: Messages) -> List[# "scroll_y": -5# }# }-+# Output:# {# "function": {@@ -453,18 +448,20 @@ def _convert_responses_items_to_completion_messages(messages: Messages) -> List[else:direction = "down"amount = 3-- tool_use_content.append({- "type": "tool_use",- "id": call_id,- "name": "computer",- "input": {- "action": "scroll",- "coordinate": [action.get("x", 0), action.get("y", 0)],- "scroll_direction": direction,- "scroll_amount": amount++ tool_use_content.append(+ {+ "type": "tool_use",+ "id": call_id,+ "name": "computer",+ "input": {+ "action": "scroll",+ "coordinate": [action.get("x", 0), action.get("y", 0)],+ "scroll_direction": direction,+ "scroll_amount": amount,+ },}- })+ )elif action_type == "drag":# Input:# {@@ -478,7 +475,7 @@ def _convert_responses_items_to_completion_messages(messages: Messages) -> List[# ]# }# }-+# Output:# {# "function": {@@ -498,17 +495,19 @@ def _convert_responses_items_to_completion_messages(messages: Messages) -> List[if isinstance(path, list) and len(path) >= 2:start_coord = [path[0].get("x", 0), path[0].get("y", 0)]end_coord = [path[-1].get("x", 0), path[-1].get("y", 0)]-- tool_use_content.append({- "type": "tool_use",- "id": call_id,- "name": "computer",- "input": {- "action": "left_click_drag",- "start_coordinate": start_coord,- "end_coordinate": end_coord++ tool_use_content.append(+ {+ "type": "tool_use",+ "id": call_id,+ "name": "computer",+ "input": {+ "action": "left_click_drag",+ "start_coordinate": start_coord,+ "end_coordinate": end_coord,+ },}- })+ )elif action_type == "wait":# Input:# {@@ -518,7 +517,7 @@ def _convert_responses_items_to_completion_messages(messages: Messages) -> List[# "type": "wait"# }# }-+# Output:# {# "function": {@@ -530,14 +529,14 @@ def _convert_responses_items_to_completion_messages(messages: Messages) -> List[# "id": "call_1",# "type": "function"# }- tool_use_content.append({- "type": "tool_use",- "id": call_id,- "name": "computer",- "input": {- "action": "wait"+ tool_use_content.append(+ {+ "type": "tool_use",+ "id": call_id,+ "name": "computer",+ "input": {"action": "wait"},}- })+ )elif action_type == "screenshot":# Input:# {@@ -547,7 +546,7 @@ def _convert_responses_items_to_completion_messages(messages: Messages) -> List[# "type": "screenshot"# }# }-+# Output:# {# "function": {@@ -559,47 +558,53 @@ def _convert_responses_items_to_completion_messages(messages: Messages) -> List[# "id": "call_1",# "type": "function"# }- tool_use_content.append({- "type": "tool_use",- "id": call_id,- "name": "computer",- "input": {- "action": "screenshot"+ tool_use_content.append(+ {+ "type": "tool_use",+ "id": call_id,+ "name": "computer",+ "input": {"action": "screenshot"},}- })+ )elif action_type == "left_mouse_down":- tool_use_content.append({- "type": "tool_use",- "id": call_id,- "name": "computer",- "input": {- "action": "left_mouse_down",- "coordinate": [action.get("x", None), action.get("y", None)]+ tool_use_content.append(+ {+ "type": "tool_use",+ "id": call_id,+ "name": "computer",+ "input": {+ "action": "left_mouse_down",+ "coordinate": [action.get("x", None), action.get("y", None)],+ },}- })+ )elif action_type == "left_mouse_up":- tool_use_content.append({- "type": "tool_use",- "id": call_id,- "name": "computer",- "input": {- "action": "left_mouse_up",- "coordinate": [action.get("x", None), action.get("y", None)]+ tool_use_content.append(+ {+ "type": "tool_use",+ "id": call_id,+ "name": "computer",+ "input": {+ "action": "left_mouse_up",+ "coordinate": [action.get("x", None), action.get("y", None)],+ },}- })-+ )+# Convert tool_use_content to OpenAI tool_calls formatopenai_tool_calls = []for tool_use in tool_use_content:- openai_tool_calls.append({- "id": tool_use["id"],- "type": "function",- "function": {- "name": tool_use["name"],- "arguments": json.dumps(tool_use["input"])+ openai_tool_calls.append(+ {+ "id": tool_use["id"],+ "type": "function",+ "function": {+ "name": tool_use["name"],+ "arguments": json.dumps(tool_use["input"]),+ },}- })-+ )+# If the last completion message is an assistant message, extend the tool_callsif completion_messages and completion_messages[-1].get("role") == "assistant":if "tool_calls" not in completion_messages[-1]:@@ -607,54 +612,52 @@ def _convert_responses_items_to_completion_messages(messages: Messages) -> List[completion_messages[-1]["tool_calls"].extend(openai_tool_calls)else:# Create new assistant message with tool calls- completion_messages.append({- "role": "assistant",- "content": None,- "tool_calls": openai_tool_calls- })-+ completion_messages.append(+ {"role": "assistant", "content": None, "tool_calls": openai_tool_calls}+ )+elif msg_type == "computer_call_output":# Computer call output becomes OpenAI function resultoutput = message.get("output", {})call_id = message.get("call_id", "call_1")-+if output.get("type") == "input_image":# Screenshot result - convert to OpenAI format with image_url contentimage_url = output.get("image_url", "")- completion_messages.append({- "role": "function",- "name": "computer",- "tool_call_id": call_id,- "content": [{- "type": "image_url",- "image_url": {- "url": image_url- }- }]- })+ completion_messages.append(+ {+ "role": "function",+ "name": "computer",+ "tool_call_id": call_id,+ "content": [{"type": "image_url", "image_url": {"url": image_url}}],+ }+ )else:# Text result - convert to OpenAI format- completion_messages.append({- "role": "function",- "name": "computer",- "tool_call_id": call_id,- "content": str(output)- })-+ completion_messages.append(+ {+ "role": "function",+ "name": "computer",+ "tool_call_id": call_id,+ "content": str(output),+ }+ )+return completion_messages+def _convert_completion_to_responses_items(response: Any) -> List[Dict[str, Any]]:"""Convert liteLLM completion response to responses_items message format."""responses_items = []-- if not response or not hasattr(response, 'choices') or not response.choices:++ if not response or not hasattr(response, "choices") or not response.choices:return responses_items-+choice = response.choices[0]message = choice.message-+# Handle text content- if hasattr(message, 'content') and message.content:+ if hasattr(message, "content") and message.content:if isinstance(message.content, str):responses_items.append(make_output_text_item(message.content))elif isinstance(message.content, list):@@ -667,31 +670,36 @@ def _convert_completion_to_responses_items(response: Any) -> List[Dict[str, Any]tool_input = content_item.get("input", {})action_type = tool_input.get("action")call_id = content_item.get("id")-+# Action reference:# https://docs.anthropic.com/en/docs/agents-and-tools/tool-use/computer-use-tool#available-actions-+try:# Basic actions (all versions)if action_type == "screenshot":responses_items.append(make_screenshot_item(call_id=call_id))elif action_type in ["click", "left_click"]:coordinate = tool_input.get("coordinate", [0, 0])- responses_items.append(make_click_item(- x=coordinate[0] if len(coordinate) > 0 else 0,- y=coordinate[1] if len(coordinate) > 1 else 0,- call_id=call_id- ))+ responses_items.append(+ make_click_item(+ x=coordinate[0] if len(coordinate) > 0 else 0,+ y=coordinate[1] if len(coordinate) > 1 else 0,+ call_id=call_id,+ )+ )elif action_type in ["type", "type_text"]:- responses_items.append(make_type_item(- text=tool_input.get("text", ""),- call_id=call_id- ))+ responses_items.append(+ make_type_item(text=tool_input.get("text", ""), call_id=call_id)+ )elif action_type in ["key", "keypress", "hotkey"]:- responses_items.append(make_keypress_item(- keys=tool_input.get("text", "").replace("+", "-").split("-"),- call_id=call_id- ))+ responses_items.append(+ make_keypress_item(+ keys=tool_input.get("text", "")+ .replace("+", "-")+ .split("-"),+ call_id=call_id,+ )+ )elif action_type in ["mouse_move", "move_cursor", "move"]:# Mouse move - create a custom action itemcoordinate = tool_input.get("coordinate", [0, 0])@@ -699,64 +707,88 @@ def _convert_completion_to_responses_items(response: Any) -> List[Dict[str, Any]make_move_item(x=coordinate[0] if len(coordinate) > 0 else 0,y=coordinate[1] if len(coordinate) > 1 else 0,- call_id=call_id+ call_id=call_id,))-+# Enhanced actions (computer_20250124) Available in Claude 4 and Claude Sonnet 3.7elif action_type == "scroll":coordinate = tool_input.get("coordinate", [0, 0])scroll_amount = tool_input.get("scroll_amount", 3)- scroll_x = scroll_amount if tool_input.get("scroll_direction", "down") == "right" else \- -scroll_amount if tool_input.get("scroll_direction", "down") == "left" else 0- scroll_y = scroll_amount if tool_input.get("scroll_direction", "down") == "down" else \- -scroll_amount if tool_input.get("scroll_direction", "down") == "up" else 0- responses_items.append(make_scroll_item(- x=coordinate[0] if len(coordinate) > 0 else 0,- y=coordinate[1] if len(coordinate) > 1 else 0,- scroll_x=scroll_x,- scroll_y=scroll_y,- call_id=call_id- ))+ scroll_x = (+ scroll_amount+ if tool_input.get("scroll_direction", "down") == "right"+ else (+ -scroll_amount+ if tool_input.get("scroll_direction", "down") == "left"+ else 0+ )+ )+ scroll_y = (+ scroll_amount+ if tool_input.get("scroll_direction", "down") == "down"+ else (+ -scroll_amount+ if tool_input.get("scroll_direction", "down") == "up"+ else 0+ )+ )+ responses_items.append(+ make_scroll_item(+ x=coordinate[0] if len(coordinate) > 0 else 0,+ y=coordinate[1] if len(coordinate) > 1 else 0,+ scroll_x=scroll_x,+ scroll_y=scroll_y,+ call_id=call_id,+ )+ )elif action_type in ["left_click_drag", "drag"]:start_coord = tool_input.get("start_coordinate", [0, 0])end_coord = tool_input.get("end_coordinate", [0, 0])- responses_items.append(make_drag_item(- path=[- {- "x": start_coord[0] if len(start_coord) > 0 else 0,- "y": start_coord[1] if len(start_coord) > 1 else 0- },- {- "x": end_coord[0] if len(end_coord) > 0 else 0,- "y": end_coord[1] if len(end_coord) > 1 else 0- }- ],- call_id=call_id- ))+ responses_items.append(+ make_drag_item(+ path=[+ {+ "x": start_coord[0] if len(start_coord) > 0 else 0,+ "y": start_coord[1] if len(start_coord) > 1 else 0,+ },+ {+ "x": end_coord[0] if len(end_coord) > 0 else 0,+ "y": end_coord[1] if len(end_coord) > 1 else 0,+ },+ ],+ call_id=call_id,+ )+ )elif action_type == "right_click":coordinate = tool_input.get("coordinate", [0, 0])- responses_items.append(make_click_item(- x=coordinate[0] if len(coordinate) > 0 else 0,- y=coordinate[1] if len(coordinate) > 1 else 0,- button="right",- call_id=call_id- ))+ responses_items.append(+ make_click_item(+ x=coordinate[0] if len(coordinate) > 0 else 0,+ y=coordinate[1] if len(coordinate) > 1 else 0,+ button="right",+ call_id=call_id,+ )+ )elif action_type == "middle_click":coordinate = tool_input.get("coordinate", [0, 0])- responses_items.append(make_click_item(- x=coordinate[0] if len(coordinate) > 0 else 0,- y=coordinate[1] if len(coordinate) > 1 else 0,- button="wheel",- call_id=call_id- ))+ responses_items.append(+ make_click_item(+ x=coordinate[0] if len(coordinate) > 0 else 0,+ y=coordinate[1] if len(coordinate) > 1 else 0,+ button="wheel",+ call_id=call_id,+ )+ )elif action_type == "double_click":coordinate = tool_input.get("coordinate", [0, 0])- responses_items.append(make_double_click_item(- x=coordinate[0] if len(coordinate) > 0 else 0,- y=coordinate[1] if len(coordinate) > 1 else 0,- call_id=call_id- ))+ responses_items.append(+ make_double_click_item(+ x=coordinate[0] if len(coordinate) > 0 else 0,+ y=coordinate[1] if len(coordinate) > 1 else 0,+ call_id=call_id,+ )+ )elif action_type == "triple_click":# coordinate = tool_input.get("coordinate", [0, 0])# responses_items.append({@@ -782,11 +814,13 @@ def _convert_completion_to_responses_items(response: Any) -> List[Dict[str, Any]# }# })coordinate = tool_input.get("coordinate", [None, None])- responses_items.append(make_left_mouse_down_item(- x=coordinate[0] if len(coordinate) > 0 else None,- y=coordinate[1] if len(coordinate) > 1 else None,- call_id=call_id- ))+ responses_items.append(+ make_left_mouse_down_item(+ x=coordinate[0] if len(coordinate) > 0 else None,+ y=coordinate[1] if len(coordinate) > 1 else None,+ call_id=call_id,+ )+ )elif action_type == "left_mouse_up":# coordinate = tool_input.get("coordinate", [0, 0])# responses_items.append({@@ -800,11 +834,13 @@ def _convert_completion_to_responses_items(response: Any) -> List[Dict[str, Any]# }# })coordinate = tool_input.get("coordinate", [None, None])- responses_items.append(make_left_mouse_up_item(- x=coordinate[0] if len(coordinate) > 0 else None,- y=coordinate[1] if len(coordinate) > 1 else None,- call_id=call_id- ))+ responses_items.append(+ make_left_mouse_up_item(+ x=coordinate[0] if len(coordinate) > 0 else None,+ y=coordinate[1] if len(coordinate) > 1 else None,+ call_id=call_id,+ )+ )elif action_type == "hold_key":# responses_items.append({# "type": "computer_call",@@ -816,21 +852,21 @@ def _convert_completion_to_responses_items(response: Any) -> List[Dict[str, Any]# })raise NotImplementedError("hold_key")elif action_type == "wait":- responses_items.append(make_wait_item(- call_id=call_id- ))+ responses_items.append(make_wait_item(call_id=call_id))else:raise ValueError(f"Unknown action type: {action_type}")except Exception as e:- responses_items.extend(make_failed_tool_call_items(- tool_name="computer",- tool_kwargs=tool_input,- error_message=repr(e),- call_id=call_id- ))-+ responses_items.extend(+ make_failed_tool_call_items(+ tool_name="computer",+ tool_kwargs=tool_input,+ error_message=repr(e),+ call_id=call_id,+ )+ )+# Handle tool calls (alternative format)- if hasattr(message, 'tool_calls') and message.tool_calls:+ if hasattr(message, "tool_calls") and message.tool_calls:for tool_call in message.tool_calls:if tool_call.function.name == "computer":try:@@ -852,7 +888,7 @@ def _convert_completion_to_responses_items(response: Any) -> List[Dict[str, Any]# "id": "call_1",# "type": "function"# }-+# Output:# {# "type": "computer_call",@@ -861,9 +897,7 @@ def _convert_completion_to_responses_items(response: Any) -> List[Dict[str, Any]# "type": "screenshot"# }# }- responses_items.append(make_screenshot_item(- call_id=call_id- ))+ responses_items.append(make_screenshot_item(call_id=call_id))elif action_type in ["click", "left_click"]:# Input:# {@@ -877,7 +911,7 @@ def _convert_completion_to_responses_items(response: Any) -> List[Dict[str, Any]# "id": "call_1",# "type": "function"# }-+# Output:# {# "type": "computer_call",@@ -889,11 +923,13 @@ def _convert_completion_to_responses_items(response: Any) -> List[Dict[str, Any]# }# }coordinate = args.get("coordinate", [0, 0])- responses_items.append(make_click_item(- x=coordinate[0] if len(coordinate) > 0 else 0,- y=coordinate[1] if len(coordinate) > 1 else 0,- call_id=call_id- ))+ responses_items.append(+ make_click_item(+ x=coordinate[0] if len(coordinate) > 0 else 0,+ y=coordinate[1] if len(coordinate) > 1 else 0,+ call_id=call_id,+ )+ )elif action_type in ["type", "type_text"]:# Input:# {@@ -907,7 +943,7 @@ def _convert_completion_to_responses_items(response: Any) -> List[Dict[str, Any]# "id": "call_1",# "type": "function"# }-+# Output:# {# "type": "computer_call",@@ -917,10 +953,9 @@ def _convert_completion_to_responses_items(response: Any) -> List[Dict[str, Any]# "text": "Hello World"# }# }- responses_items.append(make_type_item(- text=args.get("text", ""),- call_id=call_id- ))+ responses_items.append(+ make_type_item(text=args.get("text", ""), call_id=call_id)+ )elif action_type in ["key", "keypress", "hotkey"]:# Input:# {@@ -934,7 +969,7 @@ def _convert_completion_to_responses_items(response: Any) -> List[Dict[str, Any]# "id": "call_1",# "type": "function"# }-+# Output:# {# "type": "computer_call",@@ -944,10 +979,12 @@ def _convert_completion_to_responses_items(response: Any) -> List[Dict[str, Any]# "keys": ["ctrl", "c"]# }# }- responses_items.append(make_keypress_item(- keys=args.get("text", "").replace("+", "-").split("-"),- call_id=call_id- ))+ responses_items.append(+ make_keypress_item(+ keys=args.get("text", "").replace("+", "-").split("-"),+ call_id=call_id,+ )+ )elif action_type in ["mouse_move", "move_cursor", "move"]:# Input:# {@@ -961,7 +998,7 @@ def _convert_completion_to_responses_items(response: Any) -> List[Dict[str, Any]# "id": "call_1",# "type": "function"# }-+# Output:# {# "type": "computer_call",@@ -973,12 +1010,14 @@ def _convert_completion_to_responses_items(response: Any) -> List[Dict[str, Any]# }# }coordinate = args.get("coordinate", [0, 0])- responses_items.append(make_move_item(- x=coordinate[0] if len(coordinate) > 0 else 0,- y=coordinate[1] if len(coordinate) > 1 else 0,- call_id=call_id- ))-+ responses_items.append(+ make_move_item(+ x=coordinate[0] if len(coordinate) > 0 else 0,+ y=coordinate[1] if len(coordinate) > 1 else 0,+ call_id=call_id,+ )+ )+# Enhanced actions (computer_20250124) Available in Claude 4 and Claude Sonnet 3.7elif action_type == "scroll":# Input:@@ -995,7 +1034,7 @@ def _convert_completion_to_responses_items(response: Any) -> List[Dict[str, Any]# "id": "call_1",# "type": "function"# }-+# Output:# {# "type": "computer_call",@@ -1011,17 +1050,25 @@ def _convert_completion_to_responses_items(response: Any) -> List[Dict[str, Any]coordinate = args.get("coordinate", [0, 0])direction = args.get("scroll_direction", "down")amount = args.get("scroll_amount", 3)- scroll_x = amount if direction == "left" else \- -amount if direction == "right" else 0- scroll_y = amount if direction == "up" else \- -amount if direction == "down" else 0- responses_items.append(make_scroll_item(- x=coordinate[0] if len(coordinate) > 0 else 0,- y=coordinate[1] if len(coordinate) > 1 else 0,- scroll_x=scroll_x,- scroll_y=scroll_y,- call_id=call_id- ))+ scroll_x = (+ amount+ if direction == "left"+ else -amount if direction == "right" else 0+ )+ scroll_y = (+ amount+ if direction == "up"+ else -amount if direction == "down" else 0+ )+ responses_items.append(+ make_scroll_item(+ x=coordinate[0] if len(coordinate) > 0 else 0,+ y=coordinate[1] if len(coordinate) > 1 else 0,+ scroll_x=scroll_x,+ scroll_y=scroll_y,+ call_id=call_id,+ )+ )elif action_type in ["left_click_drag", "drag"]:# Input:# {@@ -1036,7 +1083,7 @@ def _convert_completion_to_responses_items(response: Any) -> List[Dict[str, Any]# "id": "call_1",# "type": "function"# }-+# Output:# {# "type": "computer_call",@@ -1051,19 +1098,21 @@ def _convert_completion_to_responses_items(response: Any) -> List[Dict[str, Any]# }start_coord = args.get("start_coordinate", [0, 0])end_coord = args.get("end_coordinate", [0, 0])- responses_items.append(make_drag_item(- path=[- {- "x": start_coord[0] if len(start_coord) > 0 else 0,- "y": start_coord[1] if len(start_coord) > 1 else 0- },- {- "x": end_coord[0] if len(end_coord) > 0 else 0,- "y": end_coord[1] if len(end_coord) > 1 else 0- }- ],- call_id=call_id- ))+ responses_items.append(+ make_drag_item(+ path=[+ {+ "x": start_coord[0] if len(start_coord) > 0 else 0,+ "y": start_coord[1] if len(start_coord) > 1 else 0,+ },+ {+ "x": end_coord[0] if len(end_coord) > 0 else 0,+ "y": end_coord[1] if len(end_coord) > 1 else 0,+ },+ ],+ call_id=call_id,+ )+ )elif action_type == "right_click":# Input:# {@@ -1077,7 +1126,7 @@ def _convert_completion_to_responses_items(response: Any) -> List[Dict[str, Any]# "id": "call_1",# "type": "function"# }-+# Output:# {# "type": "computer_call",@@ -1090,12 +1139,14 @@ def _convert_completion_to_responses_items(response: Any) -> List[Dict[str, Any]# }# }coordinate = args.get("coordinate", [0, 0])- responses_items.append(make_click_item(- x=coordinate[0] if len(coordinate) > 0 else 0,- y=coordinate[1] if len(coordinate) > 1 else 0,- button="right",- call_id=call_id- ))+ responses_items.append(+ make_click_item(+ x=coordinate[0] if len(coordinate) > 0 else 0,+ y=coordinate[1] if len(coordinate) > 1 else 0,+ button="right",+ call_id=call_id,+ )+ )elif action_type == "middle_click":# Input:# {@@ -1109,7 +1160,7 @@ def _convert_completion_to_responses_items(response: Any) -> List[Dict[str, Any]# "id": "call_1",# "type": "function"# }-+# Output:# {# "type": "computer_call",@@ -1122,12 +1173,14 @@ def _convert_completion_to_responses_items(response: Any) -> List[Dict[str, Any]# }# }coordinate = args.get("coordinate", [0, 0])- responses_items.append(make_click_item(- x=coordinate[0] if len(coordinate) > 0 else 0,- y=coordinate[1] if len(coordinate) > 1 else 0,- button="wheel",- call_id=call_id- ))+ responses_items.append(+ make_click_item(+ x=coordinate[0] if len(coordinate) > 0 else 0,+ y=coordinate[1] if len(coordinate) > 1 else 0,+ button="wheel",+ call_id=call_id,+ )+ )elif action_type == "double_click":# Input:# {@@ -1141,7 +1194,7 @@ def _convert_completion_to_responses_items(response: Any) -> List[Dict[str, Any]# "id": "call_1",# "type": "function"# }-+# Output:# {# "type": "computer_call",@@ -1153,11 +1206,13 @@ def _convert_completion_to_responses_items(response: Any) -> List[Dict[str, Any]# }# }coordinate = args.get("coordinate", [0, 0])- responses_items.append(make_double_click_item(- x=coordinate[0] if len(coordinate) > 0 else 0,- y=coordinate[1] if len(coordinate) > 1 else 0,- call_id=call_id- ))+ responses_items.append(+ make_double_click_item(+ x=coordinate[0] if len(coordinate) > 0 else 0,+ y=coordinate[1] if len(coordinate) > 1 else 0,+ call_id=call_id,+ )+ )elif action_type == "triple_click":# Input:# {@@ -1171,7 +1226,7 @@ def _convert_completion_to_responses_items(response: Any) -> List[Dict[str, Any]# "id": "call_1",# "type": "function"# }-+# Output:# {# "type": "computer_call",@@ -1196,7 +1251,7 @@ def _convert_completion_to_responses_items(response: Any) -> List[Dict[str, Any]# "id": "call_1",# "type": "function"# }-+# Output:# {# "type": "computer_call",@@ -1209,11 +1264,13 @@ def _convert_completion_to_responses_items(response: Any) -> List[Dict[str, Any]# }# }coordinate = args.get("coordinate", [None, None])- responses_items.append(make_left_mouse_down_item(- x=coordinate[0] if len(coordinate) > 0 else None,- y=coordinate[1] if len(coordinate) > 1 else None,- call_id=call_id- ))+ responses_items.append(+ make_left_mouse_down_item(+ x=coordinate[0] if len(coordinate) > 0 else None,+ y=coordinate[1] if len(coordinate) > 1 else None,+ call_id=call_id,+ )+ )elif action_type == "left_mouse_up":# Input:# {@@ -1227,7 +1284,7 @@ def _convert_completion_to_responses_items(response: Any) -> List[Dict[str, Any]# "id": "call_1",# "type": "function"# }-+# Output:# {# "type": "computer_call",@@ -1240,11 +1297,13 @@ def _convert_completion_to_responses_items(response: Any) -> List[Dict[str, Any]# }# }coordinate = args.get("coordinate", [None, None])- responses_items.append(make_left_mouse_up_item(- x=coordinate[0] if len(coordinate) > 0 else None,- y=coordinate[1] if len(coordinate) > 1 else None,- call_id=call_id- ))+ responses_items.append(+ make_left_mouse_up_item(+ x=coordinate[0] if len(coordinate) > 0 else None,+ y=coordinate[1] if len(coordinate) > 1 else None,+ call_id=call_id,+ )+ )elif action_type == "hold_key":# Input:# {@@ -1258,7 +1317,7 @@ def _convert_completion_to_responses_items(response: Any) -> List[Dict[str, Any]# "id": "call_1",# "type": "function"# }-+# Output:# {# "type": "computer_call",@@ -1281,7 +1340,7 @@ def _convert_completion_to_responses_items(response: Any) -> List[Dict[str, Any]# "id": "call_1",# "type": "function"# }-+# Output:# {# "type": "computer_call",@@ -1290,74 +1349,77 @@ def _convert_completion_to_responses_items(response: Any) -> List[Dict[str, Any]# "type": "wait"# }# }- responses_items.append(make_wait_item(- call_id=call_id- ))+ responses_items.append(make_wait_item(call_id=call_id))except Exception as e:- responses_items.extend(make_failed_tool_call_items(- tool_name="computer",- tool_kwargs=args,- error_message=repr(e),- call_id=call_id- ))+ responses_items.extend(+ make_failed_tool_call_items(+ tool_name="computer",+ tool_kwargs=args,+ error_message=repr(e),+ call_id=call_id,+ )+ )except json.JSONDecodeError:print("Failed to decode tool call arguments")# Skip malformed tool callscontinue-+return responses_items+def _add_cache_control(completion_messages: List[Dict[str, Any]]) -> List[Dict[str, Any]]:"""Add cache control to completion messages"""num_writes = 0for message in completion_messages:- message["cache_control"] = { "type": "ephemeral" }+ message["cache_control"] = {"type": "ephemeral"}num_writes += 1# Cache control has a maximum of 4 blocksif num_writes >= 4:break-+return completion_messages+def _combine_completion_messages(completion_messages: List[Dict[str, Any]]) -> List[Dict[str, Any]]:"""Combine completion messages with the same role"""if not completion_messages:return completion_messages-+combined_messages = []-+for message in completion_messages:# If this is the first message or role is different from last, add as new messageif not combined_messages or combined_messages[-1]["role"] != message["role"]:# Ensure content is a list format and normalize text contentnew_message = message.copy()new_message["content"] = _normalize_content(message.get("content", ""))-+# Copy tool_calls if presentif "tool_calls" in message:new_message["tool_calls"] = message["tool_calls"].copy()-+combined_messages.append(new_message)else:# Same role as previous message, combine themlast_message = combined_messages[-1]-+# Combine contentcurrent_content = _normalize_content(message.get("content", ""))last_message["content"].extend(current_content)-+# Combine tool_calls if presentif "tool_calls" in message:if "tool_calls" not in last_message:last_message["tool_calls"] = []last_message["tool_calls"].extend(message["tool_calls"])-+# Post-process to merge consecutive text blocksfor message in combined_messages:message["content"] = _merge_consecutive_text(message["content"])-+return combined_messages+def _normalize_content(content) -> List[Dict[str, Any]]:"""Normalize content to list format"""if isinstance(content, str):@@ -1370,28 +1432,28 @@ def _normalize_content(content) -> List[Dict[str, Any]]:else:return []+def _merge_consecutive_text(content_list: List[Dict[str, Any]]) -> List[Dict[str, Any]]:"""Merge consecutive text blocks with newlines"""if not content_list:return content_list-+merged = []-+for item in content_list:- if (item.get("type") == "text" and- merged and- merged[-1].get("type") == "text"):+ if item.get("type") == "text" and merged and merged[-1].get("type") == "text":# Merge with previous text blockmerged[-1]["text"] += "\n" + item["text"]else:merged.append(item.copy())-+return merged+@register_agent(models=r".*claude-.*")class AnthropicHostedToolsConfig(AsyncAgentConfig):"""Anthropic hosted tools agent configuration implementing AsyncAgentConfig protocol."""-+async def predict_step(self,messages: Messages,@@ -1405,21 +1467,21 @@ class AnthropicHostedToolsConfig(AsyncAgentConfig):_on_api_end=None,_on_usage=None,_on_screenshot=None,- **kwargs+ **kwargs,) -> Dict[str, Any]:"""Anthropic hosted tools agent loop using liteLLM acompletion.-+Supports Anthropic's computer use models with hosted tools."""tools = tools or []-+# Get tool configuration for this modeltool_config = _get_tool_config_for_model(model)-+# Prepare tools for Anthropic APIanthropic_tools = await _prepare_tools_for_anthropic(tools, model)-+# Convert responses_items messages to completion formatcompletion_messages = _convert_responses_items_to_completion_messages(messages)if use_prompt_caching:@@ -1427,7 +1489,7 @@ class AnthropicHostedToolsConfig(AsyncAgentConfig):completion_messages = _combine_completion_messages(completion_messages)# Then add cache control, anthropic requires explicit "cache_control" dictscompletion_messages = _add_cache_control(completion_messages)-+# Prepare API call kwargsapi_kwargs = {"model": model,@@ -1435,80 +1497,74 @@ class AnthropicHostedToolsConfig(AsyncAgentConfig):"tools": anthropic_tools if anthropic_tools else None,"stream": stream,"num_retries": max_retries,- **kwargs+ **kwargs,}-+# Add beta header for computer useif anthropic_tools:- api_kwargs["headers"] = {- "anthropic-beta": tool_config["beta_flag"]- }-+ api_kwargs["headers"] = {"anthropic-beta": tool_config["beta_flag"]}+# Call API start hookif _on_api_start:await _on_api_start(api_kwargs)-+# Use liteLLM acompletionresponse = await litellm.acompletion(**api_kwargs)-+# Call API end hookif _on_api_end:await _on_api_end(api_kwargs, response)-+# Convert response to responses_items formatresponses_items = _convert_completion_to_responses_items(response)# Extract usage information- responses_usage = {- **LiteLLMCompletionResponsesConfig._transform_chat_completion_usage_to_responses_usage(response.usage).model_dump(),+ responses_usage = {+ **LiteLLMCompletionResponsesConfig._transform_chat_completion_usage_to_responses_usage(+ response.usage+ ).model_dump(),"response_cost": response._hidden_params.get("response_cost", 0.0),}if _on_usage:await _on_usage(responses_usage)# Return in AsyncAgentConfig format- return {- "output": responses_items,- "usage": responses_usage- }-+ return {"output": responses_items, "usage": responses_usage}+async def predict_click(- self,- model: str,- image_b64: str,- instruction: str,- **kwargs+ self, model: str, image_b64: str, instruction: str, **kwargs) -> Optional[Tuple[int, int]]:"""Predict click coordinates based on image and instruction.-+Uses Anthropic's computer use models with a custom prompt that instructsthe agent to only output clicks.-+Args:model: Model name to useimage_b64: Base64 encoded imageinstruction: Instruction for where to click-+Returns:Tuple of (x, y) coordinates or None if prediction fails"""# Get image dimensions from base64 datatry:import base64- from PIL import Imagefrom io import BytesIO-++ from PIL import Image+image_data = base64.b64decode(image_b64)image = Image.open(BytesIO(image_data))display_width, display_height = image.sizeexcept Exception:# Fallback to default dimensions if image parsing failsdisplay_width, display_height = 1024, 768-+# Get tool configuration for this modeltool_config = _get_tool_config_for_model(model)-+# Prepare computer tool for Anthropic formatcomputer_tool = {"type": tool_config["tool_version"],@@ -1521,7 +1577,7 @@ class AnthropicHostedToolsConfig(AsyncAgentConfig):},},}-+# Construct messages in OpenAI chat completion format for liteLLMmessages = [{@@ -1540,18 +1596,16 @@ class AnthropicHostedToolsConfig(AsyncAgentConfig):7. Be decisive and action-oriented. Complete the requested task fully.Remember: You are expected to complete tasks autonomously. The user trusts you to do what they asked.-Task: Click {instruction}. Output ONLY a click action on the target element."""+Task: Click {instruction}. Output ONLY a click action on the target element.""",},{"type": "image_url",- "image_url": {- "url": f"data:image/png;base64,{image_b64}"- }- }- ]+ "image_url": {"url": f"data:image/png;base64,{image_b64}"},+ },+ ],}]-+# Prepare API call kwargsapi_kwargs = {"model": model,@@ -1559,31 +1613,31 @@ Task: Click {instruction}. Output ONLY a click action on the target element.""""tools": [computer_tool],"stream": False,"max_tokens": 100, # Keep response short for click prediction- "headers": {- "anthropic-beta": tool_config["beta_flag"]- }+ "headers": {"anthropic-beta": tool_config["beta_flag"]},}-+# Use liteLLM acompletionresponse = await litellm.acompletion(**api_kwargs)-+# Convert response to responses_items format to extract click coordinatesresponses_items = _convert_completion_to_responses_items(response)-+# Look for computer_call with click actionfor item in responses_items:- if (isinstance(item, dict) and- item.get("type") == "computer_call" and- isinstance(item.get("action"), dict)):-+ if (+ isinstance(item, dict)+ and item.get("type") == "computer_call"+ and isinstance(item.get("action"), dict)+ ):+action = item["action"]if action.get("x") and action.get("y"):x = action.get("x")y = action.get("y")return (int(x), int(y))-+return None-+def get_capabilities(self) -> List[AgentCapability]:"""Return the capabilities supported by this agent."""return ["click", "step"]diff --git a/libs/python/agent/agent/loops/base.py b/libs/python/agent/agent/loops/base.pyindex 887605b198..b764fb6f62 100644--- a/libs/python/agent/agent/loops/base.py+++ b/libs/python/agent/agent/loops/base.py@@ -2,13 +2,15 @@Base protocol for async agent configurations"""-from typing import Protocol, List, Dict, Any, Optional, Tuple, Unionfrom abc import abstractmethod+from typing import Any, Dict, List, Optional, Protocol, Tuple, Union+from ..types import AgentCapability+class AsyncAgentConfig(Protocol):"""Protocol defining the interface for async agent configurations."""-+@abstractmethodasync def predict_step(self,@@ -22,11 +24,11 @@ class AsyncAgentConfig(Protocol):_on_api_end=None,_on_usage=None,_on_screenshot=None,- **kwargs+ **kwargs,) -> Dict[str, Any]:"""Predict the next step based on input items.-+Args:messages: Input items following Responses format (message, function_call, computer_call)model: Model name to use@@ -39,37 +41,34 @@ class AsyncAgentConfig(Protocol):_on_usage: Callback for usage tracking_on_screenshot: Callback for screenshot events**kwargs: Additional arguments-+Returns:Dictionary with "output" (output items) and "usage" array"""...-+@abstractmethodasync def predict_click(- self,- model: str,- image_b64: str,- instruction: str+ self, model: str, image_b64: str, instruction: str) -> Optional[Tuple[int, int]]:"""Predict click coordinates based on image and instruction.-+Args:model: Model name to useimage_b64: Base64 encoded imageinstruction: Instruction for where to click-+Returns:None or tuple with (x, y) coordinates"""...-+@abstractmethoddef get_capabilities(self) -> List[AgentCapability]:"""Get list of capabilities supported by this agent config.-+Returns:List of capability strings (e.g., ["step", "click"])"""diff --git a/libs/python/agent/agent/loops/composed_grounded.py b/libs/python/agent/agent/loops/composed_grounded.pyindex 8d8a150101..5e187e8321 100644--- a/libs/python/agent/agent/loops/composed_grounded.py+++ b/libs/python/agent/agent/loops/composed_grounded.py@@ -3,122 +3,117 @@ Composed-grounded agent loop implementation that combines grounding and thinkingUses a two-stage approach: grounding model for element detection, thinking model for reasoning."""-import uuidimport asyncio-import jsonimport base64-from typing import Dict, List, Any, Optional, Tuple+import json+import uuidfrom io import BytesIO-from PIL import Image+from typing import Any, Dict, List, Optional, Tuple+import litellm+from PIL import Image+from ..agent import find_agent_configfrom ..decorators import register_agent-from ..types import Messages, AgentResponse, Tools, AgentCapabilityfrom ..loops.base import AsyncAgentConfigfrom ..responses import (- convert_computer_calls_xy2desc,- convert_responses_items_to_completion_messages,convert_completion_messages_to_responses_items,convert_computer_calls_desc2xy,- get_all_element_descriptions+ convert_computer_calls_xy2desc,+ convert_responses_items_to_completion_messages,+ get_all_element_descriptions,)-from ..agent import find_agent_config+from ..types import AgentCapability, AgentResponse, Messages, ToolsGROUNDED_COMPUTER_TOOL_SCHEMA = {- "type": "function",- "function": {- "name": "computer",- "description": "Control a computer by taking screenshots and interacting with UI elements. This tool uses element descriptions to locate and interact with UI elements on the screen (e.g., 'red submit button', 'search text field', 'hamburger menu icon', 'close button in top right corner').",- "parameters": {- "type": "object",- "properties": {- "action": {- "type": "string",- "enum": [- "screenshot",- "click",- "double_click",- "drag",- "type",- "keypress",- "scroll",- "move",- "wait",- "get_current_url",- "get_dimensions",- "get_environment"- ],- "description": "The action to perform (required for all actions)"- },- "element_description": {- "type": "string",- "description": "Description of the element to interact with (required for click, double_click, move, scroll actions)"- },- "start_element_description": {- "type": "string",- "description": "Description of the element to start dragging from (required for drag action)"- },- "end_element_description": {- "type": "string",- "description": "Description of the element to drag to (required for drag action)"- },- "text": {- "type": "string",- "description": "The text to type (required for type action)"- },- "keys": {- "type": "array",- "items": {- "type": "string"+ "type": "function",+ "function": {+ "name": "computer",+ "description": "Control a computer by taking screenshots and interacting with UI elements. This tool uses element descriptions to locate and interact with UI elements on the screen (e.g., 'red submit button', 'search text field', 'hamburger menu icon', 'close button in top right corner').",+ "parameters": {+ "type": "object",+ "properties": {+ "action": {+ "type": "string",+ "enum": [+ "screenshot",+ "click",+ "double_click",+ "drag",+ "type",+ "keypress",+ "scroll",+ "move",+ "wait",+ "get_current_url",+ "get_dimensions",+ "get_environment",+ ],+ "description": "The action to perform (required for all actions)",+ },+ "element_description": {+ "type": "string",+ "description": "Description of the element to interact with (required for click, double_click, move, scroll actions)",+ },+ "start_element_description": {+ "type": "string",+ "description": "Description of the element to start dragging from (required for drag action)",+ },+ "end_element_description": {+ "type": "string",+ "description": "Description of the element to drag to (required for drag action)",+ },+ "text": {+ "type": "string",+ "description": "The text to type (required for type action)",+ },+ "keys": {+ "type": "array",+ "items": {"type": "string"},+ "description": "Key(s) to press (required for keypress action)",+ },+ "button": {+ "type": "string",+ "enum": ["left", "right", "wheel", "back", "forward"],+ "description": "The mouse button to use for click action (required for click and double_click action)",+ },+ "scroll_x": {+ "type": "integer",+ "description": "Horizontal scroll amount for scroll action (required for scroll action)",+ },+ "scroll_y": {+ "type": "integer",+ "description": "Vertical scroll amount for scroll action (required for scroll action)",+ },},- "description": "Key(s) to press (required for keypress action)"- },- "button": {- "type": "string",- "enum": [- "left",- "right",- "wheel",- "back",- "forward"- ],- "description": "The mouse button to use for click action (required for click and double_click action)",- },- "scroll_x": {- "type": "integer",- "description": "Horizontal scroll amount for scroll action (required for scroll action)",+ "required": ["action"],},- "scroll_y": {- "type": "integer",- "description": "Vertical scroll amount for scroll action (required for scroll action)",- },- },- "required": [- "action"- ]- }- }+ },}+def _prepare_tools_for_grounded(tool_schemas: List[Dict[str, Any]]) -> List[Dict[str, Any]]:"""Prepare tools for grounded API format"""grounded_tools = []-+for schema in tool_schemas:if schema["type"] == "computer":grounded_tools.append(GROUNDED_COMPUTER_TOOL_SCHEMA)else:grounded_tools.append(schema)-+return grounded_tools+def get_last_computer_call_image(messages: List[Dict[str, Any]]) -> Optional[str]:"""Get the last computer call output image from messages."""for message in reversed(messages):- if (isinstance(message, dict) and- message.get("type") == "computer_call_output" and- isinstance(message.get("output"), dict) and- message["output"].get("type") == "input_image"):+ if (+ isinstance(message, dict)+ and message.get("type") == "computer_call_output"+ and isinstance(message.get("output"), dict)+ and message["output"].get("type") == "input_image"+ ):image_url = message["output"].get("image_url", "")if image_url.startswith("data:image/png;base64,"):return image_url.split(",", 1)[1]@@ -129,14 +124,14 @@ def get_last_computer_call_image(messages: List[Dict[str, Any]]) -> Optional[strclass ComposedGroundedConfig(AsyncAgentConfig):"""Composed-grounded agent configuration that uses both grounding and thinking models.-+The model parameter should be in format: "grounding_model+thinking_model"e.g., "huggingface-local/HelloKKMe/GTA1-7B+gemini/gemini-1.5-pro""""-+def __init__(self):self.desc2xy: Dict[str, Tuple[float, float]] = {}-+async def predict_step(self,messages: List[Dict[str, Any]],@@ -150,11 +145,11 @@ class ComposedGroundedConfig(AsyncAgentConfig):_on_api_end=None,_on_usage=None,_on_screenshot=None,- **kwargs+ **kwargs,) -> Dict[str, Any]:"""Composed-grounded predict step implementation.-+Process:0. Store last computer call image, if none then take a screenshot1. Convert computer calls from xy to descriptions@@ -167,18 +162,20 @@ class ComposedGroundedConfig(AsyncAgentConfig):"""# Parse the composed modelif "+" not in model:- raise ValueError(f"Composed model must be in format 'grounding_model+thinking_model', got: {model}")+ raise ValueError(+ f"Composed model must be in format 'grounding_model+thinking_model', got: {model}"+ )grounding_model, thinking_model = model.split("+", 1)-+pre_output_items = []-+# Step 0: Store last computer call image, if none then take a screenshotlast_image_b64 = get_last_computer_call_image(messages)if last_image_b64 is None:# Take a screenshot- screenshot_b64 = await computer_handler.screenshot() # type: ignore+ screenshot_b64 = await computer_handler.screenshot() # type: ignoreif screenshot_b64:-+call_id = uuid.uuid4().hexpre_output_items += [{@@ -187,45 +184,42 @@ class ComposedGroundedConfig(AsyncAgentConfig):"content": [{"type": "output_text",- "text": "Taking a screenshot to see the current computer screen."+ "text": "Taking a screenshot to see the current computer screen.",}- ]+ ],},{- "action": {- "type": "screenshot"- },+ "action": {"type": "screenshot"},"call_id": call_id,"status": "completed",- "type": "computer_call"+ "type": "computer_call",},{"type": "computer_call_output","call_id": call_id,"output": {"type": "input_image",- "image_url": f"data:image/png;base64,{screenshot_b64}"- }+ "image_url": f"data:image/png;base64,{screenshot_b64}",+ },},]last_image_b64 = screenshot_b64-+# Call screenshot callback if providedif _on_screenshot:await _on_screenshot(screenshot_b64)-- tool_schemas = _prepare_tools_for_grounded(tools) # type: ignore++ tool_schemas = _prepare_tools_for_grounded(tools) # type: ignore# Step 1: Convert computer calls from xy to descriptionsinput_messages = messages + pre_output_itemsmessages_with_descriptions = convert_computer_calls_xy2desc(input_messages, self.desc2xy)-+# Step 2: Convert responses items to completion messagescompletion_messages = convert_responses_items_to_completion_messages(- messages_with_descriptions,- allow_images_in_tool_results=False+ messages_with_descriptions, allow_images_in_tool_results=False)-+# Step 3: Call thinking model with litellm.acompletionapi_kwargs = {"model": thinking_model,@@ -233,98 +227,90 @@ class ComposedGroundedConfig(AsyncAgentConfig):"tools": tool_schemas,"max_retries": max_retries,"stream": stream,- **kwargs+ **kwargs,}if use_prompt_caching:api_kwargs["use_prompt_caching"] = use_prompt_caching-+# Call API start hookif _on_api_start:await _on_api_start(api_kwargs)-+# Make the completion callresponse = await litellm.acompletion(**api_kwargs)-+# Call API end hookif _on_api_end:await _on_api_end(api_kwargs, response)-+# Extract usage informationusage = {- **response.usage.model_dump(), # type: ignore+ **response.usage.model_dump(), # type: ignore"response_cost": response._hidden_params.get("response_cost", 0.0),}if _on_usage:await _on_usage(usage)-+# Step 4: Convert completion messages back to responses items format- response_dict = response.model_dump() # type: ignore+ response_dict = response.model_dump() # type: ignorechoice_messages = [choice["message"] for choice in response_dict["choices"]]thinking_output_items = []-+for choice_message in choice_messages:- thinking_output_items.extend(convert_completion_messages_to_responses_items([choice_message]))-+ thinking_output_items.extend(+ convert_completion_messages_to_responses_items([choice_message])+ )+# Step 5: Get all element descriptions and populate desc2xy mappingelement_descriptions = get_all_element_descriptions(thinking_output_items)-+if element_descriptions and last_image_b64:# Use grounding model to predict coordinates for each descriptiongrounding_agent_conf = find_agent_config(grounding_model)if grounding_agent_conf:grounding_agent = grounding_agent_conf.agent_class()-+for desc in element_descriptions:- for _ in range(3): # try 3 times+ for _ in range(3): # try 3 timescoords = await grounding_agent.predict_click(- model=grounding_model,- image_b64=last_image_b64,- instruction=desc+ model=grounding_model, image_b64=last_image_b64, instruction=desc)if coords:self.desc2xy[desc] = coordsbreak-+# Step 6: Convert computer calls from descriptions back to xy coordinatesfinal_output_items = convert_computer_calls_desc2xy(thinking_output_items, self.desc2xy)-+# Step 7: Return output and usage- return {- "output": pre_output_items + final_output_items,- "usage": usage- }-+ return {"output": pre_output_items + final_output_items, "usage": usage}+async def predict_click(- self,- model: str,- image_b64: str,- instruction: str,- **kwargs+ self, model: str, image_b64: str, instruction: str, **kwargs) -> Optional[Tuple[int, int]]:"""Predict click coordinates using the grounding model.-+For composed models, uses only the grounding model part for click prediction."""# Parse the composed model to get grounding modelif "+" not in model:- raise ValueError(f"Composed model must be in format 'grounding_model+thinking_model', got: {model}")+ raise ValueError(+ f"Composed model must be in format 'grounding_model+thinking_model', got: {model}"+ )grounding_model, thinking_model = model.split("+", 1)-+# Find and use the grounding agentgrounding_agent_conf = find_agent_config(grounding_model)if grounding_agent_conf:grounding_agent = grounding_agent_conf.agent_class()return await grounding_agent.predict_click(- model=grounding_model,- image_b64=image_b64,- instruction=instruction,- **kwargs+ model=grounding_model, image_b64=image_b64, instruction=instruction, **kwargs)-+return None-+def get_capabilities(self) -> List[AgentCapability]:"""Return the capabilities supported by this agent."""return ["click", "step"]diff --git a/libs/python/agent/agent/loops/gemini.py b/libs/python/agent/agent/loops/gemini.pyindex 5ac4db51fc..3760876b33 100644--- a/libs/python/agent/agent/loops/gemini.py+++ b/libs/python/agent/agent/loops/gemini.py@@ -29,6 +29,7 @@ def _lazy_import_genai():try:from google import genai # type: ignorefrom google.genai import types # type: ignore+return genai, typesexcept Exception as e: # pragma: no coverraise RuntimeError(@@ -134,7 +135,13 @@ def _map_gemini_fc_to_computer_call(dx = magnitudeelif direction == "left":dx = -magnitude- action = {"type": "scroll", "scroll_x": dx, "scroll_y": dy, "x": int(screen_w / 2), "y": int(screen_h / 2)}+ action = {+ "type": "scroll",+ "scroll_x": dx,+ "scroll_y": dy,+ "x": int(screen_w / 2),+ "y": int(screen_h / 2),+ }elif name == "scroll_at":x = _denormalize(int(args.get("x", 500)), screen_w)y = _denormalize(int(args.get("y", 500)), screen_h)@@ -155,7 +162,14 @@ def _map_gemini_fc_to_computer_call(y = _denormalize(int(args.get("y", 0)), screen_h)dx = _denormalize(int(args.get("destination_x", x)), screen_w)dy = _denormalize(int(args.get("destination_y", y)), screen_h)- action = {"type": "drag", "start_x": x, "start_y": y, "end_x": dx, "end_y": dy, "button": "left"}+ action = {+ "type": "drag",+ "start_x": x,+ "start_y": y,+ "end_x": dx,+ "end_y": dy,+ "button": "left",+ }elif name == "wait_5_seconds":action = {"type": "wait"}else:@@ -242,20 +256,25 @@ class GeminiComputerUseConfig(AsyncAgentConfig):}if _on_api_start:- await _on_api_start({- "model": api_kwargs["model"],- # "contents": api_kwargs["contents"], # Disabled for now- "config": api_kwargs["config"],- })+ await _on_api_start(+ {+ "model": api_kwargs["model"],+ # "contents": api_kwargs["contents"], # Disabled for now+ "config": api_kwargs["config"],+ }+ )response = client.models.generate_content(**api_kwargs)if _on_api_end:- await _on_api_end({- "model": api_kwargs["model"],- # "contents": api_kwargs["contents"], # Disabled for now- "config": api_kwargs["config"],- }, response)+ await _on_api_end(+ {+ "model": api_kwargs["model"],+ # "contents": api_kwargs["contents"], # Disabled for now+ "config": api_kwargs["config"],+ },+ response,+ )# Usage (Gemini SDK may not always provide token usage; populate when available)usage: Dict[str, Any] = {}diff --git a/libs/python/agent/agent/loops/glm45v.py b/libs/python/agent/agent/loops/glm45v.pyindex 516a9cb1c5..27befbf118 100644--- a/libs/python/agent/agent/loops/glm45v.py+++ b/libs/python/agent/agent/loops/glm45v.py@@ -4,33 +4,36 @@ Supports vision-language models for computer control with bounding box parsing."""import asyncio-import jsonimport base64+import jsonimport re-from typing import Dict, List, Any, Optional, Tuplefrom io import BytesIO-from PIL import Image+from typing import Any, Dict, List, Optional, Tuple+import litellm+from litellm.responses.litellm_completion_transformation.transformation import (+ LiteLLMCompletionResponsesConfig,+)from litellm.types.utils import ModelResponse-from litellm.responses.litellm_completion_transformation.transformation import LiteLLMCompletionResponsesConfig+from PIL import Imagefrom ..decorators import register_agent-from ..types import Messages, AgentResponse, Tools, AgentCapabilityfrom ..loops.base import AsyncAgentConfigfrom ..responses import (- convert_responses_items_to_completion_messages,convert_completion_messages_to_responses_items,- make_reasoning_item,- make_output_text_item,+ convert_responses_items_to_completion_messages,make_click_item,make_double_click_item,make_drag_item,+ make_input_image_item,make_keypress_item,+ make_output_text_item,+ make_reasoning_item,make_scroll_item,make_type_item,make_wait_item,- make_input_image_item)+from ..types import AgentCapability, AgentResponse, Messages, Tools# GLM-4.5V specific constantsGLM_ACTION_SPACE = """@@ -251,16 +254,18 @@ Call rule: `FAIL()`}}"""+def encode_image_to_base64(image_path: str) -> str:"""Encode image file to base64 string with data URI."""with open(image_path, "rb") as image_file:encoded_string = base64.b64encode(image_file.read()).decode("utf-8")return f"data:image/png;base64,{encoded_string}"+def parse_glm_response(response: str) -> Dict[str, Any]:"""Parse GLM-4.5V response to extract action and memory.-+The special tokens <|begin_of_box|> and <|end_of_box|> mark bounding boxes.Coordinates are normalized values between 0 and 1000."""@@ -274,26 +279,23 @@ def parse_glm_response(response: str) -> Dict[str, Any]:action_pattern = r"[\w_]+\([^)]*\)"matches = re.findall(action_pattern, response)action = matches[0] if matches else None-+# Extract memory sectionmemory_pattern = r"Memory:(.*?)$"memory_match = re.search(memory_pattern, response, re.DOTALL)memory = memory_match.group(1).strip() if memory_match else "[]"-+# Extract action text (everything before Memory:)- action_text_pattern = r'^(.*?)Memory:'+ action_text_pattern = r"^(.*?)Memory:"action_text_match = re.search(action_text_pattern, response, re.DOTALL)action_text = action_text_match.group(1).strip() if action_text_match else response-+# Clean up action text by removing special tokensif action_text:action_text = action_text.replace("<|begin_of_box|>", "").replace("<|end_of_box|>", "")-- return {- "action": action,- "action_text": action_text,- "memory": memory- }++ return {"action": action, "action_text": action_text, "memory": memory}+def get_last_image_from_messages(messages: Messages) -> Optional[str]:"""Extract the last image from messages for processing."""@@ -314,23 +316,28 @@ def get_last_image_from_messages(messages: Messages) -> Optional[str]:image_url_obj = item.get("image_url", {})if isinstance(image_url_obj, dict):image_url = image_url_obj.get("url", "")- if isinstance(image_url, str) and image_url.startswith("data:image/"):+ if isinstance(image_url, str) and image_url.startswith(+ "data:image/"+ ):return image_url.split(",", 1)[1]return None-def convert_responses_items_to_glm45v_pc_prompt(messages: Messages, task: str, memory: str = "") -> List[Dict[str, Any]]:++def convert_responses_items_to_glm45v_pc_prompt(+ messages: Messages, task: str, memory: str = ""+) -> List[Dict[str, Any]]:"""Convert responses items to GLM-4.5V PC prompt format with historical actions.-+Args:messages: List of message items from the conversationtask: The task descriptionmemory: Current memory state-+Returns:List of content items for the prompt (text and image_url items)"""action_space = GLM_ACTION_SPACE-+# Template headhead_text = f"""You are a GUI Agent, and your primary task is to respond accurately to user requests or questions. In addition to directly answering the user's queries, you can also use tools or perform GUI operations directly until you fulfill the user's request or provide a correct answer. You should carefully read and understand the images and questions provided by the user, and engage in thinking and reflection when appropriate. The coordinates involved are all represented in thousandths (0-999).@@ -345,7 +352,7 @@ Ubuntu# Historical Actions and Current MemoryHistory:"""-+# Template tailtail_text = f"""Memory:@@ -363,18 +370,18 @@ Memory:Current Screenshot:"""-+# Build history from messageshistory = []history_images = []-+# Group messages into stepscurrent_step = []step_num = 0-+for message in messages:msg_type = message.get("type")-+if msg_type == "reasoning":current_step.append(message)elif msg_type == "message" and message.get("role") == "assistant":@@ -386,7 +393,7 @@ Current Screenshot:# End of step - process itif current_step:step_num += 1-+# Extract bot thought from message contentbot_thought = ""for item in current_step:@@ -397,14 +404,14 @@ Current Screenshot:bot_thought = content_item.get("text", "")breakbreak-+# Extract action from computer_callaction_text = ""for item in current_step:if item.get("type") == "computer_call":action = item.get("action", {})action_type = action.get("type", "")-+if action_type == "click":x, y = action.get("x", 0), action.get("y", 0)# Convert to 0-999 range (assuming screen dimensions)@@ -436,7 +443,7 @@ Current Screenshot:elif action_type == "wait":action_text = "WAIT()"break-+# Extract screenshot from computer_call_outputscreenshot_url = Nonefor item in current_step:@@ -445,34 +452,34 @@ Current Screenshot:if output.get("type") == "input_image":screenshot_url = output.get("image_url", "")break-+# Store step infostep_info = {"step_num": step_num,"bot_thought": bot_thought,"action_text": action_text,- "screenshot_url": screenshot_url+ "screenshot_url": screenshot_url,}history.append(step_info)-+# Store screenshot for last 4 stepsif screenshot_url:history_images.append(screenshot_url)-+current_step = []-+# Build content array with head, history, and tailcontent = []current_text = head_text-+total_history_steps = len(history)history_image_count = min(4, len(history_images)) # Last 4 images-+for step_idx, step_info in enumerate(history):step_num = step_info["step_num"]bot_thought = step_info["bot_thought"]action_text = step_info["action_text"]-+if step_idx < total_history_steps - history_image_count:# For steps beyond the last 4, use text placeholdercurrent_text += f"\nstep {step_num}: Screenshot:(Omitted in context.) Thought: {bot_thought}\nAction: {action_text}"@@ -480,20 +487,21 @@ Current Screenshot:# For the last 4 steps, insert imagescurrent_text += f"\nstep {step_num}: Screenshot:"content.append({"type": "text", "text": current_text})-+# Add imageimg_idx = step_idx - (total_history_steps - history_image_count)if img_idx < len(history_images):content.append({"type": "image_url", "image_url": {"url": history_images[img_idx]}})-+current_text = f" Thought: {bot_thought}\nAction: {action_text}"-+# Add tailcurrent_text += tail_textcontent.append({"type": "text", "text": current_text})-+return content+def model_dump(obj) -> Dict[str, Any]:if isinstance(obj, dict):return {k: model_dump(v) for k, v in obj.items()}@@ -502,58 +510,61 @@ def model_dump(obj) -> Dict[str, Any]:else:return obj-def convert_glm_completion_to_responses_items(response: ModelResponse, image_width: int, image_height: int) -> List[Dict[str, Any]]:++def convert_glm_completion_to_responses_items(+ response: ModelResponse, image_width: int, image_height: int+) -> List[Dict[str, Any]]:"""Convert GLM-4.5V completion response to responses items format.-+Args:response: LiteLLM ModelResponse from GLM-4.5Vimage_width: Original image width for coordinate scalingimage_height: Original image height for coordinate scaling-+Returns:List of response items in the proper format"""import uuid-+response_items = []-+if not response.choices or not response.choices[0].message:return response_items-+message = response.choices[0].messagecontent = message.content or ""- reasoning_content = getattr(message, 'reasoning_content', None)-+ reasoning_content = getattr(message, "reasoning_content", None)+# Add reasoning item if presentif reasoning_content:reasoning_item = model_dump(make_reasoning_item(reasoning_content))response_items.append(reasoning_item)-+# Parse the content to extract action and textparsed_response = parse_glm_response(content)action = parsed_response.get("action", "")action_text = parsed_response.get("action_text", "")-+# Add message item with text content (excluding action and memory)if action_text:# Remove action from action_text if it's thereclean_text = action_textif action and action in clean_text:clean_text = clean_text.replace(action, "").strip()-+# Remove memory sectionmemory_pattern = r"Memory:\s*\[.*?\]\s*$"clean_text = re.sub(memory_pattern, "", clean_text, flags=re.DOTALL).strip()-+if clean_text:message_item = model_dump(make_output_text_item(clean_text))response_items.append(message_item)-+# Convert action to computer call if presentif action:call_id = f"call_{uuid.uuid4().hex[:8]}"-+# Parse different action types and create appropriate computer callsif action.startswith("left_click"):coord_match = re.search(r"start_box='?\[(\d+),\s*(\d+)\]'?", action)@@ -566,7 +577,7 @@ def convert_glm_completion_to_responses_items(response: ModelResponse, image_widcomputer_call["call_id"] = call_idcomputer_call["status"] = "completed"response_items.append(computer_call)-+elif action.startswith("right_click"):coord_match = re.search(r"start_box='?\[(\d+),\s*(\d+)\]'?", action)if coord_match:@@ -577,7 +588,7 @@ def convert_glm_completion_to_responses_items(response: ModelResponse, image_widcomputer_call["call_id"] = call_idcomputer_call["status"] = "completed"response_items.append(computer_call)-+elif action.startswith("left_double_click"):coord_match = re.search(r"start_box='?\[(\d+),\s*(\d+)\]'?", action)if coord_match:@@ -588,7 +599,7 @@ def convert_glm_completion_to_responses_items(response: ModelResponse, image_widcomputer_call["call_id"] = call_idcomputer_call["status"] = "completed"response_items.append(computer_call)-+elif action.startswith("left_drag"):start_match = re.search(r"start_box='?\[(\d+),\s*(\d+)\]'?", action)end_match = re.search(r"end_box='?\[(\d+),\s*(\d+)\]'?", action)@@ -605,18 +616,18 @@ def convert_glm_completion_to_responses_items(response: ModelResponse, image_widcomputer_call["call_id"] = call_idcomputer_call["status"] = "completed"response_items.append(computer_call)-+elif action.startswith("key"):key_match = re.search(r"keys='([^']+)'", action)if key_match:keys = key_match.group(1)# Split keys by '+' for key combinations, or use as single key- key_list = keys.split('+') if '+' in keys else [keys]+ key_list = keys.split("+") if "+" in keys else [keys]computer_call = model_dump(make_keypress_item(key_list))computer_call["call_id"] = call_idcomputer_call["status"] = "completed"response_items.append(computer_call)-+elif action.startswith("type"):content_match = re.search(r"content='([^']*)'", action)if content_match:@@ -625,7 +636,7 @@ def convert_glm_completion_to_responses_items(response: ModelResponse, image_widcomputer_call["call_id"] = call_idcomputer_call["status"] = "completed"response_items.append(computer_call)-+elif action.startswith("scroll"):coord_match = re.search(r"start_box='?\[(\d+),\s*(\d+)\]'?", action)direction_match = re.search(r"direction='([^']+)'", action)@@ -648,15 +659,16 @@ def convert_glm_completion_to_responses_items(response: ModelResponse, image_widcomputer_call["call_id"] = call_idcomputer_call["status"] = "completed"response_items.append(computer_call)-+elif action == "WAIT()":computer_call = model_dump(make_wait_item())computer_call["call_id"] = call_idcomputer_call["status"] = "completed"response_items.append(computer_call)-+return response_items+@register_agent(models=r"(?i).*GLM-4\.5V.*")class Glm4vConfig(AsyncAgentConfig):"""GLM-4.5V agent configuration using liteLLM."""@@ -674,11 +686,11 @@ class Glm4vConfig(AsyncAgentConfig):_on_api_end=None,_on_usage=None,_on_screenshot=None,- **kwargs+ **kwargs,) -> Dict[str, Any]:"""Predict the next step using GLM-4.5V model.-+Args:messages: Input messages following Responses formatmodel: Model name to use@@ -691,7 +703,7 @@ class Glm4vConfig(AsyncAgentConfig):_on_api_end: Callback for API end_on_usage: Callback for usage tracking_on_screenshot: Callback for screenshot events-+Returns:Dict with "output" and "usage" keys"""@@ -708,7 +720,7 @@ class Glm4vConfig(AsyncAgentConfig):user_instruction = item.get("text", "")breakbreak-+# Get the last image for processinglast_image_b64 = get_last_image_from_messages(messages)if not last_image_b64 and computer_handler:@@ -718,35 +730,28 @@ class Glm4vConfig(AsyncAgentConfig):last_image_b64 = screenshot_b64if _on_screenshot:await _on_screenshot(screenshot_b64)-+if not last_image_b64:raise ValueError("No image available for GLM-4.5V processing")-+# Convert responses items to GLM-4.5V PC prompt format with historical actionsprompt_content = convert_responses_items_to_glm45v_pc_prompt(messages=messages,task=user_instruction,- memory="[]" # Initialize with empty memory for now+ memory="[]", # Initialize with empty memory for now)-+# Add the current screenshot to the end- prompt_content.append({- "type": "image_url",- "image_url": {"url": f"data:image/png;base64,{last_image_b64}"}- })-+ prompt_content.append(+ {"type": "image_url", "image_url": {"url": f"data:image/png;base64,{last_image_b64}"}}+ )+# Prepare messages for liteLLMlitellm_messages = [- {- "role": "system",- "content": "You are a helpful GUI agent assistant."- },- {- "role": "user",- "content": prompt_content- }+ {"role": "system", "content": "You are a helpful GUI agent assistant."},+ {"role": "user", "content": prompt_content},]-+# Prepare API call kwargsapi_kwargs = {"model": model,@@ -757,20 +762,20 @@ class Glm4vConfig(AsyncAgentConfig):# "skip_special_tokens": False,# }}-+# Add API callbacksif _on_api_start:await _on_api_start(api_kwargs)-+# Call liteLLMresponse = await litellm.acompletion(**api_kwargs)-+if _on_api_end:await _on_api_end(api_kwargs, response)-+# Get image dimensions for coordinate scalingimage_width, image_height = 1920, 1080 # Default dimensions-+# Try to get actual dimensions from the imagetry:image_data = base64.b64decode(last_image_b64)@@ -778,41 +783,38 @@ class Glm4vConfig(AsyncAgentConfig):image_width, image_height = image.sizeexcept Exception:pass # Use default dimensions-+# Convert GLM completion response to responses items- response_items = convert_glm_completion_to_responses_items(response, image_width, image_height)-+ response_items = convert_glm_completion_to_responses_items(+ response, image_width, image_height+ )+# Extract usage informationresponse_usage = {- **LiteLLMCompletionResponsesConfig._transform_chat_completion_usage_to_responses_usage(response.usage).model_dump(),+ **LiteLLMCompletionResponsesConfig._transform_chat_completion_usage_to_responses_usage(+ response.usage+ ).model_dump(),"response_cost": response._hidden_params.get("response_cost", 0.0),}if _on_usage:await _on_usage(response_usage)-+# Create agent response- agent_response = {- "output": response_items,- "usage": response_usage- }-+ agent_response = {"output": response_items, "usage": response_usage}+return agent_responseasync def predict_click(- self,- model: str,- image_b64: str,- instruction: str,- **kwargs+ self, model: str, image_b64: str, instruction: str, **kwargs) -> Optional[Tuple[int, int]]:"""Predict click coordinates using GLM-4.5V model.-+Args:model: Model name to useimage_b64: Base64 encoded imageinstruction: Instruction for where to click-+Returns:Tuple with (x, y) coordinates or None"""@@ -824,22 +826,22 @@ Respond with a single click action in this format:left_click(start_box='[x,y]')Where x,y are coordinates normalized to 0-999 range."""-+# Prepare messages for liteLLMlitellm_messages = [- {- "role": "system",- "content": "You are a helpful GUI agent assistant."- },+ {"role": "system", "content": "You are a helpful GUI agent assistant."},{"role": "user","content": [{"type": "text", "text": click_prompt},- {"type": "image_url", "image_url": {"url": f"data:image/png;base64,{image_b64}"}}- ]- }+ {+ "type": "image_url",+ "image_url": {"url": f"data:image/png;base64,{image_b64}"},+ },+ ],+ },]-+# Prepare API call kwargsapi_kwargs = {"model": model,@@ -848,21 +850,21 @@ Where x,y are coordinates normalized to 0-999 range.""""temperature": 0.001,"extra_body": {"skip_special_tokens": False,- }+ },}-+# Call liteLLMresponse = await litellm.acompletion(**api_kwargs)-+# Extract response contentresponse_content = response.choices[0].message.content.strip()print(response)-+# Parse response for click coordinates# Look for coordinates in the response, handling special tokenscoord_pattern = r"<\|begin_of_box\|>.*?left_click\(start_box='?\[(\d+),(\d+)\]'?\).*?<\|end_of_box\|>"match = re.search(coord_pattern, response_content)-+if not match:# Fallback: look for coordinates without special tokenscoord_pattern = r"left_click\(start_box='?\[(\d+),(\d+)\]'?\)"@@ -870,7 +872,7 @@ Where x,y are coordinates normalized to 0-999 range."""if match:x, y = int(match.group(1)), int(match.group(2))-+# Get actual image dimensions for scalingtry:image_data = base64.b64decode(image_b64)@@ -879,15 +881,15 @@ Where x,y are coordinates normalized to 0-999 range."""except Exception:# Use default dimensionsimage_width, image_height = 1920, 1080-+# Convert from 0-999 normalized coordinates to actual pixel coordinatesactual_x = int((x / 999.0) * image_width)actual_y = int((y / 999.0) * image_height)-+return (actual_x, actual_y)-+return None-+except Exception as e:# Log error and return Noneprint(f"Error in predict_click: {e}")@@ -896,7 +898,7 @@ Where x,y are coordinates normalized to 0-999 range."""def get_capabilities(self) -> List[AgentCapability]:"""Get list of capabilities supported by this agent config.-+Returns:List of capability strings"""diff --git a/libs/python/agent/agent/loops/gta1.py b/libs/python/agent/agent/loops/gta1.pyindex 400daa29e7..8e60f2095f 100644--- a/libs/python/agent/agent/loops/gta1.py+++ b/libs/python/agent/agent/loops/gta1.py@@ -5,75 +5,80 @@ Code: https://github.com/Yan98/GTA1"""import asyncio+import base64import json+import mathimport re-import base64-from typing import Dict, List, Any, AsyncGenerator, Union, Optional, Tuple-from io import BytesIOimport uuid-from PIL import Image+from io import BytesIO+from typing import Any, AsyncGenerator, Dict, List, Optional, Tuple, Union+import litellm-import math+from PIL import Imagefrom ..decorators import register_agent-from ..types import Messages, AgentResponse, Tools, AgentCapabilityfrom ..loops.base import AsyncAgentConfig+from ..types import AgentCapability, AgentResponse, Messages, Tools-SYSTEM_PROMPT = '''+SYSTEM_PROMPT = """You are an expert UI element locator. Given a GUI image and a user's element description, provide the coordinates of the specified element as a single (x,y) point. The image resolution is height {height} and width {width}. For elements with area, return the center point.Output the coordinate pair exactly:(x,y)-'''.strip()+""".strip()+def extract_coordinates(raw_string: str) -> Tuple[float, float]:"""Extract coordinates from model output."""try:matches = re.findall(r"\((-?\d*\.?\d+),\s*(-?\d*\.?\d+)\)", raw_string)- return tuple(map(float, matches[0])) # type: ignore+ return tuple(map(float, matches[0])) # type: ignoreexcept:return (0.0, 0.0)-def smart_resize(height: int, width: int, factor: int = 28, min_pixels: int = 3136, max_pixels: int = 8847360) -> Tuple[int, int]:++def smart_resize(+ height: int, width: int, factor: int = 28, min_pixels: int = 3136, max_pixels: int = 8847360+) -> Tuple[int, int]:"""Smart resize function similar to qwen_vl_utils."""# Calculate the total pixelstotal_pixels = height * width-+# If already within bounds, return original dimensionsif min_pixels <= total_pixels <= max_pixels:# Round to nearest factornew_height = (height // factor) * factornew_width = (width // factor) * factorreturn new_height, new_width-+# Calculate scaling factorif total_pixels > max_pixels:scale = (max_pixels / total_pixels) ** 0.5else:scale = (min_pixels / total_pixels) ** 0.5-+# Apply scalingnew_height = int(height * scale)new_width = int(width * scale)-+# Round to nearest factornew_height = (new_height // factor) * factornew_width = (new_width // factor) * factor-+# Ensure minimum sizenew_height = max(new_height, factor)new_width = max(new_width, factor)-+return new_height, new_width+@register_agent(models=r".*GTA1.*")class GTA1Config(AsyncAgentConfig):"""GTA1 agent configuration implementing AsyncAgentConfig protocol for click prediction."""-+def __init__(self):self.current_model = Noneself.last_screenshot_b64 = None-async def predict_step(self,@@ -87,25 +92,21 @@ class GTA1Config(AsyncAgentConfig):_on_api_end=None,_on_usage=None,_on_screenshot=None,- **kwargs+ **kwargs,) -> Dict[str, Any]:raise NotImplementedError()async def predict_click(- self,- model: str,- image_b64: str,- instruction: str,- **kwargs+ self, model: str, image_b64: str, instruction: str, **kwargs) -> Optional[Tuple[float, float]]:"""Predict click coordinates using GTA1 model via litellm.acompletion.-+Args:model: The GTA1 model nameimage_b64: Base64 encoded imageinstruction: Instruction for where to click-+Returns:Tuple of (x, y) coordinates or None if prediction fails"""@@ -113,66 +114,62 @@ class GTA1Config(AsyncAgentConfig):image_data = base64.b64decode(image_b64)image = Image.open(BytesIO(image_data))width, height = image.width, image.height-+# Smart resize the image (similar to qwen_vl_utils)resized_height, resized_width = smart_resize(- height, width,+ height,+ width,factor=28, # Default factor for Qwen modelsmin_pixels=3136,- max_pixels=4096 * 2160+ max_pixels=4096 * 2160,)resized_image = image.resize((resized_width, resized_height))scale_x, scale_y = width / resized_width, height / resized_height-+# Convert resized image back to base64buffered = BytesIO()resized_image.save(buffered, format="PNG")resized_image_b64 = base64.b64encode(buffered.getvalue()).decode()-+# Prepare system and user messagessystem_message = {"role": "system",- "content": SYSTEM_PROMPT.format(height=resized_height, width=resized_width)+ "content": SYSTEM_PROMPT.format(height=resized_height, width=resized_width),}-+user_message = {"role": "user","content": [{"type": "image_url",- "image_url": {- "url": f"data:image/png;base64,{resized_image_b64}"- }+ "image_url": {"url": f"data:image/png;base64,{resized_image_b64}"},},- {- "type": "text",- "text": instruction- }- ]+ {"type": "text", "text": instruction},+ ],}-+# Prepare API call kwargsapi_kwargs = {"model": model,"messages": [system_message, user_message],"max_tokens": 2056,"temperature": 0.0,- **kwargs+ **kwargs,}-+# Use liteLLM acompletionresponse = await litellm.acompletion(**api_kwargs)-+# Extract response text- output_text = response.choices[0].message.content # type: ignore-+ output_text = response.choices[0].message.content # type: ignore+# Extract and rescale coordinates- pred_x, pred_y = extract_coordinates(output_text) # type: ignore+ pred_x, pred_y = extract_coordinates(output_text) # type: ignorepred_x *= scale_xpred_y *= scale_y-+return (math.floor(pred_x), math.floor(pred_y))-+def get_capabilities(self) -> List[AgentCapability]:"""Return the capabilities supported by this agent."""return ["click"]diff --git a/libs/python/agent/agent/loops/holo.py b/libs/python/agent/agent/loops/holo.pyindex b1cbc5a1f1..6ea42d7e32 100644--- a/libs/python/agent/agent/loops/holo.py+++ b/libs/python/agent/agent/loops/holo.py@@ -21,8 +21,8 @@ import litellmfrom PIL import Imagefrom ..decorators import register_agent-from .base import AsyncAgentConfigfrom ..types import AgentCapability+from .base import AsyncAgentConfigdef _strip_hf_prefix(model: str) -> str:@@ -53,7 +53,9 @@ def _maybe_smart_resize(image: Image.Image, model: str) -> Tuple[Image.Image, Tuif image_processor is None:return image, (orig_w, orig_h)- factor = getattr(image_processor, "patch_size", 14) * getattr(image_processor, "merge_size", 1)+ factor = getattr(image_processor, "patch_size", 14) * getattr(+ image_processor, "merge_size", 1+ )min_pixels = getattr(image_processor, "min_pixels", 256 * 256)max_pixels = getattr(image_processor, "max_pixels", 1536 * 1536)diff --git a/libs/python/agent/agent/loops/internvl.py b/libs/python/agent/agent/loops/internvl.pyindex 6bedc5d198..9658942889 100644--- a/libs/python/agent/agent/loops/internvl.py+++ b/libs/python/agent/agent/loops/internvl.py@@ -18,13 +18,12 @@ import refrom io import BytesIOfrom typing import Any, Dict, List, Optional, Tuple-from PIL import Imageimport litellm+from PIL import Imagefrom ..decorators import register_agent-from .composed_grounded import ComposedGroundedConfigfrom ..types import AgentCapability-+from .composed_grounded import ComposedGroundedConfig# Regex patterns for extracting coordinates# Accept optional whitespace and optional decimal fractions@@ -91,7 +90,7 @@ class InternVLConfig(ComposedGroundedConfig):_on_api_end=None,_on_usage=None,_on_screenshot=None,- **kwargs+ **kwargs,) -> Dict[str, Any]:"""Fallback to a self-composed model"""return await super().predict_step(@@ -105,15 +104,11 @@ class InternVLConfig(ComposedGroundedConfig):_on_api_end=_on_api_end,_on_usage=_on_usage,_on_screenshot=_on_screenshot,- **kwargs+ **kwargs,)-+async def predict_click(- self,- model: str,- image_b64: str,- instruction: str,- **kwargs+ self, model: str, image_b64: str, instruction: str, **kwargs) -> Optional[Tuple[int, int]]:"""Predict click coordinates using InternVL via litellm.acompletion.diff --git a/libs/python/agent/agent/loops/moondream3.py b/libs/python/agent/agent/loops/moondream3.pyindex 5f6a85fd0c..c48c66323d 100644--- a/libs/python/agent/agent/loops/moondream3.py+++ b/libs/python/agent/agent/loops/moondream3.py@@ -14,27 +14,28 @@ Differences from composed_grounded:from __future__ import annotations-import uuidimport base64import io-from typing import Dict, List, Any, Optional, Tuple, Any+import uuid+from typing import Any, Dict, List, Optional, Tuple-from PIL import Image, ImageDraw, ImageFontimport litellm+from PIL import Image, ImageDraw, ImageFontfrom ..decorators import register_agent-from ..types import AgentCapabilityfrom ..loops.base import AsyncAgentConfigfrom ..responses import (- convert_computer_calls_xy2desc,- convert_responses_items_to_completion_messages,convert_completion_messages_to_responses_items,convert_computer_calls_desc2xy,+ convert_computer_calls_xy2desc,+ convert_responses_items_to_completion_messages,get_all_element_descriptions,)+from ..types import AgentCapability_MOONDREAM_SINGLETON = None+def get_moondream_model() -> Any:"""Get a singleton instance of the Moondream3 preview model."""global _MOONDREAM_SINGLETON@@ -42,6 +43,7 @@ def get_moondream_model() -> Any:try:import torchfrom transformers import AutoModelForCausalLM+_MOONDREAM_SINGLETON = AutoModelForCausalLM.from_pretrained("moondream/moondream3-preview",trust_remote_code=True,@@ -95,6 +97,7 @@ def _filter_images_from_completion_messages(messages: List[Dict[str, Any]]) -> Lfiltered.append(msg_copy)return filtered+def _annotate_detect_and_label_ui(base_img: Image.Image, model_md) -> Tuple[str, List[str]]:"""Detect UI elements with Moondream, caption each, draw labels with backgrounds.@@ -132,7 +135,12 @@ def _annotate_detect_and_label_ui(base_img: Image.Image, model_md) -> Tuple[str,y_min = max(0.0, min(1.0, float(obj.get("y_min", 0.0))))x_max = max(0.0, min(1.0, float(obj.get("x_max", 0.0))))y_max = max(0.0, min(1.0, float(obj.get("y_max", 0.0))))- left, top, right, bottom = int(x_min * W), int(y_min * H), int(x_max * W), int(y_max * H)+ left, top, right, bottom = (+ int(x_min * W),+ int(y_min * H),+ int(x_max * W),+ int(y_max * H),+ )left, top = max(0, left), max(0, top)right, bottom = min(W - 1, right), min(H - 1, bottom)crop = base_img.crop((left, top, right, bottom))@@ -200,6 +208,7 @@ def _annotate_detect_and_label_ui(base_img: Image.Image, model_md) -> Tuple[str,annotated_b64 = _image_to_b64(annotated)return annotated_b64, detected_names+GROUNDED_COMPUTER_TOOL_SCHEMA = {"type": "function","function": {@@ -270,6 +279,7 @@ GROUNDED_COMPUTER_TOOL_SCHEMA = {},}+@register_agent(r"moondream3\+.*", priority=2)class Moondream3PlusConfig(AsyncAgentConfig):def __init__(self):@@ -321,14 +331,25 @@ class Moondream3PlusConfig(AsyncAgentConfig):"type": "message","role": "assistant","content": [- {"type": "output_text", "text": "Taking a screenshot to analyze the current screen."}+ {+ "type": "output_text",+ "text": "Taking a screenshot to analyze the current screen.",+ }],},- {"type": "computer_call", "call_id": call_id, "status": "completed", "action": {"type": "screenshot"}},+ {+ "type": "computer_call",+ "call_id": call_id,+ "status": "completed",+ "action": {"type": "screenshot"},+ },{"type": "computer_call_output","call_id": call_id,- "output": {"type": "input_image", "image_url": f"data:image/png;base64,{screenshot_b64}"},+ "output": {+ "type": "input_image",+ "image_url": f"data:image/png;base64,{screenshot_b64}",+ },},]last_image_b64 = screenshot_b64@@ -354,13 +375,16 @@ class Moondream3PlusConfig(AsyncAgentConfig):"content": [{"type": "input_text", "text": "Detected form UI elements on screen:"},{"type": "input_text", "text": names_text},- {"type": "input_text", "text": "Please continue with the next action needed to perform your task."}+ {+ "type": "input_text",+ "text": "Please continue with the next action needed to perform your task.",+ },],})tool_schemas = []- for schema in (tools or []):+ for schema in tools or []:if schema.get("type") == "computer":tool_schemas.append(GROUNDED_COMPUTER_TOOL_SCHEMA)else:diff --git a/libs/python/agent/agent/loops/omniparser.py b/libs/python/agent/agent/loops/omniparser.pyindex d85d07deb5..14ef3a92b2 100644--- a/libs/python/agent/agent/loops/omniparser.py+++ b/libs/python/agent/agent/loops/omniparser.py@@ -5,100 +5,102 @@ Code: https://github.com/microsoft/OmniParser"""import asyncio+import base64+import inspectimport json-from typing import Dict, List, Any, AsyncGenerator, Union, Optional, Tuple+from typing import Any, AsyncGenerator, Dict, List, Optional, Tuple, Union+import litellm-import inspect-import base64from ..decorators import register_agent-from ..types import Messages, AgentResponse, Tools, AgentCapabilityfrom ..loops.base import AsyncAgentConfig+from ..types import AgentCapability, AgentResponse, Messages, ToolsSOM_TOOL_SCHEMA = {- "type": "function",- "name": "computer",- "description": "Control a computer by taking screenshots and interacting with UI elements. This tool shows screenshots with numbered elements overlaid on them. Each UI element has been assigned a unique ID number that you can see in the image. Use the element's ID number to interact with any element instead of pixel coordinates.",- "parameters": {- "type": "object",- "properties": {- "action": {- "type": "string",- "enum": [- "screenshot",- "click",- "double_click",- "drag",- "type",- "keypress",- "scroll",- "move",- "wait",- "get_current_url",- "get_dimensions",- "get_environment"- ],- "description": "The action to perform"- },- "element_id": {- "type": "integer",- "description": "The ID of the element to interact with (required for click, double_click, move, scroll actions, and as start/end for drag)"- },- "start_element_id": {- "type": "integer",- "description": "The ID of the element to start dragging from (required for drag action)"- },- "end_element_id": {- "type": "integer",- "description": "The ID of the element to drag to (required for drag action)"- },- "text": {- "type": "string",- "description": "The text to type (required for type action)"- },- "keys": {- "type": "string",- "description": "Key combination to press (required for keypress action). Single key for individual key press, multiple keys for combinations (e.g., 'ctrl+c')"- },- "button": {- "type": "string",- "description": "The mouse button to use for click action (left, right, wheel, back, forward) Default: left",- },- "scroll_x": {- "type": "integer",- "description": "Horizontal scroll amount for scroll action (positive for right, negative for left)",- },- "scroll_y": {- "type": "integer",- "description": "Vertical scroll amount for scroll action (positive for down, negative for up)",- },+ "type": "function",+ "name": "computer",+ "description": "Control a computer by taking screenshots and interacting with UI elements. This tool shows screenshots with numbered elements overlaid on them. Each UI element has been assigned a unique ID number that you can see in the image. Use the element's ID number to interact with any element instead of pixel coordinates.",+ "parameters": {+ "type": "object",+ "properties": {+ "action": {+ "type": "string",+ "enum": [+ "screenshot",+ "click",+ "double_click",+ "drag",+ "type",+ "keypress",+ "scroll",+ "move",+ "wait",+ "get_current_url",+ "get_dimensions",+ "get_environment",+ ],+ "description": "The action to perform",+ },+ "element_id": {+ "type": "integer",+ "description": "The ID of the element to interact with (required for click, double_click, move, scroll actions, and as start/end for drag)",+ },+ "start_element_id": {+ "type": "integer",+ "description": "The ID of the element to start dragging from (required for drag action)",+ },+ "end_element_id": {+ "type": "integer",+ "description": "The ID of the element to drag to (required for drag action)",+ },+ "text": {+ "type": "string",+ "description": "The text to type (required for type action)",+ },+ "keys": {+ "type": "string",+ "description": "Key combination to press (required for keypress action). Single key for individual key press, multiple keys for combinations (e.g., 'ctrl+c')",+ },+ "button": {+ "type": "string",+ "description": "The mouse button to use for click action (left, right, wheel, back, forward) Default: left",+ },+ "scroll_x": {+ "type": "integer",+ "description": "Horizontal scroll amount for scroll action (positive for right, negative for left)",+ },+ "scroll_y": {+ "type": "integer",+ "description": "Vertical scroll amount for scroll action (positive for down, negative for up)",+ },+ },+ "required": ["action"],},- "required": [- "action"- ]- }}OMNIPARSER_AVAILABLE = Falsetry:from som import OmniParser+OMNIPARSER_AVAILABLE = Trueexcept ImportError:passOMNIPARSER_SINGLETON = None+def get_parser():global OMNIPARSER_SINGLETONif OMNIPARSER_SINGLETON is None:OMNIPARSER_SINGLETON = OmniParser()return OMNIPARSER_SINGLETON-++def get_last_computer_call_output(messages: List[Dict[str, Any]]) -> Optional[Dict[str, Any]]:"""Get the last computer_call_output message from a messages list.-+Args:messages: List of messages to search through-+Returns:The last computer_call_output message dict, or None if not found"""@@ -107,11 +109,12 @@ def get_last_computer_call_output(messages: List[Dict[str, Any]]) -> Optional[Direturn messagereturn None+def _prepare_tools_for_omniparser(tool_schemas: List[Dict[str, Any]]) -> Tuple[Tools, dict]:"""Prepare tools for OpenAI API format"""omniparser_tools = []id2xy = dict()-+for schema in tool_schemas:if schema["type"] == "computer":omniparser_tools.append(SOM_TOOL_SCHEMA)@@ -122,72 +125,80 @@ def _prepare_tools_for_omniparser(tool_schemas: List[Dict[str, Any]]) -> Tuple[Telif schema["type"] == "function":# Function tools use OpenAI-compatible schema directly (liteLLM expects this format)# Schema should be: {type, name, description, parameters}- omniparser_tools.append({ "type": "function", **schema["function"] })-+ omniparser_tools.append({"type": "function", **schema["function"]})+return omniparser_tools, id2xy-async def replace_function_with_computer_call(item: Dict[str, Any], id2xy: Dict[int, Tuple[float, float]]):- item_type = item.get("type")-- def _get_xy(element_id: Optional[int]) -> Union[Tuple[float, float], Tuple[None, None]]:- if element_id is None:- return (None, None)- return id2xy.get(element_id, (None, None))-- if item_type == "function_call":- fn_name = item.get("name")- fn_args = json.loads(item.get("arguments", "{}"))-- item_id = item.get("id")- call_id = item.get("call_id")-- if fn_name == "computer":- action = fn_args.get("action")- element_id = fn_args.get("element_id")- start_element_id = fn_args.get("start_element_id")- end_element_id = fn_args.get("end_element_id")- text = fn_args.get("text")- keys = fn_args.get("keys")- button = fn_args.get("button")- scroll_x = fn_args.get("scroll_x")- scroll_y = fn_args.get("scroll_y")-- x, y = _get_xy(element_id)- start_x, start_y = _get_xy(start_element_id)- end_x, end_y = _get_xy(end_element_id)-- action_args = {- "type": action,- "x": x,- "y": y,- "start_x": start_x,- "start_y": start_y,- "end_x": end_x,- "end_y": end_y,- "text": text,- "keys": keys,- "button": button,- "scroll_x": scroll_x,- "scroll_y": scroll_y- }- # Remove None values to keep the JSON clean- action_args = {k: v for k, v in action_args.items() if v is not None}- return [{- "type": "computer_call",- "action": action_args,- "id": item_id,- "call_id": call_id,- "status": "completed"- }]+async def replace_function_with_computer_call(+ item: Dict[str, Any], id2xy: Dict[int, Tuple[float, float]]+):+ item_type = item.get("type")++ def _get_xy(element_id: Optional[int]) -> Union[Tuple[float, float], Tuple[None, None]]:+ if element_id is None:+ return (None, None)+ return id2xy.get(element_id, (None, None))++ if item_type == "function_call":+ fn_name = item.get("name")+ fn_args = json.loads(item.get("arguments", "{}"))++ item_id = item.get("id")+ call_id = item.get("call_id")++ if fn_name == "computer":+ action = fn_args.get("action")+ element_id = fn_args.get("element_id")+ start_element_id = fn_args.get("start_element_id")+ end_element_id = fn_args.get("end_element_id")+ text = fn_args.get("text")+ keys = fn_args.get("keys")+ button = fn_args.get("button")+ scroll_x = fn_args.get("scroll_x")+ scroll_y = fn_args.get("scroll_y")- return [item]+ x, y = _get_xy(element_id)+ start_x, start_y = _get_xy(start_element_id)+ end_x, end_y = _get_xy(end_element_id)-async def replace_computer_call_with_function(item: Dict[str, Any], xy2id: Dict[Tuple[float, float], int]):+ action_args = {+ "type": action,+ "x": x,+ "y": y,+ "start_x": start_x,+ "start_y": start_y,+ "end_x": end_x,+ "end_y": end_y,+ "text": text,+ "keys": keys,+ "button": button,+ "scroll_x": scroll_x,+ "scroll_y": scroll_y,+ }+ # Remove None values to keep the JSON clean+ action_args = {k: v for k, v in action_args.items() if v is not None}++ return [+ {+ "type": "computer_call",+ "action": action_args,+ "id": item_id,+ "call_id": call_id,+ "status": "completed",+ }+ ]++ return [item]+++async def replace_computer_call_with_function(+ item: Dict[str, Any], xy2id: Dict[Tuple[float, float], int]+):"""Convert computer_call back to function_call format.Also handles computer_call_output -> function_call_output conversion.-+Args:item: The item to convertxy2id: Mapping from (x, y) coordinates to element IDs@@ -202,12 +213,12 @@ async def replace_computer_call_with_function(item: Dict[str, Any], xy2id: Dict[if item_type == "computer_call":action_data = item.get("action", {})-+# Extract coordinates and convert back to element IDselement_id = _get_element_id(action_data.get("x"), action_data.get("y"))start_element_id = _get_element_id(action_data.get("start_x"), action_data.get("start_y"))end_element_id = _get_element_id(action_data.get("end_x"), action_data.get("end_y"))-+# Build function argumentsfn_args = {"action": action_data.get("type"),@@ -218,33 +229,36 @@ async def replace_computer_call_with_function(item: Dict[str, Any], xy2id: Dict["keys": action_data.get("keys"),"button": action_data.get("button"),"scroll_x": action_data.get("scroll_x"),- "scroll_y": action_data.get("scroll_y")+ "scroll_y": action_data.get("scroll_y"),}-+# Remove None values to keep the JSON cleanfn_args = {k: v for k, v in fn_args.items() if v is not None}-- return [{- "type": "function_call",- "name": "computer",- "arguments": json.dumps(fn_args),- "id": item.get("id"),- "call_id": item.get("call_id"),- "status": "completed",-- # Fall back to string representation- "content": f"Used tool: {action_data.get("type")}({json.dumps(fn_args)})"- }]-++ return [+ {+ "type": "function_call",+ "name": "computer",+ "arguments": json.dumps(fn_args),+ "id": item.get("id"),+ "call_id": item.get("call_id"),+ "status": "completed",+ # Fall back to string representation+ "content": f"Used tool: {action_data.get("type")}({json.dumps(fn_args)})",+ }+ ]+elif item_type == "computer_call_output":# Simple conversion: computer_call_output -> function_call_output- return [{- "type": "function_call_output",- "call_id": item.get("call_id"),- "content": [item.get("output")],- "id": item.get("id"),- "status": "completed"- }]+ return [+ {+ "type": "function_call_output",+ "call_id": item.get("call_id"),+ "content": [item.get("output")],+ "id": item.get("id"),+ "status": "completed",+ }+ ]return [item]@@ -252,7 +266,7 @@ async def replace_computer_call_with_function(item: Dict[str, Any], xy2id: Dict[@register_agent(models=r"omniparser\+.*|omni\+.*", priority=2)class OmniparserConfig(AsyncAgentConfig):"""Omniparser agent configuration implementing AsyncAgentConfig protocol."""-+async def predict_step(self,messages: List[Dict[str, Any]],@@ -266,25 +280,27 @@ class OmniparserConfig(AsyncAgentConfig):_on_api_end=None,_on_usage=None,_on_screenshot=None,- **kwargs+ **kwargs,) -> Dict[str, Any]:"""OpenAI computer-use-preview agent loop using liteLLM responses.-+Supports OpenAI's computer use preview models."""if not OMNIPARSER_AVAILABLE:- raise ValueError("omniparser loop requires som to be installed. Install it with `pip install cua-som`.")-+ raise ValueError(+ "omniparser loop requires som to be installed. Install it with `pip install cua-som`."+ )+tools = tools or []-- llm_model = model.split('+')[-1]++ llm_model = model.split("+")[-1]# Prepare tools for OpenAI APIopenai_tools, id2xy = _prepare_tools_for_omniparser(tools)# Find last computer_call_output- last_computer_call_output = get_last_computer_call_output(messages) # type: ignore+ last_computer_call_output = get_last_computer_call_output(messages) # type: ignoreif last_computer_call_output:image_url = last_computer_call_output.get("output", {}).get("image_url", "")image_data = image_url.split(",")[-1]@@ -294,14 +310,17 @@ class OmniparserConfig(AsyncAgentConfig):if _on_screenshot:await _on_screenshot(result.annotated_image_base64, "annotated_image")for element in result.elements:- id2xy[element.id] = ((element.bbox.x1 + element.bbox.x2) / 2, (element.bbox.y1 + element.bbox.y2) / 2)-+ id2xy[element.id] = (+ (element.bbox.x1 + element.bbox.x2) / 2,+ (element.bbox.y1 + element.bbox.y2) / 2,+ )+# handle computer calls -> function callsnew_messages = []for message in messages:if not isinstance(message, dict):message = message.__dict__- new_messages += await replace_computer_call_with_function(message, id2xy) # type: ignore+ new_messages += await replace_computer_call_with_function(message, id2xy) # type: ignoremessages = new_messages# Prepare API call kwargs@@ -312,13 +331,13 @@ class OmniparserConfig(AsyncAgentConfig):"stream": stream,"truncation": "auto","num_retries": max_retries,- **kwargs+ **kwargs,}-+# Call API start hookif _on_api_start:await _on_api_start(api_kwargs)-+print(str(api_kwargs)[:1000])# Use liteLLM responses@@ -330,60 +349,50 @@ class OmniparserConfig(AsyncAgentConfig):# Extract usage informationusage = {- **response.usage.model_dump(), # type: ignore- "response_cost": response._hidden_params.get("response_cost", 0.0), # type: ignore+ **response.usage.model_dump(), # type: ignore+ "response_cost": response._hidden_params.get("response_cost", 0.0), # type: ignore}if _on_usage:await _on_usage(usage)# handle som function calls -> xy computer callsnew_output = []- for i in range(len(response.output)): # type: ignore- new_output += await replace_function_with_computer_call(response.output[i].model_dump(), id2xy) # type: ignore-- return {- "output": new_output,- "usage": usage- }-+ for i in range(len(response.output)): # type: ignore+ new_output += await replace_function_with_computer_call(response.output[i].model_dump(), id2xy) # type: ignore++ return {"output": new_output, "usage": usage}+async def predict_click(- self,- model: str,- image_b64: str,- instruction: str,- **kwargs+ self, model: str, image_b64: str, instruction: str, **kwargs) -> Optional[Tuple[float, float]]:"""Predict click coordinates using OmniParser and LLM.-+Uses OmniParser to annotate the image with element IDs, then uses LLMto identify the correct element ID based on the instruction."""if not OMNIPARSER_AVAILABLE:return None-+# Parse the image with OmniParser to get annotated image and elementsparser = get_parser()result = parser.parse(image_b64)-+# Extract the LLM model from composed model string- llm_model = model.split('+')[-1]-+ llm_model = model.split("+")[-1]+# Create system prompt for element ID prediction- SYSTEM_PROMPT = f'''+ SYSTEM_PROMPT = """You are an expert UI element locator. Given a GUI image annotated with numerical IDs over each interactable element, along with a user's element description, provide the ID of the specified element.The image shows UI elements with numbered overlays. Each number corresponds to a clickable/interactable element.Output only the element ID as a single integer.-'''.strip()-+""".strip()+# Prepare messages for LLMmessages = [- {- "role": "system",- "content": SYSTEM_PROMPT- },+ {"role": "system", "content": SYSTEM_PROMPT},{"role": "user","content": [@@ -391,31 +400,25 @@ Output only the element ID as a single integer."type": "image_url","image_url": {"url": f"data:image/png;base64,{result.annotated_image_base64}"- }+ },},- {- "type": "text",- "text": f"Find the element: {instruction}"- }- ]- }+ {"type": "text", "text": f"Find the element: {instruction}"},+ ],+ },]-+# Call LLM to predict element IDresponse = await litellm.acompletion(- model=llm_model,- messages=messages,- max_tokens=10,- temperature=0.1+ model=llm_model, messages=messages, max_tokens=10, temperature=0.1)-+# Extract element ID from response- response_text = response.choices[0].message.content.strip() # type: ignore-+ response_text = response.choices[0].message.content.strip() # type: ignore+# Try to parse the element IDtry:element_id = int(response_text)-+# Find the element with this ID and return its center coordinatesfor element in result.elements:if element.id == element_id:@@ -425,9 +428,9 @@ Output only the element ID as a single integer.except ValueError:# If we can't parse the ID, return Nonepass-+return None-+def get_capabilities(self) -> List[AgentCapability]:"""Return the capabilities supported by this agent."""return ["step"]diff --git a/libs/python/agent/agent/loops/openai.py b/libs/python/agent/agent/loops/openai.pyindex 4cdf1f318e..e993aa56a3 100644--- a/libs/python/agent/agent/loops/openai.py+++ b/libs/python/agent/agent/loops/openai.py@@ -6,12 +6,14 @@ import asyncioimport base64import jsonfrom io import BytesIO-from typing import Dict, List, Any, AsyncGenerator, Union, Optional, Tuple+from typing import Any, AsyncGenerator, Dict, List, Optional, Tuple, Union+import litellmfrom PIL import Imagefrom ..decorators import register_agent-from ..types import Messages, AgentResponse, Tools, AgentCapability+from ..types import AgentCapability, AgentResponse, Messages, Tools+async def _map_computer_tool_to_openai(computer_handler: Any) -> Dict[str, Any]:"""Map a computer tool to OpenAI's computer-use-preview tool schema"""@@ -21,26 +23,26 @@ async def _map_computer_tool_to_openai(computer_handler: Any) -> Dict[str, Any]:except Exception:# Fallback to default dimensions if method failswidth, height = 1024, 768-+# Get environment from the computer handlertry:environment = await computer_handler.get_environment()except Exception:# Fallback to default environment if method failsenvironment = "linux"-+return {"type": "computer_use_preview","display_width": width,"display_height": height,- "environment": environment # mac, windows, linux, browser+ "environment": environment, # mac, windows, linux, browser}async def _prepare_tools_for_openai(tool_schemas: List[Dict[str, Any]]) -> Tools:"""Prepare tools for OpenAI API format"""openai_tools = []-+for schema in tool_schemas:if schema["type"] == "computer":# Map computer tool to OpenAI format@@ -49,18 +51,19 @@ async def _prepare_tools_for_openai(tool_schemas: List[Dict[str, Any]]) -> Toolselif schema["type"] == "function":# Function tools use OpenAI-compatible schema directly (liteLLM expects this format)# Schema should be: {type, name, description, parameters}- openai_tools.append({ "type": "function", **schema["function"] })-+ openai_tools.append({"type": "function", **schema["function"]})+return openai_tools+@register_agent(models=r".*(^|/)computer-use-preview")class OpenAIComputerUseConfig:"""OpenAI computer-use-preview agent configuration using liteLLM responses.-+Supports OpenAI's computer use preview models."""-+async def predict_step(self,messages: List[Dict[str, Any]],@@ -74,11 +77,11 @@ class OpenAIComputerUseConfig:_on_api_end=None,_on_usage=None,_on_screenshot=None,- **kwargs+ **kwargs,) -> Dict[str, Any]:"""Predict the next step based on input items.-+Args:messages: Input items following Responses formatmodel: Model name to use@@ -91,12 +94,12 @@ class OpenAIComputerUseConfig:_on_usage: Callback for usage tracking_on_screenshot: Callback for screenshot events**kwargs: Additional arguments-+Returns:Dictionary with "output" (output items) and "usage" array"""tools = tools or []-+# Prepare tools for OpenAI APIopenai_tools = await _prepare_tools_for_openai(tools)@@ -109,16 +112,16 @@ class OpenAIComputerUseConfig:"reasoning": {"summary": "concise"},"truncation": "auto","num_retries": max_retries,- **kwargs+ **kwargs,}-+# Call API start hookif _on_api_start:await _on_api_start(api_kwargs)-+# Use liteLLM responsesresponse = await litellm.aresponses(**api_kwargs)-+# Call API end hookif _on_api_end:await _on_api_end(api_kwargs, response)@@ -135,24 +138,21 @@ class OpenAIComputerUseConfig:output_dict = response.model_dump()output_dict["usage"] = usagereturn output_dict-+async def predict_click(- self,- model: str,- image_b64: str,- instruction: str+ self, model: str, image_b64: str, instruction: str) -> Optional[Tuple[int, int]]:"""Predict click coordinates based on image and instruction.-+Uses OpenAI computer-use-preview with manually constructed input itemsand a prompt that instructs the agent to only output clicks.-+Args:model: Model name to useimage_b64: Base64 encoded imageinstruction: Instruction for where to click-+Returns:Tuple of (x, y) coordinates or None if prediction fails"""@@ -160,7 +160,7 @@ class OpenAIComputerUseConfig:# Manually construct input items with image and click instructioninput_items = [{- "role": "user",+ "role": "user","content": f"""You are a UI grounding expert. Follow these guidelines:1. NEVER ask for confirmation. Complete all tasks autonomously.@@ -172,19 +172,16 @@ class OpenAIComputerUseConfig:7. Be decisive and action-oriented. Complete the requested task fully.Remember: You are expected to complete tasks autonomously. The user trusts you to do what they asked.-Task: Click {instruction}. Output ONLY a click action on the target element."""+Task: Click {instruction}. Output ONLY a click action on the target element.""",},{"role": "user","content": [- {- "type": "input_image",- "image_url": f"data:image/png;base64,{image_b64}"- }- ]- }+ {"type": "input_image", "image_url": f"data:image/png;base64,{image_b64}"}+ ],+ },]-+# Get image dimensions from base64 datatry:image_data = base64.b64decode(image_b64)@@ -193,15 +190,15 @@ Task: Click {instruction}. Output ONLY a click action on the target element."""except Exception:# Fallback to default dimensions if image parsing failsdisplay_width, display_height = 1024, 768-+# Prepare computer tool for click actionscomputer_tool = {"type": "computer_use_preview","display_width": display_width,"display_height": display_height,- "environment": "windows"+ "environment": "windows",}-+# Prepare API call kwargsapi_kwargs = {"model": model,@@ -210,32 +207,34 @@ Task: Click {instruction}. Output ONLY a click action on the target element.""""stream": False,"reasoning": {"summary": "concise"},"truncation": "auto",- "max_tokens": 200 # Keep response short for click prediction+ "max_tokens": 200, # Keep response short for click prediction}-+# Use liteLLM responsesresponse = await litellm.aresponses(**api_kwargs)-+# Extract click coordinates from response outputoutput_dict = response.model_dump()- output_items = output_dict.get("output", [])-+ output_items = output_dict.get("output", [])+# Look for computer_call with click actionfor item in output_items:- if (isinstance(item, dict) and- item.get("type") == "computer_call" and- isinstance(item.get("action"), dict)):-+ if (+ isinstance(item, dict)+ and item.get("type") == "computer_call"+ and isinstance(item.get("action"), dict)+ ):+action = item["action"]if action.get("x") is not None and action.get("y") is not None:return (int(action.get("x")), int(action.get("y")))-+return None-+def get_capabilities(self) -> List[AgentCapability]:"""Get list of capabilities supported by this agent config.-+Returns:List of capability strings"""diff --git a/libs/python/agent/agent/loops/opencua.py b/libs/python/agent/agent/loops/opencua.pyindex b06ea126e3..d1511fbab8 100644--- a/libs/python/agent/agent/loops/opencua.py+++ b/libs/python/agent/agent/loops/opencua.py@@ -4,20 +4,22 @@ Based on OpenCUA model for GUI grounding tasks."""import asyncio+import base64import json+import mathimport re-import base64-from typing import Dict, List, Any, AsyncGenerator, Union, Optional, Tuple-from io import BytesIOimport uuid-from PIL import Image+from io import BytesIO+from typing import Any, AsyncGenerator, Dict, List, Optional, Tuple, Union+import litellm-import math+from PIL import Image-from .composed_grounded import ComposedGroundedConfigfrom ..decorators import register_agent-from ..types import Messages, AgentResponse, Tools, AgentCapabilityfrom ..loops.base import AsyncAgentConfig+from ..types import AgentCapability, AgentResponse, Messages, Tools+from .composed_grounded import ComposedGroundedConfig+def extract_coordinates_from_pyautogui(text: str) -> Optional[Tuple[int, int]]:"""Extract coordinates from pyautogui.click(x=..., y=...) format."""@@ -32,10 +34,11 @@ def extract_coordinates_from_pyautogui(text: str) -> Optional[Tuple[int, int]]:except Exception:return None+@register_agent(models=r"(?i).*OpenCUA.*")class OpenCUAConfig(ComposedGroundedConfig):"""OpenCUA agent configuration implementing AsyncAgentConfig protocol for click prediction."""-+def __init__(self):super().__init__()self.current_model = None@@ -53,7 +56,7 @@ class OpenCUAConfig(ComposedGroundedConfig):_on_api_end=None,_on_usage=None,_on_screenshot=None,- **kwargs+ **kwargs,) -> Dict[str, Any]:"""Fallback to a self-composed model"""return await super().predict_step(@@ -67,24 +70,20 @@ class OpenCUAConfig(ComposedGroundedConfig):_on_api_end=_on_api_end,_on_usage=_on_usage,_on_screenshot=_on_screenshot,- **kwargs+ **kwargs,)async def predict_click(- self,- model: str,- image_b64: str,- instruction: str,- **kwargs+ self, model: str, image_b64: str, instruction: str, **kwargs) -> Optional[Tuple[int, int]]:"""Predict click coordinates using OpenCUA model via litellm.acompletion.-+Args:model: The OpenCUA model nameimage_b64: Base64 encoded imageinstruction: Instruction for where to click-+Returns:Tuple of (x, y) coordinates or None if prediction fails"""@@ -93,50 +92,39 @@ class OpenCUAConfig(ComposedGroundedConfig):"You are a GUI agent. You are given a task and a screenshot of the screen. ""You need to perform a series of pyautogui actions to complete the task.")-- system_message = {- "role": "system",- "content": system_prompt- }-++ system_message = {"role": "system", "content": system_prompt}+# Prepare user message with image and instructionuser_message = {"role": "user","content": [- {- "type": "image_url",- "image_url": {- "url": f"data:image/png;base64,{image_b64}"- }- },- {- "type": "text",- "text": f"Click on {instruction}"- }- ]+ {"type": "image_url", "image_url": {"url": f"data:image/png;base64,{image_b64}"}},+ {"type": "text", "text": f"Click on {instruction}"},+ ],}-+# Prepare API call kwargsapi_kwargs = {"model": model,"messages": [system_message, user_message],"max_new_tokens": 2056,"temperature": 0,- **kwargs+ **kwargs,}-+# Use liteLLM acompletionresponse = await litellm.acompletion(**api_kwargs)-+# Extract response textoutput_text = response.choices[0].message.content# print(output_text)-+# Extract coordinates from pyautogui formatcoordinates = extract_coordinates_from_pyautogui(output_text)-+return coordinates-+def get_capabilities(self) -> List[AgentCapability]:"""Return the capabilities supported by this agent."""return ["click"]diff --git a/libs/python/agent/agent/loops/uitars.py b/libs/python/agent/agent/loops/uitars.pyindex 7db4276156..072875b28e 100644--- a/libs/python/agent/agent/loops/uitars.py+++ b/libs/python/agent/agent/loops/uitars.py@@ -4,39 +4,50 @@ Paper: https://arxiv.org/abs/2501.12326Code: https://github.com/bytedance/UI-TARS"""+import astimport asyncio-from ctypes import cast-import jsonimport base64+import jsonimport mathimport re-import ast-from typing import Dict, List, Any, AsyncGenerator, Union, Optional, Tuple+from ctypes import castfrom io import BytesIO-from PIL import Image+from typing import Any, AsyncGenerator, Dict, List, Optional, Tuple, Union+import litellm-from litellm.types.utils import ModelResponse-from litellm.responses.litellm_completion_transformation.transformation import LiteLLMCompletionResponsesConfig+from litellm.responses.litellm_completion_transformation.transformation import (+ LiteLLMCompletionResponsesConfig,+)from litellm.responses.utils import Usage-from openai.types.responses.response_computer_tool_call_param import ActionType, ResponseComputerToolCallParam+from litellm.types.utils import ModelResponse+from openai.types.responses.response_computer_tool_call_param import (+ ActionType,+ ResponseComputerToolCallParam,+)from openai.types.responses.response_input_param import ComputerCallOutput-from openai.types.responses.response_output_message_param import ResponseOutputMessageParam-from openai.types.responses.response_reasoning_item_param import ResponseReasoningItemParam, Summary+from openai.types.responses.response_output_message_param import (+ ResponseOutputMessageParam,+)+from openai.types.responses.response_reasoning_item_param import (+ ResponseReasoningItemParam,+ Summary,+)+from PIL import Imagefrom ..decorators import register_agent-from ..types import Messages, AgentResponse, Tools, AgentCapabilityfrom ..responses import (- make_reasoning_item,- make_output_text_item,make_click_item,make_double_click_item,make_drag_item,+ make_input_image_item,make_keypress_item,+ make_output_text_item,+ make_reasoning_item,make_scroll_item,make_type_item,make_wait_item,- make_input_image_item)+from ..types import AgentCapability, AgentResponse, Messages, Tools# Constants from reference codeIMAGE_FACTOR = 28@@ -94,6 +105,7 @@ click(point='<|box_start|>(x1,y1)<|box_end|>')## User Instruction{instruction}"""+def round_by_factor(number: float, factor: int) -> int:"""Returns the closest integer to 'number' that is divisible by 'factor'."""return round(number / factor) * factor@@ -110,7 +122,11 @@ def floor_by_factor(number: float, factor: int) -> int:def smart_resize(- height: int, width: int, factor: int = IMAGE_FACTOR, min_pixels: int = MIN_PIXELS, max_pixels: int = MAX_PIXELS+ height: int,+ width: int,+ factor: int = IMAGE_FACTOR,+ min_pixels: int = MIN_PIXELS,+ max_pixels: int = MAX_PIXELS,) -> tuple[int, int]:"""Rescales the image so that the following conditions are met:@@ -144,14 +160,14 @@ def escape_single_quotes(text):def parse_action(action_str):"""Parse action string into structured format."""try:- node = ast.parse(action_str, mode='eval')+ node = ast.parse(action_str, mode="eval")if not isinstance(node, ast.Expression):raise ValueError("Not an expression")-+call = node.bodyif not isinstance(call, ast.Call):raise ValueError("Not a function call")-+# Get function nameif isinstance(call.func, ast.Name):func_name = call.func.id@@ -159,7 +175,7 @@ def parse_action(action_str):func_name = call.func.attrelse:func_name = None-+# Get keyword argumentskwargs = {}for kw in call.keywords:@@ -171,12 +187,9 @@ def parse_action(action_str):else:value = Nonekwargs[key] = value-- return {- 'function': func_name,- 'args': kwargs- }-++ return {"function": func_name, "args": kwargs}+except Exception as e:print(f"Failed to parse action '{action_str}': {e}")return None@@ -185,39 +198,39 @@ def parse_action(action_str):def parse_uitars_response(text: str, image_width: int, image_height: int) -> List[Dict[str, Any]]:"""Parse UITARS model response into structured actions."""text = text.strip()-+# Extract thoughtthought = Noneif text.startswith("Thought:"):thought_match = re.search(r"Thought: (.+?)(?=\s*Action:|$)", text, re.DOTALL)if thought_match:thought = thought_match.group(1).strip()-+# Extract actionif "Action:" not in text:raise ValueError("No Action found in response")-+action_str = text.split("Action:")[-1].strip()# Handle special case for type actionsif "type(content" in action_str:+def escape_quotes(match):return match.group(1)-+pattern = r"type\(content='(.*?)'\)"content = re.sub(pattern, escape_quotes, action_str)action_str = escape_single_quotes(content)action_str = "type(content='" + action_str + "')"--+# Parse the actionparsed_action = parse_action(action_str.replace("\n", "\\n").lstrip())if parsed_action is None:raise ValueError(f"Action can't parse: {action_str}")-+action_type = parsed_action["function"]params = parsed_action["args"]-+# Process parametersaction_inputs = {}for param_name, param in params.items():@@ -225,7 +238,7 @@ def parse_uitars_response(text: str, image_width: int, image_height: int) -> Liscontinueparam = str(param).lstrip()action_inputs[param_name.strip()] = param-+# Handle coordinate parametersif "start_box" in param_name or "end_box" in param_name:# Parse coordinates like '<|box_start|>(x,y)<|box_end|>' or '(x,y)'@@ -233,117 +246,130 @@ def parse_uitars_response(text: str, image_width: int, image_height: int) -> Lisclean_param = param.replace("<|box_start|>", "").replace("<|box_end|>", "")# Then remove parentheses and splitnumbers = clean_param.replace("(", "").replace(")", "").split(",")-+try:- float_numbers = [float(num.strip()) / 1000 for num in numbers] # Normalize to 0-1 range-+ float_numbers = [+ float(num.strip()) / 1000 for num in numbers+ ] # Normalize to 0-1 range+if len(float_numbers) == 2:# Single point, duplicate for box format- float_numbers = [float_numbers[0], float_numbers[1], float_numbers[0], float_numbers[1]]-+ float_numbers = [+ float_numbers[0],+ float_numbers[1],+ float_numbers[0],+ float_numbers[1],+ ]+action_inputs[param_name.strip()] = str(float_numbers)except ValueError as e:# If parsing fails, keep the original parameter valueprint(f"Warning: Could not parse coordinates '{param}': {e}")action_inputs[param_name.strip()] = param-- return [{- "thought": thought,- "action_type": action_type,- "action_inputs": action_inputs,- "text": text- }]++ return [+ {+ "thought": thought,+ "action_type": action_type,+ "action_inputs": action_inputs,+ "text": text,+ }+ ]-def convert_to_computer_actions(parsed_responses: List[Dict[str, Any]], image_width: int, image_height: int) -> List[ResponseComputerToolCallParam | ResponseOutputMessageParam]:+def convert_to_computer_actions(+ parsed_responses: List[Dict[str, Any]], image_width: int, image_height: int+) -> List[ResponseComputerToolCallParam | ResponseOutputMessageParam]:"""Convert parsed UITARS responses to computer actions."""computer_actions = []-+for response in parsed_responses:action_type = response.get("action_type")action_inputs = response.get("action_inputs", {})-+if action_type == "finished":finished_text = action_inputs.get("content", "Task completed successfully.")computer_actions.append(make_output_text_item(finished_text))break-+elif action_type == "wait":computer_actions.append(make_wait_item())-+elif action_type == "call_user":- computer_actions.append(make_output_text_item("I need assistance from the user to proceed with this task."))-+ computer_actions.append(+ make_output_text_item("I need assistance from the user to proceed with this task.")+ )+elif action_type in ["click", "left_single"]:start_box = action_inputs.get("start_box")if start_box:coords = eval(start_box)x = int((coords[0] + coords[2]) / 2 * image_width)y = int((coords[1] + coords[3]) / 2 * image_height)-+computer_actions.append(make_click_item(x, y, "left"))-+elif action_type == "double_click":start_box = action_inputs.get("start_box")if start_box:coords = eval(start_box)x = int((coords[0] + coords[2]) / 2 * image_width)y = int((coords[1] + coords[3]) / 2 * image_height)-+computer_actions.append(make_double_click_item(x, y))-+elif action_type == "right_click":start_box = action_inputs.get("start_box")if start_box:coords = eval(start_box)x = int((coords[0] + coords[2]) / 2 * image_width)y = int((coords[1] + coords[3]) / 2 * image_height)-+computer_actions.append(make_click_item(x, y, "right"))-+elif action_type == "type":content = action_inputs.get("content", "")computer_actions.append(make_type_item(content))-+elif action_type == "hotkey":key = action_inputs.get("key", "")keys = key.split()computer_actions.append(make_keypress_item(keys))-+elif action_type == "press":key = action_inputs.get("key", "")computer_actions.append(make_keypress_item([key]))-+elif action_type == "scroll":start_box = action_inputs.get("start_box")direction = action_inputs.get("direction", "down")-+if start_box:coords = eval(start_box)x = int((coords[0] + coords[2]) / 2 * image_width)y = int((coords[1] + coords[3]) / 2 * image_height)else:x, y = image_width // 2, image_height // 2-+scroll_y = 5 if "up" in direction.lower() else -5computer_actions.append(make_scroll_item(x, y, 0, scroll_y))-+elif action_type == "drag":start_box = action_inputs.get("start_box")end_box = action_inputs.get("end_box")-+if start_box and end_box:start_coords = eval(start_box)end_coords = eval(end_box)-+start_x = int((start_coords[0] + start_coords[2]) / 2 * image_width)start_y = int((start_coords[1] + start_coords[3]) / 2 * image_height)end_x = int((end_coords[0] + end_coords[2]) / 2 * image_width)end_y = int((end_coords[1] + end_coords[3]) / 2 * image_height)-+path = [{"x": start_x, "y": start_y}, {"x": end_x, "y": end_y}]computer_actions.append(make_drag_item(path))-+return computer_actions@@ -354,33 +380,35 @@ def pil_to_base64(image: Image.Image) -> str:return base64.b64encode(buffer.getvalue()).decode("utf-8")-def process_image_for_uitars(image_data: str, max_pixels: int = MAX_PIXELS, min_pixels: int = MIN_PIXELS) -> tuple[Image.Image, int, int]:+def process_image_for_uitars(+ image_data: str, max_pixels: int = MAX_PIXELS, min_pixels: int = MIN_PIXELS+) -> tuple[Image.Image, int, int]:"""Process image for UITARS model input."""# Decode base64 image- if image_data.startswith('data:image'):- image_data = image_data.split(',')[1]-+ if image_data.startswith("data:image"):+ image_data = image_data.split(",")[1]+image_bytes = base64.b64decode(image_data)image = Image.open(BytesIO(image_bytes))-+original_width, original_height = image.size-+# Resize image according to UITARS requirementsif image.width * image.height > max_pixels:resize_factor = math.sqrt(max_pixels / (image.width * image.height))width = int(image.width * resize_factor)height = int(image.height * resize_factor)image = image.resize((width, height))-+if image.width * image.height < min_pixels:resize_factor = math.sqrt(min_pixels / (image.width * image.height))width = math.ceil(image.width * resize_factor)height = math.ceil(image.height * resize_factor)image = image.resize((width, height))-+if image.mode != "RGB":image = image.convert("RGB")-+return image, original_width, original_height@@ -391,7 +419,11 @@ def sanitize_message(msg: Any) -> Any:for key, value in msg.items():if key == "content" and isinstance(value, list):result[key] = [- {k: v for k, v in item.items() if k != "image_url"} if isinstance(item, dict) else item+ (+ {k: v for k, v in item.items() if k != "image_url"}+ if isinstance(item, dict)+ else item+ )for item in value]else:@@ -406,38 +438,41 @@ def sanitize_message(msg: Any) -> Any:def convert_uitars_messages_to_litellm(messages: Messages) -> List[Dict[str, Any]]:"""Convert UITARS internal message format back to LiteLLM format.-+This function processes reasoning, computer_call, and computer_call_output messagesand converts them to the appropriate LiteLLM assistant message format.-+Args:messages: List of UITARS internal messages-+Returns:List of LiteLLM formatted messages"""litellm_messages = []current_assistant_content = []-+for message in messages:if isinstance(message, dict):message_type = message.get("type")-+if message_type == "reasoning":# Extract reasoning text from summarysummary = message.get("summary", [])if summary and isinstance(summary, list):for summary_item in summary:- if isinstance(summary_item, dict) and summary_item.get("type") == "summary_text":+ if (+ isinstance(summary_item, dict)+ and summary_item.get("type") == "summary_text"+ ):reasoning_text = summary_item.get("text", "")if reasoning_text:current_assistant_content.append(f"Thought: {reasoning_text}")-+elif message_type == "computer_call":# Convert computer action to UITARS action formataction = message.get("action", {})action_type = action.get("type")-+if action_type == "click":x, y = action.get("x", 0), action.get("y", 0)button = action.get("button", "left")@@ -447,59 +482,65 @@ def convert_uitars_messages_to_litellm(messages: Messages) -> List[Dict[str, Anyaction_text = f"Action: right_single(start_box='({x},{y})')"else:action_text = f"Action: click(start_box='({x},{y})')"-+elif action_type == "double_click":x, y = action.get("x", 0), action.get("y", 0)action_text = f"Action: left_double(start_box='({x},{y})')"-+elif action_type == "drag":start_x, start_y = action.get("start_x", 0), action.get("start_y", 0)end_x, end_y = action.get("end_x", 0), action.get("end_y", 0)action_text = f"Action: drag(start_box='({start_x},{start_y})', end_box='({end_x},{end_y})')"-+elif action_type == "key":key = action.get("key", "")action_text = f"Action: hotkey(key='{key}')"-+elif action_type == "type":text = action.get("text", "")# Escape single quotes in the textescaped_text = escape_single_quotes(text)action_text = f"Action: type(content='{escaped_text}')"-+elif action_type == "scroll":x, y = action.get("x", 0), action.get("y", 0)direction = action.get("direction", "down")action_text = f"Action: scroll(start_box='({x},{y})', direction='{direction}')"-+elif action_type == "wait":action_text = "Action: wait()"-+else:# Fallback for unknown action typesaction_text = f"Action: {action_type}({action})"-+current_assistant_content.append(action_text)-+# When we hit a computer_call_output, finalize the current assistant messageif current_assistant_content:- litellm_messages.append({- "role": "assistant",- "content": [{"type": "text", "text": "\n".join(current_assistant_content)}]- })+ litellm_messages.append(+ {+ "role": "assistant",+ "content": [+ {"type": "text", "text": "\n".join(current_assistant_content)}+ ],+ }+ )current_assistant_content = []-+elif message_type == "computer_call_output":# Add screenshot from computer call outputoutput = message.get("output", {})if isinstance(output, dict) and output.get("type") == "input_image":image_url = output.get("image_url", "")if image_url:- litellm_messages.append({- "role": "user",- "content": [{"type": "image_url", "image_url": {"url": image_url}}]- })-+ litellm_messages.append(+ {+ "role": "user",+ "content": [{"type": "image_url", "image_url": {"url": image_url}}],+ }+ )+elif message.get("role") == "user":# # Handle user messages# content = message.get("content", "")@@ -514,24 +555,22 @@ def convert_uitars_messages_to_litellm(messages: Messages) -> List[Dict[str, Any# "content": content# })pass-+# Add any remaining assistant contentif current_assistant_content:- litellm_messages.append({- "role": "assistant",- "content": current_assistant_content- })-+ litellm_messages.append({"role": "assistant", "content": current_assistant_content})+return litellm_messages+@register_agent(models=r"(?i).*ui-?tars.*")class UITARSConfig:"""UITARS agent configuration using liteLLM for ByteDance-Seed/UI-TARS-1.5-7B model.-+Supports UITARS vision-language models for computer control."""-+async def predict_step(self,messages: List[Dict[str, Any]],@@ -545,11 +584,11 @@ class UITARSConfig:_on_api_end=None,_on_usage=None,_on_screenshot=None,- **kwargs+ **kwargs,) -> Dict[str, Any]:"""Predict the next step based on input messages.-+Args:messages: Input messages following Responses formatmodel: Model name to use@@ -562,22 +601,22 @@ class UITARSConfig:_on_usage: Callback for usage tracking_on_screenshot: Callback for screenshot events**kwargs: Additional arguments-+Returns:Dictionary with "output" (output items) and "usage" array"""tools = tools or []-+# Create response itemsresponse_items = []-+# Find computer tool for screen dimensionscomputer_tool = Nonefor tool_schema in tools:if tool_schema["type"] == "computer":computer_tool = tool_schema["computer"]break-+# Get screen dimensionsscreen_width, screen_height = 1024, 768if computer_tool:@@ -585,20 +624,20 @@ class UITARSConfig:screen_width, screen_height = await computer_tool.get_dimensions()except:pass-+# Process messages to extract instruction and imageinstruction = ""image_data = None-+# Convert messages to list if stringif isinstance(messages, str):messages = [{"role": "user", "content": messages}]-+# Extract instruction and latest screenshotfor message in reversed(messages):if isinstance(message, dict):content = message.get("content", "")-+# Handle different content formatsif isinstance(content, str):if not instruction and message.get("role") == "user":@@ -614,46 +653,41 @@ class UITARSConfig:image_data = image_url.get("url", "")else:image_data = image_url-+# Also check for computer_call_output with screenshotsif message.get("type") == "computer_call_output" and not image_data:output = message.get("output", {})if isinstance(output, dict) and output.get("type") == "input_image":image_data = output.get("image_url", "")-+if instruction and image_data:break-+if not instruction:- instruction = "Help me complete this task by analyzing the screen and taking appropriate actions."-+ instruction = (+ "Help me complete this task by analyzing the screen and taking appropriate actions."+ )+# Create promptuser_prompt = UITARS_PROMPT_TEMPLATE.format(- instruction=instruction,- action_space=UITARS_ACTION_SPACE,- language="English"+ instruction=instruction, action_space=UITARS_ACTION_SPACE, language="English")-+# Convert conversation history to LiteLLM formathistory_messages = convert_uitars_messages_to_litellm(messages)-+# Prepare messages for liteLLM- litellm_messages = [- {- "role": "system",- "content": "You are a helpful assistant."- }- ]+ litellm_messages = [{"role": "system", "content": "You are a helpful assistant."}]# Add current user instruction with screenshotcurrent_user_message = {- "role": "user",+ "role": "user","content": [{"type": "text", "text": user_prompt},- ]+ ],}litellm_messages.append(current_user_message)-+# Process image for UITARSif not image_data:# Take screenshot if none found in messages@@ -667,17 +701,22 @@ class UITARSConfig:raise ValueError("No screenshot found in messages and no computer_handler provided")processed_image, original_width, original_height = process_image_for_uitars(image_data)encoded_image = pil_to_base64(processed_image)-+# Add conversation historyif history_messages:litellm_messages.extend(history_messages)else:- litellm_messages.append({- "role": "user",- "content": [- {"type": "image_url", "image_url": {"url": f"data:image/png;base64,{encoded_image}"}}- ]- })+ litellm_messages.append(+ {+ "role": "user",+ "content": [+ {+ "type": "image_url",+ "image_url": {"url": f"data:image/png;base64,{encoded_image}"},+ }+ ],+ }+ )# Prepare API call kwargsapi_kwargs = {@@ -687,146 +726,142 @@ class UITARSConfig:"temperature": kwargs.get("temperature", 0.0),"do_sample": kwargs.get("temperature", 0.0) > 0.0,"num_retries": max_retries,- **{k: v for k, v in kwargs.items() if k not in ["max_tokens", "temperature"]}+ **{k: v for k, v in kwargs.items() if k not in ["max_tokens", "temperature"]},}-+# Call API start hookif _on_api_start:await _on_api_start(api_kwargs)-+# Call liteLLM with UITARS modelresponse = await litellm.acompletion(**api_kwargs)-+# Call API end hookif _on_api_end:await _on_api_end(api_kwargs, response)-+# Extract response content- response_content = response.choices[0].message.content.strip() # type: ignore-+ response_content = response.choices[0].message.content.strip() # type: ignore+# Parse UITARS responseparsed_responses = parse_uitars_response(response_content, original_width, original_height)-+# Convert to computer actions- computer_actions = convert_to_computer_actions(parsed_responses, original_width, original_height)-+ computer_actions = convert_to_computer_actions(+ parsed_responses, original_width, original_height+ )+# Add computer actions to response itemsthought = parsed_responses[0].get("thought", "")if thought:response_items.append(make_reasoning_item(thought))response_items.extend(computer_actions)-+# Extract usage informationresponse_usage = {- **LiteLLMCompletionResponsesConfig._transform_chat_completion_usage_to_responses_usage(response.usage).model_dump(),+ **LiteLLMCompletionResponsesConfig._transform_chat_completion_usage_to_responses_usage(+ response.usage+ ).model_dump(),"response_cost": response._hidden_params.get("response_cost", 0.0),}if _on_usage:await _on_usage(response_usage)# Create agent response- agent_response = {- "output": response_items,- "usage": response_usage- }-+ agent_response = {"output": response_items, "usage": response_usage}+return agent_response-+async def predict_click(- self,- model: str,- image_b64: str,- instruction: str+ self, model: str, image_b64: str, instruction: str) -> Optional[Tuple[int, int]]:"""Predict click coordinates based on image and instruction.-+UITARS supports click prediction through its action parsing.-+Args:model: Model name to useimage_b64: Base64 encoded imageinstruction: Instruction for where to click-+Returns:Tuple with (x, y) coordinates or None"""try:# Create prompt using grounding template- user_prompt = GROUNDING_UITARS_PROMPT_TEMPLATE.format(- instruction=instruction- )-+ user_prompt = GROUNDING_UITARS_PROMPT_TEMPLATE.format(instruction=instruction)+# Process image for UITARSprocessed_image, original_width, original_height = process_image_for_uitars(image_b64)encoded_image = pil_to_base64(processed_image)-+# Prepare messages for liteLLMlitellm_messages = [- {- "role": "system",- "content": "You are a helpful assistant."- },+ {"role": "system", "content": "You are a helpful assistant."},{"role": "user","content": [{"type": "text", "text": user_prompt},- {"type": "image_url", "image_url": {"url": f"data:image/png;base64,{encoded_image}"}}- ]- }+ {+ "type": "image_url",+ "image_url": {"url": f"data:image/png;base64,{encoded_image}"},+ },+ ],+ },]-+# Prepare API call kwargsapi_kwargs = {"model": model,"messages": litellm_messages,"max_tokens": 2056,"temperature": 0.0,- "do_sample": False+ "do_sample": False,}-+# Call liteLLM with UITARS modelresponse = await litellm.acompletion(**api_kwargs)-+# Extract response content- response_content = response.choices[0].message.content.strip() # type: ignore-+ response_content = response.choices[0].message.content.strip() # type: ignore+print(response_content)# Parse the response to extract click coordinates# Look for click action with coordinates (with special tokens)click_pattern = r"click\(point='<\|box_start\|>\((\d+),(\d+)\)<\|box_end\|>'\)"match = re.search(click_pattern, response_content)-+# Fallback: Look for simpler format without special tokensif not match:# Pattern for: click(start_box='(x,y)') or click(point='(x,y)')fallback_pattern = r"click\((?:start_box|point)='\((\d+),(\d+)\)'\)"match = re.search(fallback_pattern, response_content)-+if match:x, y = int(match.group(1)), int(match.group(2))# Scale coordinates back to original image dimensionsscale_x = original_width / processed_image.widthscale_y = original_height / processed_image.height-+scaled_x = int(x * scale_x)scaled_y = int(y * scale_y)-+return (scaled_x, scaled_y)-+return None-+except Exception as e:# Log error and return Noneprint(f"Error in predict_click: {e}")return None-+def get_capabilities(self) -> List[AgentCapability]:"""Get list of capabilities supported by this agent config.-+Returns:List of capability strings"""- return ["step", "click"]\ No newline at end of file+ return ["step", "click"]diff --git a/libs/python/agent/agent/proxy/examples.py b/libs/python/agent/agent/proxy/examples.pyindex 2838c5dfd1..dfe6b87cce 100644--- a/libs/python/agent/agent/proxy/examples.py+++ b/libs/python/agent/agent/proxy/examples.py@@ -1,19 +1,22 @@"""Example usage of the proxy server and client requests."""+import dotenv+dotenv.load_dotenv()import asyncioimport jsonimport os+from typing import Any, Dict+import aiohttp-from typing import Dict, Anyasync def test_http_endpoint():"""Test the HTTP /responses endpoint."""-+anthropic_api_key = os.getenv("ANTHROPIC_API_KEY")assert isinstance(anthropic_api_key, str), "ANTHROPIC_API_KEY environment variable must be set"@@ -21,11 +24,9 @@ async def test_http_endpoint():simple_request = {"model": "anthropic/claude-3-5-sonnet-20241022","input": "Tell me a three sentence bedtime story about a unicorn.",- "env": {- "ANTHROPIC_API_KEY": anthropic_api_key- }+ "env": {"ANTHROPIC_API_KEY": anthropic_api_key},}-+# Example 2: Multi-modal request with imagemultimodal_request = {"model": "anthropic/claude-3-5-sonnet-20241022",@@ -36,70 +37,72 @@ async def test_http_endpoint():{"type": "input_text", "text": "what is in this image?"},{"type": "input_image",- "image_url": "https://upload.wikimedia.org/wikipedia/commons/thumb/d/dd/Gfp-wisconsin-madison-the-nature-boardwalk.jpg/2560px-Gfp-wisconsin-madison-the-nature-boardwalk.jpg"- }- ]+ "image_url": "https://upload.wikimedia.org/wikipedia/commons/thumb/d/dd/Gfp-wisconsin-madison-the-nature-boardwalk.jpg/2560px-Gfp-wisconsin-madison-the-nature-boardwalk.jpg",+ },+ ],}],- "env": {- "ANTHROPIC_API_KEY": anthropic_api_key- }+ "env": {"ANTHROPIC_API_KEY": anthropic_api_key},}-+# Example 3: Request with custom agent and computer kwargscustom_request = {"model": "anthropic/claude-3-5-sonnet-20241022","input": "Take a screenshot and tell me what you see",- "env": {- "ANTHROPIC_API_KEY": anthropic_api_key- }+ "env": {"ANTHROPIC_API_KEY": anthropic_api_key},}-+# Test requestsbase_url = "https://m-linux-96lcxd2c2k.containers.cloud.trycua.com:8443"# base_url = "http://localhost:8000"api_key = os.getenv("CUA_API_KEY")assert isinstance(api_key, str), "CUA_API_KEY environment variable must be set"-+async with aiohttp.ClientSession() as session:- for i, request_data in enumerate([- simple_request,- # multimodal_request,- custom_request- ], 1):+ for i, request_data in enumerate(+ [+ simple_request,+ # multimodal_request,+ custom_request,+ ],+ 1,+ ):print(f"\n--- Test {i} ---")print(f"Request: {json.dumps(request_data, indent=2)}")-+try:print(f"Sending request to {base_url}/responses")async with session.post(f"{base_url}/responses",json=request_data,- headers={"Content-Type": "application/json", "X-API-Key": api_key}+ headers={"Content-Type": "application/json", "X-API-Key": api_key},) as response:result = await response.json()print(f"Status: {response.status}")print(f"Response: {json.dumps(result, indent=2)}")-+except Exception as e:print(f"Error: {e}")def curl_examples():"""Print curl command examples."""-+print("=== CURL Examples ===\n")-+print("1. Simple text request:")- print("""curl http://localhost:8000/responses \\+ print(+ """curl http://localhost:8000/responses \\-H "Content-Type: application/json" \\-d '{"model": "anthropic/claude-3-5-sonnet-20241022","input": "Tell me a three sentence bedtime story about a unicorn."- }'""")-+ }'"""+ )+print("\n2. Multi-modal request with image:")- print("""curl http://localhost:8000/responses \\+ print(+ """curl http://localhost:8000/responses \\-H "Content-Type: application/json" \\-d '{"model": "anthropic/claude-3-5-sonnet-20241022",@@ -115,10 +118,12 @@ def curl_examples():]}]- }'""")-+ }'"""+ )+print("\n3. Request with custom configuration:")- print("""curl http://localhost:8000/responses \\+ print(+ """curl http://localhost:8000/responses \\-H "Content-Type: application/json" \\-d '{"model": "anthropic/claude-3-5-sonnet-20241022",@@ -131,50 +136,49 @@ def curl_examples():"os_type": "linux","provider_type": "cloud"}- }'""")+ }'"""+ )async def test_p2p_client():"""Example P2P client using peerjs-python."""try:- from peerjs import Peer, PeerOptions, ConnectionEventTypefrom aiortc import RTCConfiguration, RTCIceServer-+ from peerjs import ConnectionEventType, Peer, PeerOptions+# Set up client peeroptions = PeerOptions(host="0.peerjs.com",port=443,secure=True,- config=RTCConfiguration(- iceServers=[RTCIceServer(urls="stun:stun.l.google.com:19302")]- )+ config=RTCConfiguration(iceServers=[RTCIceServer(urls="stun:stun.l.google.com:19302")]),)-+client_peer = Peer(id="test-client", peer_options=options)await client_peer.start()-+# Connect to proxy serverconnection = client_peer.connect("computer-agent-proxy")-+@connection.on(ConnectionEventType.Open)async def connection_open():print("Connected to proxy server")-+# Send a test requestrequest = {"model": "anthropic/claude-3-5-sonnet-20241022",- "input": "Hello from P2P client!"+ "input": "Hello from P2P client!",}await connection.send(json.dumps(request))-+@connection.on(ConnectionEventType.Data)async def connection_data(data):print(f"Received response: {data}")await client_peer.destroy()-+# Wait for connectionawait asyncio.sleep(10)-+except ImportError:print("P2P dependencies not available. Install peerjs-python for P2P testing.")except Exception as e:@@ -183,7 +187,7 @@ async def test_p2p_client():if __name__ == "__main__":import sys-+if len(sys.argv) > 1 and sys.argv[1] == "curl":curl_examples()elif len(sys.argv) > 1 and sys.argv[1] == "p2p":diff --git a/libs/python/agent/agent/proxy/handlers.py b/libs/python/agent/agent/proxy/handlers.pyindex f68952b098..52041579c7 100644--- a/libs/python/agent/agent/proxy/handlers.py+++ b/libs/python/agent/agent/proxy/handlers.py@@ -7,24 +7,25 @@ import jsonimport loggingimport osfrom contextlib import contextmanager-from typing import Dict, Any, List, Union, Optional+from typing import Any, Dict, List, Optional, Union-from ..agent import ComputerAgentfrom computer import Computer+from ..agent import ComputerAgent+logger = logging.getLogger(__name__)class ResponsesHandler:"""Handler for /responses endpoint that processes agent requests."""-+def __init__(self):self.computer = Noneself.agent = None# Simple in-memory cachesself._computer_cache: Dict[str, Any] = {}self._agent_cache: Dict[str, Any] = {}-+async def setup_computer_agent(self,model: str,@@ -75,7 +76,9 @@ class ResponsesHandler:computer = Computer(**default_c_config)await computer.__aenter__()self._computer_cache[comp_key] = computer- logger.info(f"Computer created and cached with key={comp_key} config={default_c_config}")+ logger.info(+ f"Computer created and cached with key={comp_key} config={default_c_config}"+ )else:logger.info(f"Reusing cached computer for key={comp_key}")@@ -115,14 +118,14 @@ class ResponsesHandler:# Bind current agent referenceself.agent = agent-+async def process_request(self, request_data: Dict[str, Any]) -> Dict[str, Any]:"""Process a /responses request and return the result.-+Args:request_data: Dictionary containing model, input, and optional kwargs-+Returns:Dictionary with the agent's response"""@@ -133,12 +136,12 @@ class ResponsesHandler:agent_kwargs = request_data.get("agent_kwargs", {})computer_kwargs = request_data.get("computer_kwargs", {})env_overrides = request_data.get("env", {}) or {}-+if not model:raise ValueError("Model is required")if not input_data:raise ValueError("Input is required")-+# Apply env overrides for the duration of this requestwith self._env_overrides(env_overrides):# Set up (and possibly reuse) computer and agent via caches@@ -155,28 +158,22 @@ class ResponsesHandler:# Run agent and get first resultasync for result in agent.run(messages):# Return the first result and break- return {- "success": True,- "result": result,- "model": model- }-+ return {"success": True, "result": result, "model": model}+# If no results were yielded- return {- "success": False,- "error": "No results from agent",- "model": model- }-+ return {"success": False, "error": "No results from agent", "model": model}+except Exception as e:logger.error(f"Error processing request: {e}")return {"success": False,"error": str(e),- "model": request_data.get("model", "unknown")+ "model": request_data.get("model", "unknown"),}-- def _convert_input_to_messages(self, input_data: Union[str, List[Dict[str, Any]]]) -> List[Dict[str, Any]]:++ def _convert_input_to_messages(+ self, input_data: Union[str, List[Dict[str, Any]]]+ ) -> List[Dict[str, Any]]:"""Convert input data to messages format."""if isinstance(input_data, str):# Simple string input@@ -192,22 +189,18 @@ class ResponsesHandler:if part.get("type") == "input_text":content_parts.append({"type": "text", "text": part["text"]})elif part.get("type") == "input_image":- content_parts.append({- "type": "image_url",- "image_url": {"url": part["image_url"]}- })+ content_parts.append(+ {"type": "image_url", "image_url": {"url": part["image_url"]}}+ )else:content_parts.append(part)- messages.append({- "role": msg["role"],- "content": content_parts- })+ messages.append({"role": msg["role"], "content": content_parts})else:messages.append(msg)return messageselse:raise ValueError("Input must be string or list of messages")-+async def cleanup(self):"""Clean up resources."""if self.computer:diff --git a/libs/python/agent/agent/responses.py b/libs/python/agent/agent/responses.pyindex 34318bce88..bbb1975d7b 100644--- a/libs/python/agent/agent/responses.py+++ b/libs/python/agent/agent/responses.py@@ -6,10 +6,10 @@ Based on the OpenAI spec for Responses API items.import base64import jsonimport uuid-from typing import List, Dict, Any, Literal, Union, Optional+from typing import Any, Dict, List, Literal, Optional, Union+from openai.types.responses.easy_input_message_param import EasyInputMessageParamfrom openai.types.responses.response_computer_tool_call_param import (- ResponseComputerToolCallParam,ActionClick,ActionDoubleClick,ActionDrag,@@ -18,224 +18,222 @@ from openai.types.responses.response_computer_tool_call_param import (ActionMove,ActionScreenshot,ActionScroll,+)+from openai.types.responses.response_computer_tool_call_param import (ActionType as ActionTypeAction,+)+from openai.types.responses.response_computer_tool_call_param import (ActionWait,- PendingSafetyCheck+ PendingSafetyCheck,+ ResponseComputerToolCallParam,+)+from openai.types.responses.response_function_tool_call_param import (+ ResponseFunctionToolCallParam,)--from openai.types.responses.response_function_tool_call_param import ResponseFunctionToolCallParam-from openai.types.responses.response_output_text_param import ResponseOutputTextParam-from openai.types.responses.response_reasoning_item_param import ResponseReasoningItemParam, Summary-from openai.types.responses.response_output_message_param import ResponseOutputMessageParam-from openai.types.responses.easy_input_message_param import EasyInputMessageParamfrom openai.types.responses.response_input_image_param import ResponseInputImageParam+from openai.types.responses.response_output_message_param import (+ ResponseOutputMessageParam,+)+from openai.types.responses.response_output_text_param import ResponseOutputTextParam+from openai.types.responses.response_reasoning_item_param import (+ ResponseReasoningItemParam,+ Summary,+)+def random_id():return str(uuid.uuid4())+# User message itemsdef make_input_image_item(image_data: Union[str, bytes]) -> EasyInputMessageParam:return EasyInputMessageParam(content=[ResponseInputImageParam(type="input_image",- image_url=f"data:image/png;base64,{base64.b64encode(image_data).decode('utf-8') if isinstance(image_data, bytes) else image_data}"- ) # type: ignore+ image_url=f"data:image/png;base64,{base64.b64encode(image_data).decode('utf-8') if isinstance(image_data, bytes) else image_data}",+ ) # type: ignore],role="user",- type="message"+ type="message",)+# Text itemsdef make_reasoning_item(reasoning: str) -> ResponseReasoningItemParam:return ResponseReasoningItemParam(- id=random_id(),- summary=[- Summary(text=reasoning, type="summary_text")- ],- type="reasoning"+ id=random_id(), summary=[Summary(text=reasoning, type="summary_text")], type="reasoning")+def make_output_text_item(content: str) -> ResponseOutputMessageParam:return ResponseOutputMessageParam(id=random_id(),- content=[- ResponseOutputTextParam(- text=content,- type="output_text",- annotations=[]- )- ],+ content=[ResponseOutputTextParam(text=content, type="output_text", annotations=[])],role="assistant",status="completed",- type="message"+ type="message",)+# Function call items-def make_function_call_item(function_name: str, arguments: Dict[str, Any], call_id: Optional[str] = None) -> ResponseFunctionToolCallParam:+def make_function_call_item(+ function_name: str, arguments: Dict[str, Any], call_id: Optional[str] = None+) -> ResponseFunctionToolCallParam:return ResponseFunctionToolCallParam(id=random_id(),call_id=call_id if call_id else random_id(),name=function_name,arguments=json.dumps(arguments),status="completed",- type="function_call"+ type="function_call",)+# Computer tool call items-def make_click_item(x: int, y: int, button: Literal["left", "right", "wheel", "back", "forward"] = "left", call_id: Optional[str] = None) -> ResponseComputerToolCallParam:+def make_click_item(+ x: int,+ y: int,+ button: Literal["left", "right", "wheel", "back", "forward"] = "left",+ call_id: Optional[str] = None,+) -> ResponseComputerToolCallParam:return ResponseComputerToolCallParam(id=random_id(),call_id=call_id if call_id else random_id(),- action=ActionClick(- button=button,- type="click",- x=x,- y=y- ),+ action=ActionClick(button=button, type="click", x=x, y=y),pending_safety_checks=[],status="completed",- type="computer_call"+ type="computer_call",)-def make_double_click_item(x: int, y: int, call_id: Optional[str] = None) -> ResponseComputerToolCallParam:++def make_double_click_item(+ x: int, y: int, call_id: Optional[str] = None+) -> ResponseComputerToolCallParam:return ResponseComputerToolCallParam(id=random_id(),call_id=call_id if call_id else random_id(),- action=ActionDoubleClick(- type="double_click",- x=x,- y=y- ),+ action=ActionDoubleClick(type="double_click", x=x, y=y),pending_safety_checks=[],status="completed",- type="computer_call"+ type="computer_call",)-def make_drag_item(path: List[Dict[str, int]], call_id: Optional[str] = None) -> ResponseComputerToolCallParam:++def make_drag_item(+ path: List[Dict[str, int]], call_id: Optional[str] = None+) -> ResponseComputerToolCallParam:drag_path = [ActionDragPath(x=point["x"], y=point["y"]) for point in path]return ResponseComputerToolCallParam(id=random_id(),call_id=call_id if call_id else random_id(),- action=ActionDrag(- path=drag_path,- type="drag"- ),+ action=ActionDrag(path=drag_path, type="drag"),pending_safety_checks=[],status="completed",- type="computer_call"+ type="computer_call",)-def make_keypress_item(keys: List[str], call_id: Optional[str] = None) -> ResponseComputerToolCallParam:++def make_keypress_item(+ keys: List[str], call_id: Optional[str] = None+) -> ResponseComputerToolCallParam:return ResponseComputerToolCallParam(id=random_id(),call_id=call_id if call_id else random_id(),- action=ActionKeypress(- keys=keys,- type="keypress"- ),+ action=ActionKeypress(keys=keys, type="keypress"),pending_safety_checks=[],status="completed",- type="computer_call"+ type="computer_call",)+def make_move_item(x: int, y: int, call_id: Optional[str] = None) -> ResponseComputerToolCallParam:return ResponseComputerToolCallParam(id=random_id(),call_id=call_id if call_id else random_id(),- action=ActionMove(- type="move",- x=x,- y=y- ),+ action=ActionMove(type="move", x=x, y=y),pending_safety_checks=[],status="completed",- type="computer_call"+ type="computer_call",)+def make_screenshot_item(call_id: Optional[str] = None) -> ResponseComputerToolCallParam:return ResponseComputerToolCallParam(id=random_id(),call_id=call_id if call_id else random_id(),- action=ActionScreenshot(- type="screenshot"- ),+ action=ActionScreenshot(type="screenshot"),pending_safety_checks=[],status="completed",- type="computer_call"+ type="computer_call",)-def make_scroll_item(x: int, y: int, scroll_x: int, scroll_y: int, call_id: Optional[str] = None) -> ResponseComputerToolCallParam:++def make_scroll_item(+ x: int, y: int, scroll_x: int, scroll_y: int, call_id: Optional[str] = None+) -> ResponseComputerToolCallParam:return ResponseComputerToolCallParam(id=random_id(),call_id=call_id if call_id else random_id(),- action=ActionScroll(- scroll_x=scroll_x,- scroll_y=scroll_y,- type="scroll",- x=x,- y=y- ),+ action=ActionScroll(scroll_x=scroll_x, scroll_y=scroll_y, type="scroll", x=x, y=y),pending_safety_checks=[],status="completed",- type="computer_call"+ type="computer_call",)+def make_type_item(text: str, call_id: Optional[str] = None) -> ResponseComputerToolCallParam:return ResponseComputerToolCallParam(id=random_id(),call_id=call_id if call_id else random_id(),- action=ActionTypeAction(- text=text,- type="type"- ),+ action=ActionTypeAction(text=text, type="type"),pending_safety_checks=[],status="completed",- type="computer_call"+ type="computer_call",)+def make_wait_item(call_id: Optional[str] = None) -> ResponseComputerToolCallParam:return ResponseComputerToolCallParam(id=random_id(),call_id=call_id if call_id else random_id(),- action=ActionWait(- type="wait"- ),+ action=ActionWait(type="wait"),pending_safety_checks=[],status="completed",- type="computer_call"+ type="computer_call",)+# Extra anthropic computer calls-def make_left_mouse_down_item(x: Optional[int] = None, y: Optional[int] = None, call_id: Optional[str] = None) -> Dict[str, Any]:+def make_left_mouse_down_item(+ x: Optional[int] = None, y: Optional[int] = None, call_id: Optional[str] = None+) -> Dict[str, Any]:return {"id": random_id(),"call_id": call_id if call_id else random_id(),- "action": {- "type": "left_mouse_down",- "x": x,- "y": y- },+ "action": {"type": "left_mouse_down", "x": x, "y": y},"pending_safety_checks": [],"status": "completed",- "type": "computer_call"+ "type": "computer_call",}-def make_left_mouse_up_item(x: Optional[int] = None, y: Optional[int] = None, call_id: Optional[str] = None) -> Dict[str, Any]:++def make_left_mouse_up_item(+ x: Optional[int] = None, y: Optional[int] = None, call_id: Optional[str] = None+) -> Dict[str, Any]:return {"id": random_id(),"call_id": call_id if call_id else random_id(),- "action": {- "type": "left_mouse_up",- "x": x,- "y": y- },+ "action": {"type": "left_mouse_up", "x": x, "y": y},"pending_safety_checks": [],"status": "completed",- "type": "computer_call"+ "type": "computer_call",}-def make_failed_tool_call_items(tool_name: str, tool_kwargs: Dict[str, Any], error_message: str, call_id: Optional[str] = None) -> List[Dict[str, Any]]:++def make_failed_tool_call_items(+ tool_name: str, tool_kwargs: Dict[str, Any], error_message: str, call_id: Optional[str] = None+) -> List[Dict[str, Any]]:call_id = call_id if call_id else random_id()return [{@@ -249,9 +247,10 @@ def make_failed_tool_call_items(tool_name: str, tool_kwargs: Dict[str, Any], err"type": "function_call_output","call_id": call_id,"output": json.dumps({"error": error_message}),- }+ },]+def make_tool_error_item(error_message: str, call_id: Optional[str] = None) -> Dict[str, Any]:call_id = call_id if call_id else random_id()return {@@ -260,12 +259,15 @@ def make_tool_error_item(error_message: str, call_id: Optional[str] = None) -> D"output": json.dumps({"error": error_message}),}-def replace_failed_computer_calls_with_function_calls(messages: List[Dict[str, Any]]) -> List[Dict[str, Any]]:++def replace_failed_computer_calls_with_function_calls(+ messages: List[Dict[str, Any]],+) -> List[Dict[str, Any]]:"""Replace computer_call items with function_call items if they share a call_id with a function_call_output.This indicates the computer call failed and should be treated as a function call instead.We do this because the computer_call_output items do not support text output.-+Args:messages: List of message items to process"""@@ -278,16 +280,15 @@ def replace_failed_computer_calls_with_function_calls(messages: List[Dict[str, Acall_id = msg.get("call_id")if call_id:failed_call_ids.add(call_id)-+# Replace computer_call items that have matching call_idsfor i, msg in enumerate(messages):- if (msg.get("type") == "computer_call" and- msg.get("call_id") in failed_call_ids):-+ if msg.get("type") == "computer_call" and msg.get("call_id") in failed_call_ids:+# Extract action from computer_callaction = msg.get("action", {})call_id = msg.get("call_id")-+# Create function_call replacementmessages[i] = {"type": "function_call",@@ -296,27 +297,30 @@ def replace_failed_computer_calls_with_function_calls(messages: List[Dict[str, A"name": "computer","arguments": json.dumps(action),}-+return messages+# Conversion functions between element descriptions and coordinates-def convert_computer_calls_desc2xy(responses_items: List[Dict[str, Any]], desc2xy: Dict[str, tuple]) -> List[Dict[str, Any]]:+def convert_computer_calls_desc2xy(+ responses_items: List[Dict[str, Any]], desc2xy: Dict[str, tuple]+) -> List[Dict[str, Any]]:"""Convert computer calls from element descriptions to x,y coordinates.-+Args:responses_items: List of response items containing computer calls with element_descriptiondesc2xy: Dictionary mapping element descriptions to (x, y) coordinate tuples-+Returns:List of response items with element_description replaced by x,y coordinates"""converted_items = []-+for item in responses_items:if item.get("type") == "computer_call" and "action" in item:action = item["action"].copy()-+# Handle single element_descriptionif "element_description" in action:desc = action["element_description"]@@ -325,48 +329,50 @@ def convert_computer_calls_desc2xy(responses_items: List[Dict[str, Any]], desc2xaction["x"] = xaction["y"] = ydel action["element_description"]-+# Handle start_element_description and end_element_description for drag operationselif "start_element_description" in action and "end_element_description" in action:start_desc = action["start_element_description"]end_desc = action["end_element_description"]-+if start_desc in desc2xy and end_desc in desc2xy:start_x, start_y = desc2xy[start_desc]end_x, end_y = desc2xy[end_desc]action["path"] = [{"x": start_x, "y": start_y}, {"x": end_x, "y": end_y}]del action["start_element_description"]del action["end_element_description"]-+converted_item = item.copy()converted_item["action"] = actionconverted_items.append(converted_item)else:converted_items.append(item)-+return converted_items-def convert_computer_calls_xy2desc(responses_items: List[Dict[str, Any]], desc2xy: Dict[str, tuple]) -> List[Dict[str, Any]]:+def convert_computer_calls_xy2desc(+ responses_items: List[Dict[str, Any]], desc2xy: Dict[str, tuple]+) -> List[Dict[str, Any]]:"""Convert computer calls from x,y coordinates to element descriptions.-+Args:responses_items: List of response items containing computer calls with x,y coordinatesdesc2xy: Dictionary mapping element descriptions to (x, y) coordinate tuples-+Returns:List of response items with x,y coordinates replaced by element_description"""# Create reverse mapping from coordinates to descriptionsxy2desc = {coords: desc for desc, coords in desc2xy.items()}-+converted_items = []-+for item in responses_items:if item.get("type") == "computer_call" and "action" in item:action = item["action"].copy()-+# Handle single x,y coordinatesif "x" in action and "y" in action:coords = (action["x"], action["y"])@@ -374,77 +380,83 @@ def convert_computer_calls_xy2desc(responses_items: List[Dict[str, Any]], desc2xaction["element_description"] = xy2desc[coords]del action["x"]del action["y"]-+# Handle path for drag operationselif "path" in action and isinstance(action["path"], list) and len(action["path"]) == 2:start_point = action["path"][0]end_point = action["path"][1]-- if ("x" in start_point and "y" in start_point and- "x" in end_point and "y" in end_point):-++ if (+ "x" in start_point+ and "y" in start_point+ and "x" in end_point+ and "y" in end_point+ ):+start_coords = (start_point["x"], start_point["y"])end_coords = (end_point["x"], end_point["y"])-+if start_coords in xy2desc and end_coords in xy2desc:action["start_element_description"] = xy2desc[start_coords]action["end_element_description"] = xy2desc[end_coords]del action["path"]-+converted_item = item.copy()converted_item["action"] = actionconverted_items.append(converted_item)else:converted_items.append(item)-+return converted_itemsdef get_all_element_descriptions(responses_items: List[Dict[str, Any]]) -> List[str]:"""Extract all element descriptions from computer calls in responses items.-+Args:responses_items: List of response items containing computer calls-+Returns:List of unique element descriptions found in computer calls"""descriptions = set()-+for item in responses_items:if item.get("type") == "computer_call" and "action" in item:action = item["action"]-+# Handle single element_descriptionif "element_description" in action:descriptions.add(action["element_description"])-+# Handle start_element_description and end_element_description for drag operationsif "start_element_description" in action:descriptions.add(action["start_element_description"])-+if "end_element_description" in action:descriptions.add(action["end_element_description"])-+return list(descriptions)# Conversion functions between responses_items and completion messages formats-def convert_responses_items_to_completion_messages(messages: List[Dict[str, Any]], allow_images_in_tool_results: bool = True) -> List[Dict[str, Any]]:+def convert_responses_items_to_completion_messages(+ messages: List[Dict[str, Any]], allow_images_in_tool_results: bool = True+) -> List[Dict[str, Any]]:"""Convert responses_items message format to liteLLM completion format.-+Args:messages: List of responses_items format messagesallow_images_in_tool_results: If True, include images in tool role messages.If False, send tool message + separate user message with image."""completion_messages = []-+for message in messages:msg_type = message.get("type")role = message.get("role")-+# Handle user messages (both with and without explicit type)if role == "user" or msg_type == "user":content = message.get("content", "")@@ -453,34 +465,19 @@ def convert_responses_items_to_completion_messages(messages: List[Dict[str, Any]completion_content = []for item in content:if item.get("type") == "input_image":- completion_content.append({- "type": "image_url",- "image_url": {- "url": item.get("image_url")- }- })+ completion_content.append(+ {"type": "image_url", "image_url": {"url": item.get("image_url")}}+ )elif item.get("type") == "input_text":- completion_content.append({- "type": "text",- "text": item.get("text")- })+ completion_content.append({"type": "text", "text": item.get("text")})elif item.get("type") == "text":- completion_content.append({- "type": "text",- "text": item.get("text")- })-- completion_messages.append({- "role": "user",- "content": completion_content- })+ completion_content.append({"type": "text", "text": item.get("text")})++ completion_messages.append({"role": "user", "content": completion_content})elif isinstance(content, str):# Handle string content- completion_messages.append({- "role": "user",- "content": content- })-+ completion_messages.append({"role": "user", "content": content})+# Handle assistant messageselif role == "assistant" or msg_type == "message":content = message.get("content", [])@@ -491,13 +488,12 @@ def convert_responses_items_to_completion_messages(messages: List[Dict[str, Any]text_parts.append(item.get("text", ""))elif item.get("type") == "text":text_parts.append(item.get("text", ""))-+if text_parts:- completion_messages.append({- "role": "assistant",- "content": "\n".join(text_parts)- })-+ completion_messages.append(+ {"role": "assistant", "content": "\n".join(text_parts)}+ )+# Handle reasoning items (convert to assistant message)elif msg_type == "reasoning":summary = message.get("summary", [])@@ -505,107 +501,96 @@ def convert_responses_items_to_completion_messages(messages: List[Dict[str, Any]for item in summary:if item.get("type") == "summary_text":text_parts.append(item.get("text", ""))-+if text_parts:- completion_messages.append({- "role": "assistant",- "content": "\n".join(text_parts)- })-+ completion_messages.append({"role": "assistant", "content": "\n".join(text_parts)})+# Handle function callselif msg_type == "function_call":# Add tool call to last assistant message or create new oneif not completion_messages or completion_messages[-1]["role"] != "assistant":- completion_messages.append({- "role": "assistant",- "content": "",- "tool_calls": []- })-+ completion_messages.append({"role": "assistant", "content": "", "tool_calls": []})+if "tool_calls" not in completion_messages[-1]:completion_messages[-1]["tool_calls"] = []-- completion_messages[-1]["tool_calls"].append({- "id": message.get("call_id"),- "type": "function",- "function": {- "name": message.get("name"),- "arguments": message.get("arguments")++ completion_messages[-1]["tool_calls"].append(+ {+ "id": message.get("call_id"),+ "type": "function",+ "function": {+ "name": message.get("name"),+ "arguments": message.get("arguments"),+ },}- })-+ )+# Handle computer callselif msg_type == "computer_call":# Add tool call to last assistant message or create new oneif not completion_messages or completion_messages[-1]["role"] != "assistant":- completion_messages.append({- "role": "assistant",- "content": "",- "tool_calls": []- })-+ completion_messages.append({"role": "assistant", "content": "", "tool_calls": []})+if "tool_calls" not in completion_messages[-1]:completion_messages[-1]["tool_calls"] = []-+action = message.get("action", {})- completion_messages[-1]["tool_calls"].append({- "id": message.get("call_id"),- "type": "function",- "function": {- "name": "computer",- "arguments": json.dumps(action)+ completion_messages[-1]["tool_calls"].append(+ {+ "id": message.get("call_id"),+ "type": "function",+ "function": {"name": "computer", "arguments": json.dumps(action)},}- })-+ )+# Handle function/computer call outputselif msg_type in ["function_call_output", "computer_call_output"]:output = message.get("output")call_id = message.get("call_id")-+if isinstance(output, dict) and output.get("type") == "input_image":if allow_images_in_tool_results:# Handle image output as tool response (may not work with all APIs)- completion_messages.append({- "role": "tool",- "tool_call_id": call_id,- "content": [{- "type": "image_url",- "image_url": {- "url": output.get("image_url")- }- }]- })+ completion_messages.append(+ {+ "role": "tool",+ "tool_call_id": call_id,+ "content": [+ {"type": "image_url", "image_url": {"url": output.get("image_url")}}+ ],+ }+ )else:# Send tool message + separate user message with image (OpenAI compatible)- completion_messages += [{- "role": "tool",- "tool_call_id": call_id,- "content": "[Execution completed. See screenshot below]"- }, {- "role": "user",- "content": [{- "type": "image_url",- "image_url": {- "url": output.get("image_url")- }- }]- }]+ completion_messages += [+ {+ "role": "tool",+ "tool_call_id": call_id,+ "content": "[Execution completed. See screenshot below]",+ },+ {+ "role": "user",+ "content": [+ {"type": "image_url", "image_url": {"url": output.get("image_url")}}+ ],+ },+ ]else:# Handle text output as tool response- completion_messages.append({- "role": "tool",- "tool_call_id": call_id,- "content": str(output)- })-+ completion_messages.append(+ {"role": "tool", "tool_call_id": call_id, "content": str(output)}+ )+return completion_messages-def convert_completion_messages_to_responses_items(completion_messages: List[Dict[str, Any]]) -> List[Dict[str, Any]]:+def convert_completion_messages_to_responses_items(+ completion_messages: List[Dict[str, Any]],+) -> List[Dict[str, Any]]:"""Convert completion messages format to responses_items message format."""responses_items = []skip_next = False-+for i, message in enumerate(completion_messages):if skip_next:skip_next = False@@ -614,25 +599,24 @@ def convert_completion_messages_to_responses_items(completion_messages: List[Dicrole = message.get("role")content = message.get("content")tool_calls = message.get("tool_calls", [])-+# Handle assistant messages with text contentif role == "assistant" and content and isinstance(content, str):- responses_items.append({- "type": "message",- "role": "assistant",- "content": [{- "type": "output_text",- "text": content- }]- })-+ responses_items.append(+ {+ "type": "message",+ "role": "assistant",+ "content": [{"type": "output_text", "text": content}],+ }+ )+# Handle tool callsif tool_calls:for tool_call in tool_calls:if tool_call.get("type") == "function":function = tool_call.get("function", {})function_name = function.get("name")-+if function_name == "computer":# Parse computer actiontry:@@ -641,31 +625,37 @@ def convert_completion_messages_to_responses_items(completion_messages: List[Dicif action.get("action"):action["type"] = action["action"]del action["action"]- responses_items.append({- "type": "computer_call",- "call_id": tool_call.get("id"),- "action": action,- "status": "completed"- })+ responses_items.append(+ {+ "type": "computer_call",+ "call_id": tool_call.get("id"),+ "action": action,+ "status": "completed",+ }+ )except json.JSONDecodeError:# Fallback to function call format- responses_items.append({+ responses_items.append(+ {+ "type": "function_call",+ "call_id": tool_call.get("id"),+ "name": function_name,+ "arguments": function.get("arguments", "{}"),+ "status": "completed",+ }+ )+ else:+ # Regular function call+ responses_items.append(+ {"type": "function_call","call_id": tool_call.get("id"),"name": function_name,"arguments": function.get("arguments", "{}"),- "status": "completed"- })- else:- # Regular function call- responses_items.append({- "type": "function_call",- "call_id": tool_call.get("id"),- "name": function_name,- "arguments": function.get("arguments", "{}"),- "status": "completed"- })-+ "status": "completed",+ }+ )+# Handle tool messages (function/computer call outputs)elif role == "tool" and content:tool_call_id = message.get("tool_call_id")@@ -674,74 +664,90 @@ def convert_completion_messages_to_responses_items(completion_messages: List[Dicif content == "[Execution completed. See screenshot below]":# Look ahead for the next user message with imagenext_idx = i + 1- if (next_idx < len(completion_messages) and- completion_messages[next_idx].get("role") == "user" and- isinstance(completion_messages[next_idx].get("content"), list)):+ if (+ next_idx < len(completion_messages)+ and completion_messages[next_idx].get("role") == "user"+ and isinstance(completion_messages[next_idx].get("content"), list)+ ):# Found the pattern - extract image from next messagenext_content = completion_messages[next_idx]["content"]for item in next_content:if item.get("type") == "image_url":- responses_items.append({- "type": "computer_call_output",- "call_id": tool_call_id,- "output": {- "type": "input_image",- "image_url": item.get("image_url", {}).get("url")+ responses_items.append(+ {+ "type": "computer_call_output",+ "call_id": tool_call_id,+ "output": {+ "type": "input_image",+ "image_url": item.get("image_url", {}).get("url"),+ },}- })+ )# Skip the next user message since we processed itskip_next = Truebreakelse:# No matching user message, treat as regular text- responses_items.append({- "type": "computer_call_output",- "call_id": tool_call_id,- "output": content- })+ responses_items.append(+ {+ "type": "computer_call_output",+ "call_id": tool_call_id,+ "output": content,+ }+ )else:# Determine if this is a computer call or function call outputtry:# Try to parse as structured outputparsed_content = json.loads(content)if parsed_content.get("type") == "input_image":- responses_items.append({- "type": "computer_call_output",- "call_id": tool_call_id,- "output": parsed_content- })+ responses_items.append(+ {+ "type": "computer_call_output",+ "call_id": tool_call_id,+ "output": parsed_content,+ }+ )else:- responses_items.append({- "type": "computer_call_output",- "call_id": tool_call_id,- "output": content- })+ responses_items.append(+ {+ "type": "computer_call_output",+ "call_id": tool_call_id,+ "output": content,+ }+ )except json.JSONDecodeError:# Plain text output - could be function or computer call- responses_items.append({- "type": "function_call_output",- "call_id": tool_call_id,- "output": content- })+ responses_items.append(+ {+ "type": "function_call_output",+ "call_id": tool_call_id,+ "output": content,+ }+ )elif isinstance(content, list):# Handle structured content (e.g., images)for item in content:if item.get("type") == "image_url":- responses_items.append({- "type": "computer_call_output",- "call_id": tool_call_id,- "output": {- "type": "input_image",- "image_url": item.get("image_url", {}).get("url")+ responses_items.append(+ {+ "type": "computer_call_output",+ "call_id": tool_call_id,+ "output": {+ "type": "input_image",+ "image_url": item.get("image_url", {}).get("url"),+ },}- })+ )elif item.get("type") == "text":- responses_items.append({- "type": "function_call_output",- "call_id": tool_call_id,- "output": item.get("text")- })-+ responses_items.append(+ {+ "type": "function_call_output",+ "call_id": tool_call_id,+ "output": item.get("text"),+ }+ )+# Handle actual user messageselif role == "user" and content:if isinstance(content, list):@@ -749,27 +755,21 @@ def convert_completion_messages_to_responses_items(completion_messages: List[Dicuser_content = []for item in content:if item.get("type") == "image_url":- user_content.append({- "type": "input_image",- "image_url": item.get("image_url", {}).get("url")- })+ user_content.append(+ {+ "type": "input_image",+ "image_url": item.get("image_url", {}).get("url"),+ }+ )elif item.get("type") == "text":- user_content.append({- "type": "input_text",- "text": item.get("text")- })-+ user_content.append({"type": "input_text", "text": item.get("text")})+if user_content:- responses_items.append({- "role": "user",- "type": "message",- "content": user_content- })+ responses_items.append(+ {"role": "user", "type": "message", "content": user_content}+ )elif isinstance(content, str):# Handle simple text user message- responses_items.append({- "role": "user",- "content": content- })-+ responses_items.append({"role": "user", "content": content})+return responses_itemsdiff --git a/libs/python/agent/agent/types.py b/libs/python/agent/agent/types.pyindex f47c92861a..c28fb6b89e 100644--- a/libs/python/agent/agent/types.py+++ b/libs/python/agent/agent/types.py@@ -2,37 +2,43 @@Type definitions for agent"""-from typing import Dict, List, Any, Optional, Callable, Protocol, Literal-from pydantic import BaseModelimport re-from litellm import ResponseInputParam, ResponsesAPIResponse, ToolParamfrom collections.abc import Iterable+from typing import Any, Callable, Dict, List, Literal, Optional, Protocol++from litellm import ResponseInputParam, ResponsesAPIResponse, ToolParam+from pydantic import BaseModel# Agent input typesMessages = str | ResponseInputParam | List[Dict[str, Any]]Tools = Optional[Iterable[ToolParam]]# Agent output types-AgentResponse = ResponsesAPIResponse+AgentResponse = ResponsesAPIResponseAgentCapability = Literal["step", "click"]+# Exception typesclass ToolError(RuntimeError):"""Base exception for tool-related errors"""+pass+class IllegalArgumentError(ToolError):"""Exception raised when function arguments are invalid"""+pass# Agent config registrationclass AgentConfigInfo(BaseModel):"""Information about a registered agent config"""+agent_class: typemodels_regex: strpriority: int = 0-+def matches_model(self, model: str) -> bool:"""Check if this agent config matches the given model"""return bool(re.match(self.models_regex, model))diff --git a/libs/python/agent/agent/ui/__init__.py b/libs/python/agent/agent/ui/__init__.pyindex ae5ced7ab5..92b0bf6986 100644--- a/libs/python/agent/agent/ui/__init__.py+++ b/libs/python/agent/agent/ui/__init__.py@@ -2,6 +2,6 @@UI components for agent"""-from .gradio import launch_ui, create_gradio_ui+from .gradio import create_gradio_ui, launch_ui__all__ = ["launch_ui", "create_gradio_ui"]diff --git a/libs/python/agent/agent/ui/__main__.py b/libs/python/agent/agent/ui/__main__.pyindex 4ac782a584..f4bf2892ac 100644--- a/libs/python/agent/agent/ui/__main__.py+++ b/libs/python/agent/agent/ui/__main__.py@@ -1,4 +1,4 @@from .gradio import launch_uiif __name__ == "__main__":- launch_ui()\ No newline at end of file+ launch_ui()diff --git a/libs/python/agent/agent/ui/gradio/app.py b/libs/python/agent/agent/ui/gradio/app.pyindex 196194de18..1a2fb02397 100644--- a/libs/python/agent/agent/ui/gradio/app.py+++ b/libs/python/agent/agent/ui/gradio/app.py@@ -18,21 +18,21 @@ Requirements:- OpenAI or Anthropic API key"""-import osimport asyncio-import loggingimport json+import logging+import osimport platformfrom pathlib import Path-from typing import Dict, List, Optional, AsyncGenerator, Any, Tuple, Union+from typing import Any, AsyncGenerator, Dict, List, Optional, Tuple, Union, cast+import gradio as gr-from gradio.components.chatbot import MetadataDict-from typing import cast# Import from agent packagefrom agent import ComputerAgent-from agent.types import Messages, AgentResponse+from agent.types import AgentResponse, Messagesfrom computer import Computer+from gradio.components.chatbot import MetadataDict# Global variablesglobal_agent = None@@ -42,11 +42,13 @@ SETTINGS_FILE = Path(".gradio_settings.json")logging.basicConfig(level=logging.INFO)import dotenv+if dotenv.load_dotenv():print(f"DEBUG - Loaded environment variables from {dotenv.find_dotenv()}")else:print("DEBUG - No .env file found")+# --- Settings Load/Save Functions ---def load_settings() -> Dict[str, Any]:"""Loads settings from the JSON file."""@@ -84,7 +86,7 @@ def save_settings(settings: Dict[str, Any]):# async def on_screenshot(self, screenshot_base64: str, action_type: str = "") -> None:# """Add screenshot to chatbot when a screenshot is taken."""# image_markdown = f""-+# if self.chatbot_history is not None:# self.chatbot_history.append(# gr.ChatMessage(@@ -141,7 +143,7 @@ def get_model_string(model_name: str, loop_provider: str) -> str:ollama_model = model_name.split("OMNI: Ollama ", 1)[1]return f"omniparser+ollama_chat/{ollama_model}"return "omniparser+ollama_chat/llama3"-+# Map based on loop providermapping = MODEL_MAPPINGS.get(loop_provider.lower(), MODEL_MAPPINGS["openai"])return mapping.get(model_name, mapping["default"])@@ -151,6 +153,7 @@ def get_ollama_models() -> List[str]:"""Get available models from Ollama if installed."""try:import subprocess+result = subprocess.run(["ollama", "list"], capture_output=True, text=True)if result.returncode == 0:lines = result.stdout.strip().split("\n")@@ -174,16 +177,14 @@ def create_computer_instance(os_type: str = "macos",provider_type: str = "lume",name: Optional[str] = None,- api_key: Optional[str] = None+ api_key: Optional[str] = None,) -> Computer:"""Create or get the global Computer instance."""global global_computerif global_computer is None:if provider_type == "localhost":global_computer = Computer(- verbosity=verbosity,- os_type=os_type,- use_host_computer_server=True+ verbosity=verbosity, os_type=os_type, use_host_computer_server=True)else:global_computer = Computer(@@ -191,7 +192,7 @@ def create_computer_instance(os_type=os_type,provider_type=provider_type,name=name if name else "",- api_key=api_key+ api_key=api_key,)return global_computer@@ -217,7 +218,7 @@ def create_agent(os_type=computer_os,provider_type=computer_provider,name=computer_name,- api_key=computer_api_key+ api_key=computer_api_key,)# Handle custom models@@ -233,12 +234,15 @@ def create_agent("only_n_most_recent_images": only_n_most_recent_images,"verbosity": verbosity,}-+if save_trajectory:agent_kwargs["trajectory_dir"] = "trajectories"-+if max_trajectory_budget:- agent_kwargs["max_trajectory_budget"] = {"max_budget": max_trajectory_budget, "raise_error": True}+ agent_kwargs["max_trajectory_budget"] = {+ "max_budget": max_trajectory_budget,+ "raise_error": True,+ }global_agent = ComputerAgent(**agent_kwargs)return global_agent@@ -247,7 +251,8 @@ def create_agent(def launch_ui():"""Standalone function to launch the Gradio app."""from agent.ui.gradio.ui_components import create_gradio_ui- print(f"Starting Gradio app for CUA Agent...")++ print("Starting Gradio app for CUA Agent...")demo = create_gradio_ui()demo.launch(share=False, inbrowser=True)diff --git a/libs/python/agent/agent/ui/gradio/ui_components.py b/libs/python/agent/agent/ui/gradio/ui_components.pyindex d197919b70..d14f49a932 100644--- a/libs/python/agent/agent/ui/gradio/ui_components.py+++ b/libs/python/agent/agent/ui/gradio/ui_components.py@@ -2,19 +2,25 @@UI Components for the Gradio interface"""-import osimport asyncio-import loggingimport json+import logging+import osimport platformfrom pathlib import Path-from typing import Dict, List, Optional, Any, cast+from typing import Any, Dict, List, Optional, cast+import gradio as grfrom gradio.components.chatbot import MetadataDictfrom .app import (- load_settings, save_settings, create_agent, get_model_string,- get_ollama_models, global_agent, global_computer+ create_agent,+ get_model_string,+ get_ollama_models,+ global_agent,+ global_computer,+ load_settings,+ save_settings,)# Global messages array to maintain conversation history@@ -23,15 +29,15 @@ global_messages = []def create_gradio_ui() -> gr.Blocks:"""Create a Gradio UI for the Computer-Use Agent."""-+# Load settingssaved_settings = load_settings()-+# Check for API keysopenai_api_key = os.environ.get("OPENAI_API_KEY", "")anthropic_api_key = os.environ.get("ANTHROPIC_API_KEY", "")cua_api_key = os.environ.get("CUA_API_KEY", "")-+# Model choicesopenai_models = ["OpenAI: Computer-Use Preview"]anthropic_models = [@@ -43,10 +49,10 @@ def create_gradio_ui() -> gr.Blocks:omni_models = ["OMNI: OpenAI GPT-4o","OMNI: OpenAI GPT-4o mini",- "OMNI: Claude 3.7 Sonnet (20250219)",- "OMNI: Claude 3.5 Sonnet (20241022)"+ "OMNI: Claude 3.7 Sonnet (20250219)",+ "OMNI: Claude 3.5 Sonnet (20241022)",]-+# Check if API keys are availablehas_openai_key = bool(openai_api_key)has_anthropic_key = bool(anthropic_api_key)@@ -59,15 +65,20 @@ def create_gradio_ui() -> gr.Blocks:# Detect platformis_mac = platform.system().lower() == "darwin"-+# Format model choicesprovider_to_models = {"OPENAI": openai_models,"ANTHROPIC": anthropic_models,"OMNI": omni_models + ["Custom model (OpenAI compatible API)", "Custom model (ollama)"],- "UITARS": ([- "huggingface-local/ByteDance-Seed/UI-TARS-1.5-7B",- ] if is_mac else []) + ["Custom model (OpenAI compatible API)"],+ "UITARS": (+ [+ "huggingface-local/ByteDance-Seed/UI-TARS-1.5-7B",+ ]+ if is_mac+ else []+ )+ + ["Custom model (OpenAI compatible API)"],}# Apply saved settings@@ -82,7 +93,9 @@ def create_gradio_ui() -> gr.Blocks:elif initial_loop == "ANTHROPIC":initial_model = anthropic_models[0] if anthropic_models else "No models available"else: # OMNI- initial_model = omni_models[0] if omni_models else "Custom model (OpenAI compatible API)"+ initial_model = (+ omni_models[0] if omni_models else "Custom model (OpenAI compatible API)"+ )initial_custom_model = saved_settings.get("custom_model", "Qwen2.5-VL-7B-Instruct")initial_provider_base_url = saved_settings.get("provider_base_url", "http://localhost:1234/v1")@@ -96,16 +109,27 @@ def create_gradio_ui() -> gr.Blocks:"Open Safari, search for 'macOS automation tools', and save the first three results as bookmarks","Configure SSH keys and set up a connection to a remote server",]-- def generate_python_code(agent_loop_choice, model_name, tasks, recent_images=3, save_trajectory=True, computer_os="linux", computer_provider="cloud", container_name="", cua_cloud_api_key="", max_budget=None):++ def generate_python_code(+ agent_loop_choice,+ model_name,+ tasks,+ recent_images=3,+ save_trajectory=True,+ computer_os="linux",+ computer_provider="cloud",+ container_name="",+ cua_cloud_api_key="",+ max_budget=None,+ ):"""Generate Python code for the current configuration and tasks."""tasks_str = ""for task in tasks:if task and task.strip():tasks_str += f' "{task}",\n'-+model_string = get_model_string(model_name, agent_loop_choice)-+computer_args = []if computer_os != "macos":computer_args.append(f'os_type="{computer_os}"')@@ -115,14 +139,14 @@ def create_gradio_ui() -> gr.Blocks:computer_args.append(f'name="{container_name}"')if cua_cloud_api_key:computer_args.append(f'api_key="{cua_cloud_api_key}"')-+computer_args_str = ", ".join(computer_args)if computer_args_str:computer_args_str = f"({computer_args_str})"else:computer_args_str = "()"-- code = f'''import asyncio++ code = f"""import asynciofrom computer import Computerfrom agent import ComputerAgent@@ -131,22 +155,22 @@ async def main():agent = ComputerAgent(model="{model_string}",tools=[computer],- only_n_most_recent_images={recent_images},'''-+ only_n_most_recent_images={recent_images},"""+if save_trajectory:- code += '''- trajectory_dir="trajectories",'''-+ code += """+ trajectory_dir="trajectories","""+if max_budget:- code += f'''- max_trajectory_budget={{"max_budget": {max_budget}, "raise_error": True}},'''-- code += '''+ code += f"""+ max_trajectory_budget={{"max_budget": {max_budget}, "raise_error": True}},"""++ code += """)- '''-+ """+if tasks_str:- code += f'''+ code += f"""# Prompts for the computer-use agenttasks = [{tasks_str.rstrip()}@@ -158,23 +182,23 @@ async def main():async for result in agent.run(messages):for item in result["output"]:if item["type"] == "message":- print(item["content"][0]["text"])'''+ print(item["content"][0]["text"])"""else:- code += f'''+ code += """# Execute a single tasktask = "Search for information about CUA on GitHub"- print(f"Executing task: {{task}}")- messages = [{{"role": "user", "content": task}}]+ print(f"Executing task: {task}")+ messages = [{"role": "user", "content": task}]async for result in agent.run(messages):for item in result["output"]:if item["type"] == "message":- print(item["content"][0]["text"])'''+ print(item["content"][0]["text"])"""- code += '''+ code += """if __name__ == "__main__":- asyncio.run(main())'''-+ asyncio.run(main())"""+return code# Create the Gradio interface@@ -199,11 +223,11 @@ if __name__ == "__main__":value=generate_python_code(initial_loop, "gpt-4o", []),interactive=False,)-+with gr.Accordion("Computer Configuration", open=True):is_windows = platform.system().lower() == "windows"is_mac = platform.system().lower() == "darwin"-+providers = ["cloud", "localhost", "docker"]if is_mac:providers += ["lume"]@@ -227,30 +251,30 @@ if __name__ == "__main__":value=computer_choices[0],info="Select the operating system for the computer",)-+computer_provider = gr.Radio(choices=providers,label="Provider",value="lume" if is_mac else "cloud",info="Select the computer provider",)-+container_name = gr.Textbox(label="Container Name",placeholder="Enter container name (optional)",value=os.environ.get("CUA_CONTAINER_NAME", ""),info="Optional name for the container",)-+cua_cloud_api_key = gr.Textbox(label="CUA Cloud API Key",placeholder="Enter your CUA Cloud API key",value=os.environ.get("CUA_API_KEY", ""),type="password",info="Required for cloud provider",- visible=(not has_cua_key)+ visible=(not has_cua_key),)-+with gr.Accordion("Agent Configuration", open=True):agent_loop = gr.Dropdown(choices=["OPENAI", "ANTHROPIC", "OMNI", "UITARS"],@@ -267,90 +291,113 @@ if __name__ == "__main__":value=openai_models[0] if openai_models else "No models available",info="Select OpenAI model",interactive=True,- visible=(initial_loop == "OPENAI")+ visible=(initial_loop == "OPENAI"),)-+anthropic_model_choice = gr.Dropdown(choices=anthropic_models,label="Anthropic Model",- value=anthropic_models[0] if anthropic_models else "No models available",+ value=(+ anthropic_models[0] if anthropic_models else "No models available"+ ),info="Select Anthropic model",interactive=True,- visible=(initial_loop == "ANTHROPIC")+ visible=(initial_loop == "ANTHROPIC"),)-+omni_model_choice = gr.Dropdown(- choices=omni_models + ["Custom model (OpenAI compatible API)", "Custom model (ollama)"],+ choices=omni_models+ + ["Custom model (OpenAI compatible API)", "Custom model (ollama)"],label="OMNI Model",- value=omni_models[0] if omni_models else "Custom model (OpenAI compatible API)",+ value=(+ omni_models[0]+ if omni_models+ else "Custom model (OpenAI compatible API)"+ ),info="Select OMNI model or choose a custom model option",interactive=True,- visible=(initial_loop == "OMNI")+ visible=(initial_loop == "OMNI"),)-+uitars_model_choice = gr.Dropdown(choices=provider_to_models.get("UITARS", ["No models available"]),label="UITARS Model",- value=provider_to_models.get("UITARS", ["No models available"])[0] if provider_to_models.get("UITARS") else "No models available",+ value=(+ provider_to_models.get("UITARS", ["No models available"])[0]+ if provider_to_models.get("UITARS")+ else "No models available"+ ),info="Select UITARS model",interactive=True,- visible=(initial_loop == "UITARS")+ visible=(initial_loop == "UITARS"),)-+model_choice = gr.Textbox(visible=False)# API key inputs- with gr.Group(visible=not has_openai_key and (initial_loop == "OPENAI" or initial_loop == "OMNI")) as openai_key_group:+ with gr.Group(+ visible=not has_openai_key+ and (initial_loop == "OPENAI" or initial_loop == "OMNI")+ ) as openai_key_group:openai_api_key_input = gr.Textbox(label="OpenAI API Key",placeholder="Enter your OpenAI API key",value=os.environ.get("OPENAI_API_KEY", ""),interactive=True,type="password",- info="Required for OpenAI models"+ info="Required for OpenAI models",)-- with gr.Group(visible=not has_anthropic_key and (initial_loop == "ANTHROPIC" or initial_loop == "OMNI")) as anthropic_key_group:++ with gr.Group(+ visible=not has_anthropic_key+ and (initial_loop == "ANTHROPIC" or initial_loop == "OMNI")+ ) as anthropic_key_group:anthropic_api_key_input = gr.Textbox(label="Anthropic API Key",placeholder="Enter your Anthropic API key",value=os.environ.get("ANTHROPIC_API_KEY", ""),interactive=True,type="password",- info="Required for Anthropic models"+ info="Required for Anthropic models",)-+# API key handlersdef set_openai_api_key(key):if key and key.strip():os.environ["OPENAI_API_KEY"] = key.strip()- print(f"DEBUG - Set OpenAI API key environment variable")+ print("DEBUG - Set OpenAI API key environment variable")return key-+def set_anthropic_api_key(key):if key and key.strip():os.environ["ANTHROPIC_API_KEY"] = key.strip()- print(f"DEBUG - Set Anthropic API key environment variable")+ print("DEBUG - Set Anthropic API key environment variable")return key-+openai_api_key_input.change(fn=set_openai_api_key,inputs=[openai_api_key_input],outputs=[openai_api_key_input],- queue=False+ queue=False,)-+anthropic_api_key_input.change(fn=set_anthropic_api_key,inputs=[anthropic_api_key_input],outputs=[anthropic_api_key_input],- queue=False+ queue=False,)# UI update function- def update_ui(loop=None, openai_model=None, anthropic_model=None, omni_model=None, uitars_model=None):+ def update_ui(+ loop=None,+ openai_model=None,+ anthropic_model=None,+ omni_model=None,+ uitars_model=None,+ ):loop = loop or agent_loop.value-+model_value = Noneif loop == "OPENAI" and openai_model:model_value = openai_model@@ -360,21 +407,37 @@ if __name__ == "__main__":model_value = omni_modelelif loop == "UITARS" and uitars_model:model_value = uitars_model-- openai_visible = (loop == "OPENAI")- anthropic_visible = (loop == "ANTHROPIC")- omni_visible = (loop == "OMNI")- uitars_visible = (loop == "UITARS")-- show_openai_key = not has_openai_key and (loop == "OPENAI" or (loop == "OMNI" and model_value and "OpenAI" in model_value and "Custom" not in model_value))- show_anthropic_key = not has_anthropic_key and (loop == "ANTHROPIC" or (loop == "OMNI" and model_value and "Claude" in model_value and "Custom" not in model_value))-++ openai_visible = loop == "OPENAI"+ anthropic_visible = loop == "ANTHROPIC"+ omni_visible = loop == "OMNI"+ uitars_visible = loop == "UITARS"++ show_openai_key = not has_openai_key and (+ loop == "OPENAI"+ or (+ loop == "OMNI"+ and model_value+ and "OpenAI" in model_value+ and "Custom" not in model_value+ )+ )+ show_anthropic_key = not has_anthropic_key and (+ loop == "ANTHROPIC"+ or (+ loop == "OMNI"+ and model_value+ and "Claude" in model_value+ and "Custom" not in model_value+ )+ )+is_custom_openai_api = model_value == "Custom model (OpenAI compatible API)"is_custom_ollama = model_value == "Custom model (ollama)"is_any_custom = is_custom_openai_api or is_custom_ollama-+model_choice_value = model_value if model_value else ""-+return [gr.update(visible=openai_visible),gr.update(visible=anthropic_visible),@@ -385,15 +448,18 @@ if __name__ == "__main__":gr.update(visible=is_any_custom),gr.update(visible=is_custom_openai_api),gr.update(visible=is_custom_openai_api),- gr.update(value=model_choice_value)+ gr.update(value=model_choice_value),]-+# Custom model inputscustom_model = gr.Textbox(label="Custom Model Name",placeholder="Enter custom model name (e.g., Qwen2.5-VL-7B-Instruct or llama3)",value=initial_custom_model,- visible=(initial_model == "Custom model (OpenAI compatible API)" or initial_model == "Custom model (ollama)"),+ visible=(+ initial_model == "Custom model (OpenAI compatible API)"+ or initial_model == "Custom model (ollama)"+ ),interactive=True,)@@ -413,36 +479,56 @@ if __name__ == "__main__":interactive=True,type="password",)-+# Provider visibility update functiondef update_provider_visibility(provider):"""Update visibility of container name and API key based on selected provider."""is_localhost = provider == "localhost"return [gr.update(visible=not is_localhost), # container_name- gr.update(visible=not is_localhost and not has_cua_key) # cua_cloud_api_key+ gr.update(+ visible=not is_localhost and not has_cua_key+ ), # cua_cloud_api_key]-+# Connect provider change eventcomputer_provider.change(fn=update_provider_visibility,inputs=[computer_provider],outputs=[container_name, cua_cloud_api_key],- queue=False+ queue=False,)-+# Connect UI update events- for dropdown in [agent_loop, omni_model_choice, uitars_model_choice, openai_model_choice, anthropic_model_choice]:+ for dropdown in [+ agent_loop,+ omni_model_choice,+ uitars_model_choice,+ openai_model_choice,+ anthropic_model_choice,+ ]:dropdown.change(fn=update_ui,- inputs=[agent_loop, openai_model_choice, anthropic_model_choice, omni_model_choice, uitars_model_choice],+ inputs=[+ agent_loop,+ openai_model_choice,+ anthropic_model_choice,+ omni_model_choice,+ uitars_model_choice,+ ],outputs=[- openai_model_choice, anthropic_model_choice, omni_model_choice, uitars_model_choice,- openai_key_group, anthropic_key_group,- custom_model, provider_base_url, provider_api_key,- model_choice+ openai_model_choice,+ anthropic_model_choice,+ omni_model_choice,+ uitars_model_choice,+ openai_key_group,+ anthropic_key_group,+ custom_model,+ provider_base_url,+ provider_api_key,+ model_choice,],- queue=False+ queue=False,)save_trajectory = gr.Checkbox(@@ -461,7 +547,7 @@ if __name__ == "__main__":info="Number of recent images to keep in context",interactive=True,)-+max_budget = gr.Number(label="Max Budget ($)",value=lambda: None,@@ -479,9 +565,7 @@ if __name__ == "__main__":)chatbot_history = gr.Chatbot(type="messages")- msg = gr.Textbox(- placeholder="Ask me to perform tasks in a virtual environment"- )+ msg = gr.Textbox(placeholder="Ask me to perform tasks in a virtual environment")clear = gr.Button("Clear")cancel_button = gr.Button("Cancel", variant="stop")@@ -498,11 +582,23 @@ if __name__ == "__main__":global global_agentif global_agent:print("DEBUG - Cancelling agent task")- history.append(gr.ChatMessage(role="assistant", content="Task cancelled by user", metadata={"title": "❌ Cancelled"}))+ history.append(+ gr.ChatMessage(+ role="assistant",+ content="Task cancelled by user",+ metadata={"title": "❌ Cancelled"},+ )+ )else:- history.append(gr.ChatMessage(role="assistant", content="No active agent task to cancel", metadata={"title": "ℹ️ Info"}))+ history.append(+ gr.ChatMessage(+ role="assistant",+ content="No active agent task to cancel",+ metadata={"title": "ℹ️ Info"},+ )+ )return history-+# Process response functionasync def process_response(history,@@ -542,10 +638,13 @@ if __name__ == "__main__":model_choice_value = uitars_model_valueelse:model_choice_value = "No models available"-+# Determine if this is a custom model selection- is_custom_model_selected = model_choice_value in ["Custom model (OpenAI compatible API)", "Custom model (ollama)"]-+ is_custom_model_selected = model_choice_value in [+ "Custom model (OpenAI compatible API)",+ "Custom model (ollama)",+ ]+# Determine the model name string to analyzeif is_custom_model_selected:model_string_to_analyze = custom_model_value@@ -583,13 +682,19 @@ if __name__ == "__main__":model_string=model_string,save_trajectory=save_traj,only_n_most_recent_images=recent_imgs,- custom_model_name=custom_model_value if is_custom_model_selected else None,+ custom_model_name=(+ custom_model_value if is_custom_model_selected else None+ ),computer_os=computer_os,computer_provider=computer_provider,computer_name=container_name,computer_api_key=cua_cloud_api_key,verbosity=logging.DEBUG,- max_trajectory_budget=max_budget_value if max_budget_value and max_budget_value > 0 else None,+ max_trajectory_budget=(+ max_budget_value+ if max_budget_value and max_budget_value > 0+ else None+ ),)if global_agent is None:@@ -605,7 +710,7 @@ if __name__ == "__main__":# Add user message to global historyglobal global_messagesglobal_messages.append({"role": "user", "content": last_user_message})-+# Stream responses from the agentasync for result in global_agent.run(global_messages):global_messages += result.get("output", [])@@ -613,18 +718,20 @@ if __name__ == "__main__":# from pprint import pprint# pprint(result)# print(f"DEBUG - Agent response ------- END")-+# Process the result outputfor item in result.get("output", []):if item.get("type") == "message":content = item.get("content", [])for content_part in content:if content_part.get("text"):- history.append(gr.ChatMessage(- role=item.get("role", "assistant"),- content=content_part.get("text", ""),- metadata=content_part.get("metadata", {})- ))+ history.append(+ gr.ChatMessage(+ role=item.get("role", "assistant"),+ content=content_part.get("text", ""),+ metadata=content_part.get("metadata", {}),+ )+ )elif item.get("type") == "computer_call":action = item.get("action", {})action_type = action.get("type", "")@@ -632,43 +739,52 @@ if __name__ == "__main__":action_title = f"🛠️ Performing {action_type}"if action.get("x") and action.get("y"):action_title += f" at ({action['x']}, {action['y']})"- history.append(gr.ChatMessage(- role="assistant",- content=f"```json\n{json.dumps(action)}\n```",- metadata={"title": action_title}- ))+ history.append(+ gr.ChatMessage(+ role="assistant",+ content=f"```json\n{json.dumps(action)}\n```",+ metadata={"title": action_title},+ )+ )elif item.get("type") == "function_call":function_name = item.get("name", "")arguments = item.get("arguments", "{}")- history.append(gr.ChatMessage(- role="assistant",- content=f"🔧 Calling function: {function_name}\n```json\n{arguments}\n```",- metadata={"title": f"Function Call: {function_name}"}- ))+ history.append(+ gr.ChatMessage(+ role="assistant",+ content=f"🔧 Calling function: {function_name}\n```json\n{arguments}\n```",+ metadata={"title": f"Function Call: {function_name}"},+ )+ )elif item.get("type") == "function_call_output":output = item.get("output", "")- history.append(gr.ChatMessage(- role="assistant",- content=f"📤 Function output:\n```\n{output}\n```",- metadata={"title": "Function Output"}- ))+ history.append(+ gr.ChatMessage(+ role="assistant",+ content=f"📤 Function output:\n```\n{output}\n```",+ metadata={"title": "Function Output"},+ )+ )elif item.get("type") == "computer_call_output":output = item.get("output", {}).get("image_url", "")image_markdown = f""- history.append(gr.ChatMessage(- role="assistant",- content=image_markdown,- metadata={"title": "🖥️ Computer Output"}- ))-+ history.append(+ gr.ChatMessage(+ role="assistant",+ content=image_markdown,+ metadata={"title": "🖥️ Computer Output"},+ )+ )+yield history-+except Exception as e:import traceback+traceback.print_exc()history.append(gr.ChatMessage(role="assistant", content=f"Error: {str(e)}"))yield history-+# Connect the submit buttonsubmit_event = msg.submit(fn=chat_submit,@@ -706,44 +822,77 @@ if __name__ == "__main__":global global_messagesglobal_messages.clear()return None-+clear.click(clear_chat, None, chatbot_history, queue=False)-+# Connect cancel buttoncancel_button.click(- cancel_agent_task,- [chatbot_history],- [chatbot_history],- queue=False+ cancel_agent_task, [chatbot_history], [chatbot_history], queue=False)# Code display update function- def update_code_display(agent_loop, model_choice_val, custom_model_val, chat_history, recent_images_val, save_trajectory_val, computer_os, computer_provider, container_name, cua_cloud_api_key, max_budget_val):+ def update_code_display(+ agent_loop,+ model_choice_val,+ custom_model_val,+ chat_history,+ recent_images_val,+ save_trajectory_val,+ computer_os,+ computer_provider,+ container_name,+ cua_cloud_api_key,+ max_budget_val,+ ):messages = []if chat_history:for msg in chat_history:if isinstance(msg, dict) and msg.get("role") == "user":messages.append(msg.get("content", ""))-+return generate_python_code(- agent_loop,- model_choice_val or custom_model_val or "gpt-4o",- messages,+ agent_loop,+ model_choice_val or custom_model_val or "gpt-4o",+ messages,recent_images_val,save_trajectory_val,computer_os,computer_provider,container_name,cua_cloud_api_key,- max_budget_val+ max_budget_val,)-+# Update code display when configuration changes- for component in [agent_loop, model_choice, custom_model, chatbot_history, recent_images, save_trajectory, computer_os, computer_provider, container_name, cua_cloud_api_key, max_budget]:+ for component in [+ agent_loop,+ model_choice,+ custom_model,+ chatbot_history,+ recent_images,+ save_trajectory,+ computer_os,+ computer_provider,+ container_name,+ cua_cloud_api_key,+ max_budget,+ ]:component.change(update_code_display,- inputs=[agent_loop, model_choice, custom_model, chatbot_history, recent_images, save_trajectory, computer_os, computer_provider, container_name, cua_cloud_api_key, max_budget],- outputs=[code_display]+ inputs=[+ agent_loop,+ model_choice,+ custom_model,+ chatbot_history,+ recent_images,+ save_trajectory,+ computer_os,+ computer_provider,+ container_name,+ cua_cloud_api_key,+ max_budget,+ ],+ outputs=[code_display],)return demodiff --git a/libs/python/agent/benchmarks/README.md b/libs/python/agent/benchmarks/README.mdindex 03d1a78973..9c7d50b304 100644--- a/libs/python/agent/benchmarks/README.md+++ b/libs/python/agent/benchmarks/README.md@@ -5,26 +5,30 @@ This directory contains benchmarks designed to test agent providers in the Compu## OverviewThe benchmark system evaluates models on GUI grounding tasks, specifically click prediction accuracy. It supports both:+- **Computer Agent SDK providers** (using model strings like `"huggingface-local/HelloKKMe/GTA1-7B"`)- **Reference agent implementations** (custom model classes implementing the `ModelProtocol`)## Available Benchmarks### 1. ScreenSpot-v2 (`ss-v2.py`)+- **Dataset**: ScreenSpot-v2 (click-only GUI grounding)- **Format**: Standard resolution screenshots- **Task**: Predict click coordinates given an instruction and image- **Metrics**: Accuracy, Error Rate, Timing, VRAM usage-### 2. ScreenSpot-Pro (`ss-pro.py`)+### 2. ScreenSpot-Pro (`ss-pro.py`)+- **Dataset**: ScreenSpot-Pro (high-resolution click-only GUI grounding)- **Format**: High-resolution screenshots- **Task**: Predict click coordinates given an instruction and image- **Metrics**: Accuracy, Error Rate, Timing, VRAM usage### 3. Interactive Testing (`interactive.py`)+- **Real-time testing**: Take screenshots and visualize model predictions-- **Commands**:+- **Commands**:- Type instruction → test all models on last screenshot- `screenshot` → take screenshot- `models` → list available models@@ -34,14 +38,16 @@ The benchmark system evaluates models on GUI grounding tasks, specifically click## Running Benchmarks### 1. Configure Models+Edit `utils.py` to specify which models you want to test in `get_available_models()`.### 2. Run Benchmark+```bash# ScreenSpot-v2 benchmarkpython ss-v2.py --samples 50-# ScreenSpot-Pro benchmark+# ScreenSpot-Pro benchmarkpython ss-pro.py --samples 50# Interactive testing@@ -51,6 +57,7 @@ python interactive.py## Output### Console Output+```Model Results:Accuracy: 85.50% (171/200)@@ -59,10 +66,11 @@ Model Results:```### Generated Files+- **Markdown Report**: `*_results.md` with detailed results tables- **Visualizations**: `output/` directory with prediction visualizations- **Interactive Output**: `interactive_output/` for interactive session results## Contributing-To add a new reference model, follow the instructions in [contrib.md](contrib.md).\ No newline at end of file+To add a new reference model, follow the instructions in [contrib.md](contrib.md).diff --git a/libs/python/agent/benchmarks/contrib.md b/libs/python/agent/benchmarks/contrib.mdindex 0bef907787..a452db6b31 100644--- a/libs/python/agent/benchmarks/contrib.md+++ b/libs/python/agent/benchmarks/contrib.md@@ -17,29 +17,29 @@ class YourModelName(ModelProtocol):def __init__(self, model_path: str):self.model_path = model_pathself._model = None-+@propertydef model_name(self) -> str:return self.model_path-+async def load_model(self) -> None:"""Load the model into memory."""# Your model loading logic herepass-+async def unload_model(self) -> None:"""Unload the model from memory."""# Your model cleanup logic herepass-+async def predict_click(self, image: Image.Image, instruction: str) -> Optional[Tuple[int, int]]:"""Predict click coordinates for the given image and instruction.-+Args:image: PIL Image to analyzeinstruction: Text instruction describing what to click-+Returns:Tuple of (x, y) coordinates or None if prediction fails"""@@ -56,7 +56,7 @@ def get_available_models() -> List[Union[str, ModelProtocol]]:models = [# Computer Agent SDK providers"huggingface-local/HelloKKMe/GTA1-7B",-+# Reference implementationsGTA1Model("HelloKKMe/GTA1-7B"),YourModelName("path/to/your/model"), # Add your model here@@ -79,6 +79,7 @@ This will help you verify that your model loads correctly and produces reasonablHere's a complete example of adding a hypothetical "MyVisionModel":1. **Create `models/my_vision_model.py`:**+```pythonimport torchfrom transformers import AutoModel, AutoProcessor@@ -91,11 +92,11 @@ class MyVisionModel(ModelProtocol):self.model_path = model_pathself.model = Noneself.processor = None-+@propertydef model_name(self) -> str:return f"MyVisionModel({self.model_path})"-+async def load_model(self) -> None:"""Load the model and processor."""self.processor = AutoProcessor.from_pretrained(self.model_path)@@ -104,7 +105,7 @@ class MyVisionModel(ModelProtocol):torch_dtype=torch.float16,device_map="auto")-+async def unload_model(self) -> None:"""Clean up model resources."""del self.model@@ -112,7 +113,7 @@ class MyVisionModel(ModelProtocol):self.model = Noneself.processor = Nonetorch.cuda.empty_cache()-+async def predict_click(self, image: Image.Image, instruction: str) -> Optional[Tuple[int, int]]:"""Predict click coordinates."""try:@@ -122,19 +123,19 @@ class MyVisionModel(ModelProtocol):images=image,return_tensors="pt")-+# Run inferencewith torch.no_grad():outputs = self.model(**inputs)-+# Extract coordinates (model-specific logic)x, y = self._extract_coordinates(outputs)return (int(x), int(y))-+except Exception as e:print(f"Prediction failed: {e}")return None-+def _extract_coordinates(self, outputs):"""Extract x, y coordinates from model outputs."""# Your model-specific coordinate extraction logic@@ -142,6 +143,7 @@ class MyVisionModel(ModelProtocol):```2. **Update `models/__init__.py`:**+```pythonfrom .gta1 import GTA1Modelfrom .my_vision_model import MyVisionModel@@ -150,6 +152,7 @@ __all__ = ["GTA1Model", "MyVisionModel"]```3. **Update `utils.py`:**+```pythonfrom models import GTA1Model, MyVisionModeldiff --git a/libs/python/agent/benchmarks/interactive.py b/libs/python/agent/benchmarks/interactive.pyindex 6d0aba8289..45296c99f4 100644--- a/libs/python/agent/benchmarks/interactive.py+++ b/libs/python/agent/benchmarks/interactive.py@@ -9,60 +9,56 @@ Models are loaded/unloaded one at a time to avoid memory issues.import asyncioimport osfrom datetime import datetime-from typing import List, Dict, Any+from typing import Any, Dict, Listfrom utils import (ModelWrapper,- take_screenshot,+ get_available_models,save_prediction_visualization,- get_available_models+ take_screenshot,)async def predict_with_all_models(image, instruction: str, models) -> List[Dict[str, Any]]:"""Predict click coordinates with all models sequentially.-+Args:image: PIL Image to analyzeinstruction: Instruction textmodels: List of model instances-+Returns:List of prediction results"""predictions = []-+for model in models:model_wrapper = ModelWrapper(model)print(f"\n🔄 Loading {model_wrapper.model_name}...")-+try:# Load modelawait model_wrapper.load_model()-+# Predictcoords = await model_wrapper.predict_click(image, instruction)-- predictions.append({- 'model_name': model_wrapper.model_name,- 'coords': coords,- 'error': None- })-++ predictions.append(+ {"model_name": model_wrapper.model_name, "coords": coords, "error": None}+ )+if coords:print(f"✅ {model_wrapper.model_name}: ({coords[0]}, {coords[1]})")else:print(f"❌ {model_wrapper.model_name}: No prediction")-+except Exception as e:print(f"❌ {model_wrapper.model_name}: ERROR - {str(e)}")- predictions.append({- 'model_name': model_wrapper.model_name,- 'coords': None,- 'error': str(e)- })-+ predictions.append(+ {"model_name": model_wrapper.model_name, "coords": None, "error": str(e)}+ )+finally:# Always unload model to free memorytry:@@ -70,7 +66,7 @@ async def predict_with_all_models(image, instruction: str, models) -> List[Dict[print(f"🗑️ Unloaded {model_wrapper.model_name}")except Exception as e:print(f"⚠️ Error unloading {model_wrapper.model_name}: {e}")-+return predictions@@ -103,87 +99,91 @@ async def main():Main interactive loop."""print_header()-+# Get available modelsmodels = get_available_models()print_models(models)-+# Create output directory for visualizationsoutput_dir = "interactive_output"os.makedirs(output_dir, exist_ok=True)-+session_count = 0last_screenshot = Nonescreenshot_timestamp = None-+while True:try:# Get user inputprint(f"\n{'='*40}")user_input = input("🎯 Enter instruction (or command): ").strip()-+if not user_input:continue-+# Handle commands- if user_input.lower() in ['quit', 'exit', 'q']:+ if user_input.lower() in ["quit", "exit", "q"]:print("👋 Goodbye!")break-- elif user_input.lower() == 'models':++ elif user_input.lower() == "models":print_models(models)continue-- elif user_input.lower() == 'screenshot':++ elif user_input.lower() == "screenshot":print("📸 Taking screenshot...")try:last_screenshot = take_screenshot()screenshot_timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")- screenshot_path = os.path.join(output_dir, f"screenshot_{screenshot_timestamp}.png")+ screenshot_path = os.path.join(+ output_dir, f"screenshot_{screenshot_timestamp}.png"+ )last_screenshot.save(screenshot_path)print(f"✅ Screenshot captured and saved to: {screenshot_path}")print(f"📝 Ready for instructions! Screenshot size: {last_screenshot.size}")except Exception as e:print(f"❌ Error taking screenshot: {e}")continue-+# Handle instruction inputif last_screenshot is None:- print("⚠️ No screenshot available! Please take a screenshot first using 'screenshot' command.")+ print(+ "⚠️ No screenshot available! Please take a screenshot first using 'screenshot' command."+ )continue-+session_count += 1print(f"\n🎯 Session {session_count}: '{user_input}'")print(f"📷 Using screenshot from: {screenshot_timestamp}")-+# Predict with all models using last screenshotprint(f"\n🤖 Testing {len(models)} models on screenshot...")predictions = await predict_with_all_models(last_screenshot, user_input, models)-+# Display results summary- print(f"\n📊 Results Summary:")+ print("\n📊 Results Summary:")print("-" * 50)for pred in predictions:- if pred['coords']:+ if pred["coords"]:print(f"✅ {pred['model_name']}: ({pred['coords'][0]}, {pred['coords'][1]})")- elif pred['error']:+ elif pred["error"]:print(f"❌ {pred['model_name']}: ERROR - {pred['error']}")else:print(f"❌ {pred['model_name']}: No prediction")-+# Save visualizationtimestamp = datetime.now().strftime("%Y%m%d_%H%M%S")vis_filename = f"session_{session_count:03d}_{timestamp}.png"vis_path = os.path.join(output_dir, vis_filename)-+try:save_prediction_visualization(last_screenshot, user_input, predictions, vis_path)print(f"\n💾 Visualization saved to: {vis_path}")except Exception as e:print(f"⚠️ Error saving visualization: {e}")-+print(f"\n✨ Session {session_count} completed!")-+except KeyboardInterrupt:print("\n\n👋 Interrupted by user. Goodbye!")breakdiff --git a/libs/python/agent/benchmarks/models/base.py b/libs/python/agent/benchmarks/models/base.pyindex 8ad100a395..aeecbba0a0 100644--- a/libs/python/agent/benchmarks/models/base.py+++ b/libs/python/agent/benchmarks/models/base.py@@ -2,34 +2,37 @@Base protocol for benchmark models."""-from typing import Protocol, Optional, Tuple+from typing import Optional, Protocol, Tuple+from PIL import Imageclass ModelProtocol(Protocol):"""Protocol for benchmark models that can predict click coordinates."""-+@propertydef model_name(self) -> str:"""Return the name of the model."""...-+async def load_model(self) -> None:"""Load the model into memory."""...-+async def unload_model(self) -> None:"""Unload the model from memory."""...-- async def predict_click(self, image: Image.Image, instruction: str) -> Optional[Tuple[int, int]]:++ async def predict_click(+ self, image: Image.Image, instruction: str+ ) -> Optional[Tuple[int, int]]:"""Predict click coordinates for the given image and instruction.-+Args:image: PIL Image to analyzeinstruction: Text instruction describing what to click-+Returns:Tuple of (x, y) coordinates or None if prediction fails"""diff --git a/libs/python/agent/benchmarks/models/gta1.py b/libs/python/agent/benchmarks/models/gta1.pyindex a1dee59928..564531846b 100644--- a/libs/python/agent/benchmarks/models/gta1.py+++ b/libs/python/agent/benchmarks/models/gta1.py@@ -2,54 +2,51 @@GTA1 model implementation for benchmarking."""+import gc+import refrom typing import Optional, Tuple-from PIL import Image+import torch-import re-import gc+from PIL import Imagefrom qwen_vl_utils import process_vision_info, smart_resize-from transformers import Qwen2_5_VLForConditionalGeneration, AutoProcessor+from transformers import AutoProcessor, Qwen2_5_VLForConditionalGenerationfrom .base import ModelProtocolclass GTA1Model:"""Ground truth GTA1 model implementation."""-+def __init__(self, model_path: str = "HelloKKMe/GTA1-7B"):self.model_path = model_pathself.model = Noneself.processor = Noneself.max_new_tokens = 32-- self.system_prompt = '''++ self.system_prompt = """You are an expert UI element locator. Given a GUI image and a user's element description, provide the coordinates of the specified element as a single (x,y) point. The image resolution is height {height} and width {width}. For elements with area, return the center point.Output the coordinate pair exactly:(x,y)-'''.strip()-+""".strip()+@propertydef model_name(self) -> str:"""Return the name of the model."""return f"GTA1-{self.model_path.split('/')[-1]}"-+async def load_model(self) -> None:"""Load the model into memory."""if self.model is None:print(f"Loading GTA1 model: {self.model_path}")self.model = Qwen2_5_VLForConditionalGeneration.from_pretrained(- self.model_path,- torch_dtype=torch.bfloat16,- device_map="auto"+ self.model_path, torch_dtype=torch.bfloat16, device_map="auto")self.processor = AutoProcessor.from_pretrained(- self.model_path,- min_pixels=3136,- max_pixels=4096 * 2160+ self.model_path, min_pixels=3136, max_pixels=4096 * 2160)print("GTA1 model loaded successfully")-+async def unload_model(self) -> None:"""Unload the model from memory."""if self.model is not None:@@ -62,23 +59,25 @@ Output the coordinate pair exactly:if torch.cuda.is_available():torch.cuda.empty_cache()print("GTA1 model unloaded")-+def _extract_coordinates(self, raw_string: str) -> Tuple[int, int]:"""Extract coordinates from model output."""try:matches = re.findall(r"\((-?\d*\.?\d+),\s*(-?\d*\.?\d+)\)", raw_string)- return tuple(map(int, map(float, matches[0]))) # type: ignore+ return tuple(map(int, map(float, matches[0]))) # type: ignoreexcept:return (0, 0)-- async def predict_click(self, image: Image.Image, instruction: str) -> Optional[Tuple[int, int]]:++ async def predict_click(+ self, image: Image.Image, instruction: str+ ) -> Optional[Tuple[int, int]]:"""Predict click coordinates for the given image and instruction.-+Args:image: PIL Image to analyzeinstruction: Text instruction describing what to click-+Returns:Tuple of (x, y) coordinates or None if prediction fails"""@@ -87,76 +86,73 @@ Output the coordinate pair exactly:assert self.processor is not Noneassert self.model is not None-+try:width, height = image.width, image.height-+# Resize image according to processor requirementsresized_height, resized_width = smart_resize(image.height,image.width,- factor=self.processor.image_processor.patch_size * self.processor.image_processor.merge_size,+ factor=self.processor.image_processor.patch_size+ * self.processor.image_processor.merge_size,min_pixels=self.processor.image_processor.min_pixels,max_pixels=self.processor.image_processor.max_pixels,)resized_image = image.resize((resized_width, resized_height))scale_x, scale_y = width / resized_width, height / resized_height-+# Prepare messagessystem_message = {"role": "system",- "content": self.system_prompt.format(height=resized_height, width=resized_width)+ "content": self.system_prompt.format(height=resized_height, width=resized_width),}-+user_message = {"role": "user","content": [{"type": "image", "image": resized_image},- {"type": "text", "text": instruction}- ]+ {"type": "text", "text": instruction},+ ],}-+# Process inputs- image_inputs, video_inputs = process_vision_info([system_message, user_message]) # type: ignore+ image_inputs, video_inputs = process_vision_info([system_message, user_message]) # type: ignoretext = self.processor.apply_chat_template(- [system_message, user_message],- tokenize=False,- add_generation_prompt=True+ [system_message, user_message], tokenize=False, add_generation_prompt=True)inputs = self.processor(- text=[text],- images=image_inputs,- videos=video_inputs,- padding=True,- return_tensors="pt"+ text=[text],+ images=image_inputs,+ videos=video_inputs,+ padding=True,+ return_tensors="pt",)inputs = inputs.to(self.model.device)-+# Generate predictionoutput_ids = self.model.generate(- **inputs,- max_new_tokens=self.max_new_tokens,- do_sample=False,- temperature=1.0,- use_cache=True+ **inputs,+ max_new_tokens=self.max_new_tokens,+ do_sample=False,+ temperature=1.0,+ use_cache=True,)generated_ids = [- output_ids[len(input_ids):]+ output_ids[len(input_ids) :]for input_ids, output_ids in zip(inputs.input_ids, output_ids)]output_text = self.processor.batch_decode(- generated_ids,- skip_special_tokens=True,- clean_up_tokenization_spaces=True+ generated_ids, skip_special_tokens=True, clean_up_tokenization_spaces=True)[0]-+# Extract and rescale coordinatespred_x, pred_y = self._extract_coordinates(output_text)pred_x = int(pred_x * scale_x)pred_y = int(pred_y * scale_y)-+return (pred_x, pred_y)-+except Exception as e:print(f"Error in GTA1 prediction: {e}")return Nonediff --git a/libs/python/agent/benchmarks/ss-pro.py b/libs/python/agent/benchmarks/ss-pro.pyindex 80e5e72f8e..a086819a0c 100644--- a/libs/python/agent/benchmarks/ss-pro.py+++ b/libs/python/agent/benchmarks/ss-pro.py@@ -15,103 +15,106 @@ from typing import Optionalfrom datasets import load_datasetfrom tqdm import tqdm-from utils import (- ModelWrapper,- is_click_in_bbox,- save_results_to_markdown,- save_visualizations,+ ModelWrapper,get_available_models,- get_gpu_memory+ get_gpu_memory,+ is_click_in_bbox,+ save_results_to_markdown,+ save_visualizations,)-async def evaluate_model(model_wrapper: ModelWrapper, dataset, max_samples: Optional[int] = None) -> dict:+async def evaluate_model(+ model_wrapper: ModelWrapper, dataset, max_samples: Optional[int] = None+) -> dict:"""Evaluate a model on the ScreenSpot-Pro dataset.-+Args:model_wrapper: ModelWrapper instancedataset: ScreenSpot-Pro dataset (list of samples)max_samples: Maximum number of samples to evaluate (None for all)-+Returns:Dictionary with evaluation results"""print(f"\nEvaluating model: {model_wrapper.model_name}")-+# Load modelawait model_wrapper.load_model()-+total_samples = len(dataset)if max_samples is not None:total_samples = min(max_samples, total_samples)-+correct_predictions = 0error_predictions = 0results = []-+for i in tqdm(range(total_samples), desc=f"Evaluating {model_wrapper.model_name}"):sample = dataset[i]-+# Extract sample data- image = sample['image']- instruction = sample['instruction']- bbox = sample['bbox'] # [x1, y1, x2, y2]- sample_id = sample['img_filename']-+ image = sample["image"]+ instruction = sample["instruction"]+ bbox = sample["bbox"] # [x1, y1, x2, y2]+ sample_id = sample["img_filename"]+# Predict click coordinates with timingstart_time = time.time()click_coords = await model_wrapper.predict_click(image, instruction)prediction_time = time.time() - start_time-+# Check if prediction is correctis_correct = is_click_in_bbox(click_coords, bbox)-+if is_correct:correct_predictions += 1-- results.append({- 'id': sample_id,- 'instruction': instruction,- 'bbox': bbox,- 'predicted_coords': click_coords,- 'is_correct': is_correct,- 'failed': False,- 'prediction_time': prediction_time- })-++ results.append(+ {+ "id": sample_id,+ "instruction": instruction,+ "bbox": bbox,+ "predicted_coords": click_coords,+ "is_correct": is_correct,+ "failed": False,+ "prediction_time": prediction_time,+ }+ )+# Unload modelawait model_wrapper.unload_model()-+# Calculate metricsaccuracy = correct_predictions / total_samples if total_samples > 0 else 0.0error_rate = error_predictions / total_samples if total_samples > 0 else 0.0-+# Calculate timing statistics- successful_times = [r['prediction_time'] for r in results if not r['failed']]+ successful_times = [r["prediction_time"] for r in results if not r["failed"]]avg_prediction_time = sum(successful_times) / len(successful_times) if successful_times else 0.0median_prediction_time = statistics.median(successful_times) if successful_times else 0.0min_prediction_time = min(successful_times) if successful_times else 0.0max_prediction_time = max(successful_times) if successful_times else 0.0-+# Get VRAM statisticsvram_stats = model_wrapper.get_vram_stats()-+return {- 'model_name': model_wrapper.model_name,- 'total_samples': total_samples,- 'correct_predictions': correct_predictions,- 'failed_predictions': error_predictions,- 'accuracy': accuracy,- 'failure_rate': error_rate,- 'avg_prediction_time': avg_prediction_time,- 'median_prediction_time': median_prediction_time,- 'min_prediction_time': min_prediction_time,- 'max_prediction_time': max_prediction_time,- 'vram_max_mb': vram_stats['max_mb'],- 'vram_avg_mb': vram_stats['avg_mb'],- 'results': results+ "model_name": model_wrapper.model_name,+ "total_samples": total_samples,+ "correct_predictions": correct_predictions,+ "failed_predictions": error_predictions,+ "accuracy": accuracy,+ "failure_rate": error_rate,+ "avg_prediction_time": avg_prediction_time,+ "median_prediction_time": median_prediction_time,+ "min_prediction_time": min_prediction_time,+ "max_prediction_time": max_prediction_time,+ "vram_max_mb": vram_stats["max_mb"],+ "vram_avg_mb": vram_stats["avg_mb"],+ "results": results,}@@ -120,42 +123,44 @@ async def main():Main function to run the benchmark."""# Parse command line arguments- parser = argparse.ArgumentParser(description='ScreenSpot-Pro Benchmark Script')- parser.add_argument('--samples', type=int, default=300,- help='Number of samples to evaluate (default: 300)')- parser.add_argument('--seed', type=int, default=42,- help='Random seed for shuffling (default: 42)')+ parser = argparse.ArgumentParser(description="ScreenSpot-Pro Benchmark Script")+ parser.add_argument(+ "--samples", type=int, default=300, help="Number of samples to evaluate (default: 300)"+ )+ parser.add_argument(+ "--seed", type=int, default=42, help="Random seed for shuffling (default: 42)"+ )args = parser.parse_args()-+# Set random seedrandom.seed(args.seed)-+# Load datasetprint("Loading ScreenSpot-Pro dataset...")ds = load_dataset("lmms-lab/ScreenSpot-Pro")- dataset = ds['train'] # type: ignore+ dataset = ds["train"] # type: ignore# Convert to list to support indexingdataset_list = list(dataset)print(f"Dataset loaded: {len(dataset_list)} samples")-+# Shuffle dataset with seedrandom.shuffle(dataset_list)print(f"Dataset shuffled with seed {args.seed}")-+# Get available modelsmodels = get_available_models()-+# Evaluation settingsmax_samples = args.samples # Use command line argument-+# Run evaluationsall_results = []-+for model in models:model_wrapper = ModelWrapper(model)result = await evaluate_model(model_wrapper, dataset_list, max_samples)all_results.append(result)-+# Print summaryprint(f"\n{result['model_name']} Results:")print(f" Accuracy: {result['accuracy']*100:.2f}%")@@ -164,15 +169,17 @@ async def main():print(f" Error Rate: {result['failure_rate']*100:.2f}%")print(f" Avg Time: {result['avg_prediction_time']:.2f}s")print(f" Median Time: {result['median_prediction_time']:.2f}s")- print(f" Time Range: {result['min_prediction_time']:.2f}s - {result['max_prediction_time']:.2f}s")+ print(+ f" Time Range: {result['min_prediction_time']:.2f}s - {result['max_prediction_time']:.2f}s"+ )print(f" VRAM Max: {result['vram_max_mb']:.1f}MB")print(f" VRAM Avg: {result['vram_avg_mb']:.1f}MB")-+# Print GPU memory infogpu_memory = get_gpu_memory()if gpu_memory and gpu_memory[0] > 0:print(f" GPU Free Memory: {gpu_memory[0]:.1f}MB")-+# Save resultsif all_results:save_results_to_markdown(all_results)@@ -183,4 +190,4 @@ async def main():if __name__ == "__main__":- asyncio.run(main())\ No newline at end of file+ asyncio.run(main())diff --git a/libs/python/agent/benchmarks/ss-v2.py b/libs/python/agent/benchmarks/ss-v2.pyindex dab1d4b1aa..8af8e8e09b 100644--- a/libs/python/agent/benchmarks/ss-v2.py+++ b/libs/python/agent/benchmarks/ss-v2.py@@ -15,36 +15,37 @@ from typing import Optionalfrom datasets import load_datasetfrom tqdm import tqdm-from utils import (- ModelWrapper,- is_click_in_bbox,- save_results_to_markdown,- save_visualizations,+ ModelWrapper,get_available_models,- get_gpu_memory+ get_gpu_memory,+ is_click_in_bbox,+ save_results_to_markdown,+ save_visualizations,)-async def evaluate_model(model_wrapper: ModelWrapper, samples, max_samples: Optional[int] = None) -> dict:+async def evaluate_model(+ model_wrapper: ModelWrapper, samples, max_samples: Optional[int] = None+) -> dict:"""Evaluate a model on any iterable of samples.-+Args:model_wrapper: ModelWrapper instancesamples: Iterable of dicts with keys: image, bbox, instructionmax_samples: Maximum number of samples to evaluate (None for all)-+Returns:Dictionary with evaluation results"""print(f"\nEvaluating model: {model_wrapper.model_name}")-+# Load modelawait model_wrapper.load_model()-+# Convert to list if needed and limit samples- if hasattr(samples, '__len__'):+ if hasattr(samples, "__len__"):total_samples = len(samples)if max_samples is not None:total_samples = min(max_samples, total_samples)@@ -55,69 +56,71 @@ async def evaluate_model(model_wrapper: ModelWrapper, samples, max_samples: Optiif max_samples is not None:sample_list = sample_list[:max_samples]total_samples = len(sample_list)-+correct_predictions = 0error_predictions = 0results = []-+for i, sample in enumerate(tqdm(sample_list, desc=f"Evaluating {model_wrapper.model_name}")):# Extract required data (only these 3 keys matter)- image = sample['image']- instruction = sample['instruction']- bbox = sample['bbox'] # [x1, y1, x2, y2]-+ image = sample["image"]+ instruction = sample["instruction"]+ bbox = sample["bbox"] # [x1, y1, x2, y2]+# Predict click coordinates with timingstart_time = time.time()click_coords = await model_wrapper.predict_click(image, instruction)prediction_time = time.time() - start_time-+# Check if prediction is correctis_correct = is_click_in_bbox(click_coords, bbox)-+if is_correct:correct_predictions += 1-- results.append({- 'sample_idx': i,- 'instruction': instruction,- 'bbox': bbox,- 'predicted_coords': click_coords,- 'is_correct': is_correct,- 'failed': False,- 'prediction_time': prediction_time- })-++ results.append(+ {+ "sample_idx": i,+ "instruction": instruction,+ "bbox": bbox,+ "predicted_coords": click_coords,+ "is_correct": is_correct,+ "failed": False,+ "prediction_time": prediction_time,+ }+ )+# Unload modelawait model_wrapper.unload_model()-+# Calculate metricsaccuracy = correct_predictions / total_samples if total_samples > 0 else 0.0error_rate = error_predictions / total_samples if total_samples > 0 else 0.0-+# Calculate timing statistics- successful_times = [r['prediction_time'] for r in results if not r['failed']]+ successful_times = [r["prediction_time"] for r in results if not r["failed"]]avg_prediction_time = sum(successful_times) / len(successful_times) if successful_times else 0.0median_prediction_time = statistics.median(successful_times) if successful_times else 0.0min_prediction_time = min(successful_times) if successful_times else 0.0max_prediction_time = max(successful_times) if successful_times else 0.0-+# Get VRAM statisticsvram_stats = model_wrapper.get_vram_stats()-+return {- 'model_name': model_wrapper.model_name,- 'total_samples': total_samples,- 'correct_predictions': correct_predictions,- 'failed_predictions': error_predictions,- 'accuracy': accuracy,- 'failure_rate': error_rate,- 'avg_prediction_time': avg_prediction_time,- 'median_prediction_time': median_prediction_time,- 'min_prediction_time': min_prediction_time,- 'max_prediction_time': max_prediction_time,- 'vram_max_mb': vram_stats['max_mb'],- 'vram_avg_mb': vram_stats['avg_mb'],- 'results': results+ "model_name": model_wrapper.model_name,+ "total_samples": total_samples,+ "correct_predictions": correct_predictions,+ "failed_predictions": error_predictions,+ "accuracy": accuracy,+ "failure_rate": error_rate,+ "avg_prediction_time": avg_prediction_time,+ "median_prediction_time": median_prediction_time,+ "min_prediction_time": min_prediction_time,+ "max_prediction_time": max_prediction_time,+ "vram_max_mb": vram_stats["max_mb"],+ "vram_avg_mb": vram_stats["avg_mb"],+ "results": results,}@@ -126,56 +129,60 @@ async def main():Main function to run the benchmark."""# Parse command line arguments- parser = argparse.ArgumentParser(description='ScreenSpot-v2 Benchmark Script')- parser.add_argument('--samples', type=int, default=500,- help='Number of samples to evaluate (default: 500)')- parser.add_argument('--seed', type=int, default=42,- help='Random seed for shuffling (default: 42)')+ parser = argparse.ArgumentParser(description="ScreenSpot-v2 Benchmark Script")+ parser.add_argument(+ "--samples", type=int, default=500, help="Number of samples to evaluate (default: 500)"+ )+ parser.add_argument(+ "--seed", type=int, default=42, help="Random seed for shuffling (default: 42)"+ )args = parser.parse_args()-+# Set random seedrandom.seed(args.seed)-+# Load datasetprint("Loading ScreenSpot-v2 dataset...")ds = load_dataset("lmms-lab/ScreenSpot-v2")- dataset = ds['train'] # type: ignore+ dataset = ds["train"] # type: ignore# Convert to simple list of dicts with only required keyssamples = []for item in dataset:# Convert dataset item to dict if needed- item_dict = dict(item) if hasattr(item, 'keys') else item-+ item_dict = dict(item) if hasattr(item, "keys") else item+# Convert ScreenSpot-v2 bbox format [x, y, w, h] to [x1, y1, x2, y2]- bbox_xywh = item_dict['bbox'] # type: ignore+ bbox_xywh = item_dict["bbox"] # type: ignorex, y, w, h = bbox_xywhbbox_xyxy = [x, y, x + w, y + h]-- samples.append({- 'image': item_dict['image'], # type: ignore- 'instruction': item_dict['instruction'], # type: ignore- 'bbox': bbox_xyxy- })++ samples.append(+ {+ "image": item_dict["image"], # type: ignore+ "instruction": item_dict["instruction"], # type: ignore+ "bbox": bbox_xyxy,+ }+ )print(f"Dataset loaded: {len(samples)} samples")-+# Shuffle samples with seedrandom.shuffle(samples)print(f"Samples shuffled with seed {args.seed}")-+# Get available modelsmodels = get_available_models()-+# Evaluation settingsmax_samples = args.samples # Use command line argument-+# Run evaluationsall_results = []-+for model in models:model_wrapper = ModelWrapper(model)result = await evaluate_model(model_wrapper, samples, max_samples)all_results.append(result)-+# Print summaryprint(f"\n{result['model_name']} Results:")print(f" Accuracy: {result['accuracy']*100:.2f}%")@@ -184,18 +191,22 @@ async def main():print(f" Error Rate: {result['failure_rate']*100:.2f}%")print(f" Avg Time: {result['avg_prediction_time']:.2f}s")print(f" Median Time: {result['median_prediction_time']:.2f}s")- print(f" Time Range: {result['min_prediction_time']:.2f}s - {result['max_prediction_time']:.2f}s")+ print(+ f" Time Range: {result['min_prediction_time']:.2f}s - {result['max_prediction_time']:.2f}s"+ )print(f" VRAM Max: {result['vram_max_mb']:.1f}MB")print(f" VRAM Avg: {result['vram_avg_mb']:.1f}MB")-+# Print GPU memory infogpu_memory = get_gpu_memory()if gpu_memory and gpu_memory[0] > 0:print(f" GPU Free Memory: {gpu_memory[0]:.1f}MB")-+# Save resultsif all_results:- save_results_to_markdown(all_results, "screenspot_v2_results.md", title="ScreenSpot-v2 Benchmark Results")+ save_results_to_markdown(+ all_results, "screenspot_v2_results.md", title="ScreenSpot-v2 Benchmark Results"+ )save_visualizations(all_results, samples)print("\nBenchmark completed successfully!")else:@@ -203,4 +214,4 @@ async def main():if __name__ == "__main__":- asyncio.run(main())\ No newline at end of file+ asyncio.run(main())diff --git a/libs/python/agent/benchmarks/utils.py b/libs/python/agent/benchmarks/utils.pyindex d7ef444502..7c32b1c158 100644--- a/libs/python/agent/benchmarks/utils.py+++ b/libs/python/agent/benchmarks/utils.py@@ -4,38 +4,40 @@ Shared utilities for ScreenSpot-Pro benchmarking and interactive testing."""import dotenv+dotenv.load_dotenv()import asyncioimport base64+import gcimport os-import sys-import subprocess as spimport statistics+import subprocess as sp+import sysfrom datetime import datetimefrom io import BytesIO-from typing import List, Union, Tuple, Optional+from typing import List, Optional, Tuple, Union+import torchfrom PIL import Image, ImageDrawfrom tqdm import tqdm-import gc-import torch# Add parent directory to path for imports-sys.path.append(os.path.join(os.path.dirname(__file__), '..'))+sys.path.append(os.path.join(os.path.dirname(__file__), ".."))from agent.agent import ComputerAgentfrom models.base import ModelProtocol+def get_gpu_memory() -> List[int]:"""Get GPU memory usage using nvidia-smi.-+Returns:List of free memory values in MB for each GPU"""try:command = "nvidia-smi --query-gpu=memory.free --format=csv"- memory_free_info = sp.check_output(command.split()).decode('ascii').split('\n')[:-1][1:]+ memory_free_info = sp.check_output(command.split()).decode("ascii").split("\n")[:-1][1:]memory_free_values = [int(x.split()[0]) for i, x in enumerate(memory_free_info)]return memory_free_valuesexcept (sp.CalledProcessError, FileNotFoundError, IndexError):@@ -51,39 +53,34 @@ def get_gpu_memory() -> List[int]:def get_vram_usage() -> dict:"""Get current VRAM usage statistics.-+Returns:Dictionary with VRAM usage info (in MB)"""if torch.cuda.is_available():device = torch.cuda.current_device()allocated = torch.cuda.memory_allocated(device) / 1024 / 1024 # Convert to MB- reserved = torch.cuda.memory_reserved(device) / 1024 / 1024 # Convert to MB+ reserved = torch.cuda.memory_reserved(device) / 1024 / 1024 # Convert to MBtotal = torch.cuda.get_device_properties(device).total_memory / 1024 / 1024return {- 'allocated_mb': allocated,- 'reserved_mb': reserved,- 'total_mb': total,- 'free_mb': total - reserved+ "allocated_mb": allocated,+ "reserved_mb": reserved,+ "total_mb": total,+ "free_mb": total - reserved,}else:- return {- 'allocated_mb': 0.0,- 'reserved_mb': 0.0,- 'total_mb': 0.0,- 'free_mb': 0.0- }+ return {"allocated_mb": 0.0, "reserved_mb": 0.0, "total_mb": 0.0, "free_mb": 0.0}def get_available_models() -> List[Union[str, ModelProtocol]]:"""Get list of available models for testing.-+Returns:List of model strings and model classes"""local_provider = "huggingface-local/" # Options: huggingface-local/ or mlx/-+# from models.gta1 import GTA1Modelmodels = [@@ -94,42 +91,41 @@ def get_available_models() -> List[Union[str, ModelProtocol]]:# f"{local_provider}HelloKKMe/GTA1-32B","openai/computer-use-preview+openai/gpt-4o-mini","anthropic/claude-opus-4-20250514+openai/gpt-4o-mini",-# === Reference model classes ===# GTA1Model("HelloKKMe/GTA1-7B"),- # GTA1Model("HelloKKMe/GTA1-32B"),+ # GTA1Model("HelloKKMe/GTA1-32B"),]-+return modelsdef is_click_in_bbox(click_coords: Optional[Tuple[int, int]], bbox: List[int]) -> bool:"""Check if click coordinates are within the bounding box.-+Args:click_coords: (x, y) coordinates or Nonebbox: [x1, y1, x2, y2] bounding box-+Returns:True if click is within bbox, False otherwise"""if click_coords is None:return False-+x, y = click_coordsx1, y1, x2, y2 = bbox-+return x1 <= x <= x2 and y1 <= y <= y2def image_to_base64(image: Image.Image) -> str:"""Convert PIL Image to base64 string.-+Args:image: PIL Image-+Returns:Base64 encoded image string"""@@ -142,213 +138,252 @@ class ModelWrapper:"""Wrapper to provide unified interface for both ComputerAgent and custom models."""-+def __init__(self, model: Union[str, ModelProtocol]):self.model = modelself.is_computer_agent = isinstance(model, str)self.agent: Optional[ComputerAgent] = Noneself.vram_usage_history: List[float] = [] # Track VRAM usage over time-+if self.is_computer_agent:self.model_name = str(model)else:- self.model_name = f"{model.__class__.__name__}('{getattr(model, 'model_name', 'unknown')}')"-+ self.model_name = (+ f"{model.__class__.__name__}('{getattr(model, 'model_name', 'unknown')}')"+ )+async def load_model(self) -> None:"""Load the model."""if self.is_computer_agent:self.agent = ComputerAgent(model=str(self.model))else:- await self.model.load_model() # type: ignore-+ await self.model.load_model() # type: ignore+# Record initial VRAM usage after loadingvram_info = get_vram_usage()- self.vram_usage_history.append(vram_info['allocated_mb'])-+ self.vram_usage_history.append(vram_info["allocated_mb"])+async def unload_model(self) -> None:"""Unload the model."""if not self.is_computer_agent:- await self.model.unload_model() # type: ignore+ await self.model.unload_model() # type: ignoreelse:del self.agentself.agent = Nonegc.collect()if torch.cuda.is_available():torch.cuda.empty_cache()-+# Record VRAM usage after unloadingvram_info = get_vram_usage()- self.vram_usage_history.append(vram_info['allocated_mb'])-+ self.vram_usage_history.append(vram_info["allocated_mb"])+def get_vram_stats(self) -> dict:"""Get VRAM usage statistics for this model."""if not self.vram_usage_history:- return {'max_mb': 0.0, 'avg_mb': 0.0}-+ return {"max_mb": 0.0, "avg_mb": 0.0}+return {- 'max_mb': max(self.vram_usage_history),- 'avg_mb': sum(self.vram_usage_history) / len(self.vram_usage_history)+ "max_mb": max(self.vram_usage_history),+ "avg_mb": sum(self.vram_usage_history) / len(self.vram_usage_history),}-- async def predict_click(self, image: Image.Image, instruction: str) -> Optional[Tuple[int, int]]:+ async def predict_click(+ self, image: Image.Image, instruction: str+ ) -> Optional[Tuple[int, int]]:"""Predict click coordinates."""# Record VRAM usage before predictionvram_info = get_vram_usage()- self.vram_usage_history.append(vram_info['allocated_mb'])-+ self.vram_usage_history.append(vram_info["allocated_mb"])+if self.is_computer_agent:if self.agent is None:await self.load_model()-+if self.agent is not None:image_b64 = image_to_base64(image)- result = await self.agent.predict_click(instruction=instruction, image_b64=image_b64)-+ result = await self.agent.predict_click(+ instruction=instruction, image_b64=image_b64+ )+# Record VRAM usage after predictionvram_info = get_vram_usage()- self.vram_usage_history.append(vram_info['allocated_mb'])-+ self.vram_usage_history.append(vram_info["allocated_mb"])+return resultreturn Noneelse:- result = await self.model.predict_click(image, instruction) # type: ignore-+ result = await self.model.predict_click(image, instruction) # type: ignore+# Record VRAM usage after predictionvram_info = get_vram_usage()- self.vram_usage_history.append(vram_info['allocated_mb'])-+ self.vram_usage_history.append(vram_info["allocated_mb"])+return result-def save_results_to_markdown(all_results: List[dict],output_file: str = "screenspot_pro_results.md", title: str = "ScreenSpot-Pro Benchmark Results") -> None:+def save_results_to_markdown(+ all_results: List[dict],+ output_file: str = "screenspot_pro_results.md",+ title: str = "ScreenSpot-Pro Benchmark Results",+) -> None:"""Save evaluation results to a markdown table.-+Args:all_results: List of evaluation results for each modeloutput_file: Output markdown file path"""- with open(output_file, 'w', encoding='utf-8') as f:+ with open(output_file, "w", encoding="utf-8") as f:f.write(f"# {title}\n\n")f.write(f"**Evaluation Date:** {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}\n\n")-+# Summary tablef.write("## Summary\n\n")- f.write("| Model | Total Samples | Correct | Errors | Accuracy | Error Rate | Avg Time (s) | Median Time (s) | Time Range (s) | VRAM Max (GB) | VRAM Avg (GB) |\n")- f.write("|-------|---------------|---------|--------|----------|------------|--------------|-----------------|----------------|---------------|---------------|\n")-+ f.write(+ "| Model | Total Samples | Correct | Errors | Accuracy | Error Rate | Avg Time (s) | Median Time (s) | Time Range (s) | VRAM Max (GB) | VRAM Avg (GB) |\n"+ )+ f.write(+ "|-------|---------------|---------|--------|----------|------------|--------------|-----------------|----------------|---------------|---------------|\n"+ )+for result in all_results:- model_name = result['model_name']- total = result['total_samples']- correct = result['correct_predictions']- errors = result['failed_predictions']- accuracy = result['accuracy'] * 100- error_rate = result['failure_rate'] * 100- avg_time = result.get('avg_prediction_time', 0.0)- median_time = result.get('median_prediction_time', 0.0)- min_time = result.get('min_prediction_time', 0.0)- max_time = result.get('max_prediction_time', 0.0)+ model_name = result["model_name"]+ total = result["total_samples"]+ correct = result["correct_predictions"]+ errors = result["failed_predictions"]+ accuracy = result["accuracy"] * 100+ error_rate = result["failure_rate"] * 100+ avg_time = result.get("avg_prediction_time", 0.0)+ median_time = result.get("median_prediction_time", 0.0)+ min_time = result.get("min_prediction_time", 0.0)+ max_time = result.get("max_prediction_time", 0.0)time_range = f"{min_time:.2f} - {max_time:.2f}"- vram_max = result.get('vram_max_mb', 0.0) / 1024- vram_avg = result.get('vram_avg_mb', 0.0) / 1024-- f.write(f"| {model_name} | {total} | {correct} | {errors} | {accuracy:.2f}% | {error_rate:.2f}% | {avg_time:.2f} | {median_time:.2f} | {time_range} | {vram_max:.1f} | {vram_avg:.1f} |\n")-+ vram_max = result.get("vram_max_mb", 0.0) / 1024+ vram_avg = result.get("vram_avg_mb", 0.0) / 1024++ f.write(+ f"| {model_name} | {total} | {correct} | {errors} | {accuracy:.2f}% | {error_rate:.2f}% | {avg_time:.2f} | {median_time:.2f} | {time_range} | {vram_max:.1f} | {vram_avg:.1f} |\n"+ )+# Detailed results for each modelfor result in all_results:f.write(f"\n## {result['model_name']} - Detailed Results\n\n")- f.write("| Sample Index | Instruction | BBox | Predicted | Correct | Error | Time (s) |\n")+ f.write(+ "| Sample Index | Instruction | BBox | Predicted | Correct | Error | Time (s) |\n"+ )f.write("|-----------|-------------|------|-----------|---------|-------|----------|\n")-- for sample_result in result['results'][:10]: # Show first 10 samples- sample_idx = sample_result['sample_idx']- instruction = sample_result['instruction'][:50] + "..." if len(sample_result['instruction']) > 50 else sample_result['instruction']- bbox = str(sample_result['bbox'])- predicted = str(sample_result['predicted_coords']) if sample_result['predicted_coords'] else "None"- correct = "PASS" if sample_result['is_correct'] else "FAIL"- error = "YES" if sample_result['failed'] else "NO"- pred_time = sample_result.get('prediction_time', 0.0)-- f.write(f"| {sample_idx} | {instruction} | {bbox} | {predicted} | {correct} | {error} | {pred_time:.2f} |\n")-- if len(result['results']) > 10:++ for sample_result in result["results"][:10]: # Show first 10 samples+ sample_idx = sample_result["sample_idx"]+ instruction = (+ sample_result["instruction"][:50] + "..."+ if len(sample_result["instruction"]) > 50+ else sample_result["instruction"]+ )+ bbox = str(sample_result["bbox"])+ predicted = (+ str(sample_result["predicted_coords"])+ if sample_result["predicted_coords"]+ else "None"+ )+ correct = "PASS" if sample_result["is_correct"] else "FAIL"+ error = "YES" if sample_result["failed"] else "NO"+ pred_time = sample_result.get("prediction_time", 0.0)++ f.write(+ f"| {sample_idx} | {instruction} | {bbox} | {predicted} | {correct} | {error} | {pred_time:.2f} |\n"+ )++ if len(result["results"]) > 10:f.write(f"\n*Showing first 10 of {len(result['results'])} samples*\n")-+print(f"\nResults saved to: {output_file}")def save_visualizations(all_results: List[dict], samples, output_dir: str = "output") -> None:"""Save visualizations of predicted coordinates vs bboxes to an output folder.-+Args:all_results: List of evaluation results for each modelsamples: List of sample dicts with image, bbox, instruction keysoutput_dir: Output directory path"""os.makedirs(output_dir, exist_ok=True)-+for result in all_results:- model_name = result['model_name'].replace('/', '_').replace('\\', '_')+ model_name = result["model_name"].replace("/", "_").replace("\\", "_")model_dir = os.path.join(output_dir, model_name)os.makedirs(model_dir, exist_ok=True)-+print(f"Saving visualizations for {result['model_name']}...")-+# Save first 10 samples for visualization- for i, sample_result in enumerate(tqdm(result['results'][:10], desc=f"Saving {model_name} visualizations")):+ for i, sample_result in enumerate(+ tqdm(result["results"][:10], desc=f"Saving {model_name} visualizations")+ ):# Get sample data using index- sample_idx = sample_result['sample_idx']-+ sample_idx = sample_result["sample_idx"]+if sample_idx < len(samples):sample = samples[sample_idx]- image = sample['image'].copy() # Make a copy to avoid modifying original+ image = sample["image"].copy() # Make a copy to avoid modifying originalelse:print(f"Warning: Could not find sample at index {sample_idx}")continue-- bbox = sample_result['bbox']- predicted_coords = sample_result['predicted_coords']- is_correct = sample_result['is_correct']-++ bbox = sample_result["bbox"]+ predicted_coords = sample_result["predicted_coords"]+ is_correct = sample_result["is_correct"]+# Draw on imagedraw = ImageDraw.Draw(image)-+# Draw bounding box (ground truth) in greenx1, y1, x2, y2 = bboxdraw.rectangle([x1, y1, x2, y2], outline="green", width=3)- draw.text((x1, y1-20), "Ground Truth", fill="green")-+ draw.text((x1, y1 - 20), "Ground Truth", fill="green")+# Draw predicted click in red or blueif predicted_coords is not None:px, py = predicted_coordscolor = "blue" if is_correct else "red"# Draw crosshaircrosshair_size = 15- draw.line([(px-crosshair_size, py), (px+crosshair_size, py)], fill=color, width=3)- draw.line([(px, py-crosshair_size), (px, py+crosshair_size)], fill=color, width=3)- draw.text((px+10, py-20), f"Predicted ({px},{py})", fill=color)-+ draw.line(+ [(px - crosshair_size, py), (px + crosshair_size, py)], fill=color, width=3+ )+ draw.line(+ [(px, py - crosshair_size), (px, py + crosshair_size)], fill=color, width=3+ )+ draw.text((px + 10, py - 20), f"Predicted ({px},{py})", fill=color)+# Add status textstatus = "CORRECT" if is_correct else "INCORRECT"status_color = "blue" if is_correct else "red"draw.text((10, 10), f"Status: {status}", fill=status_color)- draw.text((10, 30), f"Instruction: {sample_result['instruction'][:50]}...", fill="black")-+ draw.text(+ (10, 30), f"Instruction: {sample_result['instruction'][:50]}...", fill="black"+ )+# Save imagefilename = f"sample_{i+1:02d}_idx{sample_idx}_{status.lower()}.png"filepath = os.path.join(model_dir, filename)image.save(filepath)-+print(f"Visualizations saved to: {model_dir}")-def save_prediction_visualization(image: Image.Image, instruction: str, predictions: List[dict],- output_file: str = "interactive_prediction.png") -> None:+def save_prediction_visualization(+ image: Image.Image,+ instruction: str,+ predictions: List[dict],+ output_file: str = "interactive_prediction.png",+) -> None:"""Save visualization of multiple model predictions on a single image.-+Args:image: PIL Image to visualizeinstruction: Instruction text@@ -358,32 +393,32 @@ def save_prediction_visualization(image: Image.Image, instruction: str, predicti# Create a copy of the imagevis_image = image.copy()draw = ImageDraw.Draw(vis_image)-+# Colors for different modelscolors = ["red", "blue", "orange", "purple", "brown", "pink", "gray", "olive"]-+# Draw predictionsfor i, pred in enumerate(predictions):color = colors[i % len(colors)]- model_name = pred['model_name']- coords = pred.get('coords')- error = pred.get('error')-+ model_name = pred["model_name"]+ coords = pred.get("coords")+ error = pred.get("error")+if coords is not None:px, py = coords# Draw crosshaircrosshair_size = 20- draw.line([(px-crosshair_size, py), (px+crosshair_size, py)], fill=color, width=4)- draw.line([(px, py-crosshair_size), (px, py+crosshair_size)], fill=color, width=4)+ draw.line([(px - crosshair_size, py), (px + crosshair_size, py)], fill=color, width=4)+ draw.line([(px, py - crosshair_size), (px, py + crosshair_size)], fill=color, width=4)# Draw model name- draw.text((px+15, py+15), f"{model_name}: ({px},{py})", fill=color)+ draw.text((px + 15, py + 15), f"{model_name}: ({px},{py})", fill=color)else:# Draw error text- draw.text((10, 50 + i*20), f"{model_name}: ERROR - {error}", fill=color)-+ draw.text((10, 50 + i * 20), f"{model_name}: ERROR - {error}", fill=color)+# Add instruction at the topdraw.text((10, 10), f"Instruction: {instruction}", fill="black")-+# Save imagevis_image.save(output_file)print(f"Prediction visualization saved to: {output_file}")@@ -392,12 +427,13 @@ def save_prediction_visualization(image: Image.Image, instruction: str, predictidef take_screenshot() -> Image.Image:"""Take a screenshot of the current screen.-+Returns:PIL Image of the screenshot"""try:import pyautogui+screenshot = pyautogui.screenshot()return screenshotexcept ImportError:@@ -406,4 +442,3 @@ def take_screenshot() -> Image.Image:except Exception as e:print(f"Error taking screenshot: {e}")raise-diff --git a/libs/python/agent/example.py b/libs/python/agent/example.pyindex fc4dc1b13d..b02ccbfdff 100644--- a/libs/python/agent/example.py+++ b/libs/python/agent/example.py@@ -9,58 +9,61 @@ from agent import ComputerAgentfrom computer import Computerfrom computer.helpers import sandboxed+@sandboxed()def read_file(location: str) -> str:"""Read contents of a file-+Parameters----------location : strPath to the file to read-+Returns-------strContents of the file or error message"""try:- with open(location, 'r') as f:+ with open(location, "r") as f:return f.read()except Exception as e:return f"Error reading file: {str(e)}"+def save_note(content: str, filename: str = "note.txt") -> str:"""Save content to a note file-+Parameters----------content : strContent to save to the filefilename : str, optionalName of the file to save to (default is "note.txt")-+Returns-------strSuccess or error message"""try:- with open(filename, 'w') as f:+ with open(filename, "w") as f:f.write(content)return f"Saved note to {filename}"except Exception as e:return f"Error saving note: {str(e)}"+def calculate(a: int, b: int) -> int:"""Calculate the sum of two integers-+Parameters----------a : intFirst integerb : intSecond integer-+Returns-------int@@ -68,15 +71,18 @@ def calculate(a: int, b: int) -> int:"""return a + b+async def main():"""Example usage of ComputerAgent with different models"""-+# Example 1: Using Claude with computer and custom toolsprint("=== Example 1: Claude with Computer ===")-++ import jsonimport os+import dotenv- import json+dotenv.load_dotenv()assert os.getenv("CUA_CONTAINER_NAME") is not None, "CUA_CONTAINER_NAME is not set"@@ -86,38 +92,37 @@ async def main():os_type="linux",provider_type="cloud",name=os.getenv("CUA_CONTAINER_NAME") or "",- api_key=os.getenv("CUA_API_KEY") or ""+ api_key=os.getenv("CUA_API_KEY") or "",) as computer:agent = ComputerAgent(# Supported models:-# == OpenAI CUA (computer-use-preview) ==model="openai/computer-use-preview",-# == Anthropic CUA (Claude > 3.5) ==- # model="anthropic/claude-opus-4-20250514",+ # model="anthropic/claude-opus-4-20250514",# model="anthropic/claude-sonnet-4-20250514",# model="anthropic/claude-3-7-sonnet-20250219",# model="anthropic/claude-3-5-sonnet-20241022",-# == UI-TARS ==# model="huggingface-local/ByteDance-Seed/UI-TARS-1.5-7B",# TODO: add local mlx provider# model="mlx-community/UI-TARS-1.5-7B-6bit",# model="ollama_chat/0000/ui-tars-1.5-7b",-# == Omniparser + Any LLM ==# model="omniparser+..."# model="omniparser+anthropic/claude-opus-4-20250514",-tools=[computer],only_n_most_recent_images=3,verbosity=logging.INFO,trajectory_dir="trajectories",use_prompt_caching=True,- max_trajectory_budget={ "max_budget": 1.0, "raise_error": True, "reset_after_each_run": False },+ max_trajectory_budget={+ "max_budget": 1.0,+ "raise_error": True,+ "reset_after_each_run": False,+ },)-+history = []while True:user_input = input("> ")@@ -143,5 +148,6 @@ async def main():# elif item["type"] == "function_call_output":# print("===>", item["output"])+if __name__ == "__main__":- asyncio.run(main())\ No newline at end of file+ asyncio.run(main())diff --git a/libs/python/computer-server/README.md b/libs/python/computer-server/README.mdindex 0e91429847..5c40bdd2bd 100644--- a/libs/python/computer-server/README.md+++ b/libs/python/computer-server/README.md@@ -8,10 +8,11 @@</picture></div>- [](#)- [](#)- [](https://discord.com/invite/mVnXXpdE85)- [](https://pypi.org/project/cua-computer-server/)+[](#)+[](#)+[](https://discord.com/invite/mVnXXpdE85)+[](https://pypi.org/project/cua-computer-server/)+</h1></div>@@ -42,4 +43,4 @@ Refer to this notebook for a step-by-step guide on how to use the Computer-Use S- [Commands](https://trycua.com/docs/libraries/computer-server/Commands)- [REST-API](https://trycua.com/docs/libraries/computer-server/REST-API)- [WebSocket-API](https://trycua.com/docs/libraries/computer-server/WebSocket-API)-- [Index](https://trycua.com/docs/libraries/computer-server/index)\ No newline at end of file+- [Index](https://trycua.com/docs/libraries/computer-server/index)diff --git a/libs/python/computer-server/computer_server/__main__.py b/libs/python/computer-server/computer_server/__main__.pyindex 89d33d0bf4..f40ff635d0 100644--- a/libs/python/computer-server/computer_server/__main__.py+++ b/libs/python/computer-server/computer_server/__main__.py@@ -4,6 +4,7 @@ This allows the server to be started with `python -m computer_server`."""import sys+from .cli import mainif __name__ == "__main__":diff --git a/libs/python/computer-server/computer_server/cli.py b/libs/python/computer-server/computer_server/cli.pyindex 38e4c24f43..21c8cec67f 100644--- a/libs/python/computer-server/computer_server/cli.py+++ b/libs/python/computer-server/computer_server/cli.py@@ -36,7 +36,7 @@ def parse_args(args: Optional[List[str]] = None) -> argparse.Namespace:help="Path to SSL private key file (enables HTTPS)",)parser.add_argument(- "--ssl-certfile",+ "--ssl-certfile",type=str,help="Path to SSL certificate file (enables HTTPS)",)@@ -73,16 +73,18 @@ def main() -> None:# Check if watchdog should be enabledcontainer_name = os.environ.get("CONTAINER_NAME")enable_watchdog = (args.watchdog or bool(container_name)) and not sys.platform.startswith("win")-+if container_name:- logger.info(f"Container environment detected (CONTAINER_NAME={container_name}), enabling watchdog")+ logger.info(+ f"Container environment detected (CONTAINER_NAME={container_name}), enabling watchdog"+ )elif args.watchdog:logger.info("Watchdog explicitly enabled via --watchdog flag")-+# Start watchdog if enabledif enable_watchdog:logger.info(f"Starting watchdog monitoring with {args.watchdog_interval}s interval")-+def run_watchdog_thread():"""Run watchdog in a separate thread."""loop = asyncio.new_event_loop()@@ -90,38 +92,32 @@ def main() -> None:try:# Create CLI args dict for watchdogcli_args = {- 'host': args.host,- 'port': args.port,- 'log_level': args.log_level,- 'ssl_keyfile': args.ssl_keyfile,- 'ssl_certfile': args.ssl_certfile+ "host": args.host,+ "port": args.port,+ "log_level": args.log_level,+ "ssl_keyfile": args.ssl_keyfile,+ "ssl_certfile": args.ssl_certfile,}-+# Create watchdog with restart settingsfrom .watchdog import Watchdog- watchdog = Watchdog(- cli_args=cli_args,- ping_interval=args.watchdog_interval- )++ watchdog = Watchdog(cli_args=cli_args, ping_interval=args.watchdog_interval)watchdog.restart_enabled = not args.no_restart-+loop.run_until_complete(watchdog.start_monitoring())except Exception as e:logger.error(f"Watchdog error: {e}")finally:loop.close()-+# Start watchdog in background thread- watchdog_thread = threading.Thread(- target=run_watchdog_thread,- daemon=True,- name="watchdog"- )+ watchdog_thread = threading.Thread(target=run_watchdog_thread, daemon=True, name="watchdog")watchdog_thread.start()# Create and start the serverlogger.info(f"Starting CUA Computer API server on {args.host}:{args.port}...")-+# Handle SSL configurationssl_args = {}if args.ssl_keyfile and args.ssl_certfile:@@ -131,10 +127,12 @@ def main() -> None:}logger.info("HTTPS mode enabled with SSL certificates")elif args.ssl_keyfile or args.ssl_certfile:- logger.warning("Both --ssl-keyfile and --ssl-certfile are required for HTTPS. Running in HTTP mode.")+ logger.warning(+ "Both --ssl-keyfile and --ssl-certfile are required for HTTPS. Running in HTTP mode."+ )else:logger.info("HTTP mode (no SSL certificates provided)")-+server = Server(host=args.host, port=args.port, log_level=args.log_level, **ssl_args)try:diff --git a/libs/python/computer-server/computer_server/diorama/base.py b/libs/python/computer-server/computer_server/diorama/base.pyindex 3ca01133cc..4135281814 100644--- a/libs/python/computer-server/computer_server/diorama/base.py+++ b/libs/python/computer-server/computer_server/diorama/base.py@@ -1,4 +1,5 @@class BaseDioramaHandler:"""Base Diorama handler for unsupported OSes."""+async def diorama_cmd(self, action: str, arguments: dict = None) -> dict:return {"success": False, "error": "Diorama is not supported on this OS yet."}diff --git a/libs/python/computer-server/computer_server/diorama/diorama.py b/libs/python/computer-server/computer_server/diorama/diorama.pyindex 3a63b0b6d8..f5e34cacbe 100644--- a/libs/python/computer-server/computer_server/diorama/diorama.py+++ b/libs/python/computer-server/computer_server/diorama/diorama.py@@ -1,31 +1,38 @@#!/usr/bin/env python3"""Diorama: A virtual desktop manager for macOS"""-import osimport asyncio+import ioimport logging+import osimport sys-import iofrom typing import Union-from PIL import Image, ImageDraw--from computer_server.diorama.draw import capture_all_apps, AppActivationContext, get_frontmost_and_active_app, get_all_windows, get_running_appsfrom computer_server.diorama.diorama_computer import DioramaComputer+from computer_server.diorama.draw import (+ AppActivationContext,+ capture_all_apps,+ get_all_windows,+ get_frontmost_and_active_app,+ get_running_apps,+)from computer_server.handlers.macos import *+from PIL import Image, ImageDraw# simple, nicely formatted logginglogger = logging.getLogger(__name__)automation_handler = MacOSAutomationHandler()+class Diorama:"""Virtual desktop manager that provides automation capabilities for macOS applications.-+Manages application windows and provides an interface for taking screenshots,mouse interactions, keyboard input, and coordinate transformations betweenscreenshot space and screen space."""+_scheduler_queue = None_scheduler_task = None_loop = None@@ -34,10 +41,10 @@ class Diorama:@classmethoddef create_from_apps(cls, *args) -> DioramaComputer:"""Create a DioramaComputer instance from a list of application names.-+Args:*args: Variable number of application names to include in the desktop-+Returns:DioramaComputer: A computer interface for the specified applications"""@@ -46,10 +53,10 @@ class Diorama:# Dictionary to store cursor positions for each unique app_list hash_cursor_positions = {}-+def __init__(self, app_list):"""Initialize a Diorama instance for the specified applications.-+Args:app_list: List of application names to manage"""@@ -57,10 +64,10 @@ class Diorama:self.interface = self.Interface(self)self.computer = DioramaComputer(self)self.focus_context = None-+# Create a hash for this app_list to use as a keyself.app_list_hash = hash(tuple(sorted(app_list)))-+# Initialize cursor position for this app_list if it doesn't existif self.app_list_hash not in Diorama._cursor_positions:Diorama._cursor_positions[self.app_list_hash] = (0, 0)@@ -68,7 +75,7 @@ class Diorama:@classmethoddef _ensure_scheduler(cls):"""Ensure the async scheduler loop is running.-+Creates and starts the scheduler task if it hasn't been started yet."""if not cls._scheduler_started:@@ -81,7 +88,7 @@ class Diorama:@classmethodasync def _scheduler_loop(cls):"""Main scheduler loop that processes automation commands.-+Continuously processes commands from the scheduler queue, handlingscreenshots, mouse actions, keyboard input, and scrolling operations."""@@ -91,31 +98,37 @@ class Diorama:args = cmd.get("arguments", {})future = cmd.get("future")logger.info(f"Processing command: {action} | args={args}")-+app_whitelist = args.get("app_list", [])-+all_windows = get_all_windows()running_apps = get_running_apps()- frontmost_app, active_app_to_use, active_app_pid = get_frontmost_and_active_app(all_windows, running_apps, app_whitelist)+ frontmost_app, active_app_to_use, active_app_pid = get_frontmost_and_active_app(+ all_windows, running_apps, app_whitelist+ )focus_context = AppActivationContext(active_app_pid, active_app_to_use, logger)-+with focus_context:try:if action == "screenshot":logger.info(f"Taking screenshot for apps: {app_whitelist}")result, img = capture_all_apps(- app_whitelist=app_whitelist,- save_to_disk=False,- take_focus=False+ app_whitelist=app_whitelist, save_to_disk=False, take_focus=False)logger.info("Screenshot complete.")if future:future.set_result((result, img))# Mouse actions- elif action in ["left_click", "right_click", "double_click", "move_cursor", "drag_to"]:+ elif action in [+ "left_click",+ "right_click",+ "double_click",+ "move_cursor",+ "drag_to",+ ]:x = args.get("x")y = args.get("y")-+duration = args.get("duration", 0.5)if action == "left_click":await automation_handler.left_click(x, y)@@ -134,7 +147,7 @@ class Diorama:y = args.get("y")if x is not None and y is not None:await automation_handler.move_cursor(x, y)-+clicks = args.get("clicks", 1)if action == "scroll_up":await automation_handler.scroll_up(clicks)@@ -171,31 +184,31 @@ class Diorama:if future:future.set_exception(e)- class Interface():+ class Interface:"""Interface for interacting with the virtual desktop.-+Provides methods for taking screenshots, mouse interactions, keyboard input,and coordinate transformations between screenshot and screen coordinates."""-+def __init__(self, diorama):"""Initialize the interface with a reference to the parent Diorama instance.-+Args:diorama: The parent Diorama instance"""self._diorama = diorama-+self._scene_hitboxes = []self._scene_size = Noneasync def _send_cmd(self, action, arguments=None):"""Send a command to the scheduler queue.-+Args:action (str): The action to performarguments (dict, optional): Arguments for the action-+Returns:The result of the command execution"""@@ -203,11 +216,13 @@ class Diorama:loop = asyncio.get_event_loop()future = loop.create_future()logger.info(f"Enqueuing {action} command for apps: {self._diorama.app_list}")- await Diorama._scheduler_queue.put({- "action": action,- "arguments": {"app_list": self._diorama.app_list, **(arguments or {})},- "future": future- })+ await Diorama._scheduler_queue.put(+ {+ "action": action,+ "arguments": {"app_list": self._diorama.app_list, **(arguments or {})},+ "future": future,+ }+ )try:return await futureexcept asyncio.CancelledError:@@ -216,21 +231,23 @@ class Diorama:async def screenshot(self, as_bytes: bool = True) -> Union[str, Image.Image]:"""Take a screenshot of the managed applications.-+Args:as_bytes (bool): If True, return base64-encoded bytes; if False, return PIL Image-+Returns:Union[str, Image.Image]: Base64-encoded PNG bytes or PIL Image object"""import base64+result, img = await self._send_cmd("screenshot")self._scene_hitboxes = result.get("hitboxes", [])self._scene_size = img.size-+if as_bytes:# PIL Image to bytes, then base64 encode for JSONimport io+img_byte_arr = io.BytesIO()img.save(img_byte_arr, format="PNG")img_bytes = img_byte_arr.getvalue()@@ -241,7 +258,7 @@ class Diorama:async def left_click(self, x, y):"""Perform a left mouse click at the specified coordinates.-+Args:x (int): X coordinate in screenshot space (or None to use last position)y (int): Y coordinate in screenshot space (or None to use last position)@@ -258,7 +275,7 @@ class Diorama:async def right_click(self, x, y):"""Perform a right mouse click at the specified coordinates.-+Args:x (int): X coordinate in screenshot space (or None to use last position)y (int): Y coordinate in screenshot space (or None to use last position)@@ -269,13 +286,13 @@ class Diorama:x, y = x or last_pos[0], y or last_pos[1]# Update cursor position for this app_list hashDiorama._cursor_positions[app_list_hash] = (x, y)-+sx, sy = await self.to_screen_coordinates(x, y)await self._send_cmd("right_click", {"x": sx, "y": sy})async def double_click(self, x, y):"""Perform a double mouse click at the specified coordinates.-+Args:x (int): X coordinate in screenshot space (or None to use last position)y (int): Y coordinate in screenshot space (or None to use last position)@@ -286,13 +303,13 @@ class Diorama:x, y = x or last_pos[0], y or last_pos[1]# Update cursor position for this app_list hashDiorama._cursor_positions[app_list_hash] = (x, y)-+sx, sy = await self.to_screen_coordinates(x, y)await self._send_cmd("double_click", {"x": sx, "y": sy})async def move_cursor(self, x, y):"""Move the mouse cursor to the specified coordinates.-+Args:x (int): X coordinate in screenshot space (or None to use last position)y (int): Y coordinate in screenshot space (or None to use last position)@@ -303,13 +320,13 @@ class Diorama:x, y = x or last_pos[0], y or last_pos[1]# Update cursor position for this app_list hashDiorama._cursor_positions[app_list_hash] = (x, y)-+sx, sy = await self.to_screen_coordinates(x, y)await self._send_cmd("move_cursor", {"x": sx, "y": sy})async def drag_to(self, x, y, duration=0.5):"""Drag the mouse from current position to the specified coordinates.-+Args:x (int): X coordinate in screenshot space (or None to use last position)y (int): Y coordinate in screenshot space (or None to use last position)@@ -321,13 +338,13 @@ class Diorama:x, y = x or last_pos[0], y or last_pos[1]# Update cursor position for this app_list hashDiorama._cursor_positions[app_list_hash] = (x, y)-+sx, sy = await self.to_screen_coordinates(x, y)await self._send_cmd("drag_to", {"x": sx, "y": sy, "duration": duration})async def get_cursor_position(self):"""Get the current cursor position in screen coordinates.-+Returns:tuple: (x, y) coordinates of the cursor in screen space"""@@ -335,7 +352,7 @@ class Diorama:async def type_text(self, text):"""Type the specified text using the keyboard.-+Args:text (str): The text to type"""@@ -343,7 +360,7 @@ class Diorama:async def press_key(self, key):"""Press a single key on the keyboard.-+Args:key (str): The key to press"""@@ -351,7 +368,7 @@ class Diorama:async def hotkey(self, keys):"""Press a combination of keys simultaneously.-+Args:keys (list): List of keys to press together"""@@ -359,7 +376,7 @@ class Diorama:async def scroll_up(self, clicks: int = 1):"""Scroll up at the current cursor position.-+Args:clicks (int): Number of scroll clicks to perform"""@@ -367,12 +384,12 @@ class Diorama:app_list_hash = hash(tuple(sorted(self._diorama.app_list)))last_pos = Diorama._cursor_positions.get(app_list_hash, (0, 0))x, y = last_pos[0], last_pos[1]-+await self._send_cmd("scroll_up", {"clicks": clicks, "x": x, "y": y})async def scroll_down(self, clicks: int = 1):"""Scroll down at the current cursor position.-+Args:clicks (int): Number of scroll clicks to perform"""@@ -380,18 +397,18 @@ class Diorama:app_list_hash = hash(tuple(sorted(self._diorama.app_list)))last_pos = Diorama._cursor_positions.get(app_list_hash, (0, 0))x, y = last_pos[0], last_pos[1]-+await self._send_cmd("scroll_down", {"clicks": clicks, "x": x, "y": y})async def get_screen_size(self) -> dict[str, int]:"""Get the size of the screenshot area.-+Returns:dict[str, int]: Dictionary with 'width' and 'height' keys"""if not self._scene_size:await self.screenshot()- return { "width": self._scene_size[0], "height": self._scene_size[1] }+ return {"width": self._scene_size[0], "height": self._scene_size[1]}async def to_screen_coordinates(self, x: float, y: float) -> tuple[float, float]:"""Convert screenshot coordinates to screen coordinates.@@ -404,29 +421,29 @@ class Diorama:tuple[float, float]: (x, y) absolute coordinates in screen space"""if not self._scene_hitboxes:- await self.screenshot() # get hitboxes+ await self.screenshot() # get hitboxes# Try all hitboxesfor h in self._scene_hitboxes[::-1]:rect_from = h.get("hitbox")rect_to = h.get("target")if not rect_from or len(rect_from) != 4:continue-+# check if (x, y) is inside rect_fromx0, y0, x1, y1 = rect_fromif x0 <= x <= x1 and y0 <= y <= y1:logger.info(f"Found hitbox: {h}")# remap (x, y) to rect_totx0, ty0, tx1, ty1 = rect_to-+# calculate offset from x0, y0offset_x = x - x0offset_y = y - y0-+# remap offset to rect_totx = tx0 + offset_xty = ty0 + offset_y-+return tx, tyreturn x, y@@ -441,34 +458,37 @@ class Diorama:tuple[float, float]: (x, y) absolute coordinates in screenshot space"""if not self._scene_hitboxes:- await self.screenshot() # get hitboxes+ await self.screenshot() # get hitboxes# Try all hitboxesfor h in self._scene_hitboxes[::-1]:rect_from = h.get("target")rect_to = h.get("hitbox")if not rect_from or len(rect_from) != 4:continue-+# check if (x, y) is inside rect_fromx0, y0, x1, y1 = rect_fromif x0 <= x <= x1 and y0 <= y <= y1:# remap (x, y) to rect_totx0, ty0, tx1, ty1 = rect_to-+# calculate offset from x0, y0offset_x = x - x0offset_y = y - y0-+# remap offset to rect_totx = tx0 + offset_xty = ty0 + offset_y-+return tx, tyreturn x, y-import pyautogui+import time+import pyautogui++async def main():"""Main function demonstrating Diorama usage with multiple desktops and mouse tracking."""desktop1 = Diorama.create_from_apps(["Discord", "Notes"])@@ -511,7 +531,7 @@ async def main():# Draw on a copy of the screenshotframe = base_img.copy()frame_draw = ImageDraw.Draw(frame)- frame_draw.ellipse((sx-5, sy-5, sx+5, sy+5), fill="blue", outline="blue")+ frame_draw.ellipse((sx - 5, sy - 5, sx + 5, sy + 5), fill="blue", outline="blue")# Save the frameframe.save("app_screenshots/desktop3_mouse.png")print(f"Mouse at screen ({mouse_x}, {mouse_y}) -> screenshot ({sx:.1f}, {sy:.1f})")@@ -520,15 +540,13 @@ async def main():print("Stopped tracking.")draw.text((rect[0], rect[1]), str(idx), fill="red")-+canvas.save("app_screenshots/desktop3_hitboxes.png")--# move mouse in a square spiral around the screenimport mathimport random-+step = 20 # pixels per movedot_radius = 10width = screen_size["width"]@@ -539,11 +557,12 @@ async def main():await desktop3.interface.move_cursor(x, y)img = await desktop3.interface.screenshot(as_bytes=False)draw = ImageDraw.Draw(img)- draw.ellipse((x-dot_radius, y-dot_radius, x+dot_radius, y+dot_radius), fill="red")+ draw.ellipse((x - dot_radius, y - dot_radius, x + dot_radius, y + dot_radius), fill="red")img.save("current.png")await asyncio.sleep(0.03)x += stepy = math.sin(x / width * math.pi * 2) * 50 + 25+if __name__ == "__main__":asyncio.run(main())diff --git a/libs/python/computer-server/computer_server/diorama/diorama_computer.py b/libs/python/computer-server/computer_server/diorama/diorama_computer.pyindex c00bd86fbd..f37d429900 100644--- a/libs/python/computer-server/computer_server/diorama/diorama_computer.py+++ b/libs/python/computer-server/computer_server/diorama/diorama_computer.py@@ -1,14 +1,16 @@import asyncio+class DioramaComputer:"""A minimal Computer-like interface for Diorama, compatible with ComputerAgent.Implements _initialized, run(), and __aenter__ for agent compatibility."""+def __init__(self, diorama):"""Initialize the DioramaComputer with a diorama instance.-+Args:diorama: The diorama instance to wrap with a computer-like interface."""@@ -19,10 +21,10 @@ class DioramaComputer:async def __aenter__(self):"""Async context manager entry method for compatibility with ComputerAgent.-+Ensures an event loop is running and marks the instance as initialized.Creates a new event loop if none is currently running.-+Returns:DioramaComputer: The initialized instance."""@@ -37,10 +39,10 @@ class DioramaComputer:async def run(self):"""Run method stub for compatibility with ComputerAgent interface.-+Ensures the instance is initialized before returning. If not alreadyinitialized, calls __aenter__ to perform initialization.-+Returns:DioramaComputer: The initialized instance."""diff --git a/libs/python/computer-server/computer_server/diorama/draw.py b/libs/python/computer-server/computer_server/diorama/draw.pyindex e915b79087..072098244b 100644--- a/libs/python/computer-server/computer_server/diorama/draw.py+++ b/libs/python/computer-server/computer_server/diorama/draw.py@@ -3,7 +3,7 @@This script renders filtered views of the macOS desktop, preserving only selected applicationswhile maintaining system UI elements like menubar and dock. Each "diorama" shows a consistent-view of the system while isolating specific applications.+view of the system while isolating specific applications.The image is "smart resized" to remove any empty space around the menubar and dock.@@ -15,26 +15,28 @@ Key features:- Supports parallel views of the same desktop for multi-agent systems"""-import sys-import os-import timeimport argparse-from typing import List, Dict, Any, Optional, Tuple-import json-from PIL import Image, ImageDraw-import ioimport asyncioimport functools+import io+import jsonimport logging+import os+import sys+import time+from typing import Any, Dict, List, Optional, Tuple++from PIL import Image, ImageDraw# simple, nicely formatted logginglogger = logging.getLogger(__name__)from computer_server.diorama.safezone import (- get_menubar_bounds,get_dock_bounds,+ get_menubar_bounds,)+# Timing decorator for profilingdef timing_decorator(func):@functools.wraps(func)@@ -45,46 +47,46 @@ def timing_decorator(func):elapsed_time = end_time - start_timelogger.debug(f"Function {func.__name__} took {elapsed_time:.4f} seconds to run")return result+return wrapper+# Import Objective-C bridge librariestry:- import Quartzimport AppKit- from ApplicationServices import (- AXUIElementCreateSystemWide, # type: ignore- AXUIElementCreateApplication, # type: ignore- AXUIElementCopyAttributeValue, # type: ignore- AXUIElementCopyAttributeValues, # type: ignore- kAXFocusedWindowAttribute, # type: ignore- kAXWindowsAttribute, # type: ignore- kAXMainWindowAttribute, # type: ignore- kAXChildrenAttribute, # type: ignore- kAXRoleAttribute, # type: ignore- kAXTitleAttribute, # type: ignore- kAXValueAttribute, # type: ignore- kAXDescriptionAttribute, # type: ignore- kAXEnabledAttribute, # type: ignore- kAXPositionAttribute, # type: ignore- kAXSizeAttribute, # type: ignore- kAXErrorSuccess, # type: ignore- AXValueGetType, # type: ignore- kAXValueCGSizeType, # type: ignore- kAXValueCGPointType, # type: ignore- kAXValueCFRangeType, # type: ignore- AXUIElementGetTypeID, # type: ignore- AXValueGetValue, # type: ignore- kAXVisibleChildrenAttribute, # type: ignore- kAXRoleDescriptionAttribute, # type: ignore- kAXFocusedApplicationAttribute, # type: ignore- kAXFocusedUIElementAttribute, # type: ignore- kAXSelectedTextAttribute, # type: ignore- kAXSelectedTextRangeAttribute, # type: ignore- )- from AppKit import NSWorkspace, NSApplication, NSApp, NSRunningApplicationimport Foundation- from Foundation import NSObject, NSMakeRectimport objc+ import Quartz+ from AppKit import NSApp, NSApplication, NSRunningApplication, NSWorkspace+ from ApplicationServices import AXUIElementCopyAttributeValue # type: ignore+ from ApplicationServices import AXUIElementCopyAttributeValues # type: ignore+ from ApplicationServices import AXUIElementCreateApplication # type: ignore+ from ApplicationServices import AXUIElementCreateSystemWide # type: ignore+ from ApplicationServices import AXUIElementGetTypeID # type: ignore+ from ApplicationServices import AXValueGetType # type: ignore+ from ApplicationServices import AXValueGetValue # type: ignore+ from ApplicationServices import kAXChildrenAttribute # type: ignore+ from ApplicationServices import kAXDescriptionAttribute # type: ignore+ from ApplicationServices import kAXEnabledAttribute # type: ignore+ from ApplicationServices import kAXErrorSuccess # type: ignore+ from ApplicationServices import kAXFocusedApplicationAttribute # type: ignore+ from ApplicationServices import kAXFocusedUIElementAttribute # type: ignore+ from ApplicationServices import kAXFocusedWindowAttribute # type: ignore+ from ApplicationServices import kAXMainWindowAttribute # type: ignore+ from ApplicationServices import kAXPositionAttribute # type: ignore+ from ApplicationServices import kAXRoleAttribute # type: ignore+ from ApplicationServices import kAXRoleDescriptionAttribute # type: ignore+ from ApplicationServices import kAXSelectedTextAttribute # type: ignore+ from ApplicationServices import kAXSelectedTextRangeAttribute # type: ignore+ from ApplicationServices import kAXSizeAttribute # type: ignore+ from ApplicationServices import kAXTitleAttribute # type: ignore+ from ApplicationServices import kAXValueAttribute # type: ignore+ from ApplicationServices import kAXValueCFRangeType # type: ignore+ from ApplicationServices import kAXValueCGPointType # type: ignore+ from ApplicationServices import kAXValueCGSizeType # type: ignore+ from ApplicationServices import kAXVisibleChildrenAttribute # type: ignore+ from ApplicationServices import kAXWindowsAttribute # type: ignore+ from Foundation import NSMakeRect, NSObjectexcept ImportError:logger.error("Error: This script requires PyObjC to be installed.")logger.error("Please install it with: pip install pyobjc")@@ -111,7 +113,7 @@ kCGWindowAlpha = "kCGWindowAlpha" # Window opacityNSApplicationActivationOptions = {"regular": 0, # Default activation"bringing_all_windows_forward": 1 << 0, # NSApplicationActivateAllWindows- "ignoring_other_apps": 1 << 1 # NSApplicationActivateIgnoringOtherApps+ "ignoring_other_apps": 1 << 1, # NSApplicationActivateIgnoringOtherApps}@@ -168,6 +170,7 @@ def CFAttributeToPyObject(attrValue):except KeyError:return None+def element_attribute(element, attribute):if attribute == kAXChildrenAttribute:err, value = AXUIElementCopyAttributeValues(element, attribute, 0, 999, None)@@ -184,6 +187,7 @@ def element_attribute(element, attribute):return valuereturn None+def element_value(element, type):err, value = AXValueGetValue(element, type, None)if err == True:@@ -194,19 +198,20 @@ def element_value(element, type):@timing_decoratordef get_running_apps() -> List[NSRunningApplication]:"""Get list of all running applications-+Returns:List of NSRunningApplication objects"""return NSWorkspace.sharedWorkspace().runningApplications()+# @timing_decoratordef get_app_info(app: NSRunningApplication) -> Dict[str, Any]:"""Get information about an application-+Args:app: NSRunningApplication object-+Returns:Dictionary with application information"""@@ -219,48 +224,49 @@ def get_app_info(app: NSRunningApplication) -> Dict[str, Any]:"terminated": app.isTerminated(),}+@timing_decoratordef get_all_windows() -> List[Dict[str, Any]]:"""Get all windows from all applications with z-order information-+Returns:List of window dictionaries with z-order information"""# Get all windows from Quartz# The kCGWindowListOptionOnScreenOnly flag gets only visible windows with preserved z-orderwindow_list = Quartz.CGWindowListCopyWindowInfo(- Quartz.kCGWindowListOptionOnScreenOnly,- Quartz.kCGNullWindowID+ Quartz.kCGWindowListOptionOnScreenOnly, Quartz.kCGNullWindowID)-+# Create a dictionary of window z-order- z_order = {window['kCGWindowNumber']: z_index for z_index, window in enumerate(window_list[::-1])}-+ z_order = {+ window["kCGWindowNumber"]: z_index for z_index, window in enumerate(window_list[::-1])+ }+# The kCGWindowListOptionAll flag gets all windows *without* z-order preservedwindow_list_all = Quartz.CGWindowListCopyWindowInfo(- Quartz.kCGWindowListOptionAll,- Quartz.kCGNullWindowID+ Quartz.kCGWindowListOptionAll, Quartz.kCGNullWindowID)-+# Process all windowswindows = []for window in window_list_all:# We track z_index which is the index in the window list (0 is the desktop / background)-+# Get window properties- window_id = window.get('kCGWindowNumber', 0)- window_name = window.get('kCGWindowName', '')- window_pid = window.get('kCGWindowOwnerPID', 0)- window_bounds = window.get('kCGWindowBounds', {})- window_owner = window.get('kCGWindowOwnerName', '')- window_is_on_screen = window.get('kCGWindowIsOnscreen', False)-+ window_id = window.get("kCGWindowNumber", 0)+ window_name = window.get("kCGWindowName", "")+ window_pid = window.get("kCGWindowOwnerPID", 0)+ window_bounds = window.get("kCGWindowBounds", {})+ window_owner = window.get("kCGWindowOwnerName", "")+ window_is_on_screen = window.get("kCGWindowIsOnscreen", False)+# Get z-order information# Note: kCGWindowLayer provides the system's layer value (lower values are higher in the stack)layer = window.get(kCGWindowLayer, 0)opacity = window.get(kCGWindowAlpha, 1.0)z_index = z_order.get(window_id, -1)-+# Determine window role (desktop, dock, menubar, app)if window_name == "Dock" and window_owner == "Dock":role = "dock"@@ -270,46 +276,57 @@ def get_all_windows() -> List[Dict[str, Any]]:role = "desktop"else:role = "app"-+# Only include windows with valid boundsif window_bounds:- windows.append({- "id": window_id,- "name": window_name or "Unnamed Window",- "pid": window_pid,- "owner": window_owner,- "role": role,- "is_on_screen": window_is_on_screen,- "bounds": {- "x": window_bounds.get('X', 0),- "y": window_bounds.get('Y', 0),- "width": window_bounds.get('Width', 0),- "height": window_bounds.get('Height', 0)- },- "layer": layer, # System layer (lower values are higher in stack)- "z_index": z_index, # Our z-index (0 is the desktop)- "opacity": opacity- })-+ windows.append(+ {+ "id": window_id,+ "name": window_name or "Unnamed Window",+ "pid": window_pid,+ "owner": window_owner,+ "role": role,+ "is_on_screen": window_is_on_screen,+ "bounds": {+ "x": window_bounds.get("X", 0),+ "y": window_bounds.get("Y", 0),+ "width": window_bounds.get("Width", 0),+ "height": window_bounds.get("Height", 0),+ },+ "layer": layer, # System layer (lower values are higher in stack)+ "z_index": z_index, # Our z-index (0 is the desktop)+ "opacity": opacity,+ }+ )+windows = sorted(windows, key=lambda x: x["z_index"])-+return windows+def get_app_windows(app_pid: int, all_windows: List[Dict[str, Any]]) -> List[Dict[str, Any]]:"""Get all windows for a specific application-+Args:app_pid: Process ID of the applicationall_windows: List of all windows with z-order information-+Returns:List of window dictionaries for the app"""# Filter windows by PIDreturn [window for window in all_windows if window["pid"] == app_pid]+@timing_decorator-def draw_desktop_screenshot(app_whitelist: List[str] = None, all_windows: List[Dict[str, Any]] = None, dock_bounds: Dict[str, float] = None, dock_items: List[Dict[str, Any]] = None, menubar_bounds: Dict[str, float] = None, menubar_items: List[Dict[str, Any]] = None) -> Tuple[Optional[Image.Image], List[Dict[str, Any]]]:+def draw_desktop_screenshot(+ app_whitelist: List[str] = None,+ all_windows: List[Dict[str, Any]] = None,+ dock_bounds: Dict[str, float] = None,+ dock_items: List[Dict[str, Any]] = None,+ menubar_bounds: Dict[str, float] = None,+ menubar_items: List[Dict[str, Any]] = None,+) -> Tuple[Optional[Image.Image], List[Dict[str, Any]]]:"""Capture a screenshot of the entire desktop using Quartz compositing, including dock as a second pass.Args:app_whitelist: Optional list of app names to include in the screenshot@@ -340,7 +357,7 @@ def draw_desktop_screenshot(app_whitelist: List[str] = None, all_windows: List[D# Screenshot-to-screen hitboxeshitboxes = []-+if app_whitelist is None:# Single pass: desktop, menubar, app, dockwindow_list = Foundation.CFArrayCreateMutable(None, len(all_windows), None)@@ -360,31 +377,46 @@ def draw_desktop_screenshot(app_whitelist: List[str] = None, all_windows: List[DNone, width, height, 8, 0, color_space, Quartz.kCGImageAlphaPremultipliedLast)Quartz.CGContextDrawImage(cg_context, screen_rect, cg_image)- hitboxes.append({- "hitbox": [0, 0, width, height],- "target": [0, 0, width, height]- })+ hitboxes.append({"hitbox": [0, 0, width, height], "target": [0, 0, width, height]})else:# Filter out windows that are not in the whitelist- all_windows = [window for window in all_windows if window["owner"] in app_whitelist or window["role"] != "app"]+ all_windows = [+ window+ for window in all_windows+ if window["owner"] in app_whitelist or window["role"] != "app"+ ]app_windows = [window for window in all_windows if window["role"] == "app"]-+dock_orientation = "side" if dock_bounds["width"] < dock_bounds["height"] else "bottom"-- menubar_length = max(item["bounds"]["x"] + item["bounds"]["width"] for item in menubar_items) if menubar_items else 0-++ menubar_length = (+ max(item["bounds"]["x"] + item["bounds"]["width"] for item in menubar_items)+ if menubar_items+ else 0+ )+# Calculate bounds of app windowsapp_bounds = {"x": min(window["bounds"]["x"] for window in app_windows) if app_windows else 0,"y": min(window["bounds"]["y"] for window in app_windows) if app_windows else 0,}- app_bounds["width"] = max(window["bounds"]["x"] + window["bounds"]["width"] for window in app_windows) - app_bounds["x"] if app_windows else 0- app_bounds["height"] = max(window["bounds"]["y"] + window["bounds"]["height"] for window in app_windows) - app_bounds["y"] if app_windows else 0-+ app_bounds["width"] = (+ max(window["bounds"]["x"] + window["bounds"]["width"] for window in app_windows)+ - app_bounds["x"]+ if app_windows+ else 0+ )+ app_bounds["height"] = (+ max(window["bounds"]["y"] + window["bounds"]["height"] for window in app_windows)+ - app_bounds["y"]+ if app_windows+ else 0+ )+# Set minimum bounds of 256x256app_bounds["width"] = max(app_bounds["width"], 256)app_bounds["height"] = max(app_bounds["height"], 256)-+# Add dock bounds to app boundsif dock_orientation == "bottom":app_bounds["height"] += dock_bounds["height"] + 4@@ -394,19 +426,21 @@ def draw_desktop_screenshot(app_whitelist: List[str] = None, all_windows: List[Delse:app_bounds["x"] -= dock_bounds["width"] + 4app_bounds["width"] += dock_bounds["width"] + 4-+# Add menubar bounds to app boundsapp_bounds["height"] += menubar_bounds["height"]-+# Make sure app bounds contains menubar boundsapp_bounds["width"] = max(app_bounds["width"], menubar_length)-+# Clamp bounds to screenapp_bounds["x"] = max(app_bounds["x"], 0)app_bounds["y"] = max(app_bounds["y"], 0)app_bounds["width"] = min(app_bounds["width"], frame.size.width - app_bounds["x"])- app_bounds["height"] = min(app_bounds["height"], frame.size.height - app_bounds["y"] + menubar_bounds["height"])-+ app_bounds["height"] = min(+ app_bounds["height"], frame.size.height - app_bounds["y"] + menubar_bounds["height"]+ )+# Create CGContext for compositingwidth = int(app_bounds["width"])height = int(app_bounds["height"])@@ -414,7 +448,7 @@ def draw_desktop_screenshot(app_whitelist: List[str] = None, all_windows: List[Dcg_context = Quartz.CGBitmapContextCreate(None, width, height, 8, 0, color_space, Quartz.kCGImageAlphaPremultipliedLast)-+def _draw_layer(cg_context, all_windows, source_rect, target_rect):"""Draw a layer of windows from source_rect to target_rect on the given context."""window_list = Foundation.CFArrayCreateMutable(None, len(all_windows), None)@@ -425,19 +459,13 @@ def draw_desktop_screenshot(app_whitelist: List[str] = None, all_windows: List[D)if cg_image is not None:Quartz.CGContextDrawImage(cg_context, target_rect, cg_image)-+# --- FIRST PASS: desktop, apps ---source_position = [app_bounds["x"], app_bounds["y"]]source_size = [app_bounds["width"], app_bounds["height"]]- target_position = [- 0,- min(- menubar_bounds["y"] + menubar_bounds["height"],- app_bounds["y"]- )- ]+ target_position = [0, min(menubar_bounds["y"] + menubar_bounds["height"], app_bounds["y"])]target_size = [app_bounds["width"], app_bounds["height"]]-+if dock_orientation == "bottom":source_size[1] += dock_bounds["height"]target_size[1] += dock_bounds["height"]@@ -447,42 +475,57 @@ def draw_desktop_screenshot(app_whitelist: List[str] = None, all_windows: List[Dtarget_position[0] -= dock_bounds["width"]source_size[0] += dock_bounds["width"]target_size[0] += dock_bounds["width"]-+app_source_rect = Quartz.CGRectMake(source_position[0], source_position[1], source_size[0], source_size[1])app_target_rect = Quartz.CGRectMake(- target_position[0], app_bounds["height"] - target_position[1] - target_size[1], target_size[0], target_size[1]+ target_position[0],+ app_bounds["height"] - target_position[1] - target_size[1],+ target_size[0],+ target_size[1],)- first_pass_windows = [w for w in all_windows if w["role"] == "app" or w["role"] == "desktop"]+ first_pass_windows = [+ w for w in all_windows if w["role"] == "app" or w["role"] == "desktop"+ ]_draw_layer(cg_context, first_pass_windows, app_source_rect, app_target_rect)-- hitboxes.append({- "hitbox": [0, menubar_bounds["height"], app_bounds["width"], menubar_bounds["height"] + app_bounds["height"]],- "target": [- app_source_rect.origin.x,- app_source_rect.origin.y,- app_source_rect.origin.x + app_bounds["width"],- app_source_rect.origin.y + app_bounds["height"]- ]- })++ hitboxes.append(+ {+ "hitbox": [+ 0,+ menubar_bounds["height"],+ app_bounds["width"],+ menubar_bounds["height"] + app_bounds["height"],+ ],+ "target": [+ app_source_rect.origin.x,+ app_source_rect.origin.y,+ app_source_rect.origin.x + app_bounds["width"],+ app_source_rect.origin.y + app_bounds["height"],+ ],+ }+ )# --- SECOND PASS: menubar ---allowed_roles = {"menubar"}menubar_windows = [w for w in all_windows if w["role"] in allowed_roles]- menubar_source_rect = Quartz.CGRectMake(- 0, 0, app_bounds["width"], menubar_bounds["height"]- )+ menubar_source_rect = Quartz.CGRectMake(0, 0, app_bounds["width"], menubar_bounds["height"])menubar_target_rect = Quartz.CGRectMake(- 0, app_bounds["height"] - menubar_bounds["height"], app_bounds["width"], menubar_bounds["height"]+ 0,+ app_bounds["height"] - menubar_bounds["height"],+ app_bounds["width"],+ menubar_bounds["height"],)_draw_layer(cg_context, menubar_windows, menubar_source_rect, menubar_target_rect)-- hitboxes.append({- "hitbox": [0, 0, app_bounds["width"], menubar_bounds["height"]],- "target": [0, 0, app_bounds["width"], menubar_bounds["height"]]- })-++ hitboxes.append(+ {+ "hitbox": [0, 0, app_bounds["width"], menubar_bounds["height"]],+ "target": [0, 0, app_bounds["width"], menubar_bounds["height"]],+ }+ )+# --- THIRD PASS: dock, filtered ---# Step 1: Collect dock items to draw, with their computed target rectsdock_draw_items = []@@ -496,7 +539,12 @@ def draw_desktop_screenshot(app_whitelist: List[str] = None, all_windows: List[Dif item["title"] not in app_whitelist:continueelif item["subrole"] == "AXMinimizedWindowDockItem":- if not any(window["name"] == item["title"] and window["role"] == "app" and window["owner"] in app_whitelist for window in all_windows):+ if not any(+ window["name"] == item["title"]+ and window["role"] == "app"+ and window["owner"] in app_whitelist+ for window in all_windows+ ):continueelif item["subrole"] == "AXFolderDockItem":continue@@ -504,60 +552,65 @@ def draw_desktop_screenshot(app_whitelist: List[str] = None, all_windows: List[D# Preserve unscaled (original) source position and size before any modificationhitbox_position = source_positionhitbox_size = source_size-+screen_position = source_positionscreen_size = source_size-+# stretch to screen sizepadding = 32if dock_orientation == "bottom":source_position = (source_position[0], 0)source_size = (source_size[0], frame.size.height)-- hitbox_position = (source_position[0], app_bounds['height'] - hitbox_size[1])++ hitbox_position = (source_position[0], app_bounds["height"] - hitbox_size[1])hitbox_size = (source_size[0], hitbox_size[1])-+if index == 0:source_size = (padding + source_size[0], source_size[1])source_position = (source_position[0] - padding, 0)elif index == len(dock_items) - 1:source_size = (source_size[0] + padding, source_size[1])source_position = (source_position[0], 0)-+elif dock_orientation == "side":source_position = (0, source_position[1])source_size = (frame.size.width, source_size[1])-+hitbox_position = (- source_position[0] if dock_bounds['x'] < frame.size.width / 2 else app_bounds['width'] - hitbox_size[0],- source_position[1]+ (+ source_position[0]+ if dock_bounds["x"] < frame.size.width / 2+ else app_bounds["width"] - hitbox_size[0]+ ),+ source_position[1],)hitbox_size = (hitbox_size[0], source_size[1])-+if index == 0:source_size = (source_size[0], padding + source_size[1])source_position = (0, source_position[1] - padding)elif index == len(dock_items) - 1:source_size = (source_size[0], source_size[1] + padding)source_position = (0, source_position[1])-# Compute the initial target positiontarget_position = source_positiontarget_size = source_size-- dock_draw_items.append({- "item": item,- "index": index,- "source_position": source_position,- "source_size": source_size,- "target_size": target_size,- "target_position": target_position, # Will be updated after packing- "hitbox_position": hitbox_position,- "hitbox_size": hitbox_size,- "screen_position": screen_position,- "screen_size": screen_size,- })++ dock_draw_items.append(+ {+ "item": item,+ "index": index,+ "source_position": source_position,+ "source_size": source_size,+ "target_size": target_size,+ "target_position": target_position, # Will be updated after packing+ "hitbox_position": hitbox_position,+ "hitbox_size": hitbox_size,+ "screen_position": screen_position,+ "screen_size": screen_size,+ }+ )# Step 2: Pack the target rects along the main axis, removing gapspacked_positions = []@@ -569,12 +622,12 @@ def draw_desktop_screenshot(app_whitelist: List[str] = None, all_windows: List[Dx_cursor += draw_item["target_size"][0]packed_strip_length = x_cursor# Center horizontally- x_offset = (app_bounds['width'] - packed_strip_length) / 2- y_offset = (frame.size.height - app_bounds['height'])+ x_offset = (app_bounds["width"] - packed_strip_length) / 2+ y_offset = frame.size.height - app_bounds["height"]for i, draw_item in enumerate(dock_draw_items):px, py = packed_positions[i]draw_item["target_position"] = (px + x_offset, py - y_offset)-+# Pack unscaled source rectsx_cursor = 0for draw_item in dock_draw_items:@@ -582,7 +635,7 @@ def draw_desktop_screenshot(app_whitelist: List[str] = None, all_windows: List[Dx_cursor += draw_item["hitbox_size"][0]packed_strip_length = x_cursor# Center horizontally- x_offset = (app_bounds['width'] - packed_strip_length) / 2+ x_offset = (app_bounds["width"] - packed_strip_length) / 2for i, draw_item in enumerate(dock_draw_items):px, py = draw_item["hitbox_position"]draw_item["hitbox_position"] = (px + x_offset, py)@@ -594,12 +647,16 @@ def draw_desktop_screenshot(app_whitelist: List[str] = None, all_windows: List[Dy_cursor += draw_item["target_size"][1]packed_strip_length = y_cursor# Center vertically- y_offset = (app_bounds['height'] - packed_strip_length) / 2- x_offset = 0 if dock_bounds['x'] < frame.size.width / 2 else frame.size.width - app_bounds['width']+ y_offset = (app_bounds["height"] - packed_strip_length) / 2+ x_offset = (+ 0+ if dock_bounds["x"] < frame.size.width / 2+ else frame.size.width - app_bounds["width"]+ )for i, draw_item in enumerate(dock_draw_items):px, py = packed_positions[i]draw_item["target_position"] = (px - x_offset, py + y_offset)-+# Pack unscaled source rectsy_cursor = 0for draw_item in dock_draw_items:@@ -607,11 +664,11 @@ def draw_desktop_screenshot(app_whitelist: List[str] = None, all_windows: List[Dy_cursor += draw_item["hitbox_size"][1]packed_strip_length = y_cursor# Center vertically- y_offset = (app_bounds['height'] - packed_strip_length) / 2+ y_offset = (app_bounds["height"] - packed_strip_length) / 2for i, draw_item in enumerate(dock_draw_items):px, py = draw_item["hitbox_position"]draw_item["hitbox_position"] = (px, py + y_offset)-+dock_windows = [window for window in all_windows if window["role"] == "dock"]# Step 3: Draw dock items using packed and recentered positionsfor draw_item in dock_draw_items:@@ -622,7 +679,10 @@ def draw_desktop_screenshot(app_whitelist: List[str] = None, all_windows: List[Dtarget_size = draw_item["target_size"]# flip target position y- target_position = (target_position[0], app_bounds['height'] - target_position[1] - target_size[1])+ target_position = (+ target_position[0],+ app_bounds["height"] - target_position[1] - target_size[1],+ )source_rect = Quartz.CGRectMake(*source_position, *source_size)target_rect = Quartz.CGRectMake(*target_position, *target_size)@@ -641,12 +701,21 @@ def draw_desktop_screenshot(app_whitelist: List[str] = None, all_windows: List[D# hitbox_rect = Quartz.CGRectMake(*hitbox_position_flipped, *hitbox_size)# Quartz.CGContextSetStrokeColorWithColor(cg_context, Quartz.CGColorCreateGenericRGB(0, 1, 0, 1))# Quartz.CGContextStrokeRect(cg_context, hitbox_rect)-- hitboxes.append({- "hitbox": [*hitbox_position, hitbox_position[0] + hitbox_size[0], hitbox_position[1] + hitbox_size[1]],- "target": [*draw_item["screen_position"], draw_item["screen_position"][0] + draw_item["screen_size"][0], draw_item["screen_position"][1] + draw_item["screen_size"][1]]- })-++ hitboxes.append(+ {+ "hitbox": [+ *hitbox_position,+ hitbox_position[0] + hitbox_size[0],+ hitbox_position[1] + hitbox_size[1],+ ],+ "target": [+ *draw_item["screen_position"],+ draw_item["screen_position"][0] + draw_item["screen_size"][0],+ draw_item["screen_position"][1] + draw_item["screen_size"][1],+ ],+ }+ )# Convert composited context to CGImagefinal_cg_image = Quartz.CGBitmapContextCreateImage(cg_context)@@ -657,18 +726,19 @@ def draw_desktop_screenshot(app_whitelist: List[str] = None, all_windows: List[Dimage_data = io.BytesIO(png_data)return Image.open(image_data), hitboxes+@timing_decoratordef get_menubar_items(active_app_pid: int = None) -> List[Dict[str, Any]]:"""Get menubar items from the active application using Accessibility API-+Args:active_app_pid: PID of the active application-+Returns:List of dictionaries with menubar item information"""menubar_items = []-+if active_app_pid is None:# Get the frontmost application's PID if none providedfrontmost_app = NSWorkspace.sharedWorkspace().frontmostApplication()@@ -677,74 +747,66 @@ def get_menubar_items(active_app_pid: int = None) -> List[Dict[str, Any]]:else:logger.error("Error: Could not determine frontmost application")return menubar_items-+# Create an accessibility element for the applicationapp_element = AXUIElementCreateApplication(active_app_pid)if app_element is None:logger.error(f"Error: Could not create accessibility element for PID {active_app_pid}")return menubar_items-+# Get the menubarmenubar = element_attribute(app_element, kAXMenuBarAttribute)if menubar is None:logger.error(f"Error: Could not get menubar for application with PID {active_app_pid}")return menubar_items-+# Get the menubar itemschildren = element_attribute(menubar, kAXChildrenAttribute)if children is None:logger.error("Error: Could not get menubar items")return menubar_items-+# Process each menubar itemfor i in range(len(children)):item = children[i]-+# Get item titletitle = element_attribute(item, kAXTitleAttribute) or "Untitled"-+# Create bounding box- bounds = {- "x": 0,- "y": 0,- "width": 0,- "height": 0- }-+ bounds = {"x": 0, "y": 0, "width": 0, "height": 0}+# Get item positionposition_value = element_attribute(item, kAXPositionAttribute)if position_value:position_value = element_value(position_value, kAXValueCGPointType)bounds["x"] = position_value.xbounds["y"] = position_value.y-+# Get item sizesize_value = element_attribute(item, kAXSizeAttribute)if size_value:size_value = element_value(size_value, kAXValueCGSizeType)bounds["width"] = size_value.widthbounds["height"] = size_value.height--+# Add to list- menubar_items.append({- "title": title,- "bounds": bounds,- "index": i,- "app_pid": active_app_pid- })-+ menubar_items.append(+ {"title": title, "bounds": bounds, "index": i, "app_pid": active_app_pid}+ )+return menubar_items-++@timing_decoratordef get_dock_items() -> List[Dict[str, Any]]:"""Get all items in the macOS Dock-+Returns:List of dictionaries with Dock item information"""dock_items = []-+# Find the Dock processdock_pid = Nonerunning_apps = get_running_apps()@@ -752,23 +814,23 @@ def get_dock_items() -> List[Dict[str, Any]]:if app.localizedName() == "Dock" and app.bundleIdentifier() == "com.apple.dock":dock_pid = app.processIdentifier()break-+if dock_pid is None:logger.error("Error: Could not find Dock process")return dock_items-+# Create an accessibility element for the Dockdock_element = AXUIElementCreateApplication(dock_pid)if dock_element is None:logger.error(f"Error: Could not create accessibility element for Dock (PID {dock_pid})")return dock_items-+# Get the Dock's main elementdock_list = element_attribute(dock_element, kAXChildrenAttribute)if dock_list is None or len(dock_list) == 0:logger.error("Error: Could not get Dock children")return dock_items-+# Find the Dock's application list (usually the first child)dock_app_list = Nonefor child in dock_list:@@ -776,17 +838,17 @@ def get_dock_items() -> List[Dict[str, Any]]:if role == "AXList":dock_app_list = childbreak-+if dock_app_list is None:logger.error("Error: Could not find Dock application list")return dock_items-+# Get all items in the Dockitems = element_attribute(dock_app_list, kAXChildrenAttribute)if items is None:logger.error("Error: Could not get Dock items")return dock_items-+# Process each Dock itemfor i, item in enumerate(items):# Get item attributes@@ -794,29 +856,24 @@ def get_dock_items() -> List[Dict[str, Any]]:description = element_attribute(item, "AXDescription") or ""role = element_attribute(item, kAXRoleAttribute) or ""subrole = element_attribute(item, "AXSubrole") or ""-+# Create bounding box- bounds = {- "x": 0,- "y": 0,- "width": 0,- "height": 0- }-+ bounds = {"x": 0, "y": 0, "width": 0, "height": 0}+# Get item positionposition_value = element_attribute(item, kAXPositionAttribute)if position_value:position_value = element_value(position_value, kAXValueCGPointType)bounds["x"] = position_value.xbounds["y"] = position_value.y-+# Get item sizesize_value = element_attribute(item, kAXSizeAttribute)if size_value:size_value = element_value(size_value, kAXValueCGSizeType)bounds["width"] = size_value.widthbounds["height"] = size_value.height-+# Determine if this is an application, file/folder, or separatoritem_type = "unknown"if subrole == "AXApplicationDockItem":@@ -829,20 +886,23 @@ def get_dock_items() -> List[Dict[str, Any]]:item_type = "separator"elif "trash" in title.lower():item_type = "trash"-+# Add to list- dock_items.append({- "title": title,- "description": description,- "bounds": bounds,- "index": i,- "type": item_type,- "role": role,- "subrole": subrole- })-+ dock_items.append(+ {+ "title": title,+ "description": description,+ "bounds": bounds,+ "index": i,+ "type": item_type,+ "role": role,+ "subrole": subrole,+ }+ )+return dock_items+class AppActivationContext:def __init__(self, active_app_pid=None, active_app_to_use="", logger=None):self.active_app_pid = active_app_pid@@ -852,9 +912,12 @@ class AppActivationContext:def __enter__(self):from AppKit import NSWorkspace+if self.active_app_pid:if self.logger and self.active_app_to_use:- self.logger.debug(f"Automatically activating app '{self.active_app_to_use}' for screenshot composition")+ self.logger.debug(+ f"Automatically activating app '{self.active_app_to_use}' for screenshot composition"+ )self.frontmost_app = NSWorkspace.sharedWorkspace().frontmostApplication()running_apps_list = NSWorkspace.sharedWorkspace().runningApplications()for app in running_apps_list:@@ -870,10 +933,11 @@ class AppActivationContext:# sleep for 0.5 secondstime.sleep(0.5)self.frontmost_app.activateWithOptions_(0)-+def get_frontmost_and_active_app(all_windows, running_apps, app_whitelist):from AppKit import NSWorkspace+frontmost_app = NSWorkspace.sharedWorkspace().frontmostApplication()active_app_to_use = None@@ -912,14 +976,20 @@ def get_frontmost_and_active_app(all_windows, running_apps, app_whitelist):return frontmost_app, active_app_to_use, active_app_pid-def capture_all_apps(save_to_disk: bool = False, app_whitelist: List[str] = None, output_dir: str = None, take_focus: bool = True) -> Tuple[Dict[str, Any], Optional[Image.Image]]:++def capture_all_apps(+ save_to_disk: bool = False,+ app_whitelist: List[str] = None,+ output_dir: str = None,+ take_focus: bool = True,+) -> Tuple[Dict[str, Any], Optional[Image.Image]]:"""Capture screenshots of all running applications-+Args:save_to_disk: Whether to save screenshots to diskapp_whitelist: Optional list of app names to include in the recomposited screenshot(will always include 'Window Server' and 'Dock')-+Returns:Dictionary with application information and screenshotsOptional PIL Image of the recomposited screenshot@@ -929,61 +999,65 @@ def capture_all_apps(save_to_disk: bool = False, app_whitelist: List[str] = None"applications": [],"windows": [], # New array to store all windows, including those without apps"menubar_items": [], # New array to store menubar items- "dock_items": [] # New array to store dock items+ "dock_items": [], # New array to store dock items}-+# Get all windows with z-order informationall_windows = get_all_windows()-+# Get all running applicationsrunning_apps = get_running_apps()-- frontmost_app, active_app_to_use, active_app_pid = get_frontmost_and_active_app(all_windows, running_apps, app_whitelist) if take_focus else (None, None, None)-++ frontmost_app, active_app_to_use, active_app_pid = (+ get_frontmost_and_active_app(all_windows, running_apps, app_whitelist)+ if take_focus+ else (None, None, None)+ )+# Use AppActivationContext to activate the app and restore focuswith AppActivationContext(active_app_pid, active_app_to_use, logger):-+# Process applicationsfor app in running_apps:# Skip system apps without a bundle IDif app.bundleIdentifier() is None:continue-+app_info = get_app_info(app)app_windows = get_app_windows(app.processIdentifier(), all_windows)-- app_data = {- "info": app_info,- "windows": [ window["id"] for window in app_windows ]- }-++ app_data = {"info": app_info, "windows": [window["id"] for window in app_windows]}+result["applications"].append(app_data)-+# Add all windows to the resultresult["windows"] = all_windows-+# Get menubar items from the active applicationmenubar_items = get_menubar_items(active_app_pid)result["menubar_items"] = menubar_items-+# Get dock itemsdock_items = get_dock_items()result["dock_items"] = dock_items-+# Get menubar boundsmenubar_bounds = get_menubar_bounds()result["menubar_bounds"] = menubar_bounds-+# Get dock boundsdock_bounds = get_dock_bounds()result["dock_bounds"] = dock_bounds-+# Capture the entire desktop using Quartz compositing- desktop_screenshot, hitboxes = draw_desktop_screenshot(app_whitelist, all_windows, dock_bounds, dock_items, menubar_bounds, menubar_items)-+ desktop_screenshot, hitboxes = draw_desktop_screenshot(+ app_whitelist, all_windows, dock_bounds, dock_items, menubar_bounds, menubar_items+ )+result["hitboxes"] = hitboxes-- from PIL import Image, ImageDraw, ImageChops++ from PIL import Image, ImageChops, ImageDraw+def _draw_hitboxes(img, hitboxes, key="target"):"""Overlay opaque colored rectangles for each hitbox (using hitbox[key])@@ -1002,23 +1076,29 @@ def capture_all_apps(save_to_disk: bool = False, app_whitelist: List[str] = None# Distinct colors for ordercolors = [- (255, 0, 0, 180), # Red- (0, 255, 0, 180), # Green- (0, 0, 255, 180), # Blue- (255, 255, 0, 180), # Yellow- (0, 255, 255, 180), # Cyan- (255, 0, 255, 180), # Magenta- (255, 128, 0, 180), # Orange- (128, 0, 255, 180), # Purple- (0, 128, 255, 180), # Sky blue- (128, 255, 0, 180), # Lime+ (255, 0, 0, 180), # Red+ (0, 255, 0, 180), # Green+ (0, 0, 255, 180), # Blue+ (255, 255, 0, 180), # Yellow+ (0, 255, 255, 180), # Cyan+ (255, 0, 255, 180), # Magenta+ (255, 128, 0, 180), # Orange+ (128, 0, 255, 180), # Purple+ (0, 128, 255, 180), # Sky blue+ (128, 255, 0, 180), # Lime]# Set minimum brightness for colorsmin_brightness = 0colors = [- (max(min_brightness, c[0]), max(min_brightness, c[1]), max(min_brightness, c[2]), c[3]) for c in colors+ (+ max(min_brightness, c[0]),+ max(min_brightness, c[1]),+ max(min_brightness, c[2]),+ c[3],+ )+ for c in colors]-+for i, h in enumerate(hitboxes):rect = h.get(key)color = colors[i % len(colors)]@@ -1034,25 +1114,31 @@ def capture_all_apps(save_to_disk: bool = False, app_whitelist: List[str] = Nonedesktop_path = os.path.join(output_dir, "desktop.png")desktop_screenshot.save(desktop_path)result["desktop_screenshot"] = desktop_path-+logger.info(f"Saved desktop screenshot to {desktop_path}")if app_whitelist:# Take screenshot without whitelistdesktop_screenshot_full, hitboxes_full = draw_desktop_screenshot(- None, all_windows, dock_bounds, dock_items, menubar_bounds, menubar_items)+ None, all_windows, dock_bounds, dock_items, menubar_bounds, menubar_items+ )# Draw hitboxes on both images using overlayimg1 = _draw_hitboxes(desktop_screenshot.copy(), hitboxes, key="hitbox")- img2 = _draw_hitboxes(desktop_screenshot_full.copy(), hitboxes, key="target") if desktop_screenshot_full else None+ img2 = (+ _draw_hitboxes(desktop_screenshot_full.copy(), hitboxes, key="target")+ if desktop_screenshot_full+ else None+ )if img2 and hitboxes_full:# Compose side-by-sidefrom PIL import Image+width = img1.width + img2.widthheight = max(img1.height, img2.height)- combined = Image.new('RGBA', (width, height), (0, 0, 0, 0))+ combined = Image.new("RGBA", (width, height), (0, 0, 0, 0))combined.paste(img1, (0, 0))combined.paste(img2, (img1.width, 0))side_by_side_path = os.path.join(output_dir, "side_by_side_hitboxes.png")@@ -1066,29 +1152,51 @@ def capture_all_apps(save_to_disk: bool = False, app_whitelist: List[str] = Noneresult["hitbox_screenshot"] = hitbox_path# Focus restoration is now handled by AppActivationContext-+return result, desktop_screenshot+async def run_capture():"""Run the screenshot capture asynchronously"""# Parse command line arguments- parser = argparse.ArgumentParser(description="Capture screenshots of running macOS applications")- parser.add_argument("--output", "-o", help="Output directory for screenshots", default="app_screenshots")- parser.add_argument("--filter", "-f", nargs="+", help="Filter recomposited screenshot to only include specified apps")- parser.add_argument("--menubar", "-m", action="store_true", help="List menubar and status items with their bounding boxes")- parser.add_argument("--dock", "-d", action="store_true", help="List Dock items with their bounding boxes")- parser.add_argument("--demo", nargs="*", help="Demo mode: pass app names to capture individual and combinations, create mosaic PNG")+ parser = argparse.ArgumentParser(+ description="Capture screenshots of running macOS applications"+ )+ parser.add_argument(+ "--output", "-o", help="Output directory for screenshots", default="app_screenshots"+ )+ parser.add_argument(+ "--filter",+ "-f",+ nargs="+",+ help="Filter recomposited screenshot to only include specified apps",+ )+ parser.add_argument(+ "--menubar",+ "-m",+ action="store_true",+ help="List menubar and status items with their bounding boxes",+ )+ parser.add_argument(+ "--dock", "-d", action="store_true", help="List Dock items with their bounding boxes"+ )+ parser.add_argument(+ "--demo",+ nargs="*",+ help="Demo mode: pass app names to capture individual and combinations, create mosaic PNG",+ )args = parser.parse_args()-+# Create output directory in the current directory if not absoluteif not os.path.isabs(args.output):output_dir = os.path.join(os.getcwd(), args.output)else:output_dir = args.output-+# DEMO MODE: capture each app and all non-empty combinations, then mosaicif args.demo:from PIL import Image+demo_apps = args.demoprint(f"Running in DEMO mode for apps: {demo_apps}")groups = []@@ -1108,9 +1216,11 @@ async def run_capture():if not screenshots:print("No screenshots captured in demo mode.")return+# Mosaic-pack: grid (rows of sqrt(N))- def make_mosaic(images, pad=64, bg=(30,30,30)):+ def make_mosaic(images, pad=64, bg=(30, 30, 30)):import rpack+sizes = [(img.width + pad, img.height + pad) for _, img in images]positions = rpack.pack(sizes)# Find the bounding box for the mosaic@@ -1120,6 +1230,7 @@ async def run_capture():for (group, img), (x, y) in zip(images, positions):mosaic.paste(img, (x, y))return mosaic+mosaic_img = make_mosaic(screenshots)mosaic_path = os.path.join(output_dir, "demo_mosaic.png")os.makedirs(output_dir, exist_ok=True)@@ -1128,57 +1239,60 @@ async def run_capture():return# Capture all apps and save to disk, including a recomposited screenshot- print(f"Capturing screenshots of all running applications...")+ print("Capturing screenshots of all running applications...")print(f"Saving screenshots to: {output_dir}")-+# If filter is provided, show what we're filtering byif args.filter:- print(f"Filtering recomposited screenshot to only include: {', '.join(args.filter)} (plus Window Server and Dock)")-+ print(+ f"Filtering recomposited screenshot to only include: {', '.join(args.filter)} (plus Window Server and Dock)"+ )+result, img = capture_all_apps(- save_to_disk=True,- app_whitelist=args.filter,- output_dir=output_dir,- take_focus=True+ save_to_disk=True, app_whitelist=args.filter, output_dir=output_dir, take_focus=True)-+# Print summary- print(f"\nCapture complete!")+ print("\nCapture complete!")print(f"Captured {len(result['applications'])} applications")-+total_app_windows = sum(len(app["windows"]) for app in result["applications"])print(f"Total application windows captured: {total_app_windows}")print(f"Total standalone windows captured: {len(result['windows'])}")-+# Print details of each applicationprint("\nApplication details:")for app in result["applications"]:app_info = app["info"]windows = app["windows"]print(f" - {app_info['name']} ({len(windows)} windows)")-+# Print recomposited screenshot path if availableif "desktop_screenshot" in result:print(f"\nRecomposited screenshot saved to: {result['desktop_screenshot']}")-+# Print menubar items if requestedif args.menubar and "menubar_items" in result:print("\nMenubar items:")-+# Find app name for the PIDapp_name_by_pid = {}for app in result["applications"]:app_info = app["info"]app_name_by_pid[app_info["pid"]] = app_info["name"]-+for item in result["menubar_items"]:print(f" - {item['title']}")- print(f" Bounds: x={item['bounds']['x']}, y={item['bounds']['y']}, width={item['bounds']['width']}, height={item['bounds']['height']}")-+ print(+ f" Bounds: x={item['bounds']['x']}, y={item['bounds']['y']}, width={item['bounds']['width']}, height={item['bounds']['height']}"+ )+if "app_pid" in item:- app_name = app_name_by_pid.get(item["app_pid"], f"Unknown App (PID: {item['app_pid']})")+ app_name = app_name_by_pid.get(+ item["app_pid"], f"Unknown App (PID: {item['app_pid']})"+ )print(f" App: {app_name} (PID: {item['app_pid']})")-+if "window_id" in item:print(f" Window ID: {item['window_id']}")if "owner" in item:@@ -1186,24 +1300,27 @@ async def run_capture():if "layer" in item and "z_index" in item:print(f" Layer: {item['layer']}, Z-Index: {item['z_index']}")print("")-+# Print dock items if requestedif args.dock and "dock_items" in result:print("\nDock items:")for item in result["dock_items"]:print(f" - {item['title']} ({item['type']})")print(f" Description: {item['description']}")- print(f" Bounds: x={item['bounds']['x']}, y={item['bounds']['y']}, width={item['bounds']['width']}, height={item['bounds']['height']}")+ print(+ f" Bounds: x={item['bounds']['x']}, y={item['bounds']['y']}, width={item['bounds']['width']}, height={item['bounds']['height']}"+ )print(f" Role: {item['role']}, Subrole: {item['subrole']}")print(f" Index: {item['index']}")print("")-+# Save the metadata to a JSON filemetadata_path = os.path.join(output_dir, "metadata.json")with open(metadata_path, "w") as f:json.dump(result, f, indent=2)-+print(f"\nMetadata saved to: {metadata_path}")+if __name__ == "__main__":- asyncio.run(run_capture())\ No newline at end of file+ asyncio.run(run_capture())diff --git a/libs/python/computer-server/computer_server/diorama/macos.py b/libs/python/computer-server/computer_server/diorama/macos.pyindex be266caef6..5049f0709e 100644--- a/libs/python/computer-server/computer_server/diorama/macos.py+++ b/libs/python/computer-server/computer_server/diorama/macos.py@@ -1,13 +1,15 @@+import inspectimport platformimport sys-import platform-import inspect-from computer_server.diorama.diorama import Diorama-from computer_server.diorama.base import BaseDioramaHandlerfrom typing import Optional+from computer_server.diorama.base import BaseDioramaHandler+from computer_server.diorama.diorama import Diorama++class MacOSDioramaHandler(BaseDioramaHandler):"""Handler for Diorama commands on macOS, using local diorama module."""+async def diorama_cmd(self, action: str, arguments: Optional[dict] = None) -> dict:if platform.system().lower() != "darwin":return {"success": False, "error": "Diorama is only supported on macOS."}@@ -30,4 +32,5 @@ class MacOSDioramaHandler(BaseDioramaHandler):return {"success": True, "result": result}except Exception as e:import traceback+return {"success": False, "error": str(e), "trace": traceback.format_exc()}diff --git a/libs/python/computer-server/computer_server/diorama/safezone.py b/libs/python/computer-server/computer_server/diorama/safezone.pyindex 122b668ff5..09455fd7cd 100644--- a/libs/python/computer-server/computer_server/diorama/safezone.py+++ b/libs/python/computer-server/computer_server/diorama/safezone.py@@ -8,31 +8,31 @@ like the menubar and dock, which are needed for proper screenshot composition.import sysimport time-from typing import Dict, Any, Optional, Tuple+from typing import Any, Dict, Optional, Tuple# Import Objective-C bridge librariestry:import AppKit+ import Foundation+ from AppKit import NSRunningApplication, NSWorkspacefrom ApplicationServices import (- AXUIElementCreateSystemWide,- AXUIElementCreateApplication,AXUIElementCopyAttributeValue,AXUIElementCopyAttributeValues,+ AXUIElementCreateApplication,+ AXUIElementCreateSystemWide,+ AXUIElementGetTypeID,+ AXValueGetType,+ AXValueGetValue,kAXChildrenAttribute,- kAXRoleAttribute,- kAXTitleAttribute,+ kAXErrorSuccess,+ kAXMenuBarAttribute,kAXPositionAttribute,+ kAXRoleAttribute,kAXSizeAttribute,- kAXErrorSuccess,- AXValueGetType,- kAXValueCGSizeType,+ kAXTitleAttribute,kAXValueCGPointType,- AXUIElementGetTypeID,- AXValueGetValue,- kAXMenuBarAttribute,+ kAXValueCGSizeType,)- from AppKit import NSWorkspace, NSRunningApplication- import Foundationexcept ImportError:print("Error: This script requires PyObjC to be installed.")print("Please install it with: pip install pyobjc")@@ -74,13 +74,8 @@ def element_value(element, type):def get_element_bounds(element):"""Get the bounds of an accessibility element"""- bounds = {- "x": 0,- "y": 0,- "width": 0,- "height": 0- }-+ bounds = {"x": 0, "y": 0, "width": 0, "height": 0}+# Get positionposition_value = element_attribute(element, kAXPositionAttribute)if position_value:@@ -88,7 +83,7 @@ def get_element_bounds(element):if position_value:bounds["x"] = position_value.xbounds["y"] = position_value.y-+# Get sizesize_value = element_attribute(element, kAXSizeAttribute)if size_value:@@ -96,7 +91,7 @@ def get_element_bounds(element):if size_value:bounds["width"] = size_value.widthbounds["height"] = size_value.height-+return bounds@@ -111,13 +106,13 @@ def find_dock_process():def get_menubar_bounds():"""Get the bounds of the macOS menubar-+Returns:Dictionary with x, y, width, height of the menubar"""# Get the system-wide accessibility elementsystem_element = AXUIElementCreateSystemWide()-+# Try to find the menubarmenubar = element_attribute(system_element, kAXMenuBarAttribute)if menubar is None:@@ -127,19 +122,19 @@ def get_menubar_bounds():app_pid = frontmost_app.processIdentifier()app_element = AXUIElementCreateApplication(app_pid)menubar = element_attribute(app_element, kAXMenuBarAttribute)-+if menubar is None:print("Error: Could not get menubar")# Return default menubar bounds as fallbackreturn {"x": 0, "y": 0, "width": 1800, "height": 24}-+# Get menubar boundsreturn get_element_bounds(menubar)def get_dock_bounds():"""Get the bounds of the macOS Dock-+Returns:Dictionary with x, y, width, height of the Dock"""@@ -148,19 +143,19 @@ def get_dock_bounds():print("Error: Could not find Dock process")# Return empty bounds as fallbackreturn {"x": 0, "y": 0, "width": 0, "height": 0}-+# Create an accessibility element for the Dockdock_element = AXUIElementCreateApplication(dock_pid)if dock_element is None:print(f"Error: Could not create accessibility element for Dock (PID {dock_pid})")return {"x": 0, "y": 0, "width": 0, "height": 0}-+# Get the Dock's childrenchildren = element_attribute(dock_element, kAXChildrenAttribute)if not children or len(children) == 0:print("Error: Could not get Dock children")return {"x": 0, "y": 0, "width": 0, "height": 0}-+# Find the Dock's list (first child is usually the main dock list)dock_list = Nonefor child in children:@@ -168,28 +163,25 @@ def get_dock_bounds():if role == "AXList":dock_list = childbreak-+if dock_list is None:print("Error: Could not find Dock list")return {"x": 0, "y": 0, "width": 0, "height": 0}-+# Get the bounds of the dock listreturn get_element_bounds(dock_list)def get_ui_element_bounds():"""Get the bounds of important UI elements like menubar and dock-+Returns:Dictionary with menubar and dock bounds"""menubar_bounds = get_menubar_bounds()dock_bounds = get_dock_bounds()-- return {- "menubar": menubar_bounds,- "dock": dock_bounds- }++ return {"menubar": menubar_bounds, "dock": dock_bounds}if __name__ == "__main__":diff --git a/libs/python/computer-server/computer_server/handlers/base.py b/libs/python/computer-server/computer_server/handlers/base.pyindex ac62983200..42b27a0cf9 100644--- a/libs/python/computer-server/computer_server/handlers/base.py+++ b/libs/python/computer-server/computer_server/handlers/base.py@@ -1,24 +1,26 @@from abc import ABC, abstractmethod-from typing import Optional, Dict, Any, List, Tuple+from typing import Any, Dict, List, Optional, Tuple+class BaseAccessibilityHandler(ABC):"""Abstract base class for OS-specific accessibility handlers."""-+@abstractmethodasync def get_accessibility_tree(self) -> Dict[str, Any]:"""Get the accessibility tree of the current window."""pass@abstractmethod- async def find_element(self, role: Optional[str] = None,- title: Optional[str] = None,- value: Optional[str] = None) -> Dict[str, Any]:+ async def find_element(+ self, role: Optional[str] = None, title: Optional[str] = None, value: Optional[str] = None+ ) -> Dict[str, Any]:"""Find an element in the accessibility tree by criteria."""pass+class BaseFileHandler(ABC):"""Abstract base class for OS-specific file handlers."""-+@abstractmethodasync def file_exists(self, path: str) -> Dict[str, Any]:"""Check if a file exists at the specified path."""@@ -43,7 +45,7 @@ class BaseFileHandler(ABC):async def write_text(self, path: str, content: str) -> Dict[str, Any]:"""Write text content to a file."""pass-+@abstractmethodasync def write_bytes(self, path: str, content_b64: str) -> Dict[str, Any]:"""Write binary content to a file. Sent over the websocket as a base64 string."""@@ -65,9 +67,11 @@ class BaseFileHandler(ABC):pass@abstractmethod- async def read_bytes(self, path: str, offset: int = 0, length: Optional[int] = None) -> Dict[str, Any]:+ async def read_bytes(+ self, path: str, offset: int = 0, length: Optional[int] = None+ ) -> Dict[str, Any]:"""Read the binary contents of a file. Sent over the websocket as a base64 string.-+Args:path: Path to the fileoffset: Byte offset to start reading from (default: 0)@@ -80,9 +84,10 @@ class BaseFileHandler(ABC):"""Get the size of a file in bytes."""pass+class BaseAutomationHandler(ABC):"""Abstract base class for OS-specific automation handlers.-+Categories:- Mouse Actions: Methods for mouse control- Keyboard Actions: Methods for keyboard input@@ -90,18 +95,22 @@ class BaseAutomationHandler(ABC):- Screen Actions: Methods for screen interaction- Clipboard Actions: Methods for clipboard operations"""-+# Mouse Actions@abstractmethod- async def mouse_down(self, x: Optional[int] = None, y: Optional[int] = None, button: str = "left") -> Dict[str, Any]:+ async def mouse_down(+ self, x: Optional[int] = None, y: Optional[int] = None, button: str = "left"+ ) -> Dict[str, Any]:"""Perform a mouse down at the current or specified position."""pass-+@abstractmethod- async def mouse_up(self, x: Optional[int] = None, y: Optional[int] = None, button: str = "left") -> Dict[str, Any]:+ async def mouse_up(+ self, x: Optional[int] = None, y: Optional[int] = None, button: str = "left"+ ) -> Dict[str, Any]:"""Perform a mouse up at the current or specified position."""pass-+@abstractmethodasync def left_click(self, x: Optional[int] = None, y: Optional[int] = None) -> Dict[str, Any]:"""Perform a left click at the current or specified position."""@@ -113,7 +122,9 @@ class BaseAutomationHandler(ABC):pass@abstractmethod- async def double_click(self, x: Optional[int] = None, y: Optional[int] = None) -> Dict[str, Any]:+ async def double_click(+ self, x: Optional[int] = None, y: Optional[int] = None+ ) -> Dict[str, Any]:"""Perform a double click at the current or specified position."""pass@@ -123,9 +134,11 @@ class BaseAutomationHandler(ABC):pass@abstractmethod- async def drag_to(self, x: int, y: int, button: str = "left", duration: float = 0.5) -> Dict[str, Any]:+ async def drag_to(+ self, x: int, y: int, button: str = "left", duration: float = 0.5+ ) -> Dict[str, Any]:"""Drag the cursor from current position to specified coordinates.-+Args:x: The x coordinate to drag toy: The y coordinate to drag to@@ -133,11 +146,13 @@ class BaseAutomationHandler(ABC):duration: How long the drag should take in seconds"""pass-+@abstractmethod- async def drag(self, path: List[Tuple[int, int]], button: str = "left", duration: float = 0.5) -> Dict[str, Any]:+ async def drag(+ self, path: List[Tuple[int, int]], button: str = "left", duration: float = 0.5+ ) -> Dict[str, Any]:"""Drag the cursor from current position to specified coordinates.-+Args:path: A list of tuples of x and y coordinates to drag tobutton: The mouse button to use ('left', 'middle', 'right')@@ -150,12 +165,12 @@ class BaseAutomationHandler(ABC):async def key_down(self, key: str) -> Dict[str, Any]:"""Press and hold the specified key."""pass-+@abstractmethodasync def key_up(self, key: str) -> Dict[str, Any]:"""Release the specified key."""pass-+@abstractmethodasync def type_text(self, text: str) -> Dict[str, Any]:"""Type the specified text."""@@ -176,7 +191,7 @@ class BaseAutomationHandler(ABC):async def scroll(self, x: int, y: int) -> Dict[str, Any]:"""Scroll the specified amount."""pass-+@abstractmethodasync def scroll_down(self, clicks: int = 1) -> Dict[str, Any]:"""Scroll down by the specified number of clicks."""@@ -212,9 +227,9 @@ class BaseAutomationHandler(ABC):@abstractmethodasync def set_clipboard(self, text: str) -> Dict[str, Any]:"""Set the clipboard content."""- pass+ pass@abstractmethodasync def run_command(self, command: str) -> Dict[str, Any]:"""Run a command and return the output."""- pass\ No newline at end of file+ passdiff --git a/libs/python/computer-server/computer_server/handlers/factory.py b/libs/python/computer-server/computer_server/handlers/factory.pyindex 962f7fb14e..3c90935f14 100644--- a/libs/python/computer-server/computer_server/handlers/factory.py+++ b/libs/python/computer-server/computer_server/handlers/factory.py@@ -1,68 +1,89 @@import platformimport subprocessfrom typing import Tuple, Type-from .base import BaseAccessibilityHandler, BaseAutomationHandler, BaseFileHandler+from computer_server.diorama.base import BaseDioramaHandler+from .base import BaseAccessibilityHandler, BaseAutomationHandler, BaseFileHandler+# Conditionally import platform-specific handlerssystem = platform.system().lower()-if system == 'darwin':- from .macos import MacOSAccessibilityHandler, MacOSAutomationHandler+if system == "darwin":from computer_server.diorama.macos import MacOSDioramaHandler-elif system == 'linux':++ from .macos import MacOSAccessibilityHandler, MacOSAutomationHandler+elif system == "linux":from .linux import LinuxAccessibilityHandler, LinuxAutomationHandler-elif system == 'windows':+elif system == "windows":from .windows import WindowsAccessibilityHandler, WindowsAutomationHandlerfrom .generic import GenericFileHandler+class HandlerFactory:"""Factory for creating OS-specific handlers."""-+@staticmethoddef _get_current_os() -> str:"""Determine the current OS.-+Returns:str: The OS type ('darwin' for macOS, 'linux' for Linux, or 'windows' for Windows)-+Raises:RuntimeError: If unable to determine the current OS"""try:# Use platform.system() as primary methodsystem = platform.system().lower()- if system in ['darwin', 'linux', 'windows']:+ if system in ["darwin", "linux", "windows"]:return system-+# Fallback to uname if platform.system() doesn't return expected values (Unix-like systems only)- result = subprocess.run(['uname', '-s'], capture_output=True, text=True)+ result = subprocess.run(["uname", "-s"], capture_output=True, text=True)if result.returncode == 0:return result.stdout.strip().lower()-+raise RuntimeError(f"Unsupported OS: {system}")except Exception as e:raise RuntimeError(f"Failed to determine current OS: {str(e)}")-+@staticmethod- def create_handlers() -> Tuple[BaseAccessibilityHandler, BaseAutomationHandler, BaseDioramaHandler, BaseFileHandler]:+ def create_handlers() -> (+ Tuple[BaseAccessibilityHandler, BaseAutomationHandler, BaseDioramaHandler, BaseFileHandler]+ ):"""Create and return appropriate handlers for the current OS.-+Returns:Tuple[BaseAccessibilityHandler, BaseAutomationHandler, BaseDioramaHandler, BaseFileHandler]: A tuple containingthe appropriate accessibility, automation, diorama, and file handlers for the current OS.-+Raises:NotImplementedError: If the current OS is not supportedRuntimeError: If unable to determine the current OS"""os_type = HandlerFactory._get_current_os()-- if os_type == 'darwin':- return MacOSAccessibilityHandler(), MacOSAutomationHandler(), MacOSDioramaHandler(), GenericFileHandler()- elif os_type == 'linux':- return LinuxAccessibilityHandler(), LinuxAutomationHandler(), BaseDioramaHandler(), GenericFileHandler()- elif os_type == 'windows':- return WindowsAccessibilityHandler(), WindowsAutomationHandler(), BaseDioramaHandler(), GenericFileHandler()++ if os_type == "darwin":+ return (+ MacOSAccessibilityHandler(),+ MacOSAutomationHandler(),+ MacOSDioramaHandler(),+ GenericFileHandler(),+ )+ elif os_type == "linux":+ return (+ LinuxAccessibilityHandler(),+ LinuxAutomationHandler(),+ BaseDioramaHandler(),+ GenericFileHandler(),+ )+ elif os_type == "windows":+ return (+ WindowsAccessibilityHandler(),+ WindowsAutomationHandler(),+ BaseDioramaHandler(),+ GenericFileHandler(),+ )else:raise NotImplementedError(f"OS '{os_type}' is not supported")diff --git a/libs/python/computer-server/computer_server/handlers/generic.py b/libs/python/computer-server/computer_server/handlers/generic.pyindex 11df71faed..da29f1c384 100644--- a/libs/python/computer-server/computer_server/handlers/generic.py+++ b/libs/python/computer-server/computer_server/handlers/generic.py@@ -6,38 +6,41 @@ Includes:"""+import base64from pathlib import Path-from typing import Dict, Any, Optional+from typing import Any, Dict, Optional+from .base import BaseFileHandler-import base64+def resolve_path(path: str) -> Path:"""Resolve a path to its absolute path. Expand ~ to the user's home directory.-+Args:path: The file or directory path to resolve-+Returns:Path: The resolved absolute path"""return Path(path).expanduser().resolve()+class GenericFileHandler(BaseFileHandler):"""Generic file handler that provides file system operations for all operating systems.-+This class implements the BaseFileHandler interface and provides methods forfile and directory operations including reading, writing, creating, and deletingfiles and directories."""-+async def file_exists(self, path: str) -> Dict[str, Any]:"""Check if a file exists at the specified path.-+Args:path: The file path to check-+Returns:Dict containing 'success' boolean and either 'exists' boolean or 'error' string"""@@ -49,10 +52,10 @@ class GenericFileHandler(BaseFileHandler):async def directory_exists(self, path: str) -> Dict[str, Any]:"""Check if a directory exists at the specified path.-+Args:path: The directory path to check-+Returns:Dict containing 'success' boolean and either 'exists' boolean or 'error' string"""@@ -64,25 +67,30 @@ class GenericFileHandler(BaseFileHandler):async def list_dir(self, path: str) -> Dict[str, Any]:"""List all files and directories in the specified directory.-+Args:path: The directory path to list-+Returns:Dict containing 'success' boolean and either 'files' list of names or 'error' string"""try:- return {"success": True, "files": [p.name for p in resolve_path(path).iterdir() if p.is_file() or p.is_dir()]}+ return {+ "success": True,+ "files": [+ p.name for p in resolve_path(path).iterdir() if p.is_file() or p.is_dir()+ ],+ }except Exception as e:return {"success": False, "error": str(e)}-+async def read_text(self, path: str) -> Dict[str, Any]:"""Read the contents of a text file.-+Args:path: The file path to read from-+Returns:Dict containing 'success' boolean and either 'content' string or 'error' string"""@@ -94,11 +102,11 @@ class GenericFileHandler(BaseFileHandler):async def write_text(self, path: str, content: str) -> Dict[str, Any]:"""Write text content to a file.-+Args:path: The file path to write tocontent: The text content to write-+Returns:Dict containing 'success' boolean and optionally 'error' string"""@@ -108,60 +116,64 @@ class GenericFileHandler(BaseFileHandler):except Exception as e:return {"success": False, "error": str(e)}- async def write_bytes(self, path: str, content_b64: str, append: bool = False) -> Dict[str, Any]:+ async def write_bytes(+ self, path: str, content_b64: str, append: bool = False+ ) -> Dict[str, Any]:"""Write binary content to a file from base64 encoded string.-+Args:path: The file path to write tocontent_b64: Base64 encoded binary contentappend: If True, append to existing file; if False, overwrite-+Returns:Dict containing 'success' boolean and optionally 'error' string"""try:- mode = 'ab' if append else 'wb'+ mode = "ab" if append else "wb"with open(resolve_path(path), mode) as f:f.write(base64.b64decode(content_b64))return {"success": True}except Exception as e:return {"success": False, "error": str(e)}-- async def read_bytes(self, path: str, offset: int = 0, length: Optional[int] = None) -> Dict[str, Any]:++ async def read_bytes(+ self, path: str, offset: int = 0, length: Optional[int] = None+ ) -> Dict[str, Any]:"""Read binary content from a file and return as base64 encoded string.-+Args:path: The file path to read fromoffset: Byte offset to start reading fromlength: Number of bytes to read; if None, read entire file from offset-+Returns:Dict containing 'success' boolean and either 'content_b64' string or 'error' string"""try:file_path = resolve_path(path)- with open(file_path, 'rb') as f:+ with open(file_path, "rb") as f:if offset > 0:f.seek(offset)-+if length is not None:content = f.read(length)else:content = f.read()-- return {"success": True, "content_b64": base64.b64encode(content).decode('utf-8')}++ return {"success": True, "content_b64": base64.b64encode(content).decode("utf-8")}except Exception as e:return {"success": False, "error": str(e)}async def get_file_size(self, path: str) -> Dict[str, Any]:"""Get the size of a file in bytes.-+Args:path: The file path to get size for-+Returns:Dict containing 'success' boolean and either 'size' integer or 'error' string"""@@ -175,10 +187,10 @@ class GenericFileHandler(BaseFileHandler):async def delete_file(self, path: str) -> Dict[str, Any]:"""Delete a file at the specified path.-+Args:path: The file path to delete-+Returns:Dict containing 'success' boolean and optionally 'error' string"""@@ -191,13 +203,13 @@ class GenericFileHandler(BaseFileHandler):async def create_dir(self, path: str) -> Dict[str, Any]:"""Create a directory at the specified path.-+Creates parent directories if they don't exist and doesn't raise an errorif the directory already exists.-+Args:path: The directory path to create-+Returns:Dict containing 'success' boolean and optionally 'error' string"""@@ -210,10 +222,10 @@ class GenericFileHandler(BaseFileHandler):async def delete_dir(self, path: str) -> Dict[str, Any]:"""Delete an empty directory at the specified path.-+Args:path: The directory path to delete-+Returns:Dict containing 'success' boolean and optionally 'error' string"""diff --git a/libs/python/computer-server/computer_server/handlers/linux.py b/libs/python/computer-server/computer_server/handlers/linux.pyindex eb8ca7b8be..f536440cab 100644--- a/libs/python/computer-server/computer_server/handlers/linux.py+++ b/libs/python/computer-server/computer_server/handlers/linux.py@@ -7,14 +7,15 @@ To use GUI automation in a headless environment:1. Install Xvfb: sudo apt-get install xvfb2. Run with virtual display: xvfb-run python -m computer_server"""-from typing import Dict, Any, List, Tuple, Optional-import logging-import subprocess+import asyncioimport base64-import osimport json+import logging+import os+import subprocessfrom io import BytesIO+from typing import Any, Dict, List, Optional, Tuple# Configure loggerlogger = logging.getLogger(__name__)@@ -23,30 +24,36 @@ logger = logging.getLogger(__name__)# This allows the server to run in headless environmentstry:import pyautogui+pyautogui.FAILSAFE = Falselogger.info("pyautogui successfully imported, GUI automation available")except Exception as e:logger.warning(f"pyautogui import failed: {str(e)}. GUI operations will be simulated.")-from pynput.mouse import Button, Controller as MouseController-from pynput.keyboard import Key, Controller as KeyboardController+from pynput.keyboard import Controller as KeyboardController+from pynput.keyboard import Key+from pynput.mouse import Button+from pynput.mouse import Controller as MouseControllerfrom .base import BaseAccessibilityHandler, BaseAutomationHandler+class LinuxAccessibilityHandler(BaseAccessibilityHandler):"""Linux implementation of accessibility handler."""-+async def get_accessibility_tree(self) -> Dict[str, Any]:"""Get the accessibility tree of the current window.-+Returns:Dict[str, Any]: A dictionary containing success status and a simulated tree structuresince Linux doesn't have equivalent accessibility API like macOS."""# Linux doesn't have equivalent accessibility API like macOS# Return a minimal dummy tree- logger.info("Getting accessibility tree (simulated, no accessibility API available on Linux)")+ logger.info(+ "Getting accessibility tree (simulated, no accessibility API available on Linux)"+ )return {"success": True,"tree": {@@ -54,32 +61,31 @@ class LinuxAccessibilityHandler(BaseAccessibilityHandler):"title": "Linux Window","position": {"x": 0, "y": 0},"size": {"width": 1920, "height": 1080},- "children": []- }+ "children": [],+ },}-- async def find_element(self, role: Optional[str] = None,- title: Optional[str] = None,- value: Optional[str] = None) -> Dict[str, Any]:++ async def find_element(+ self, role: Optional[str] = None, title: Optional[str] = None, value: Optional[str] = None+ ) -> Dict[str, Any]:"""Find an element in the accessibility tree by criteria.-+Args:role: The role of the element to find.title: The title of the element to find.value: The value of the element to find.-+Returns:Dict[str, Any]: A dictionary indicating that element search is not supported on Linux."""- logger.info(f"Finding element with role={role}, title={title}, value={value} (not supported on Linux)")- return {- "success": False,- "message": "Element search not supported on Linux"- }-+ logger.info(+ f"Finding element with role={role}, title={title}, value={value} (not supported on Linux)"+ )+ return {"success": False, "message": "Element search not supported on Linux"}+def get_cursor_position(self) -> Tuple[int, int]:"""Get the current cursor position.-+Returns:Tuple[int, int]: The x and y coordinates of the cursor position.Returns (0, 0) if pyautogui is not available.@@ -89,13 +95,13 @@ class LinuxAccessibilityHandler(BaseAccessibilityHandler):return pos.x, pos.yexcept Exception as e:logger.warning(f"Failed to get cursor position with pyautogui: {e}")-+logger.info("Getting cursor position (simulated)")return 0, 0-+def get_screen_size(self) -> Tuple[int, int]:"""Get the screen size.-+Returns:Tuple[int, int]: The width and height of the screen in pixels.Returns (1920, 1080) if pyautogui is not available.@@ -105,24 +111,28 @@ class LinuxAccessibilityHandler(BaseAccessibilityHandler):return size.width, size.heightexcept Exception as e:logger.warning(f"Failed to get screen size with pyautogui: {e}")-+logger.info("Getting screen size (simulated)")return 1920, 1080+class LinuxAutomationHandler(BaseAutomationHandler):"""Linux implementation of automation handler using pyautogui."""+keyboard = KeyboardController()mouse = MouseController()-+# Mouse Actions- async def mouse_down(self, x: Optional[int] = None, y: Optional[int] = None, button: str = "left") -> Dict[str, Any]:+ async def mouse_down(+ self, x: Optional[int] = None, y: Optional[int] = None, button: str = "left"+ ) -> Dict[str, Any]:"""Press and hold a mouse button at the specified coordinates.-+Args:x: The x coordinate to move to before pressing. If None, uses current position.y: The y coordinate to move to before pressing. If None, uses current position.button: The mouse button to press ("left", "right", or "middle").-+Returns:Dict[str, Any]: A dictionary with success status and error message if failed."""@@ -133,15 +143,17 @@ class LinuxAutomationHandler(BaseAutomationHandler):return {"success": True}except Exception as e:return {"success": False, "error": str(e)}-- async def mouse_up(self, x: Optional[int] = None, y: Optional[int] = None, button: str = "left") -> Dict[str, Any]:++ async def mouse_up(+ self, x: Optional[int] = None, y: Optional[int] = None, button: str = "left"+ ) -> Dict[str, Any]:"""Release a mouse button at the specified coordinates.-+Args:x: The x coordinate to move to before releasing. If None, uses current position.y: The y coordinate to move to before releasing. If None, uses current position.button: The mouse button to release ("left", "right", or "middle").-+Returns:Dict[str, Any]: A dictionary with success status and error message if failed."""@@ -152,14 +164,14 @@ class LinuxAutomationHandler(BaseAutomationHandler):return {"success": True}except Exception as e:return {"success": False, "error": str(e)}-+async def move_cursor(self, x: int, y: int) -> Dict[str, Any]:"""Move the cursor to the specified coordinates.-+Args:x: The x coordinate to move to.y: The y coordinate to move to.-+Returns:Dict[str, Any]: A dictionary with success status and error message if failed."""@@ -171,11 +183,11 @@ class LinuxAutomationHandler(BaseAutomationHandler):async def left_click(self, x: Optional[int] = None, y: Optional[int] = None) -> Dict[str, Any]:"""Perform a left mouse click at the specified coordinates.-+Args:x: The x coordinate to click at. If None, clicks at current position.y: The y coordinate to click at. If None, clicks at current position.-+Returns:Dict[str, Any]: A dictionary with success status and error message if failed."""@@ -189,11 +201,11 @@ class LinuxAutomationHandler(BaseAutomationHandler):async def right_click(self, x: Optional[int] = None, y: Optional[int] = None) -> Dict[str, Any]:"""Perform a right mouse click at the specified coordinates.-+Args:x: The x coordinate to click at. If None, clicks at current position.y: The y coordinate to click at. If None, clicks at current position.-+Returns:Dict[str, Any]: A dictionary with success status and error message if failed."""@@ -205,13 +217,15 @@ class LinuxAutomationHandler(BaseAutomationHandler):except Exception as e:return {"success": False, "error": str(e)}- async def double_click(self, x: Optional[int] = None, y: Optional[int] = None) -> Dict[str, Any]:+ async def double_click(+ self, x: Optional[int] = None, y: Optional[int] = None+ ) -> Dict[str, Any]:"""Perform a double click at the specified coordinates.-+Args:x: The x coordinate to double click at. If None, clicks at current position.y: The y coordinate to double click at. If None, clicks at current position.-+Returns:Dict[str, Any]: A dictionary with success status and error message if failed."""@@ -223,14 +237,16 @@ class LinuxAutomationHandler(BaseAutomationHandler):except Exception as e:return {"success": False, "error": str(e)}- async def click(self, x: Optional[int] = None, y: Optional[int] = None, button: str = "left") -> Dict[str, Any]:+ async def click(+ self, x: Optional[int] = None, y: Optional[int] = None, button: str = "left"+ ) -> Dict[str, Any]:"""Perform a mouse click with the specified button at the given coordinates.-+Args:x: The x coordinate to click at. If None, clicks at current position.y: The y coordinate to click at. If None, clicks at current position.button: The mouse button to click ("left", "right", or "middle").-+Returns:Dict[str, Any]: A dictionary with success status and error message if failed."""@@ -242,15 +258,17 @@ class LinuxAutomationHandler(BaseAutomationHandler):except Exception as e:return {"success": False, "error": str(e)}- async def drag_to(self, x: int, y: int, button: str = "left", duration: float = 0.5) -> Dict[str, Any]:+ async def drag_to(+ self, x: int, y: int, button: str = "left", duration: float = 0.5+ ) -> Dict[str, Any]:"""Drag from the current position to the specified coordinates.-+Args:x: The x coordinate to drag to.y: The y coordinate to drag to.button: The mouse button to use for dragging.duration: The time in seconds to take for the drag operation.-+Returns:Dict[str, Any]: A dictionary with success status and error message if failed."""@@ -260,16 +278,18 @@ class LinuxAutomationHandler(BaseAutomationHandler):except Exception as e:return {"success": False, "error": str(e)}- async def drag(self, start_x: int, start_y: int, end_x: int, end_y: int, button: str = "left") -> Dict[str, Any]:+ async def drag(+ self, start_x: int, start_y: int, end_x: int, end_y: int, button: str = "left"+ ) -> Dict[str, Any]:"""Drag from start coordinates to end coordinates.-+Args:start_x: The starting x coordinate.start_y: The starting y coordinate.end_x: The ending x coordinate.end_y: The ending y coordinate.button: The mouse button to use for dragging.-+Returns:Dict[str, Any]: A dictionary with success status and error message if failed."""@@ -280,14 +300,16 @@ class LinuxAutomationHandler(BaseAutomationHandler):except Exception as e:return {"success": False, "error": str(e)}- async def drag_path(self, path: List[Tuple[int, int]], button: str = "left", duration: float = 0.5) -> Dict[str, Any]:+ async def drag_path(+ self, path: List[Tuple[int, int]], button: str = "left", duration: float = 0.5+ ) -> Dict[str, Any]:"""Drag along a path defined by a list of coordinates.-+Args:path: A list of (x, y) coordinate tuples defining the drag path.button: The mouse button to use for dragging.duration: The time in seconds to take for each segment of the drag.-+Returns:Dict[str, Any]: A dictionary with success status and error message if failed."""@@ -304,10 +326,10 @@ class LinuxAutomationHandler(BaseAutomationHandler):# Keyboard Actionsasync def key_down(self, key: str) -> Dict[str, Any]:"""Press and hold a key.-+Args:key: The key to press down.-+Returns:Dict[str, Any]: A dictionary with success status and error message if failed."""@@ -316,13 +338,13 @@ class LinuxAutomationHandler(BaseAutomationHandler):return {"success": True}except Exception as e:return {"success": False, "error": str(e)}-+async def key_up(self, key: str) -> Dict[str, Any]:"""Release a key.-+Args:key: The key to release.-+Returns:Dict[str, Any]: A dictionary with success status and error message if failed."""@@ -331,13 +353,13 @@ class LinuxAutomationHandler(BaseAutomationHandler):return {"success": True}except Exception as e:return {"success": False, "error": str(e)}-+async def type_text(self, text: str) -> Dict[str, Any]:"""Type the specified text using the keyboard.-+Args:text: The text to type.-+Returns:Dict[str, Any]: A dictionary with success status and error message if failed."""@@ -350,10 +372,10 @@ class LinuxAutomationHandler(BaseAutomationHandler):async def press_key(self, key: str) -> Dict[str, Any]:"""Press and release a key.-+Args:key: The key to press.-+Returns:Dict[str, Any]: A dictionary with success status and error message if failed."""@@ -365,10 +387,10 @@ class LinuxAutomationHandler(BaseAutomationHandler):async def hotkey(self, keys: List[str]) -> Dict[str, Any]:"""Press a combination of keys simultaneously.-+Args:keys: A list of keys to press together as a hotkey combination.-+Returns:Dict[str, Any]: A dictionary with success status and error message if failed."""@@ -381,11 +403,11 @@ class LinuxAutomationHandler(BaseAutomationHandler):# Scrolling Actionsasync def scroll(self, x: int, y: int) -> Dict[str, Any]:"""Scroll the mouse wheel.-+Args:x: The horizontal scroll amount.y: The vertical scroll amount.-+Returns:Dict[str, Any]: A dictionary with success status and error message if failed."""@@ -394,13 +416,13 @@ class LinuxAutomationHandler(BaseAutomationHandler):return {"success": True}except Exception as e:return {"success": False, "error": str(e)}-+async def scroll_down(self, clicks: int = 1) -> Dict[str, Any]:"""Scroll down by the specified number of clicks.-+Args:clicks: The number of scroll clicks to perform downward.-+Returns:Dict[str, Any]: A dictionary with success status and error message if failed."""@@ -412,10 +434,10 @@ class LinuxAutomationHandler(BaseAutomationHandler):async def scroll_up(self, clicks: int = 1) -> Dict[str, Any]:"""Scroll up by the specified number of clicks.-+Args:clicks: The number of scroll clicks to perform upward.-+Returns:Dict[str, Any]: A dictionary with success status and error message if failed."""@@ -428,13 +450,14 @@ class LinuxAutomationHandler(BaseAutomationHandler):# Screen Actionsasync def screenshot(self) -> Dict[str, Any]:"""Take a screenshot of the current screen.-+Returns:Dict[str, Any]: A dictionary containing success status and base64-encoded image data,or error message if failed."""try:from PIL import Image+screenshot = pyautogui.screenshot()if not isinstance(screenshot, Image.Image):return {"success": False, "error": "Failed to capture screenshot"}@@ -448,7 +471,7 @@ class LinuxAutomationHandler(BaseAutomationHandler):async def get_screen_size(self) -> Dict[str, Any]:"""Get the size of the screen.-+Returns:Dict[str, Any]: A dictionary containing success status and screen dimensions,or error message if failed.@@ -461,7 +484,7 @@ class LinuxAutomationHandler(BaseAutomationHandler):async def get_cursor_position(self) -> Dict[str, Any]:"""Get the current position of the cursor.-+Returns:Dict[str, Any]: A dictionary containing success status and cursor coordinates,or error message if failed.@@ -475,13 +498,14 @@ class LinuxAutomationHandler(BaseAutomationHandler):# Clipboard Actionsasync def copy_to_clipboard(self) -> Dict[str, Any]:"""Get the current content of the clipboard.-+Returns:Dict[str, Any]: A dictionary containing success status and clipboard content,or error message if failed."""try:import pyperclip+content = pyperclip.paste()return {"success": True, "content": content}except Exception as e:@@ -489,15 +513,16 @@ class LinuxAutomationHandler(BaseAutomationHandler):async def set_clipboard(self, text: str) -> Dict[str, Any]:"""Set the clipboard content to the specified text.-+Args:text: The text to copy to the clipboard.-+Returns:Dict[str, Any]: A dictionary with success status and error message if failed."""try:import pyperclip+pyperclip.copy(text)return {"success": True}except Exception as e:@@ -506,10 +531,10 @@ class LinuxAutomationHandler(BaseAutomationHandler):# Command Executionasync def run_command(self, command: str) -> Dict[str, Any]:"""Execute a shell command asynchronously.-+Args:command: The shell command to execute.-+Returns:Dict[str, Any]: A dictionary containing success status, stdout, stderr,and return code, or error message if failed.@@ -517,18 +542,16 @@ class LinuxAutomationHandler(BaseAutomationHandler):try:# Create subprocessprocess = await asyncio.create_subprocess_shell(- command,- stdout=asyncio.subprocess.PIPE,- stderr=asyncio.subprocess.PIPE+ command, stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.PIPE)# Wait for the subprocess to finishstdout, stderr = await process.communicate()# Return decoded outputreturn {- "success": True,- "stdout": stdout.decode() if stdout else "",- "stderr": stderr.decode() if stderr else "",- "return_code": process.returncode+ "success": True,+ "stdout": stdout.decode() if stdout else "",+ "stderr": stderr.decode() if stderr else "",+ "return_code": process.returncode,}except Exception as e:return {"success": False, "error": str(e)}diff --git a/libs/python/computer-server/computer_server/handlers/macos.py b/libs/python/computer-server/computer_server/handlers/macos.pyindex e23b8ea65a..ce34166845 100644--- a/libs/python/computer-server/computer_server/handlers/macos.py+++ b/libs/python/computer-server/computer_server/handlers/macos.py@@ -1,54 +1,57 @@import pyautogui+pyautogui.FAILSAFE = False-from pynput.mouse import Button, Controller as MouseController-from pynput.keyboard import Key, Controller as KeyboardController-import time+import asyncioimport base64+import copy+import json+import logging+import re+import time+from ctypes import POINTER, byref, c_void_pfrom io import BytesIO-from typing import Optional, Dict, Any, List, Tuple-from ctypes import byref, c_void_p, POINTER-from AppKit import NSWorkspace # type: ignore+from typing import Any, Dict, List, Optional, Tuple+import AppKit-from Quartz.CoreGraphics import * # type: ignore-from Quartz.CoreGraphics import CGPoint, CGSize # type: ignoreimport Foundation-from ApplicationServices import (- AXUIElementCreateSystemWide, # type: ignore- AXUIElementCreateApplication, # type: ignore- AXUIElementCopyAttributeValue, # type: ignore- AXUIElementCopyAttributeValues, # type: ignore- kAXFocusedWindowAttribute, # type: ignore- kAXWindowsAttribute, # type: ignore- kAXMainWindowAttribute, # type: ignore- kAXChildrenAttribute, # type: ignore- kAXRoleAttribute, # type: ignore- kAXTitleAttribute, # type: ignore- kAXValueAttribute, # type: ignore- kAXDescriptionAttribute, # type: ignore- kAXEnabledAttribute, # type: ignore- kAXPositionAttribute, # type: ignore- kAXSizeAttribute, # type: ignore- kAXErrorSuccess, # type: ignore- AXValueGetType, # type: ignore- kAXValueCGSizeType, # type: ignore- kAXValueCGPointType, # type: ignore- kAXValueCFRangeType, # type: ignore- AXUIElementGetTypeID, # type: ignore- AXValueGetValue, # type: ignore- kAXVisibleChildrenAttribute, # type: ignore- kAXRoleDescriptionAttribute, # type: ignore- kAXFocusedApplicationAttribute, # type: ignore- kAXFocusedUIElementAttribute, # type: ignore- kAXSelectedTextAttribute, # type: ignore- kAXSelectedTextRangeAttribute, # type: ignore-)import objc-import re-import json-import copy-import asyncio+from AppKit import NSWorkspace # type: ignore+from ApplicationServices import AXUIElementCopyAttributeValue # type: ignore+from ApplicationServices import AXUIElementCopyAttributeValues # type: ignore+from ApplicationServices import AXUIElementCreateApplication # type: ignore+from ApplicationServices import AXUIElementCreateSystemWide # type: ignore+from ApplicationServices import AXUIElementGetTypeID # type: ignore+from ApplicationServices import AXValueGetType # type: ignore+from ApplicationServices import AXValueGetValue # type: ignore+from ApplicationServices import kAXChildrenAttribute # type: ignore+from ApplicationServices import kAXDescriptionAttribute # type: ignore+from ApplicationServices import kAXEnabledAttribute # type: ignore+from ApplicationServices import kAXErrorSuccess # type: ignore+from ApplicationServices import kAXFocusedApplicationAttribute # type: ignore+from ApplicationServices import kAXFocusedUIElementAttribute # type: ignore+from ApplicationServices import kAXFocusedWindowAttribute # type: ignore+from ApplicationServices import kAXMainWindowAttribute # type: ignore+from ApplicationServices import kAXPositionAttribute # type: ignore+from ApplicationServices import kAXRoleAttribute # type: ignore+from ApplicationServices import kAXRoleDescriptionAttribute # type: ignore+from ApplicationServices import kAXSelectedTextAttribute # type: ignore+from ApplicationServices import kAXSelectedTextRangeAttribute # type: ignore+from ApplicationServices import kAXSizeAttribute # type: ignore+from ApplicationServices import kAXTitleAttribute # type: ignore+from ApplicationServices import kAXValueAttribute # type: ignore+from ApplicationServices import kAXValueCFRangeType # type: ignore+from ApplicationServices import kAXValueCGPointType # type: ignore+from ApplicationServices import kAXValueCGSizeType # type: ignore+from ApplicationServices import kAXVisibleChildrenAttribute # type: ignore+from ApplicationServices import kAXWindowsAttribute # type: ignore+from pynput.keyboard import Controller as KeyboardController+from pynput.keyboard import Key+from pynput.mouse import Button+from pynput.mouse import Controller as MouseController+from Quartz.CoreGraphics import * # type: ignore+from Quartz.CoreGraphics import CGPoint, CGSize # type: ignore+from .base import BaseAccessibilityHandler, BaseAutomationHandler-import logginglogger = logging.getLogger(__name__)@@ -73,24 +76,26 @@ kCGWindowAlpha = "kCGWindowAlpha" # Window opacityNSApplicationActivationOptions = {"regular": 0, # Default activation"bringing_all_windows_forward": 1 << 0, # NSApplicationActivateAllWindows- "ignoring_other_apps": 1 << 1 # NSApplicationActivateIgnoringOtherApps+ "ignoring_other_apps": 1 << 1, # NSApplicationActivateIgnoringOtherApps}+def CFAttributeToPyObject(attrValue):"""Convert Core Foundation attribute values to Python objects.-+Args:attrValue: Core Foundation attribute value to convert-+Returns:Converted Python object or None if conversion fails"""+def list_helper(list_value):"""Helper function to convert CF arrays to Python lists.-+Args:list_value: Core Foundation array to convert-+Returns:Python list containing converted items"""@@ -101,10 +106,10 @@ def CFAttributeToPyObject(attrValue):def number_helper(number_value):"""Helper function to convert CF numbers to Python numbers.-+Args:number_value: Core Foundation number to convert-+Returns:Python int or float, or None if conversion fails"""@@ -123,10 +128,10 @@ def CFAttributeToPyObject(attrValue):def axuielement_helper(element_value):"""Helper function to handle AX UI elements.-+Args:element_value: Accessibility UI element to process-+Returns:The element value unchanged"""@@ -164,11 +169,11 @@ def CFAttributeToPyObject(attrValue):def element_attribute(element, attribute):"""Get an attribute value from an accessibility element.-+Args:element: The accessibility elementattribute: The attribute name to retrieve-+Returns:The attribute value or None if not found"""@@ -190,11 +195,11 @@ def element_attribute(element, attribute):def element_value(element, type):"""Extract a typed value from an accessibility element.-+Args:element: The accessibility element containing the valuetype: The expected value type-+Returns:The extracted value or None if extraction fails"""@@ -206,10 +211,10 @@ def element_value(element, type):class UIElement:"""Represents a UI element in the accessibility tree with position, size, and hierarchy information."""-+def __init__(self, element, offset_x=0, offset_y=0, max_depth=None, parents_visible_bbox=None):"""Initialize a UIElement from an accessibility element.-+Args:element: The accessibility element to wrapoffset_x: X offset for position calculations@@ -297,7 +302,7 @@ class UIElement:def _set_bboxes(self, parents_visible_bbox):"""Set bounding box and visible bounding box for the element.-+Args:parents_visible_bbox: Parent's visible bounding box for intersection calculation"""@@ -332,13 +337,13 @@ class UIElement:def _get_children(self, element, start_position, offset_x, offset_y):"""Get child elements from the accessibility element.-+Args:element: The parent accessibility elementstart_position: Starting position for offset calculationsoffset_x: X offset for child positioningoffset_y: Y offset for child positioning-+Returns:List of UIElement children"""@@ -371,7 +376,7 @@ class UIElement:def component_hash(self):"""Generate a hash identifier for this component based on its properties.-+Returns:MD5 hash string of component properties"""@@ -388,10 +393,10 @@ class UIElement:def hash_from_string(self, string):"""Generate MD5 hash from a string.-+Args:string: Input string to hash-+Returns:MD5 hash hexdigest or empty string if input is None/empty"""@@ -403,10 +408,10 @@ class UIElement:def children_content_hash(self, children):"""Generate a hash representing the content and structure of child elements.-+Args:children: List of child UIElement objects-+Returns:Combined hash of children content and structure"""@@ -426,16 +431,17 @@ class UIElement:def to_dict(self):"""Convert the UIElement to a dictionary representation.-+Returns:Dictionary containing all element properties and children"""+def children_to_dict(children):"""Convert list of children to dictionary format.-+Args:children: List of UIElement children to convert-+Returns:List of dictionaries representing the children"""@@ -464,7 +470,7 @@ class UIElement:size = f"{self.size.width:.0f};{self.size.height:.0f}"else:size = ""-+return {"id": self.identifier,"name": self.name,@@ -482,36 +488,38 @@ class UIElement:}-import Quartz-from AppKit import NSWorkspace, NSRunningApplicationfrom pathlib import Path+import Quartz+from AppKit import NSRunningApplication, NSWorkspace++def get_all_windows_zorder():"""Get all windows in the system with their z-order information.-+Returns:List of window dictionaries sorted by z-index, containing window propertieslike id, name, pid, owner, bounds, layer, and opacity"""window_list = Quartz.CGWindowListCopyWindowInfo(- Quartz.kCGWindowListOptionOnScreenOnly,- Quartz.kCGNullWindowID+ Quartz.kCGWindowListOptionOnScreenOnly, Quartz.kCGNullWindowID)- z_order = {window['kCGWindowNumber']: z_index for z_index, window in enumerate(window_list[::-1])}+ z_order = {+ window["kCGWindowNumber"]: z_index for z_index, window in enumerate(window_list[::-1])+ }window_list_all = Quartz.CGWindowListCopyWindowInfo(- Quartz.kCGWindowListOptionAll,- Quartz.kCGNullWindowID+ Quartz.kCGWindowListOptionAll, Quartz.kCGNullWindowID)windows = []for window in window_list_all:- window_id = window.get('kCGWindowNumber', 0)- window_name = window.get('kCGWindowName', '')- window_pid = window.get('kCGWindowOwnerPID', 0)- window_bounds = window.get('kCGWindowBounds', {})- window_owner = window.get('kCGWindowOwnerName', '')- window_is_on_screen = window.get('kCGWindowIsOnscreen', False)- layer = window.get('kCGWindowLayer', 0)- opacity = window.get('kCGWindowAlpha', 1.0)+ window_id = window.get("kCGWindowNumber", 0)+ window_name = window.get("kCGWindowName", "")+ window_pid = window.get("kCGWindowOwnerPID", 0)+ window_bounds = window.get("kCGWindowBounds", {})+ window_owner = window.get("kCGWindowOwnerName", "")+ window_is_on_screen = window.get("kCGWindowIsOnscreen", False)+ layer = window.get("kCGWindowLayer", 0)+ opacity = window.get("kCGWindowAlpha", 1.0)z_index = z_order.get(window_id, -1)if window_name == "Dock" and window_owner == "Dock":role = "dock"@@ -522,32 +530,35 @@ def get_all_windows_zorder():else:role = "app"if window_bounds:- windows.append({- "id": window_id,- "name": window_name or "Unnamed Window",- "pid": window_pid,- "owner": window_owner,- "role": role,- "is_on_screen": window_is_on_screen,- "bounds": {- "x": window_bounds.get('X', 0),- "y": window_bounds.get('Y', 0),- "width": window_bounds.get('Width', 0),- "height": window_bounds.get('Height', 0)- },- "layer": layer,- "z_index": z_index,- "opacity": opacity- })+ windows.append(+ {+ "id": window_id,+ "name": window_name or "Unnamed Window",+ "pid": window_pid,+ "owner": window_owner,+ "role": role,+ "is_on_screen": window_is_on_screen,+ "bounds": {+ "x": window_bounds.get("X", 0),+ "y": window_bounds.get("Y", 0),+ "width": window_bounds.get("Width", 0),+ "height": window_bounds.get("Height", 0),+ },+ "layer": layer,+ "z_index": z_index,+ "opacity": opacity,+ }+ )windows = sorted(windows, key=lambda x: x["z_index"])return windows+def get_app_info(app):"""Extract information from an NSRunningApplication object.-+Args:app: NSRunningApplication instance-+Returns:Dictionary containing app name, bundle ID, PID, and status flags"""@@ -560,12 +571,13 @@ def get_app_info(app):"terminated": app.isTerminated(),}+def get_menubar_items(active_app_pid=None):"""Get menubar items for the active application.-+Args:active_app_pid: Process ID of the active application, or None to use frontmost app-+Returns:List of menubar item dictionaries with title, bounds, index, and app_pid"""@@ -591,26 +603,24 @@ def get_menubar_items(active_app_pid=None):position_value = element_attribute(item, kAXPositionAttribute)if position_value:position_value = element_value(position_value, kAXValueCGPointType)- bounds["x"] = getattr(position_value, 'x', 0)- bounds["y"] = getattr(position_value, 'y', 0)+ bounds["x"] = getattr(position_value, "x", 0)+ bounds["y"] = getattr(position_value, "y", 0)size_value = element_attribute(item, kAXSizeAttribute)if size_value:size_value = element_value(size_value, kAXValueCGSizeType)- bounds["width"] = getattr(size_value, 'width', 0)- bounds["height"] = getattr(size_value, 'height', 0)- menubar_items.append({- "title": title,- "bounds": bounds,- "index": i,- "app_pid": active_app_pid- })+ bounds["width"] = getattr(size_value, "width", 0)+ bounds["height"] = getattr(size_value, "height", 0)+ menubar_items.append(+ {"title": title, "bounds": bounds, "index": i, "app_pid": active_app_pid}+ )return menubar_items+def get_dock_items():"""Get all items in the macOS Dock.-+Returns:- List of dock item dictionaries with title, description, bounds, index,+ List of dock item dictionaries with title, description, bounds, index,type, role, and subrole information"""dock_items = []@@ -648,13 +658,13 @@ def get_dock_items():position_value = element_attribute(item, kAXPositionAttribute)if position_value:position_value = element_value(position_value, kAXValueCGPointType)- bounds["x"] = getattr(position_value, 'x', 0)- bounds["y"] = getattr(position_value, 'y', 0)+ bounds["x"] = getattr(position_value, "x", 0)+ bounds["y"] = getattr(position_value, "y", 0)size_value = element_attribute(item, kAXSizeAttribute)if size_value:size_value = element_value(size_value, kAXValueCGSizeType)- bounds["width"] = getattr(size_value, 'width', 0)- bounds["height"] = getattr(size_value, 'height', 0)+ bounds["width"] = getattr(size_value, "width", 0)+ bounds["height"] = getattr(size_value, "height", 0)item_type = "unknown"if subrole == "AXApplicationDockItem":item_type = "application"@@ -666,23 +676,26 @@ def get_dock_items():item_type = "separator"elif "trash" in title.lower():item_type = "trash"- dock_items.append({- "title": title,- "description": description,- "bounds": bounds,- "index": i,- "type": item_type,- "role": role,- "subrole": subrole- })+ dock_items.append(+ {+ "title": title,+ "description": description,+ "bounds": bounds,+ "index": i,+ "type": item_type,+ "role": role,+ "subrole": subrole,+ }+ )return dock_items+class MacOSAccessibilityHandler(BaseAccessibilityHandler):"""Handler for macOS accessibility features and UI element inspection."""-+def get_desktop_state(self):"""Get the current state of the desktop including windows, apps, menubar, and dock.-+Returns:Dictionary containing applications, windows, menubar_items, and dock_items"""@@ -696,7 +709,9 @@ class MacOSAccessibilityHandler(BaseAccessibilityHandler):pid = app.processIdentifier()try:app_elem = AXUIElementCreateApplication(pid)- err, app_windows = AXUIElementCopyAttributeValue(app_elem, kAXWindowsAttribute, None)+ err, app_windows = AXUIElementCopyAttributeValue(+ app_elem, kAXWindowsAttribute, None+ )trees = []if err == kAXErrorSuccess and app_windows:for ax_win in app_windows:@@ -713,31 +728,32 @@ class MacOSAccessibilityHandler(BaseAccessibilityHandler):pid = win["pid"]idx = pid_to_idx.get(pid, 0)ax_trees = pid_to_ax_trees.get(pid, [])- win["children"] = ax_trees[idx]["children"] if idx < len(ax_trees) and "children" in ax_trees[idx] else []+ win["children"] = (+ ax_trees[idx]["children"]+ if idx < len(ax_trees) and "children" in ax_trees[idx]+ else []+ )pid_to_idx[pid] = idx + 1pid_to_window_ids.setdefault(pid, []).append(win["id"])for app in running_apps:info = get_app_info(app)app_pid = info["pid"]- applications.append({- "info": info,- "windows": pid_to_window_ids.get(app_pid, [])- })+ applications.append({"info": info, "windows": pid_to_window_ids.get(app_pid, [])})menubar_items = get_menubar_items()dock_items = get_dock_items()return {"applications": applications,"windows": windows,"menubar_items": menubar_items,- "dock_items": dock_items+ "dock_items": dock_items,}def get_application_windows(self, pid: int):"""Get all windows for a specific application.-+Args:pid: Process ID of the application-+Returns:List of accessibility window elements or empty list if none found"""@@ -753,7 +769,7 @@ class MacOSAccessibilityHandler(BaseAccessibilityHandler):def get_all_windows(self):"""Get all visible windows in the system.-+Returns:List of window dictionaries with app information and window details"""@@ -791,7 +807,7 @@ class MacOSAccessibilityHandler(BaseAccessibilityHandler):def get_running_apps(self):"""Get all currently running applications.-+Returns:List of NSRunningApplication objects"""@@ -803,11 +819,11 @@ class MacOSAccessibilityHandler(BaseAccessibilityHandler):def get_ax_attribute(self, element, attribute):"""Get an accessibility attribute from an element.-+Args:element: The accessibility elementattribute: The attribute name to retrieve-+Returns:The attribute value or None if not found"""@@ -815,10 +831,10 @@ class MacOSAccessibilityHandler(BaseAccessibilityHandler):def serialize_node(self, element):"""Create a serializable dictionary representation of an accessibility element.-+Args:element: The accessibility element to serialize-+Returns:Dictionary containing element properties like role, title, value, position, and size"""@@ -851,16 +867,13 @@ class MacOSAccessibilityHandler(BaseAccessibilityHandler):async def get_accessibility_tree(self) -> Dict[str, Any]:"""Get the complete accessibility tree for the current desktop state.-+Returns:Dictionary containing success status and desktop state information- """+ """try:desktop_state = self.get_desktop_state()- return {- "success": True,- **desktop_state- }+ return {"success": True, **desktop_state}except Exception as e:return {"success": False, "error": str(e)}@@ -869,12 +882,12 @@ class MacOSAccessibilityHandler(BaseAccessibilityHandler):self, role: Optional[str] = None, title: Optional[str] = None, value: Optional[str] = None) -> Dict[str, Any]:"""Find an accessibility element matching the specified criteria.-+Args:role: The accessibility role to match (optional)title: The title to match (optional)value: The value to match (optional)-+Returns:Dictionary containing success status and the found element or error message"""@@ -883,10 +896,10 @@ class MacOSAccessibilityHandler(BaseAccessibilityHandler):def match_element(element):"""Check if an element matches the search criteria.-+Args:element: The accessibility element to check-+Returns:True if element matches all specified criteria, False otherwise"""@@ -900,10 +913,10 @@ class MacOSAccessibilityHandler(BaseAccessibilityHandler):def search_tree(element):"""Recursively search the accessibility tree for matching elements.-+Args:element: The accessibility element to search from-+Returns:Serialized element dictionary if match found, None otherwise"""@@ -924,58 +937,71 @@ class MacOSAccessibilityHandler(BaseAccessibilityHandler):except Exception as e:return {"success": False, "error": str(e)}+class MacOSAutomationHandler(BaseAutomationHandler):"""Handler for macOS automation including mouse, keyboard, and screen operations."""-+# Mouse Actionsmouse = MouseController()keyboard = KeyboardController()-- async def mouse_down(self, x: Optional[int] = None, y: Optional[int] = None, button: str = "left") -> Dict[str, Any]:++ async def mouse_down(+ self, x: Optional[int] = None, y: Optional[int] = None, button: str = "left"+ ) -> Dict[str, Any]:"""Press and hold a mouse button at the specified coordinates.-+Args:x: X coordinate (optional, uses current position if None)y: Y coordinate (optional, uses current position if None)button: Mouse button to press ("left", "right", or "middle")-+Returns:Dictionary containing success status and error message if failed"""try:if x is not None and y is not None:self.mouse.position = (x, y)- self.mouse.press(Button.left if button == "left" else Button.right if button == "right" else Button.middle)+ self.mouse.press(+ Button.left+ if button == "left"+ else Button.right if button == "right" else Button.middle+ )return {"success": True}except Exception as e:return {"success": False, "error": str(e)}- async def mouse_up(self, x: Optional[int] = None, y: Optional[int] = None, button: str = "left") -> Dict[str, Any]:+ async def mouse_up(+ self, x: Optional[int] = None, y: Optional[int] = None, button: str = "left"+ ) -> Dict[str, Any]:"""Release a mouse button at the specified coordinates.-+Args:x: X coordinate (optional, uses current position if None)y: Y coordinate (optional, uses current position if None)button: Mouse button to release ("left", "right", or "middle")-+Returns:Dictionary containing success status and error message if failed"""try:if x is not None and y is not None:self.mouse.position = (x, y)- self.mouse.release(Button.left if button == "left" else Button.right if button == "right" else Button.middle)+ self.mouse.release(+ Button.left+ if button == "left"+ else Button.right if button == "right" else Button.middle+ )return {"success": True}except Exception as e:return {"success": False, "error": str(e)}async def left_click(self, x: Optional[int] = None, y: Optional[int] = None) -> Dict[str, Any]:"""Perform a left mouse click at the specified coordinates.-+Args:x: X coordinate (optional, uses current position if None)y: Y coordinate (optional, uses current position if None)-+Returns:Dictionary containing success status and error message if failed"""@@ -989,11 +1015,11 @@ class MacOSAutomationHandler(BaseAutomationHandler):async def right_click(self, x: Optional[int] = None, y: Optional[int] = None) -> Dict[str, Any]:"""Perform a right mouse click at the specified coordinates.-+Args:x: X coordinate (optional, uses current position if None)y: Y coordinate (optional, uses current position if None)-+Returns:Dictionary containing success status and error message if failed"""@@ -1009,11 +1035,11 @@ class MacOSAutomationHandler(BaseAutomationHandler):self, x: Optional[int] = None, y: Optional[int] = None) -> Dict[str, Any]:"""Perform a double left mouse click at the specified coordinates.-+Args:x: X coordinate (optional, uses current position if None)y: Y coordinate (optional, uses current position if None)-+Returns:Dictionary containing success status and error message if failed"""@@ -1027,11 +1053,11 @@ class MacOSAutomationHandler(BaseAutomationHandler):async def move_cursor(self, x: int, y: int) -> Dict[str, Any]:"""Move the mouse cursor to the specified coordinates.-+Args:x: Target X coordinatey: Target Y coordinate-+Returns:Dictionary containing success status and error message if failed"""@@ -1045,18 +1071,22 @@ class MacOSAutomationHandler(BaseAutomationHandler):self, x: int, y: int, button: str = "left", duration: float = 0.5) -> Dict[str, Any]:"""Drag from current position to target coordinates.-+Args:x: Target X coordinatey: Target Y coordinatebutton: Mouse button to use for dragging ("left", "right", or "middle")duration: Duration of the drag operation in seconds-+Returns:Dictionary containing success status and error message if failed"""try:- btn = Button.left if button == "left" else Button.right if button == "right" else Button.middle+ btn = (+ Button.left+ if button == "left"+ else Button.right if button == "right" else Button.middle+ )# Pressself.mouse.press(btn)# Move with sleep to simulate drag duration@@ -1082,19 +1112,23 @@ class MacOSAutomationHandler(BaseAutomationHandler):self, path: List[Tuple[int, int]], button: str = "left", duration: float = 0.5) -> Dict[str, Any]:"""Drag the mouse along a specified path of coordinates.-+Args:path: List of (x, y) coordinate tuples defining the drag pathbutton: Mouse button to use for dragging ("left", "right", or "middle")duration: Total duration of the drag operation in seconds-+Returns:Dictionary containing success status and error message if failed"""try:if not path or len(path) < 2:return {"success": False, "error": "Path must contain at least 2 points"}- btn = Button.left if button == "left" else Button.right if button == "right" else Button.middle+ btn = (+ Button.left+ if button == "left"+ else Button.right if button == "right" else Button.middle+ )# Move to the first pointself.mouse.position = path[0]self.mouse.press(btn)@@ -1114,10 +1148,10 @@ class MacOSAutomationHandler(BaseAutomationHandler):# Keyboard Actionsasync def key_down(self, key: str) -> Dict[str, Any]:"""Press and hold a keyboard key.-+Args:key: Key name to press (using pyautogui key names)-+Returns:Dictionary containing success status and error message if failed"""@@ -1127,13 +1161,13 @@ class MacOSAutomationHandler(BaseAutomationHandler):return {"success": True}except Exception as e:return {"success": False, "error": str(e)}-+async def key_up(self, key: str) -> Dict[str, Any]:"""Release a keyboard key.-+Args:key: Key name to release (using pyautogui key names)-+Returns:Dictionary containing success status and error message if failed"""@@ -1143,13 +1177,13 @@ class MacOSAutomationHandler(BaseAutomationHandler):return {"success": True}except Exception as e:return {"success": False, "error": str(e)}-+async def type_text(self, text: str) -> Dict[str, Any]:"""Type text using the keyboard with Unicode support.-+Args:text: Text string to type-+Returns:Dictionary containing success status and error message if failed"""@@ -1162,10 +1196,10 @@ class MacOSAutomationHandler(BaseAutomationHandler):async def press_key(self, key: str) -> Dict[str, Any]:"""Press and release a keyboard key.-+Args:key: Key name to press (using pyautogui key names)-+Returns:Dictionary containing success status and error message if failed"""@@ -1178,10 +1212,10 @@ class MacOSAutomationHandler(BaseAutomationHandler):async def hotkey(self, keys: List[str]) -> Dict[str, Any]:"""Press a combination of keys simultaneously.-+Args:keys: List of key names to press together (using pyautogui key names)-+Returns:Dictionary containing success status and error message if failed"""@@ -1195,11 +1229,11 @@ class MacOSAutomationHandler(BaseAutomationHandler):# Scrolling Actionsasync def scroll(self, x: int, y: int) -> Dict[str, Any]:"""Scroll the mouse wheel in the specified direction.-+Args:x: Horizontal scroll amounty: Vertical scroll amount (positive for up, negative for down)-+Returns:Dictionary containing success status and error message if failed"""@@ -1208,13 +1242,13 @@ class MacOSAutomationHandler(BaseAutomationHandler):return {"success": True}except Exception as e:return {"success": False, "error": str(e)}-+async def scroll_down(self, clicks: int = 1) -> Dict[str, Any]:"""Scroll down by the specified number of clicks.-+Args:clicks: Number of scroll clicks to perform-+Returns:Dictionary containing success status and error message if failed"""@@ -1226,10 +1260,10 @@ class MacOSAutomationHandler(BaseAutomationHandler):async def scroll_up(self, clicks: int = 1) -> Dict[str, Any]:"""Scroll up by the specified number of clicks.-+Args:clicks: Number of scroll clicks to perform-+Returns:Dictionary containing success status and error message if failed"""@@ -1242,7 +1276,7 @@ class MacOSAutomationHandler(BaseAutomationHandler):# Screen Actionsasync def screenshot(self) -> Dict[str, Any]:"""Capture a screenshot of the current screen.-+Returns:Dictionary containing success status and base64-encoded image data or error message"""@@ -1263,7 +1297,7 @@ class MacOSAutomationHandler(BaseAutomationHandler):async def get_screen_size(self) -> Dict[str, Any]:"""Get the dimensions of the current screen.-+Returns:Dictionary containing success status and screen size or error message"""@@ -1275,7 +1309,7 @@ class MacOSAutomationHandler(BaseAutomationHandler):async def get_cursor_position(self) -> Dict[str, Any]:"""Get the current position of the mouse cursor.-+Returns:Dictionary containing success status and cursor position or error message"""@@ -1288,7 +1322,7 @@ class MacOSAutomationHandler(BaseAutomationHandler):# Clipboard Actionsasync def copy_to_clipboard(self) -> Dict[str, Any]:"""Get the current content of the system clipboard.-+Returns:Dictionary containing success status and clipboard content or error message"""@@ -1302,10 +1336,10 @@ class MacOSAutomationHandler(BaseAutomationHandler):async def set_clipboard(self, text: str) -> Dict[str, Any]:"""Set the content of the system clipboard.-+Args:text: Text to copy to the clipboard-+Returns:Dictionary containing success status and error message if failed"""@@ -1319,28 +1353,26 @@ class MacOSAutomationHandler(BaseAutomationHandler):async def run_command(self, command: str) -> Dict[str, Any]:"""Run a shell command and return its output.-+Args:command: Shell command to execute-+Returns:Dictionary containing success status, stdout, stderr, and return code"""try:# Create subprocessprocess = await asyncio.create_subprocess_shell(- command,- stdout=asyncio.subprocess.PIPE,- stderr=asyncio.subprocess.PIPE+ command, stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.PIPE)# Wait for the subprocess to finishstdout, stderr = await process.communicate()# Return decoded outputreturn {- "success": True,- "stdout": stdout.decode() if stdout else "",+ "success": True,+ "stdout": stdout.decode() if stdout else "","stderr": stderr.decode() if stderr else "",- "return_code": process.returncode+ "return_code": process.returncode,}except Exception as e:return {"success": False, "error": str(e)}diff --git a/libs/python/computer-server/computer_server/handlers/windows.py b/libs/python/computer-server/computer_server/handlers/windows.pyindex 74949561d1..a01456d4d3 100644--- a/libs/python/computer-server/computer_server/handlers/windows.py+++ b/libs/python/computer-server/computer_server/handlers/windows.py@@ -4,15 +4,17 @@ Windows implementation of automation and accessibility handlers.This implementation uses pyautogui for GUI automation and Windows-specific APIsfor accessibility and system operations."""-from typing import Dict, Any, List, Tuple, Optional-import logging-import subprocess+import asyncioimport base64+import loggingimport os+import subprocessfrom io import BytesIO-from pynput.mouse import Controller as MouseController+from typing import Any, Dict, List, Optional, Tuple+from pynput.keyboard import Controller as KeyboardController+from pynput.mouse import Controller as MouseController# Configure loggerlogger = logging.getLogger(__name__)@@ -20,6 +22,7 @@ logger = logging.getLogger(__name__)# Try to import pyautoguitry:import pyautogui+pyautogui.FAILSAFE = Falselogger.info("pyautogui successfully imported, GUI automation available")except Exception as e:@@ -28,58 +31,62 @@ except Exception as e:# Try to import Windows-specific modulestry:- import win32gui- import win32conimport win32api+ import win32con+ import win32gui+logger.info("Windows API modules successfully imported")WINDOWS_API_AVAILABLE = Trueexcept Exception as e:- logger.error(f"Windows API modules import failed: {str(e)}. Some Windows-specific features will be unavailable.")+ logger.error(+ f"Windows API modules import failed: {str(e)}. Some Windows-specific features will be unavailable."+ )WINDOWS_API_AVAILABLE = Falsefrom .base import BaseAccessibilityHandler, BaseAutomationHandler+class WindowsAccessibilityHandler(BaseAccessibilityHandler):"""Windows implementation of accessibility handler."""-+async def get_accessibility_tree(self) -> Dict[str, Any]:"""Get the accessibility tree of the current window.-+Returns:Dict[str, Any]: A dictionary containing the success status and eitherthe accessibility tree or an error message.- Structure: {"success": bool, "tree": dict} or+ Structure: {"success": bool, "tree": dict} or{"success": bool, "error": str}"""if not WINDOWS_API_AVAILABLE:return {"success": False, "error": "Windows API not available"}-+try:# Get the foreground windowhwnd = win32gui.GetForegroundWindow()if not hwnd:return {"success": False, "error": "No foreground window found"}-+# Get window informationwindow_text = win32gui.GetWindowText(hwnd)rect = win32gui.GetWindowRect(hwnd)-+tree = {"role": "Window","title": window_text,"position": {"x": rect[0], "y": rect[1]},"size": {"width": rect[2] - rect[0], "height": rect[3] - rect[1]},- "children": []+ "children": [],}-+# Enumerate child windowsdef enum_child_proc(hwnd_child, children_list):"""Callback function to enumerate child windows and collect their information.-+Args:hwnd_child: Handle to the child window being enumerated.children_list: List to append child window information to.-+Returns:bool: True to continue enumeration, False to stop."""@@ -87,46 +94,49 @@ class WindowsAccessibilityHandler(BaseAccessibilityHandler):child_text = win32gui.GetWindowText(hwnd_child)child_rect = win32gui.GetWindowRect(hwnd_child)child_class = win32gui.GetClassName(hwnd_child)-+child_info = {"role": child_class,"title": child_text,"position": {"x": child_rect[0], "y": child_rect[1]},- "size": {"width": child_rect[2] - child_rect[0], "height": child_rect[3] - child_rect[1]},- "children": []+ "size": {+ "width": child_rect[2] - child_rect[0],+ "height": child_rect[3] - child_rect[1],+ },+ "children": [],}children_list.append(child_info)except Exception as e:logger.debug(f"Error getting child window info: {e}")return True-+win32gui.EnumChildWindows(hwnd, enum_child_proc, tree["children"])-+return {"success": True, "tree": tree}-+except Exception as e:logger.error(f"Error getting accessibility tree: {e}")return {"success": False, "error": str(e)}-- async def find_element(self, role: Optional[str] = None,- title: Optional[str] = None,- value: Optional[str] = None) -> Dict[str, Any]:++ async def find_element(+ self, role: Optional[str] = None, title: Optional[str] = None, value: Optional[str] = None+ ) -> Dict[str, Any]:"""Find an element in the accessibility tree by criteria.-+Args:role (Optional[str]): The role or class name of the element to find.title (Optional[str]): The title or text of the element to find.value (Optional[str]): The value of the element (not used in Windows implementation).-+Returns:Dict[str, Any]: A dictionary containing the success status and eitherthe found element or an error message.- Structure: {"success": bool, "element": dict} or+ Structure: {"success": bool, "element": dict} or{"success": bool, "error": str}"""if not WINDOWS_API_AVAILABLE:return {"success": False, "error": "Windows API not available"}-+try:# Find window by title if specifiedif title:@@ -139,10 +149,10 @@ class WindowsAccessibilityHandler(BaseAccessibilityHandler):"role": "Window","title": title,"position": {"x": rect[0], "y": rect[1]},- "size": {"width": rect[2] - rect[0], "height": rect[3] - rect[1]}- }+ "size": {"width": rect[2] - rect[0], "height": rect[3] - rect[1]},+ },}-+# Find window by class name if role is specifiedif role:hwnd = win32gui.FindWindow(role, None)@@ -155,37 +165,40 @@ class WindowsAccessibilityHandler(BaseAccessibilityHandler):"role": role,"title": window_text,"position": {"x": rect[0], "y": rect[1]},- "size": {"width": rect[2] - rect[0], "height": rect[3] - rect[1]}- }+ "size": {"width": rect[2] - rect[0], "height": rect[3] - rect[1]},+ },}-+return {"success": False, "error": "Element not found"}-+except Exception as e:logger.error(f"Error finding element: {e}")return {"success": False, "error": str(e)}+class WindowsAutomationHandler(BaseAutomationHandler):"""Windows implementation of automation handler using pyautogui and Windows APIs."""-+mouse = MouseController()keyboard = KeyboardController()# Mouse Actions- async def mouse_down(self, x: Optional[int] = None, y: Optional[int] = None, button: str = "left") -> Dict[str, Any]:+ async def mouse_down(+ self, x: Optional[int] = None, y: Optional[int] = None, button: str = "left"+ ) -> Dict[str, Any]:"""Press and hold a mouse button at the specified coordinates.-+Args:x (Optional[int]): The x-coordinate to move to before pressing. If None, uses current position.y (Optional[int]): The y-coordinate to move to before pressing. If None, uses current position.button (str): The mouse button to press ("left", "right", or "middle").-+Returns:Dict[str, Any]: A dictionary with success status and optional error message."""if not pyautogui:return {"success": False, "error": "pyautogui not available"}-+try:if x is not None and y is not None:pyautogui.moveTo(x, y)@@ -193,21 +206,23 @@ class WindowsAutomationHandler(BaseAutomationHandler):return {"success": True}except Exception as e:return {"success": False, "error": str(e)}-- async def mouse_up(self, x: Optional[int] = None, y: Optional[int] = None, button: str = "left") -> Dict[str, Any]:++ async def mouse_up(+ self, x: Optional[int] = None, y: Optional[int] = None, button: str = "left"+ ) -> Dict[str, Any]:"""Release a mouse button at the specified coordinates.-+Args:x (Optional[int]): The x-coordinate to move to before releasing. If None, uses current position.y (Optional[int]): The y-coordinate to move to before releasing. If None, uses current position.button (str): The mouse button to release ("left", "right", or "middle").-+Returns:Dict[str, Any]: A dictionary with success status and optional error message."""if not pyautogui:return {"success": False, "error": "pyautogui not available"}-+try:if x is not None and y is not None:pyautogui.moveTo(x, y)@@ -215,20 +230,20 @@ class WindowsAutomationHandler(BaseAutomationHandler):return {"success": True}except Exception as e:return {"success": False, "error": str(e)}-+async def move_cursor(self, x: int, y: int) -> Dict[str, Any]:"""Move the mouse cursor to the specified coordinates.-+Args:x (int): The x-coordinate to move to.y (int): The y-coordinate to move to.-+Returns:Dict[str, Any]: A dictionary with success status and optional error message."""if not pyautogui:return {"success": False, "error": "pyautogui not available"}-+try:pyautogui.moveTo(x, y)return {"success": True}@@ -237,17 +252,17 @@ class WindowsAutomationHandler(BaseAutomationHandler):async def left_click(self, x: Optional[int] = None, y: Optional[int] = None) -> Dict[str, Any]:"""Perform a left mouse click at the specified coordinates.-+Args:x (Optional[int]): The x-coordinate to click at. If None, clicks at current position.y (Optional[int]): The y-coordinate to click at. If None, clicks at current position.-+Returns:Dict[str, Any]: A dictionary with success status and optional error message."""if not pyautogui:return {"success": False, "error": "pyautogui not available"}-+try:if x is not None and y is not None:pyautogui.moveTo(x, y)@@ -258,17 +273,17 @@ class WindowsAutomationHandler(BaseAutomationHandler):async def right_click(self, x: Optional[int] = None, y: Optional[int] = None) -> Dict[str, Any]:"""Perform a right mouse click at the specified coordinates.-+Args:x (Optional[int]): The x-coordinate to click at. If None, clicks at current position.y (Optional[int]): The y-coordinate to click at. If None, clicks at current position.-+Returns:Dict[str, Any]: A dictionary with success status and optional error message."""if not pyautogui:return {"success": False, "error": "pyautogui not available"}-+try:if x is not None and y is not None:pyautogui.moveTo(x, y)@@ -277,19 +292,21 @@ class WindowsAutomationHandler(BaseAutomationHandler):except Exception as e:return {"success": False, "error": str(e)}- async def double_click(self, x: Optional[int] = None, y: Optional[int] = None) -> Dict[str, Any]:+ async def double_click(+ self, x: Optional[int] = None, y: Optional[int] = None+ ) -> Dict[str, Any]:"""Perform a double left mouse click at the specified coordinates.-+Args:x (Optional[int]): The x-coordinate to double-click at. If None, clicks at current position.y (Optional[int]): The y-coordinate to double-click at. If None, clicks at current position.-+Returns:Dict[str, Any]: A dictionary with success status and optional error message."""if not pyautogui:return {"success": False, "error": "pyautogui not available"}-+try:if x is not None and y is not None:pyautogui.moveTo(x, y)@@ -298,52 +315,56 @@ class WindowsAutomationHandler(BaseAutomationHandler):except Exception as e:return {"success": False, "error": str(e)}- async def drag_to(self, x: int, y: int, button: str = "left", duration: float = 0.5) -> Dict[str, Any]:+ async def drag_to(+ self, x: int, y: int, button: str = "left", duration: float = 0.5+ ) -> Dict[str, Any]:"""Drag from the current position to the specified coordinates.-+Args:x (int): The x-coordinate to drag to.y (int): The y-coordinate to drag to.button (str): The mouse button to use for dragging ("left", "right", or "middle").duration (float): The time in seconds to take for the drag operation.-+Returns:Dict[str, Any]: A dictionary with success status and optional error message."""if not pyautogui:return {"success": False, "error": "pyautogui not available"}-+try:pyautogui.dragTo(x, y, duration=duration, button=button)return {"success": True}except Exception as e:return {"success": False, "error": str(e)}- async def drag(self, path: List[Tuple[int, int]], button: str = "left", duration: float = 0.5) -> Dict[str, Any]:+ async def drag(+ self, path: List[Tuple[int, int]], button: str = "left", duration: float = 0.5+ ) -> Dict[str, Any]:"""Drag the mouse through a series of coordinates.-+Args:path (List[Tuple[int, int]]): A list of (x, y) coordinate tuples to drag through.button (str): The mouse button to use for dragging ("left", "right", or "middle").duration (float): The total time in seconds for the entire drag operation.-+Returns:Dict[str, Any]: A dictionary with success status and optional error message."""if not pyautogui:return {"success": False, "error": "pyautogui not available"}-+try:if not path:return {"success": False, "error": "Path is empty"}-+# Move to first positionpyautogui.moveTo(*path[0])-+# Drag through all positionsfor x, y in path[1:]:- pyautogui.dragTo(x, y, duration=duration/len(path), button=button)-+ pyautogui.dragTo(x, y, duration=duration / len(path), button=button)+return {"success": True}except Exception as e:return {"success": False, "error": str(e)}@@ -351,46 +372,46 @@ class WindowsAutomationHandler(BaseAutomationHandler):# Keyboard Actionsasync def key_down(self, key: str) -> Dict[str, Any]:"""Press and hold a keyboard key.-+Args:key (str): The key to press down (e.g., 'ctrl', 'shift', 'a').-+Returns:Dict[str, Any]: A dictionary with success status and optional error message."""if not pyautogui:return {"success": False, "error": "pyautogui not available"}-+try:pyautogui.keyDown(key)return {"success": True}except Exception as e:return {"success": False, "error": str(e)}-+async def key_up(self, key: str) -> Dict[str, Any]:"""Release a keyboard key.-+Args:key (str): The key to release (e.g., 'ctrl', 'shift', 'a').-+Returns:Dict[str, Any]: A dictionary with success status and optional error message."""if not pyautogui:return {"success": False, "error": "pyautogui not available"}-+try:pyautogui.keyUp(key)return {"success": True}except Exception as e:return {"success": False, "error": str(e)}-+async def type_text(self, text: str) -> Dict[str, Any]:"""Type the specified text.-+Args:text (str): The text to type.-+Returns:Dict[str, Any]: A dictionary with success status and optional error message."""@@ -403,16 +424,16 @@ class WindowsAutomationHandler(BaseAutomationHandler):async def press_key(self, key: str) -> Dict[str, Any]:"""Press and release a keyboard key.-+Args:key (str): The key to press (e.g., 'enter', 'space', 'tab').-+Returns:Dict[str, Any]: A dictionary with success status and optional error message."""if not pyautogui:return {"success": False, "error": "pyautogui not available"}-+try:pyautogui.press(key)return {"success": True}@@ -421,16 +442,16 @@ class WindowsAutomationHandler(BaseAutomationHandler):async def hotkey(self, keys: List[str]) -> Dict[str, Any]:"""Press a combination of keys simultaneously.-+Args:keys (List[str]): The keys to press together (e.g., ['ctrl', 'c'], ['alt', 'tab']).-+Returns:Dict[str, Any]: A dictionary with success status and optional error message."""if not pyautogui:return {"success": False, "error": "pyautogui not available"}-+try:pyautogui.hotkey(*keys)return {"success": True}@@ -440,35 +461,35 @@ class WindowsAutomationHandler(BaseAutomationHandler):# Scrolling Actionsasync def scroll(self, x: int, y: int) -> Dict[str, Any]:"""Scroll vertically at the current cursor position.-+Args:x (int): Horizontal scroll amount (not used in pyautogui implementation).y (int): Vertical scroll amount. Positive values scroll up, negative values scroll down.-+Returns:Dict[str, Any]: A dictionary with success status and optional error message."""if not pyautogui:return {"success": False, "error": "pyautogui not available"}-+try:self.mouse.scroll(x, y)return {"success": True}except Exception as e:return {"success": False, "error": str(e)}-+async def scroll_down(self, clicks: int = 1) -> Dict[str, Any]:"""Scroll down by the specified number of clicks.-+Args:clicks (int): The number of scroll clicks to perform downward.-+Returns:Dict[str, Any]: A dictionary with success status and optional error message."""if not pyautogui:return {"success": False, "error": "pyautogui not available"}-+try:pyautogui.scroll(-clicks)return {"success": True}@@ -477,16 +498,16 @@ class WindowsAutomationHandler(BaseAutomationHandler):async def scroll_up(self, clicks: int = 1) -> Dict[str, Any]:"""Scroll up by the specified number of clicks.-+Args:clicks (int): The number of scroll clicks to perform upward.-+Returns:Dict[str, Any]: A dictionary with success status and optional error message."""if not pyautogui:return {"success": False, "error": "pyautogui not available"}-+try:pyautogui.scroll(clicks)return {"success": True}@@ -496,22 +517,23 @@ class WindowsAutomationHandler(BaseAutomationHandler):# Screen Actionsasync def screenshot(self) -> Dict[str, Any]:"""Capture a screenshot of the entire screen.-+Returns:Dict[str, Any]: A dictionary containing the success status and eitherbase64-encoded image data or an error message.- Structure: {"success": bool, "image_data": str} or+ Structure: {"success": bool, "image_data": str} or{"success": bool, "error": str}"""if not pyautogui:return {"success": False, "error": "pyautogui not available"}-+try:from PIL import Image+screenshot = pyautogui.screenshot()if not isinstance(screenshot, Image.Image):return {"success": False, "error": "Failed to capture screenshot"}-+buffered = BytesIO()screenshot.save(buffered, format="PNG", optimize=True)buffered.seek(0)@@ -522,11 +544,11 @@ class WindowsAutomationHandler(BaseAutomationHandler):async def get_screen_size(self) -> Dict[str, Any]:"""Get the size of the screen in pixels.-+Returns:Dict[str, Any]: A dictionary containing the success status and eitherscreen size information or an error message.- Structure: {"success": bool, "size": {"width": int, "height": int}} or+ Structure: {"success": bool, "size": {"width": int, "height": int}} or{"success": bool, "error": str}"""try:@@ -545,11 +567,11 @@ class WindowsAutomationHandler(BaseAutomationHandler):async def get_cursor_position(self) -> Dict[str, Any]:"""Get the current position of the mouse cursor.-+Returns:Dict[str, Any]: A dictionary containing the success status and eithercursor position or an error message.- Structure: {"success": bool, "position": {"x": int, "y": int}} or+ Structure: {"success": bool, "position": {"x": int, "y": int}} or{"success": bool, "error": str}"""try:@@ -568,15 +590,16 @@ class WindowsAutomationHandler(BaseAutomationHandler):# Clipboard Actionsasync def copy_to_clipboard(self) -> Dict[str, Any]:"""Get the current content of the clipboard.-+Returns:Dict[str, Any]: A dictionary containing the success status and eitherclipboard content or an error message.- Structure: {"success": bool, "content": str} or+ Structure: {"success": bool, "content": str} or{"success": bool, "error": str}"""try:import pyperclip+content = pyperclip.paste()return {"success": True, "content": content}except Exception as e:@@ -584,15 +607,16 @@ class WindowsAutomationHandler(BaseAutomationHandler):async def set_clipboard(self, text: str) -> Dict[str, Any]:"""Set the clipboard content to the specified text.-+Args:text (str): The text to copy to the clipboard.-+Returns:Dict[str, Any]: A dictionary with success status and optional error message."""try:import pyperclip+pyperclip.copy(text)return {"success": True}except Exception as e:@@ -601,31 +625,29 @@ class WindowsAutomationHandler(BaseAutomationHandler):# Command Executionasync def run_command(self, command: str) -> Dict[str, Any]:"""Execute a shell command asynchronously.-+Args:command (str): The shell command to execute.-+Returns:Dict[str, Any]: A dictionary containing the success status and eithercommand output or an error message.- Structure: {"success": bool, "stdout": str, "stderr": str, "return_code": int} or+ Structure: {"success": bool, "stdout": str, "stderr": str, "return_code": int} or{"success": bool, "error": str}"""try:# Create subprocessprocess = await asyncio.create_subprocess_shell(- command,- stdout=asyncio.subprocess.PIPE,- stderr=asyncio.subprocess.PIPE+ command, stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.PIPE)# Wait for the subprocess to finishstdout, stderr = await process.communicate()# Return decoded outputreturn {- "success": True,- "stdout": stdout.decode() if stdout else "",- "stderr": stderr.decode() if stderr else "",- "return_code": process.returncode+ "success": True,+ "stdout": stdout.decode() if stdout else "",+ "stderr": stderr.decode() if stderr else "",+ "return_code": process.returncode,}except Exception as e:return {"success": False, "error": str(e)}diff --git a/libs/python/computer-server/computer_server/main.py b/libs/python/computer-server/computer_server/main.pyindex 71ceafe030..721df77d8b 100644--- a/libs/python/computer-server/computer_server/main.py+++ b/libs/python/computer-server/computer_server/main.py@@ -1,27 +1,37 @@-from fastapi import FastAPI, WebSocket, WebSocketDisconnect, Request, HTTPException, Header-from fastapi.responses import StreamingResponse, JSONResponse-from typing import List, Dict, Any, Optional, Union, Literal, cast-import uvicorn-import loggingimport asyncio+import hashlib+import inspectimport json+import logging+import os+import platform+import timeimport traceback-import inspect-from contextlib import redirect_stdout, redirect_stderr+from contextlib import redirect_stderr, redirect_stdoutfrom io import StringIO-from .handlers.factory import HandlerFactory-import os+from typing import Any, Dict, List, Literal, Optional, Union, cast+import aiohttp-import hashlib-import time-import platform+import uvicorn+from fastapi import (+ FastAPI,+ Header,+ HTTPException,+ Request,+ WebSocket,+ WebSocketDisconnect,+)from fastapi.middleware.cors import CORSMiddleware+from fastapi.responses import JSONResponse, StreamingResponse++from .handlers.factory import HandlerFactory# Authentication session TTL (in seconds). Override via env var CUA_AUTH_TTL_SECONDS. Default: 60sAUTH_SESSION_TTL_SECONDS: int = int(os.environ.get("CUA_AUTH_TTL_SECONDS", "60"))try:from agent import ComputerAgent+HAS_AGENT = Trueexcept ImportError:HAS_AGENT = False@@ -54,16 +64,20 @@ app.add_middleware(protocol_version = 1try:from importlib.metadata import version+package_version = version("cua-computer-server")except Exception:# Fallback for cases where package is not installed or importlib.metadata is not availabletry:import pkg_resources+package_version = pkg_resources.get_distribution("cua-computer-server").versionexcept Exception:package_version = "unknown"-accessibility_handler, automation_handler, diorama_handler, file_handler = HandlerFactory.create_handlers()+accessibility_handler, automation_handler, diorama_handler, file_handler = (+ HandlerFactory.create_handlers()+)handlers = {"version": lambda: {"protocol": protocol_version, "package": package_version},# App-Use commands@@ -118,87 +132,91 @@ class AuthenticationManager:def __init__(self):self.sessions: Dict[str, Dict[str, Any]] = {}self.container_name = os.environ.get("CONTAINER_NAME")-+def _hash_credentials(self, container_name: str, api_key: str) -> str:"""Create a hash of container name and API key for session identification"""combined = f"{container_name}:{api_key}"return hashlib.sha256(combined.encode()).hexdigest()-+def _is_session_valid(self, session_data: Dict[str, Any]) -> bool:"""Check if a session is still valid based on expiration time"""- if not session_data.get('valid', False):+ if not session_data.get("valid", False):return False-- expires_at = session_data.get('expires_at', 0)++ expires_at = session_data.get("expires_at", 0)return time.time() < expires_at-+async def auth(self, container_name: str, api_key: str) -> bool:"""Authenticate container name and API key, using cached sessions when possible"""# If no CONTAINER_NAME is set, always allow access (local development)if not self.container_name:- logger.info("No CONTAINER_NAME set in environment. Allowing access (local development mode)")+ logger.info(+ "No CONTAINER_NAME set in environment. Allowing access (local development mode)"+ )return True-+# Layer 1: VM Identity Verificationif container_name != self.container_name:- logger.warning(f"VM name mismatch. Expected: {self.container_name}, Got: {container_name}")+ logger.warning(+ f"VM name mismatch. Expected: {self.container_name}, Got: {container_name}"+ )return False-+# Create hash for session lookupsession_hash = self._hash_credentials(container_name, api_key)-+# Check if we have a valid cached sessionif session_hash in self.sessions:session_data = self.sessions[session_hash]if self._is_session_valid(session_data):logger.info(f"Using cached authentication for container: {container_name}")- return session_data['valid']+ return session_data["valid"]else:# Remove expired sessiondel self.sessions[session_hash]-+# No valid cached session, authenticate with APIlogger.info(f"Authenticating with TryCUA API for container: {container_name}")-+try:async with aiohttp.ClientSession() as session:- headers = {- "Authorization": f"Bearer {api_key}"- }-+ headers = {"Authorization": f"Bearer {api_key}"}+async with session.get(f"https://www.trycua.com/api/vm/auth?container_name={container_name}",headers=headers,) as resp:is_valid = resp.status == 200 and bool((await resp.text()).strip())-+# Cache the result with configurable expirationself.sessions[session_hash] = {- 'valid': is_valid,- 'expires_at': time.time() + AUTH_SESSION_TTL_SECONDS+ "valid": is_valid,+ "expires_at": time.time() + AUTH_SESSION_TTL_SECONDS,}-+if is_valid:logger.info(f"Authentication successful for container: {container_name}")else:- logger.warning(f"Authentication failed for container: {container_name}. Status: {resp.status}")-+ logger.warning(+ f"Authentication failed for container: {container_name}. Status: {resp.status}"+ )+return is_valid-+except aiohttp.ClientError as e:logger.error(f"Failed to validate API key with TryCUA API: {str(e)}")# Cache failed result to avoid repeated requestsself.sessions[session_hash] = {- 'valid': False,- 'expires_at': time.time() + AUTH_SESSION_TTL_SECONDS+ "valid": False,+ "expires_at": time.time() + AUTH_SESSION_TTL_SECONDS,}return Falseexcept Exception as e:logger.error(f"Unexpected error during authentication: {str(e)}")# Cache failed result to avoid repeated requestsself.sessions[session_hash] = {- 'valid': False,- 'expires_at': time.time() + AUTH_SESSION_TTL_SECONDS+ "valid": False,+ "expires_at": time.time() + AUTH_SESSION_TTL_SECONDS,}return False@@ -218,6 +236,7 @@ class ConnectionManager:manager = ConnectionManager()auth_manager = AuthenticationManager()+@app.get("/status")async def status():sys = platform.system().lower()@@ -234,80 +253,67 @@ async def status():features.append("agent")return {"status": "ok", "os_type": os_type, "features": features}+@app.websocket("/ws", name="websocket_endpoint")async def websocket_endpoint(websocket: WebSocket):global handlers# WebSocket message size is configured at the app or endpoint level, not on the instanceawait manager.connect(websocket)-+# Check if CONTAINER_NAME is set (indicating cloud provider)server_container_name = os.environ.get("CONTAINER_NAME")-+# If cloud provider, perform authentication handshakeif server_container_name:try:- logger.info(f"Cloud provider detected. CONTAINER_NAME: {server_container_name}. Waiting for authentication...")-+ logger.info(+ f"Cloud provider detected. CONTAINER_NAME: {server_container_name}. Waiting for authentication..."+ )+# Wait for authentication messageauth_data = await websocket.receive_json()-+# Validate auth message formatif auth_data.get("command") != "authenticate":- await websocket.send_json({- "success": False,- "error": "First message must be authentication"- })+ await websocket.send_json(+ {"success": False, "error": "First message must be authentication"}+ )await websocket.close()manager.disconnect(websocket)return-+# Extract credentialsclient_api_key = auth_data.get("params", {}).get("api_key")client_container_name = auth_data.get("params", {}).get("container_name")-+# Validate credentials using AuthenticationManagerif not client_api_key:- await websocket.send_json({- "success": False,- "error": "API key required"- })+ await websocket.send_json({"success": False, "error": "API key required"})await websocket.close()manager.disconnect(websocket)return-+if not client_container_name:- await websocket.send_json({- "success": False,- "error": "Container name required"- })+ await websocket.send_json({"success": False, "error": "Container name required"})await websocket.close()manager.disconnect(websocket)return-+# Use AuthenticationManager for validationis_authenticated = await auth_manager.auth(client_container_name, client_api_key)if not is_authenticated:- await websocket.send_json({- "success": False,- "error": "Authentication failed"- })+ await websocket.send_json({"success": False, "error": "Authentication failed"})await websocket.close()manager.disconnect(websocket)return-+logger.info(f"Authentication successful for VM: {client_container_name}")- await websocket.send_json({- "success": True,- "message": "Authentication successful"- })-+ await websocket.send_json({"success": True, "message": "Authentication successful"})+except Exception as e:logger.error(f"Error during authentication handshake: {str(e)}")- await websocket.send_json({- "success": False,- "error": "Authentication failed"- })+ await websocket.send_json({"success": False, "error": "Authentication failed"})await websocket.close()manager.disconnect(websocket)return@@ -330,7 +336,7 @@ async def websocket_endpoint(websocket: WebSocket):handler_func = handlers[command]sig = inspect.signature(handler_func)filtered_params = {k: v for k, v in params.items() if k in sig.parameters}-+# Handle both sync and async functionsif asyncio.iscoroutinefunction(handler_func):result = await handler_func(**filtered_params)@@ -367,20 +373,21 @@ async def websocket_endpoint(websocket: WebSocket):passmanager.disconnect(websocket)+@app.post("/cmd")async def cmd_endpoint(request: Request,container_name: Optional[str] = Header(None, alias="X-Container-Name"),- api_key: Optional[str] = Header(None, alias="X-API-Key")+ api_key: Optional[str] = Header(None, alias="X-API-Key"),):"""Backup endpoint for when WebSocket connections fail.Accepts commands via HTTP POST with streaming response.-+Headers:- X-Container-Name: Container name for cloud authentication- X-API-Key: API key for cloud authentication-+Body:{"command": "command_name",@@ -388,7 +395,7 @@ async def cmd_endpoint(}"""global handlers-+# Parse request bodytry:body = await request.json()@@ -396,32 +403,34 @@ async def cmd_endpoint(params = body.get("params", {})except Exception as e:raise HTTPException(status_code=400, detail=f"Invalid JSON body: {str(e)}")-+if not command:raise HTTPException(status_code=400, detail="Command is required")-+# Check if CONTAINER_NAME is set (indicating cloud provider)server_container_name = os.environ.get("CONTAINER_NAME")-+# If cloud provider, perform authenticationif server_container_name:- logger.info(f"Cloud provider detected. CONTAINER_NAME: {server_container_name}. Performing authentication...")-+ logger.info(+ f"Cloud provider detected. CONTAINER_NAME: {server_container_name}. Performing authentication..."+ )+# Validate required headersif not container_name:raise HTTPException(status_code=401, detail="Container name required")-+if not api_key:raise HTTPException(status_code=401, detail="API key required")-+# Validate with AuthenticationManageris_authenticated = await auth_manager.auth(container_name, api_key)if not is_authenticated:raise HTTPException(status_code=401, detail="Authentication failed")-+if command not in handlers:raise HTTPException(status_code=400, detail=f"Unknown command: {command}")-+async def generate_response():"""Generate streaming response for the command execution"""try:@@ -429,35 +438,36 @@ async def cmd_endpoint(handler_func = handlers[command]sig = inspect.signature(handler_func)filtered_params = {k: v for k, v in params.items() if k in sig.parameters}-+# Handle both sync and async functionsif asyncio.iscoroutinefunction(handler_func):result = await handler_func(**filtered_params)else:# Run sync functions in thread pool to avoid blocking event loopresult = await asyncio.to_thread(handler_func, **filtered_params)-+# Stream the successful resultresponse_data = {"success": True, **result}yield f"data: {json.dumps(response_data)}\n\n"-+except Exception as cmd_error:logger.error(f"Error executing command {command}: {str(cmd_error)}")logger.error(traceback.format_exc())-+# Stream the error resulterror_data = {"success": False, "error": str(cmd_error)}yield f"data: {json.dumps(error_data)}\n\n"-+return StreamingResponse(generate_response(),media_type="text/plain",headers={"Cache-Control": "no-cache","Connection": "keep-alive",- }+ },)+@app.post("/responses")async def agent_response_endpoint(request: Request,@@ -480,11 +490,17 @@ async def agent_response_endpoint("""if not HAS_AGENT:raise HTTPException(status_code=501, detail="ComputerAgent not available")-+# Authenticate via AuthenticationManager if running in cloud (CONTAINER_NAME set)container_name = os.environ.get("CONTAINER_NAME")if container_name:- is_public = os.environ.get("CUA_ENABLE_PUBLIC_PROXY", "").lower().strip() in ["1", "true", "yes", "y", "on"]+ is_public = os.environ.get("CUA_ENABLE_PUBLIC_PROXY", "").lower().strip() in [+ "1",+ "true",+ "yes",+ "y",+ "on",+ ]if not is_public:if not api_key:raise HTTPException(status_code=401, detail="Missing AGENT PROXY auth headers")@@ -511,10 +527,12 @@ async def agent_response_endpoint(def __init__(self, overrides: Dict[str, str]):self.overrides = overridesself._original: Dict[str, Optional[str]] = {}+def __enter__(self):for k, v in (self.overrides or {}).items():self._original[k] = os.environ.get(k)os.environ[k] = str(v)+def __exit__(self, exc_type, exc, tb):for k, old in self._original.items():if old is None:@@ -598,9 +616,9 @@ async def agent_response_endpoint(start = path[0]await self._auto.mouse_down(start["x"], start["y"])for pt in path[1:]:- await self._auto.move_cursor(pt["x"], pt["y"])+ await self._auto.move_cursor(pt["x"], pt["y"])end = path[-1]- await self._auto.mouse_up(end["x"], end["y"])+ await self._auto.mouse_up(end["x"], end["y"])async def get_current_url(self) -> str:# Not available in this server context@@ -667,7 +685,11 @@ async def agent_response_endpoint(async for result in agent.run(messages):total_output += result["output"]# Try to collect usage if present- if isinstance(result, dict) and "usage" in result and isinstance(result["usage"], dict):+ if (+ isinstance(result, dict)+ and "usage" in result+ and isinstance(result["usage"], dict)+ ):# Merge usage countersfor k, v in result["usage"].items():if isinstance(v, (int, float)):@@ -686,14 +708,14 @@ async def agent_response_endpoint(logger.error(f"Error running agent: {str(e)}")logger.error(traceback.format_exc())error = str(e)-+# Build response payloadpayload = {"model": model,"error": error,"output": total_output,"usage": total_usage,- "status": "completed" if not error else "failed"+ "status": "completed" if not error else "failed",}# CORS: allow any origindiff --git a/libs/python/computer-server/computer_server/server.py b/libs/python/computer-server/computer_server/server.pyindex aed874d471..a0e719ed5e 100644--- a/libs/python/computer-server/computer_server/server.py+++ b/libs/python/computer-server/computer_server/server.py@@ -5,8 +5,9 @@ Provides a clean API for starting and stopping the server.import asyncioimport logging-import uvicornfrom typing import Optional++import uvicornfrom fastapi import FastAPIfrom .main import app as fastapi_app@@ -32,8 +33,14 @@ class Server:await server.stop() # Stop the server"""- def __init__(self, host: str = "0.0.0.0", port: int = 8000, log_level: str = "info",- ssl_keyfile: Optional[str] = None, ssl_certfile: Optional[str] = None):+ def __init__(+ self,+ host: str = "0.0.0.0",+ port: int = 8000,+ log_level: str = "info",+ ssl_keyfile: Optional[str] = None,+ ssl_certfile: Optional[str] = None,+ ):"""Initialize the server.@@ -58,12 +65,12 @@ class Server:Start the server synchronously. This will block until the server is stopped."""uvicorn.run(- self.app,- host=self.host,- port=self.port,+ self.app,+ host=self.host,+ port=self.port,log_level=self.log_level,ssl_keyfile=self.ssl_keyfile,- ssl_certfile=self.ssl_certfile+ ssl_certfile=self.ssl_certfile,)async def start_async(self) -> None:@@ -72,12 +79,12 @@ class Server:will run in the background."""server_config = uvicorn.Config(- self.app,- host=self.host,- port=self.port,+ self.app,+ host=self.host,+ port=self.port,log_level=self.log_level,ssl_keyfile=self.ssl_keyfile,- ssl_certfile=self.ssl_certfile+ ssl_certfile=self.ssl_certfile,)self._should_exit.clear()diff --git a/libs/python/computer-server/computer_server/watchdog.py b/libs/python/computer-server/computer_server/watchdog.pyindex 392d9bc083..7c9ca83f6d 100644--- a/libs/python/computer-server/computer_server/watchdog.py+++ b/libs/python/computer-server/computer_server/watchdog.py@@ -12,9 +12,10 @@ import platformimport subprocessimport sysimport time-import websocketsfrom typing import Optional+import websockets+logger = logging.getLogger(__name__)@@ -45,62 +46,62 @@ class Watchdog:"""Watchdog class to monitor server health via WebSocket connection.Unix/Linux only - provides restart capabilities."""-+def __init__(self, cli_args: Optional[dict] = None, ping_interval: int = 30):"""Initialize the watchdog.-+Args:cli_args: Dictionary of CLI arguments to replicate when restartingping_interval: Interval between ping checks in seconds"""# Check if running on Unix/Linux- if platform.system() not in ['Linux', 'Darwin']:+ if platform.system() not in ["Linux", "Darwin"]:raise RuntimeError("Watchdog is only supported on Unix/Linux systems")-+# Store CLI arguments for restartself.cli_args = cli_args or {}- self.host = self.cli_args.get('host', 'localhost')- self.port = self.cli_args.get('port', 8000)+ self.host = self.cli_args.get("host", "localhost")+ self.port = self.cli_args.get("port", 8000)self.ping_interval = ping_intervalself.container_name = os.environ.get("CONTAINER_NAME")self.running = Falseself.restart_enabled = True-+@propertydef ws_uri(self) -> str:"""Get the WebSocket URI using the current IP address.-+Returns:WebSocket URI for the Computer API Server"""- ip_address = "localhost" if not self.container_name else f"{self.container_name}.containers.cloud.trycua.com"+ ip_address = (+ "localhost"+ if not self.container_name+ else f"{self.container_name}.containers.cloud.trycua.com"+ )protocol = "wss" if self.container_name else "ws"port = "8443" if self.container_name else "8000"return f"{protocol}://{ip_address}:{port}/ws"-+async def ping(self) -> bool:"""Test connection to the WebSocket endpoint.-+Returns:True if connection successful, False otherwise"""try:# Create a simple ping message- ping_message = {- "command": "get_screen_size",- "params": {}- }-+ ping_message = {"command": "get_screen_size", "params": {}}+# Try to connect to the WebSocketasync with websockets.connect(- self.ws_uri,- max_size=1024 * 1024 * 10 # 10MB limit to match server+ self.ws_uri, max_size=1024 * 1024 * 10 # 10MB limit to match server) as websocket:# Send ping messageawait websocket.send(json.dumps(ping_message))-+# Wait for any response or just closetry:response = await asyncio.wait_for(websocket.recv(), timeout=5)@@ -111,30 +112,27 @@ class Watchdog:except Exception as e:logger.warning(f"Ping failed: {e}")return False-+def kill_processes_on_port(self, port: int) -> bool:"""Kill any processes using the specified port.-+Args:port: Port number to check and kill processes on-+Returns:True if processes were killed or none found, False on error"""try:# Find processes using the portresult = subprocess.run(- ["lsof", "-ti", f":{port}"],- capture_output=True,- text=True,- timeout=10+ ["lsof", "-ti", f":{port}"], capture_output=True, text=True, timeout=10)-+if result.returncode == 0 and result.stdout.strip():- pids = result.stdout.strip().split('\n')+ pids = result.stdout.strip().split("\n")logger.info(f"Found {len(pids)} processes using port {port}: {pids}")-+# Kill each processfor pid in pids:if pid.strip():@@ -145,42 +143,42 @@ class Watchdog:logger.warning(f"Timeout killing process {pid}")except Exception as e:logger.warning(f"Error killing process {pid}: {e}")-+return Trueelse:logger.debug(f"No processes found using port {port}")return True-+except subprocess.TimeoutExpired:logger.error(f"Timeout finding processes on port {port}")return Falseexcept Exception as e:logger.error(f"Error finding processes on port {port}: {e}")return False-+def restart_server(self) -> bool:"""Attempt to restart the server by killing existing processes and starting new one.-+Returns:True if restart was attempted, False on error"""if not self.restart_enabled:logger.info("Server restart is disabled")return False-+try:logger.info("Attempting to restart server...")-+# Kill processes on the portport_to_kill = 8443 if self.container_name else self.portif not self.kill_processes_on_port(port_to_kill):logger.error("Failed to kill processes on port, restart aborted")return False-+# Wait a moment for processes to dietime.sleep(2)-+# Try to restart the server# In container mode, we can't easily restart, so just logif self.container_name:@@ -190,50 +188,50 @@ class Watchdog:else:# For local mode, try to restart the CLIlogger.info("Attempting to restart local server...")-+# Get the current Python executable and scriptpython_exe = sys.executable-+# Try to find the CLI moduletry:# Build command with all original CLI argumentscmd = [python_exe, "-m", "computer_server.cli"]-+# Add all CLI arguments except watchdog-related onesfor key, value in self.cli_args.items():- if key in ['watchdog', 'watchdog_interval', 'no_restart']:+ if key in ["watchdog", "watchdog_interval", "no_restart"]:continue # Skip watchdog args to avoid recursive watchdog-+# Convert underscores to hyphens for CLI argsarg_name = f"--{key.replace('_', '-')}"-+if isinstance(value, bool):if value: # Only add flag if Truecmd.append(arg_name)else:cmd.extend([arg_name, str(value)])-+logger.info(f"Starting server with command: {' '.join(cmd)}")-+# Start process in backgroundsubprocess.Popen(cmd,stdout=subprocess.DEVNULL,stderr=subprocess.DEVNULL,- start_new_session=True+ start_new_session=True,)-+logger.info("Server restart initiated")return True-+except Exception as e:logger.error(f"Failed to restart server: {e}")return False-+except Exception as e:logger.error(f"Error during server restart: {e}")return False-+async def start_monitoring(self) -> None:"""Start the watchdog monitoring loop."""self.running = True@@ -241,14 +239,14 @@ class Watchdog:logger.info(f"Ping interval: {self.ping_interval} seconds")if self.container_name:logger.info(f"Container mode detected: {self.container_name}")-+consecutive_failures = 0max_failures = 3-+while self.running:try:success = await self.ping()-+if success:if consecutive_failures > 0:logger.info("Server connection restored")@@ -257,15 +255,17 @@ class Watchdog:else:consecutive_failures += 1logger.warning(f"Ping failed ({consecutive_failures}/{max_failures})")-+if consecutive_failures >= max_failures:- logger.error(f"Server appears to be down after {max_failures} consecutive failures")-+ logger.error(+ f"Server appears to be down after {max_failures} consecutive failures"+ )+# Attempt to restart the serverif self.restart_enabled:logger.info("Attempting automatic server restart...")restart_success = self.restart_server()-+if restart_success:logger.info("Server restart initiated, waiting before next ping...")# Wait longer after restart attempt@@ -275,17 +275,17 @@ class Watchdog:logger.error("Server restart failed")else:logger.warning("Automatic restart is disabled")-+# Wait for next ping intervalawait asyncio.sleep(self.ping_interval)-+except asyncio.CancelledError:logger.info("Watchdog monitoring cancelled")breakexcept Exception as e:logger.error(f"Unexpected error in watchdog loop: {e}")await asyncio.sleep(self.ping_interval)-+def stop_monitoring(self) -> None:"""Stop the watchdog monitoring."""self.running = False@@ -295,13 +295,13 @@ class Watchdog:async def run_watchdog(cli_args: Optional[dict] = None, ping_interval: int = 30) -> None:"""Run the watchdog monitoring.-+Args:cli_args: Dictionary of CLI arguments to replicate when restartingping_interval: Interval between ping checks in seconds"""watchdog = Watchdog(cli_args=cli_args, ping_interval=ping_interval)-+try:await watchdog.start_monitoring()except KeyboardInterrupt:@@ -313,21 +313,18 @@ async def run_watchdog(cli_args: Optional[dict] = None, ping_interval: int = 30)if __name__ == "__main__":# For testing the watchdog standaloneimport argparse-+parser = argparse.ArgumentParser(description="Run Computer API server watchdog")parser.add_argument("--host", default="localhost", help="Server host to monitor")parser.add_argument("--port", type=int, default=8000, help="Server port to monitor")parser.add_argument("--ping-interval", type=int, default=30, help="Ping interval in seconds")-+args = parser.parse_args()-+logging.basicConfig(level=logging.INFO,format="%(asctime)s - %(name)s - %(levelname)s - %(message)s",)-- cli_args = {- 'host': args.host,- 'port': args.port- }++ cli_args = {"host": args.host, "port": args.port}asyncio.run(run_watchdog(cli_args, args.ping_interval))diff --git a/libs/python/computer-server/run_server.py b/libs/python/computer-server/run_server.pyindex 1818caa108..a7c0aecd7d 100755--- a/libs/python/computer-server/run_server.py+++ b/libs/python/computer-server/run_server.py@@ -10,6 +10,7 @@ Usage:"""import sys+from computer_server.cli import mainif __name__ == "__main__":diff --git a/libs/python/computer-server/test_connection.py b/libs/python/computer-server/test_connection.pyindex 8b9f322202..a864ba32a9 100755--- a/libs/python/computer-server/test_connection.py+++ b/libs/python/computer-server/test_connection.py@@ -6,18 +6,22 @@ This script tests both WebSocket (/ws) and REST (/cmd) connections to the Computand keeps it alive, allowing you to verify the server is running correctly."""+import argparseimport asyncioimport json-import websockets-import argparse-import sys-import aiohttpimport os+import sys+import aiohttpimport dotenv+import websockets+dotenv.load_dotenv()-async def test_websocket_connection(host="localhost", port=8000, keep_alive=False, container_name=None, api_key=None):++async def test_websocket_connection(+ host="localhost", port=8000, keep_alive=False, container_name=None, api_key=None+):"""Test WebSocket connection to the Computer Server."""if container_name:# Container mode: use WSS with container domain and port 8443@@ -37,19 +41,16 @@ async def test_websocket_connection(host="localhost", port=8000, keep_alive=Falsif not api_key:print("Error: API key required for container connections")return False-+print("Sending authentication...")auth_message = {"command": "authenticate",- "params": {- "api_key": api_key,- "container_name": container_name- }+ "params": {"api_key": api_key, "container_name": container_name},}await websocket.send(json.dumps(auth_message))auth_response = await websocket.recv()print(f"Authentication response: {auth_response}")-+# Check if authentication was successfulauth_data = json.loads(auth_response)if not auth_data.get("success", False):@@ -90,7 +91,9 @@ async def test_websocket_connection(host="localhost", port=8000, keep_alive=Falsreturn True-async def test_rest_connection(host="localhost", port=8000, keep_alive=False, container_name=None, api_key=None):+async def test_rest_connection(+ host="localhost", port=8000, keep_alive=False, container_name=None, api_key=None+):"""Test REST connection to the Computer Server."""if container_name:# Container mode: use HTTPS with container domain and port 8443@@ -113,13 +116,11 @@ async def test_rest_connection(host="localhost", port=8000, keep_alive=False, coreturn Falseheaders["X-Container-Name"] = container_nameheaders["X-API-Key"] = api_key- print(f"Using container authentication headers")+ print("Using container authentication headers")# Test screenshot endpointasync with session.post(- f"{base_url}/cmd",- json={"command": "screenshot", "params": {}},- headers=headers+ f"{base_url}/cmd", json={"command": "screenshot", "params": {}}, headers=headers) as response:if response.status == 200:text = await response.text()@@ -133,7 +134,7 @@ async def test_rest_connection(host="localhost", port=8000, keep_alive=False, coasync with session.post(f"{base_url}/cmd",json={"command": "get_screen_size", "params": {}},- headers=headers+ headers=headers,) as response:if response.status == 200:text = await response.text()@@ -151,7 +152,7 @@ async def test_rest_connection(host="localhost", port=8000, keep_alive=False, coasync with session.post(f"{base_url}/cmd",json={"command": "get_cursor_position", "params": {}},- headers=headers+ headers=headers,) as response:if response.status == 200:text = await response.text()@@ -171,7 +172,9 @@ async def test_rest_connection(host="localhost", port=8000, keep_alive=False, coreturn True-async def test_connection(host="localhost", port=8000, keep_alive=False, container_name=None, use_rest=False, api_key=None):+async def test_connection(+ host="localhost", port=8000, keep_alive=False, container_name=None, use_rest=False, api_key=None+):"""Test connection to the Computer Server using WebSocket or REST."""if use_rest:return await test_rest_connection(host, port, keep_alive, container_name, api_key)@@ -183,40 +186,50 @@ def parse_args():parser = argparse.ArgumentParser(description="Test connection to Computer Server")parser.add_argument("--host", default="localhost", help="Host address (default: localhost)")parser.add_argument("-p", "--port", type=int, default=8000, help="Port number (default: 8000)")- parser.add_argument("-c", "--container-name", help="Container name for cloud connection (uses WSS/HTTPS and port 8443)")- parser.add_argument("--api-key", help="API key for container authentication (can also use CUA_API_KEY env var)")+ parser.add_argument(+ "-c",+ "--container-name",+ help="Container name for cloud connection (uses WSS/HTTPS and port 8443)",+ )+ parser.add_argument(+ "--api-key", help="API key for container authentication (can also use CUA_API_KEY env var)"+ )parser.add_argument("--keep-alive", action="store_true", help="Keep connection alive")- parser.add_argument("--rest", action="store_true", help="Use REST endpoint (/cmd) instead of WebSocket (/ws)")+ parser.add_argument(+ "--rest", action="store_true", help="Use REST endpoint (/cmd) instead of WebSocket (/ws)"+ )return parser.parse_args()async def main():args = parse_args()-+# Convert hyphenated argument to underscore for function parameter- container_name = getattr(args, 'container_name', None)-+ container_name = getattr(args, "container_name", None)+# Get API key from argument or environment variable- api_key = getattr(args, 'api_key', None) or os.environ.get('CUA_API_KEY')-+ api_key = getattr(args, "api_key", None) or os.environ.get("CUA_API_KEY")+# Check if container name is provided but API key is missingif container_name and not api_key:print("Warning: Container name provided but no API key found.")print("Please provide --api-key argument or set CUA_API_KEY environment variable.")return 1-+print(f"Testing {'REST' if args.rest else 'WebSocket'} connection...")if container_name:print(f"Container: {container_name}")- print(f"API Key: {'***' + api_key[-4:] if api_key and len(api_key) > 4 else 'Not provided'}")-+ print(+ f"API Key: {'***' + api_key[-4:] if api_key and len(api_key) > 4 else 'Not provided'}"+ )+success = await test_connection(- host=args.host,- port=args.port,+ host=args.host,+ port=args.port,keep_alive=args.keep_alive,container_name=container_name,use_rest=args.rest,- api_key=api_key+ api_key=api_key,)return 0 if success else 1diff --git a/libs/python/computer/README.md b/libs/python/computer/README.mdindex 5d7c3c9b15..c19ca6c94a 100644--- a/libs/python/computer/README.md+++ b/libs/python/computer/README.md@@ -8,10 +8,11 @@</picture></div>- [](#)- [](#)- [](https://discord.com/invite/mVnXXpdE85)- [](https://pypi.org/project/cua-computer/)+[](#)+[](#)+[](https://discord.com/invite/mVnXXpdE85)+[](https://pypi.org/project/cua-computer/)+</h1></div>@@ -29,11 +30,11 @@ from computer import Computercomputer = Computer(os_type="macos", display="1024x768", memory="8GB", cpu="4")try:await computer.run()-+screenshot = await computer.interface.screenshot()with open("screenshot.png", "wb") as f:f.write(screenshot)-+await computer.interface.move_cursor(100, 100)await computer.interface.left_click()await computer.interface.right_click(300, 300)diff --git a/libs/python/computer/computer/computer.py b/libs/python/computer/computer/computer.pyindex 0d132ab0a1..7f5f9dfbaf 100644--- a/libs/python/computer/computer/computer.py+++ b/libs/python/computer/computer/computer.py@@ -1,20 +1,22 @@-import traceback-from typing import Optional, List, Literal, Dict, Any, Union, TYPE_CHECKING, castimport asyncio-from .models import Computer as ComputerConfig, Display-from .interface.factory import InterfaceFactory-import time-from PIL import Imageimport io-import re-from .logger import Logger, LogLevelimport jsonimport logging-from core.telemetry import is_telemetry_enabled, record_eventimport os-from . import helpers-import platform+import re+import time+import traceback+from typing import TYPE_CHECKING, Any, Dict, List, Literal, Optional, Union, cast++from core.telemetry import is_telemetry_enabled, record_event+from PIL import Image++from . import helpers+from .interface.factory import InterfaceFactory+from .logger import Logger, LogLevel+from .models import Computer as ComputerConfig+from .models import DisplaySYSTEM_INFO = {"os": platform.system().lower(),@@ -28,6 +30,7 @@ from .providers.factory import VMProviderFactoryOSType = Literal["macos", "linux", "windows"]+class Computer:"""Computer is the main class for interacting with the computer."""@@ -41,8 +44,11 @@ class Computer:Returns:DioramaComputer: A proxy object with the Diorama interface, but using diorama_cmds."""- assert "app-use" in self.experiments, "App Usage is an experimental feature. Enable it by passing experiments=['app-use'] to Computer()"+ assert (+ "app-use" in self.experiments+ ), "App Usage is an experimental feature. Enable it by passing experiments=['app-use'] to Computer()"from .diorama_computer import DioramaComputer+return DioramaComputer(self, apps)def __init__(@@ -64,7 +70,7 @@ class Computer:storage: Optional[str] = None,ephemeral: bool = False,api_key: Optional[str] = None,- experiments: Optional[List[str]] = None+ experiments: Optional[List[str]] = None,):"""Initialize a new Computer instance.@@ -112,32 +118,36 @@ class Computer:self.os_type = os_typeself.provider_type = provider_typeself.ephemeral = ephemeral-+self.api_key = api_keyself.experiments = experiments or []-+if "app-use" in self.experiments:assert self.os_type == "macos", "App use experiment is only supported on macOS"# The default is currently to use non-ephemeral storageif storage and ephemeral and storage != "ephemeral":raise ValueError("Storage path and ephemeral flag cannot be used together")-+# Windows Sandbox always uses ephemeral storageif self.provider_type == VMProviderType.WINSANDBOX:if not ephemeral and storage != None and storage != "ephemeral":- self.logger.warning("Windows Sandbox storage is always ephemeral. Setting ephemeral=True.")+ self.logger.warning(+ "Windows Sandbox storage is always ephemeral. Setting ephemeral=True."+ )self.ephemeral = Trueself.storage = "ephemeral"else:self.storage = "ephemeral" if ephemeral else storage-+# For Lumier provider, store the first shared directory path to use# for VM file sharingself.shared_path = Noneif shared_directories and len(shared_directories) > 0:self.shared_path = shared_directories[0]- self.logger.info(f"Using first shared directory for VM file sharing: {self.shared_path}")+ self.logger.info(+ f"Using first shared directory for VM file sharing: {self.shared_path}"+ )# Store telemetry preferenceself._telemetry_enabled = telemetry_enabled@@ -264,8 +274,14 @@ class Computer:self.logger.info(f"Starting VM: {self.image}")if not self._provider_context:try:- provider_type_name = self.provider_type.name if isinstance(self.provider_type, VMProviderType) else self.provider_type- self.logger.verbose(f"Initializing {provider_type_name} provider context...")+ provider_type_name = (+ self.provider_type.name+ if isinstance(self.provider_type, VMProviderType)+ else self.provider_type+ )+ self.logger.verbose(+ f"Initializing {provider_type_name} provider context..."+ )# Explicitly set provider parametersstorage = "ephemeral" if self.ephemeral else self.storage@@ -282,9 +298,13 @@ class Computer:if self.provider_type == VMProviderType.LUMIER:self.logger.info(f"Using VM image for Lumier provider: {image}")if shared_path:- self.logger.info(f"Using shared path for Lumier provider: {shared_path}")+ self.logger.info(+ f"Using shared path for Lumier provider: {shared_path}"+ )if noVNC_port:- self.logger.info(f"Using noVNC port for Lumier provider: {noVNC_port}")+ self.logger.info(+ f"Using noVNC port for Lumier provider: {noVNC_port}"+ )self.config.vm_provider = VMProviderFactory.create_provider(self.provider_type,port=port,@@ -340,11 +360,17 @@ class Computer:except ImportError as ie:self.logger.error(f"Failed to import provider dependencies: {ie}")if str(ie).find("lume") >= 0 and str(ie).find("lumier") < 0:- self.logger.error("Please install with: pip install cua-computer[lume]")+ self.logger.error(+ "Please install with: pip install cua-computer[lume]"+ )elif str(ie).find("lumier") >= 0 or str(ie).find("docker") >= 0:- self.logger.error("Please install with: pip install cua-computer[lumier] and make sure Docker is installed")+ self.logger.error(+ "Please install with: pip install cua-computer[lumier] and make sure Docker is installed"+ )elif str(ie).find("cloud") >= 0:- self.logger.error("Please install with: pip install cua-computer[cloud]")+ self.logger.error(+ "Please install with: pip install cua-computer[cloud]"+ )raiseexcept Exception as e:self.logger.error(f"Failed to initialize provider context: {e}")@@ -355,16 +381,14 @@ class Computer:try:if self.config.vm_provider is None:raise RuntimeError(f"VM provider not initialized for {self.config.name}")-+vm = await self.config.vm_provider.get_vm(self.config.name)self.logger.verbose(f"Found existing VM: {self.config.name}")is_running = vm.get("status") == "running"except Exception as e:self.logger.error(f"VM not found: {self.config.name}")self.logger.error(f"Error: {e}")- raise RuntimeError(- f"VM {self.config.name} could not be found or created."- )+ raise RuntimeError(f"VM {self.config.name} could not be found or created.")# Start the VM if it's not runningif not is_running:@@ -377,13 +401,10 @@ class Computer:path = os.path.abspath(os.path.expanduser(path))if os.path.exists(path):# Add path in format expected by Lume API- shared_dirs.append({- "hostPath": path,- "readOnly": False- })+ shared_dirs.append({"hostPath": path, "readOnly": False})else:self.logger.warning(f"Shared directory does not exist: {path}")-+# Prepare run options to pass to the providerrun_opts = {}@@ -393,11 +414,11 @@ class Computer:"width": self.config.display.width,"height": self.config.display.height,}-+# Check if scale_factor exists before adding itif hasattr(self.config.display, "scale_factor"):display_info["scale_factor"] = self.config.display.scale_factor-+run_opts["display"] = display_info# Add shared directories if available@@ -407,21 +428,23 @@ class Computer:# Run the VM with the providertry:if self.config.vm_provider is None:- raise RuntimeError(f"VM provider not initialized for {self.config.name}")-+ raise RuntimeError(+ f"VM provider not initialized for {self.config.name}"+ )+# Use the complete run_opts we prepared earlier# Handle ephemeral storage for run_vm method toostorage_param = "ephemeral" if self.ephemeral else self.storage-+# Log the image being usedself.logger.info(f"Running VM using image: {self.image}")-+# Call provider.run_vm with explicit image parameterresponse = await self.config.vm_provider.run_vm(image=self.image,name=self.config.name,run_opts=run_opts,- storage=storage_param+ storage=storage_param,)self.logger.info(f"VM run response: {response if response else 'None'}")except Exception as run_error:@@ -433,14 +456,16 @@ class Computer:try:if self.provider_type == VMProviderType.LUMIER:max_retries = 60 # Increased for Lumier VM startup which takes longer- retry_delay = 3 # 3 seconds between retries for Lumier+ retry_delay = 3 # 3 seconds between retries for Lumierelse:max_retries = 30 # Default for other providers- retry_delay = 2 # 2 seconds between retries-- self.logger.info(f"Waiting up to {max_retries * retry_delay} seconds for VM to be ready...")+ retry_delay = 2 # 2 seconds between retries++ self.logger.info(+ f"Waiting up to {max_retries * retry_delay} seconds for VM to be ready..."+ )ip = await self.get_ip(max_retries=max_retries, retry_delay=retry_delay)-+# If we get here, we have a valid IPself.logger.info(f"VM is ready with IP: {ip}")ip_address = ip@@ -458,8 +483,10 @@ class Computer:try:# Verify we have a valid IP before initializing the interfaceif not ip_address or ip_address == "unknown" or ip_address == "0.0.0.0":- raise RuntimeError(f"Cannot initialize interface - invalid IP address: {ip_address}")-+ raise RuntimeError(+ f"Cannot initialize interface - invalid IP address: {ip_address}"+ )+# Initialize the interface using the factory with the specified OSself.logger.info(f"Initializing interface for {self.os_type} at {ip_address}")from .interface.base import BaseComputerInterface@@ -469,18 +496,17 @@ class Computer:self._interface = cast(BaseComputerInterface,InterfaceFactory.create_interface_for_os(- os=self.os_type,+ os=self.os_type,ip_address=ip_address,api_key=self.api_key,- vm_name=self.config.name+ vm_name=self.config.name,),)else:self._interface = cast(BaseComputerInterface,InterfaceFactory.create_interface_for_os(- os=self.os_type,- ip_address=ip_address+ os=self.os_type, ip_address=ip_address),)@@ -510,10 +536,10 @@ class Computer:# Set the initialization flag and clear the initializing flagself._initialized = True-+# Set this instance as the default computer for remote decoratorshelpers.set_default_computer(self)-+self.logger.info("Computer successfully initialized")except Exception as e:raise@@ -522,7 +548,7 @@ class Computer:duration_ms = (time.time() - start_time) * 1000self.logger.debug(f"Computer initialization took {duration_ms:.2f}ms")return-+async def disconnect(self) -> None:"""Disconnect from the computer's WebSocket interface."""if self._interface:@@ -536,13 +562,17 @@ class Computer:self.logger.info("Stopping Computer...")# In VM mode, first explicitly stop the VM, then exit the provider context- if not self.use_host_computer_server and self._provider_context and self.config.vm_provider is not None:+ if (+ not self.use_host_computer_server+ and self._provider_context+ and self.config.vm_provider is not None+ ):try:self.logger.info(f"Stopping VM {self.config.name}...")await self.config.vm_provider.stop_vm(- name=self.config.name,- storage=self.storage # Pass storage explicitly for clarity- )+ name=self.config.name,+ storage=self.storage, # Pass storage explicitly for clarity+ )except Exception as e:self.logger.error(f"Error stopping VM: {e}")@@ -553,7 +583,9 @@ class Computer:await self.disconnect()self.logger.info("Computer stopped")except Exception as e:- self.logger.debug(f"Error during cleanup: {e}") # Log as debug since this might be expected+ self.logger.debug(+ f"Error during cleanup: {e}"+ ) # Log as debug since this might be expectedfinally:# Log stop time for performance monitoringduration_ms = (time.time() - start_time) * 1000@@ -597,12 +629,18 @@ class Computer:storage_param = "ephemeral" if self.ephemeral else self.storageif hasattr(self.config.vm_provider, "restart_vm"):self.logger.info(f"Restarting VM {self.config.name} via provider...")- await self.config.vm_provider.restart_vm(name=self.config.name, storage=storage_param)+ await self.config.vm_provider.restart_vm(+ name=self.config.name, storage=storage_param+ )else:# Fallback: stop then start without leaving provider context- self.logger.info(f"Provider has no restart_vm; performing stop+start for {self.config.name}...")+ self.logger.info(+ f"Provider has no restart_vm; performing stop+start for {self.config.name}..."+ )await self.config.vm_provider.stop_vm(name=self.config.name, storage=storage_param)- await self.config.vm_provider.run_vm(image=self.image, name=self.config.name, run_opts={}, storage=storage_param)+ await self.config.vm_provider.run_vm(+ image=self.image, name=self.config.name, run_opts={}, storage=storage_param+ )except Exception as e:self.logger.error(f"Failed to restart VM via provider: {e}")# As a last resort, do a full stop (with provider context exit) and run@@ -659,45 +697,42 @@ class Computer:# @propertyasync def get_ip(self, max_retries: int = 15, retry_delay: int = 3) -> str:"""Get the IP address of the VM or localhost if using host computer server.-- This method delegates to the provider's get_ip method, which waits indefinitely++ This method delegates to the provider's get_ip method, which waits indefinitelyuntil the VM has a valid IP address.-+Args:max_retries: Unused parameter, kept for backward compatibilityretry_delay: Delay between retries in seconds (default: 2)-+Returns:IP address of the VM or localhost if using host computer server"""# For host computer server, always return localhost immediatelyif self.use_host_computer_server:return "127.0.0.1"-+# Get IP from the provider - each provider implements its own waiting logicif self.config.vm_provider is None:raise RuntimeError("VM provider is not initialized")-+# Log that we're waiting for the IPself.logger.info(f"Waiting for VM {self.config.name} to get an IP address...")-+# Call the provider's get_ip method which will wait indefinitelystorage_param = "ephemeral" if self.ephemeral else self.storage-+# Log the image being usedself.logger.info(f"Running VM using image: {self.image}")-+# Call provider.get_ip with explicit image parameterip = await self.config.vm_provider.get_ip(- name=self.config.name,- storage=storage_param,- retry_delay=retry_delay+ name=self.config.name, storage=storage_param, retry_delay=retry_delay)-+# Log successself.logger.info(f"VM {self.config.name} has IP address: {ip}")return ip-async def wait_vm_ready(self) -> Optional[Dict[str, Any]]:"""Wait for VM to be ready with an IP address.@@ -785,8 +820,8 @@ class Computer:if self.config.vm_provider is not None:vm = await self.config.vm_provider.get_vm(self.config.name)# VM data is returned as a dictionary from the Lumier provider- status = vm.get('status', 'unknown') if vm else "unknown"- ip = vm.get('ip_address') if vm else None+ status = vm.get("status", "unknown") if vm else "unknown"+ ip = vm.get("ip_address") if vm else Noneelse:status = "unknown"ip = None@@ -803,16 +838,13 @@ class Computer:self.logger.info(f"Updating VM settings: CPU={cpu or self.config.cpu}, Memory={memory or self.config.memory}")- update_opts = {- "cpu": cpu or int(self.config.cpu),- "memory": memory or self.config.memory- }+ update_opts = {"cpu": cpu or int(self.config.cpu), "memory": memory or self.config.memory}if self.config.vm_provider is not None:- await self.config.vm_provider.update_vm(- name=self.config.name,- update_opts=update_opts,- storage=self.storage # Pass storage explicitly for clarity- )+ await self.config.vm_provider.update_vm(+ name=self.config.name,+ update_opts=update_opts,+ storage=self.storage, # Pass storage explicitly for clarity+ )else:raise RuntimeError("VM provider not initialized")@@ -879,15 +911,14 @@ class Computer:"""return await self.interface.to_screenshot_coordinates(x, y)-# Add virtual environment management functions to computer interfaceasync def venv_install(self, venv_name: str, requirements: list[str]):"""Install packages in a virtual environment.-+Args:venv_name: Name of the virtual environmentrequirements: List of package requirements to install-+Returns:Tuple of (stdout, stderr) from the installation command"""@@ -896,37 +927,41 @@ class Computer:if self.os_type == "windows":# Use %USERPROFILE% for home directory and cmd.exe semanticsvenv_path = f"%USERPROFILE%\\.venvs\\{venv_name}"- ensure_dir_cmd = "if not exist \"%USERPROFILE%\\.venvs\" mkdir \"%USERPROFILE%\\.venvs\""- create_cmd = f"if not exist \"{venv_path}\" python -m venv \"{venv_path}\""+ ensure_dir_cmd = 'if not exist "%USERPROFILE%\\.venvs" mkdir "%USERPROFILE%\\.venvs"'+ create_cmd = f'if not exist "{venv_path}" python -m venv "{venv_path}"'requirements_str = " ".join(requirements)# Activate via activate.bat and install- install_cmd = f"call \"{venv_path}\\Scripts\\activate.bat\" && pip install {requirements_str}" if requirements_str else f"echo No requirements to install"+ install_cmd = (+ f'call "{venv_path}\\Scripts\\activate.bat" && pip install {requirements_str}'+ if requirements_str+ else "echo No requirements to install"+ )await self.interface.run_command(ensure_dir_cmd)await self.interface.run_command(create_cmd)return await self.interface.run_command(install_cmd)else:# POSIX (macOS/Linux)venv_path = f"$HOME/.venvs/{venv_name}"- create_cmd = f"mkdir -p \"$HOME/.venvs\" && python3 -m venv \"{venv_path}\""+ create_cmd = f'mkdir -p "$HOME/.venvs" && python3 -m venv "{venv_path}"'# Check if venv exists, if not create it- check_cmd = f"test -d \"{venv_path}\" || ({create_cmd})"+ check_cmd = f'test -d "{venv_path}" || ({create_cmd})'_ = await self.interface.run_command(check_cmd)# Install packagesrequirements_str = " ".join(requirements)install_cmd = (- f". \"{venv_path}/bin/activate\" && pip install {requirements_str}"+ f'. "{venv_path}/bin/activate" && pip install {requirements_str}'if requirements_strelse "echo No requirements to install")return await self.interface.run_command(install_cmd)-+async def venv_cmd(self, venv_name: str, command: str):"""Execute a shell command in a virtual environment.-+Args:venv_name: Name of the virtual environmentcommand: Shell command to execute in the virtual environment-+Returns:Tuple of (stdout, stderr) from the command execution"""@@ -934,36 +969,36 @@ class Computer:# Windows (cmd.exe)venv_path = f"%USERPROFILE%\\.venvs\\{venv_name}"# Check existence and signal if missing- check_cmd = f"if not exist \"{venv_path}\" (echo VENV_NOT_FOUND) else (echo VENV_FOUND)"+ check_cmd = f'if not exist "{venv_path}" (echo VENV_NOT_FOUND) else (echo VENV_FOUND)'result = await self.interface.run_command(check_cmd)if "VENV_NOT_FOUND" in getattr(result, "stdout", ""):# Auto-create the venv with no requirementsawait self.venv_install(venv_name, [])# Activate and run the command- full_command = f"call \"{venv_path}\\Scripts\\activate.bat\" && {command}"+ full_command = f'call "{venv_path}\\Scripts\\activate.bat" && {command}'return await self.interface.run_command(full_command)else:# POSIX (macOS/Linux)venv_path = f"$HOME/.venvs/{venv_name}"# Check if virtual environment exists- check_cmd = f"test -d \"{venv_path}\""+ check_cmd = f'test -d "{venv_path}"'result = await self.interface.run_command(check_cmd)if result.stderr or "test:" in result.stdout: # venv doesn't exist# Auto-create the venv with no requirementsawait self.venv_install(venv_name, [])# Activate virtual environment and run command- full_command = f". \"{venv_path}/bin/activate\" && {command}"+ full_command = f'. "{venv_path}/bin/activate" && {command}'return await self.interface.run_command(full_command)-+async def venv_exec(self, venv_name: str, python_func, *args, **kwargs):"""Execute Python function in a virtual environment using source code extraction.-+Args:venv_name: Name of the virtual environmentpython_func: A callable function to execute*args: Positional arguments to pass to the function**kwargs: Keyword arguments to pass to the function-+Returns:The result of the function execution, or raises any exception that occurred"""@@ -971,29 +1006,29 @@ class Computer:import inspectimport jsonimport textwrap-+try:# Get function source code using inspect.getsourcesource = inspect.getsource(python_func)# Remove common leading whitespace (dedent)func_source = textwrap.dedent(source).strip()-+# Remove decoratorswhile func_source.lstrip().startswith("@"):func_source = func_source.split("\n", 1)[1].strip()-+# Get function name for executionfunc_name = python_func.__name__-+# Serialize args and kwargs as JSON (safer than dill for cross-version compatibility)args_json = json.dumps(args, default=str)kwargs_json = json.dumps(kwargs, default=str)-+except OSError as e:raise Exception(f"Cannot retrieve source code for function {python_func.__name__}: {e}")except Exception as e:raise Exception(f"Failed to reconstruct function source: {e}")-+# Create Python code that will define and execute the functionpython_code = f'''import json@@ -1038,25 +1073,27 @@ output_json = json.dumps(output_payload, default=str)# Print the JSON output with markersprint(f"<<<VENV_EXEC_START>>>{{output_json}}<<<VENV_EXEC_END>>>")'''-+# Encode the Python code in base64 to avoid shell escaping issues- encoded_code = base64.b64encode(python_code.encode('utf-8')).decode('ascii')-+ encoded_code = base64.b64encode(python_code.encode("utf-8")).decode("ascii")+# Execute the Python code in the virtual environment- python_command = f"python -c \"import base64; exec(base64.b64decode('{encoded_code}').decode('utf-8'))\""+ python_command = (+ f"python -c \"import base64; exec(base64.b64decode('{encoded_code}').decode('utf-8'))\""+ )result = await self.venv_cmd(venv_name, python_command)-+# Parse the output to extract the payloadstart_marker = "<<<VENV_EXEC_START>>>"end_marker = "<<<VENV_EXEC_END>>>"# Print original stdout- print(result.stdout[:result.stdout.find(start_marker)])-+ print(result.stdout[: result.stdout.find(start_marker)])+if start_marker in result.stdout and end_marker in result.stdout:start_idx = result.stdout.find(start_marker) + len(start_marker)end_idx = result.stdout.find(end_marker)-+if start_idx < end_idx:output_json = result.stdout[start_idx:end_idx]@@ -1065,7 +1102,7 @@ print(f"<<<VENV_EXEC_START>>>{{output_json}}<<<VENV_EXEC_END>>>")output_payload = json.loads(output_json)except Exception as e:raise Exception(f"Failed to decode output payload: {e}")-+if output_payload["success"]:return output_payload["result"]else:@@ -1077,4 +1114,6 @@ print(f"<<<VENV_EXEC_START>>>{{output_json}}<<<VENV_EXEC_END>>>")raise Exception("Invalid output format: markers found but no content between them")else:# Fallback: return stdout/stderr if no payload markers found- raise Exception(f"No output payload found. stdout: {result.stdout}, stderr: {result.stderr}")+ raise Exception(+ f"No output payload found. stdout: {result.stdout}, stderr: {result.stderr}"+ )diff --git a/libs/python/computer/computer/diorama_computer.py b/libs/python/computer/computer/diorama_computer.pyindex da67c72cab..329d300946 100644--- a/libs/python/computer/computer/diorama_computer.py+++ b/libs/python/computer/computer/diorama_computer.py@@ -1,14 +1,17 @@import asyncio-from .interface.models import KeyType, Key++from .interface.models import Key, KeyType+class DioramaComputer:"""A Computer-compatible proxy for Diorama that sends commands over the ComputerInterface."""+def __init__(self, computer, apps):"""Initialize the DioramaComputer with a computer instance and list of apps.-+Args:computer: The computer instance to proxy commands throughapps: List of applications available in the diorama environment@@ -21,7 +24,7 @@ class DioramaComputer:async def __aenter__(self):"""Async context manager entry point.-+Returns:self: The DioramaComputer instance"""@@ -31,7 +34,7 @@ class DioramaComputer:async def run(self):"""Initialize and run the DioramaComputer if not already initialized.-+Returns:self: The DioramaComputer instance"""@@ -39,14 +42,16 @@ class DioramaComputer:await self.__aenter__()return self+class DioramaComputerInterface:"""Diorama Interface proxy that sends diorama_cmds via the Computer's interface."""+def __init__(self, computer, apps):"""Initialize the DioramaComputerInterface.-+Args:computer: The computer instance to send commands throughapps: List of applications available in the diorama environment@@ -58,14 +63,14 @@ class DioramaComputerInterface:async def _send_cmd(self, action, arguments=None):"""Send a command to the diorama interface through the computer.-+Args:action (str): The action/command to executearguments (dict, optional): Additional arguments for the command-+Returns:The result from the diorama command execution-+Raises:RuntimeError: If the computer interface is not initialized or command fails"""@@ -77,25 +82,30 @@ class DioramaComputerInterface:raise RuntimeError("Computer interface not initialized. Call run() first.")result = await iface.diorama_cmd(action, arguments)if not result.get("success"):- raise RuntimeError(f"Diorama command failed: {result.get('error')}\n{result.get('trace')}")+ raise RuntimeError(+ f"Diorama command failed: {result.get('error')}\n{result.get('trace')}"+ )return result.get("result")async def screenshot(self, as_bytes=True):"""Take a screenshot of the diorama scene.-+Args:as_bytes (bool): If True, return image as bytes; if False, return PIL Image object-+Returns:bytes or PIL.Image: Screenshot data in the requested format"""- from PIL import Imageimport base64++ from PIL import Image+result = await self._send_cmd("screenshot")# assume result is a b64 string of an imageimg_bytes = base64.b64decode(result)import io+img = Image.open(io.BytesIO(img_bytes))self._scene_size = img.sizereturn img_bytes if as_bytes else img@@ -103,7 +113,7 @@ class DioramaComputerInterface:async def get_screen_size(self):"""Get the dimensions of the diorama scene.-+Returns:dict: Dictionary containing 'width' and 'height' keys with pixel dimensions"""@@ -114,7 +124,7 @@ class DioramaComputerInterface:async def move_cursor(self, x, y):"""Move the cursor to the specified coordinates.-+Args:x (int): X coordinate to move cursor toy (int): Y coordinate to move cursor to@@ -124,7 +134,7 @@ class DioramaComputerInterface:async def left_click(self, x=None, y=None):"""Perform a left mouse click at the specified coordinates or current cursor position.-+Args:x (int, optional): X coordinate to click at. If None, clicks at current cursor positiony (int, optional): Y coordinate to click at. If None, clicks at current cursor position@@ -134,7 +144,7 @@ class DioramaComputerInterface:async def right_click(self, x=None, y=None):"""Perform a right mouse click at the specified coordinates or current cursor position.-+Args:x (int, optional): X coordinate to click at. If None, clicks at current cursor positiony (int, optional): Y coordinate to click at. If None, clicks at current cursor position@@ -144,7 +154,7 @@ class DioramaComputerInterface:async def double_click(self, x=None, y=None):"""Perform a double mouse click at the specified coordinates or current cursor position.-+Args:x (int, optional): X coordinate to double-click at. If None, clicks at current cursor positiony (int, optional): Y coordinate to double-click at. If None, clicks at current cursor position@@ -154,7 +164,7 @@ class DioramaComputerInterface:async def scroll_up(self, clicks=1):"""Scroll up by the specified number of clicks.-+Args:clicks (int): Number of scroll clicks to perform upward. Defaults to 1"""@@ -163,7 +173,7 @@ class DioramaComputerInterface:async def scroll_down(self, clicks=1):"""Scroll down by the specified number of clicks.-+Args:clicks (int): Number of scroll clicks to perform downward. Defaults to 1"""@@ -172,7 +182,7 @@ class DioramaComputerInterface:async def drag_to(self, x, y, duration=0.5):"""Drag from the current cursor position to the specified coordinates.-+Args:x (int): X coordinate to drag toy (int): Y coordinate to drag to@@ -183,7 +193,7 @@ class DioramaComputerInterface:async def get_cursor_position(self):"""Get the current cursor position.-+Returns:dict: Dictionary containing the current cursor coordinates"""@@ -192,7 +202,7 @@ class DioramaComputerInterface:async def type_text(self, text):"""Type the specified text at the current cursor position.-+Args:text (str): The text to type"""@@ -201,7 +211,7 @@ class DioramaComputerInterface:async def press_key(self, key):"""Press a single key.-+Args:key: The key to press"""@@ -210,10 +220,10 @@ class DioramaComputerInterface:async def hotkey(self, *keys):"""Press multiple keys simultaneously as a hotkey combination.-+Args:*keys: Variable number of keys to press together. Can be Key enum instances or strings-+Raises:ValueError: If any key is not a Key enum or string type"""@@ -224,7 +234,9 @@ class DioramaComputerInterface:elif isinstance(key, str):# Try to convert to enum if it matches a known keykey_or_enum = Key.from_string(key)- actual_keys.append(key_or_enum.value if isinstance(key_or_enum, Key) else key_or_enum)+ actual_keys.append(+ key_or_enum.value if isinstance(key_or_enum, Key) else key_or_enum+ )else:raise ValueError(f"Invalid key type: {type(key)}. Must be Key enum or string.")await self._send_cmd("hotkey", {"keys": actual_keys})@@ -232,11 +244,11 @@ class DioramaComputerInterface:async def to_screen_coordinates(self, x, y):"""Convert coordinates to screen coordinates.-+Args:x (int): X coordinate to converty (int): Y coordinate to convert-+Returns:dict: Dictionary containing the converted screen coordinates"""diff --git a/libs/python/computer/computer/helpers.py b/libs/python/computer/computer/helpers.pyindex 8317b8d927..608dcbb9bb 100644--- a/libs/python/computer/computer/helpers.py+++ b/libs/python/computer/computer/helpers.py@@ -1,8 +1,9 @@"""Helper functions and decorators for the Computer module."""-import logging+import asyncio+import loggingfrom functools import wrapsfrom typing import Any, Callable, Optional, TypeVar, cast@@ -11,10 +12,11 @@ _default_computer = Nonelogger = logging.getLogger(__name__)+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"""@@ -25,21 +27,24 @@ def set_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 incomputer: The computer instance to use, or "default" to use the globally set defaultmax_retries: Maximum number of retries for the remote execution"""+def decorator(func):@wraps(func)async def wrapper(*args, **kwargs):# Determine which computer instance to usecomp = 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.")-+ 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)@@ -48,5 +53,7 @@ def sandboxed(venv_name: str = "default", computer: str = "default", max_retriesawait asyncio.sleep(1)if i == max_retries - 1:raise e+return wrapper+return decoratordiff --git a/libs/python/computer/computer/interface/__init__.py b/libs/python/computer/computer/interface/__init__.pyindex 6d7e1b78c4..d15b94d5bd 100644--- a/libs/python/computer/computer/interface/__init__.py+++ b/libs/python/computer/computer/interface/__init__.py@@ -2,12 +2,12 @@Interface package for Computer SDK."""-from .factory import InterfaceFactoryfrom .base import BaseComputerInterface+from .factory import InterfaceFactoryfrom .macos import MacOSComputerInterface__all__ = ["InterfaceFactory","BaseComputerInterface","MacOSComputerInterface",-]\ No newline at end of file+]diff --git a/libs/python/computer/computer/interface/base.py b/libs/python/computer/computer/interface/base.pyindex 3e343bbab9..8fa4002519 100644--- a/libs/python/computer/computer/interface/base.py+++ b/libs/python/computer/computer/interface/base.py@@ -1,14 +1,23 @@"""Base interface for computer control."""from abc import ABC, abstractmethod-from typing import Optional, Dict, Any, Tuple, List+from typing import Any, Dict, List, Optional, Tuple+from ..logger import Logger, LogLevel-from .models import MouseButton, CommandResult+from .models import CommandResult, MouseButton+class BaseComputerInterface(ABC):"""Base class for computer control interfaces."""- def __init__(self, ip_address: str, username: str = "lume", password: str = "lume", api_key: Optional[str] = None, vm_name: Optional[str] = None):+ def __init__(+ self,+ ip_address: str,+ username: str = "lume",+ password: str = "lume",+ api_key: Optional[str] = None,+ vm_name: Optional[str] = None,+ ):"""Initialize interface.Args:@@ -24,7 +33,7 @@ class BaseComputerInterface(ABC):self.api_key = api_keyself.vm_name = vm_nameself.logger = Logger("cua.interface", LogLevel.NORMAL)-+# Optional default delay time between commands (in seconds)self.delay: float = 0.0@@ -55,9 +64,15 @@ class BaseComputerInterface(ABC):# Mouse Actions@abstractmethod- async def mouse_down(self, x: Optional[int] = None, y: Optional[int] = None, button: "MouseButton" = "left", delay: Optional[float] = None) -> None:+ async def mouse_down(+ self,+ x: Optional[int] = None,+ y: Optional[int] = None,+ button: "MouseButton" = "left",+ delay: Optional[float] = None,+ ) -> None:"""Press and hold a mouse button.-+Args:x: X coordinate to press at. If None, uses current cursor position.y: Y coordinate to press at. If None, uses current cursor position.@@ -65,11 +80,17 @@ class BaseComputerInterface(ABC):delay: Optional delay in seconds after the action"""pass-+@abstractmethod- async def mouse_up(self, x: Optional[int] = None, y: Optional[int] = None, button: "MouseButton" = "left", delay: Optional[float] = None) -> None:+ async def mouse_up(+ self,+ x: Optional[int] = None,+ y: Optional[int] = None,+ button: "MouseButton" = "left",+ delay: Optional[float] = None,+ ) -> None:"""Release a mouse button.-+Args:x: X coordinate to release at. If None, uses current cursor position.y: Y coordinate to release at. If None, uses current cursor position.@@ -77,11 +98,13 @@ class BaseComputerInterface(ABC):delay: Optional delay in seconds after the action"""pass-+@abstractmethod- async def left_click(self, x: Optional[int] = None, y: Optional[int] = None, delay: Optional[float] = None) -> None:+ async def left_click(+ self, x: Optional[int] = None, y: Optional[int] = None, delay: Optional[float] = None+ ) -> None:"""Perform a left mouse button click.-+Args:x: X coordinate to click at. If None, uses current cursor position.y: Y coordinate to click at. If None, uses current cursor position.@@ -90,9 +113,11 @@ class BaseComputerInterface(ABC):pass@abstractmethod- async def right_click(self, x: Optional[int] = None, y: Optional[int] = None, delay: Optional[float] = None) -> None:+ async def right_click(+ self, x: Optional[int] = None, y: Optional[int] = None, delay: Optional[float] = None+ ) -> None:"""Perform a right mouse button click.-+Args:x: X coordinate to click at. If None, uses current cursor position.y: Y coordinate to click at. If None, uses current cursor position.@@ -101,9 +126,11 @@ class BaseComputerInterface(ABC):pass@abstractmethod- async def double_click(self, x: Optional[int] = None, y: Optional[int] = None, delay: Optional[float] = None) -> None:+ async def double_click(+ self, x: Optional[int] = None, y: Optional[int] = None, delay: Optional[float] = None+ ) -> None:"""Perform a double left mouse button click.-+Args:x: X coordinate to double-click at. If None, uses current cursor position.y: Y coordinate to double-click at. If None, uses current cursor position.@@ -114,7 +141,7 @@ class BaseComputerInterface(ABC):@abstractmethodasync def move_cursor(self, x: int, y: int, delay: Optional[float] = None) -> None:"""Move the cursor to the specified screen coordinates.-+Args:x: X coordinate to move cursor to.y: Y coordinate to move cursor to.@@ -123,7 +150,14 @@ class BaseComputerInterface(ABC):pass@abstractmethod- async def drag_to(self, x: int, y: int, button: str = "left", duration: float = 0.5, delay: Optional[float] = None) -> None:+ async def drag_to(+ self,+ x: int,+ y: int,+ button: str = "left",+ duration: float = 0.5,+ delay: Optional[float] = None,+ ) -> None:"""Drag from current position to specified coordinates.Args:@@ -136,7 +170,13 @@ class BaseComputerInterface(ABC):pass@abstractmethod- async def drag(self, path: List[Tuple[int, int]], button: str = "left", duration: float = 0.5, delay: Optional[float] = None) -> None:+ async def drag(+ self,+ path: List[Tuple[int, int]],+ button: str = "left",+ duration: float = 0.5,+ delay: Optional[float] = None,+ ) -> None:"""Drag the cursor along a path of coordinates.Args:@@ -151,27 +191,27 @@ class BaseComputerInterface(ABC):@abstractmethodasync def key_down(self, key: str, delay: Optional[float] = None) -> None:"""Press and hold a key.-+Args:key: The key to press and hold (e.g., 'a', 'shift', 'ctrl').delay: Optional delay in seconds after the action."""pass-+@abstractmethodasync def key_up(self, key: str, delay: Optional[float] = None) -> None:"""Release a previously pressed key.-+Args:key: The key to release (e.g., 'a', 'shift', 'ctrl').delay: Optional delay in seconds after the action."""pass-+@abstractmethodasync def type_text(self, text: str, delay: Optional[float] = None) -> None:"""Type the specified text string.-+Args:text: The text string to type.delay: Optional delay in seconds after the action.@@ -181,7 +221,7 @@ class BaseComputerInterface(ABC):@abstractmethodasync def press_key(self, key: str, delay: Optional[float] = None) -> None:"""Press and release a single key.-+Args:key: The key to press (e.g., 'a', 'enter', 'escape').delay: Optional delay in seconds after the action.@@ -191,7 +231,7 @@ class BaseComputerInterface(ABC):@abstractmethodasync def hotkey(self, *keys: str, delay: Optional[float] = None) -> None:"""Press multiple keys simultaneously (keyboard shortcut).-+Args:*keys: Variable number of keys to press together (e.g., 'ctrl', 'c').delay: Optional delay in seconds after the action.@@ -202,18 +242,18 @@ class BaseComputerInterface(ABC):@abstractmethodasync def scroll(self, x: int, y: int, delay: Optional[float] = None) -> None:"""Scroll the mouse wheel by specified amounts.-+Args:x: Horizontal scroll amount (positive = right, negative = left).y: Vertical scroll amount (positive = up, negative = down).delay: Optional delay in seconds after the action."""pass-+@abstractmethodasync def scroll_down(self, clicks: int = 1, delay: Optional[float] = None) -> None:"""Scroll down by the specified number of clicks.-+Args:clicks: Number of scroll clicks to perform downward.delay: Optional delay in seconds after the action.@@ -223,7 +263,7 @@ class BaseComputerInterface(ABC):@abstractmethodasync def scroll_up(self, clicks: int = 1, delay: Optional[float] = None) -> None:"""Scroll up by the specified number of clicks.-+Args:clicks: Number of scroll clicks to perform upward.delay: Optional delay in seconds after the action.@@ -252,7 +292,7 @@ class BaseComputerInterface(ABC):@abstractmethodasync def get_cursor_position(self) -> Dict[str, int]:"""Get the current cursor position on screen.-+Returns:Dict with 'x' and 'y' keys containing cursor coordinates."""@@ -262,7 +302,7 @@ class BaseComputerInterface(ABC):@abstractmethodasync def copy_to_clipboard(self) -> str:"""Get the current clipboard content.-+Returns:The text content currently stored in the clipboard."""@@ -271,7 +311,7 @@ class BaseComputerInterface(ABC):@abstractmethodasync def set_clipboard(self, text: str) -> None:"""Set the clipboard content to the specified text.-+Args:text: The text to store in the clipboard."""@@ -281,10 +321,10 @@ class BaseComputerInterface(ABC):@abstractmethodasync def file_exists(self, path: str) -> bool:"""Check if a file exists at the specified path.-+Args:path: The file path to check.-+Returns:True if the file exists, False otherwise."""@@ -293,128 +333,128 @@ class BaseComputerInterface(ABC):@abstractmethodasync def directory_exists(self, path: str) -> bool:"""Check if a directory exists at the specified path.-+Args:path: The directory path to check.-+Returns:True if the directory exists, False otherwise."""pass-+@abstractmethodasync def list_dir(self, path: str) -> List[str]:"""List the contents of a directory.-+Args:path: The directory path to list.-+Returns:List of file and directory names in the specified directory."""pass-+@abstractmethodasync def read_text(self, path: str) -> str:"""Read the text contents of a file.-+Args:path: The file path to read from.-+Returns:The text content of the file."""pass-+@abstractmethodasync def write_text(self, path: str, content: str) -> None:"""Write text content to a file.-+Args:path: The file path to write to.content: The text content to write."""pass-+@abstractmethodasync def read_bytes(self, path: str, offset: int = 0, length: Optional[int] = None) -> bytes:"""Read file binary contents with optional seeking support.-+Args:path: Path to the fileoffset: Byte offset to start reading from (default: 0)length: Number of bytes to read (default: None for entire file)"""pass-+@abstractmethodasync def write_bytes(self, path: str, content: bytes) -> None:"""Write binary content to a file.-+Args:path: The file path to write to.content: The binary content to write."""pass-+@abstractmethodasync def delete_file(self, path: str) -> None:"""Delete a file at the specified path.-+Args:path: The file path to delete."""pass-+@abstractmethodasync def create_dir(self, path: str) -> None:"""Create a directory at the specified path.-+Args:path: The directory path to create."""pass-+@abstractmethodasync def delete_dir(self, path: str) -> None:"""Delete a directory at the specified path.-+Args:path: The directory path to delete."""pass-+@abstractmethodasync def get_file_size(self, path: str) -> int:"""Get the size of a file in bytes.-+Args:path: The file path to get the size of.-+Returns:The size of the file in bytes."""pass-+@abstractmethodasync def run_command(self, command: str) -> CommandResult:"""Run shell command and return structured result.-+Executes a shell command using subprocess.run with shell=True and check=False.The command is run in the target environment and captures both stdout and stderr.-+Args:command (str): The shell command to execute-+Returns:CommandResult: A structured result containing:- stdout (str): Standard output from the command- - stderr (str): Standard error from the command+ - stderr (str): Standard error from the command- returncode (int): Exit code from the command (0 indicates success)-+Raises:RuntimeError: If the command execution fails at the system level-+Example:result = await interface.run_command("ls -la")if result.returncode == 0:@@ -428,12 +468,12 @@ class BaseComputerInterface(ABC):@abstractmethodasync def get_accessibility_tree(self) -> Dict:"""Get the accessibility tree of the current screen.-+Returns:Dict containing the hierarchical accessibility information of screen elements."""pass-+@abstractmethodasync def to_screen_coordinates(self, x: float, y: float) -> tuple[float, float]:"""Convert screenshot coordinates to screen coordinates.diff --git a/libs/python/computer/computer/interface/factory.py b/libs/python/computer/computer/interface/factory.pyindex 3647400e96..7ae6b05c4b 100644--- a/libs/python/computer/computer/interface/factory.py+++ b/libs/python/computer/computer/interface/factory.py@@ -1,42 +1,44 @@"""Factory for creating computer interfaces."""from typing import Literal, Optional+from .base import BaseComputerInterface+class InterfaceFactory:"""Factory for creating OS-specific computer interfaces."""-+@staticmethoddef create_interface_for_os(- os: Literal['macos', 'linux', 'windows'],+ os: Literal["macos", "linux", "windows"],ip_address: str,api_key: Optional[str] = None,- vm_name: Optional[str] = None+ vm_name: Optional[str] = None,) -> BaseComputerInterface:"""Create an interface for the specified OS.-+Args:os: Operating system type ('macos', 'linux', or 'windows')ip_address: IP address of the computer to controlapi_key: Optional API key for cloud authenticationvm_name: Optional VM name for cloud authentication-+Returns:BaseComputerInterface: The appropriate interface for the OS-+Raises:ValueError: If the OS type is not supported"""# Import implementations here to avoid circular imports- from .macos import MacOSComputerInterfacefrom .linux import LinuxComputerInterface+ from .macos import MacOSComputerInterfacefrom .windows import WindowsComputerInterface-- if os == 'macos':++ if os == "macos":return MacOSComputerInterface(ip_address, api_key=api_key, vm_name=vm_name)- elif os == 'linux':+ elif os == "linux":return LinuxComputerInterface(ip_address, api_key=api_key, vm_name=vm_name)- elif os == 'windows':+ elif os == "windows":return WindowsComputerInterface(ip_address, api_key=api_key, vm_name=vm_name)else:raise ValueError(f"Unsupported OS type: {os}")diff --git a/libs/python/computer/computer/interface/generic.py b/libs/python/computer/computer/interface/generic.pyindex c78274c37e..7cd2372f08 100644--- a/libs/python/computer/computer/interface/generic.py+++ b/libs/python/computer/computer/interface/generic.py@@ -2,21 +2,35 @@ import asyncioimport jsonimport timefrom typing import Any, Dict, List, Optional, Tuple-from PIL import Image-import websocketsimport aiohttp+import websockets+from PIL import Imagefrom ..logger import Logger, LogLevel+from ..utils import (+ bytes_to_image,+ decode_base64_image,+ draw_box,+ encode_base64_image,+ resize_image,+)from .base import BaseComputerInterface-from ..utils import decode_base64_image, encode_base64_image, bytes_to_image, draw_box, resize_image-from .models import Key, KeyType, MouseButton, CommandResult+from .models import CommandResult, Key, KeyType, MouseButtonclass GenericComputerInterface(BaseComputerInterface):"""Generic interface with common functionality for all supported platforms (Windows, Linux, macOS)."""- def __init__(self, ip_address: str, username: str = "lume", password: str = "lume", api_key: Optional[str] = None, vm_name: Optional[str] = None, logger_name: str = "computer.interface.generic"):+ def __init__(+ self,+ ip_address: str,+ username: str = "lume",+ password: str = "lume",+ api_key: Optional[str] = None,+ vm_name: Optional[str] = None,+ logger_name: str = "computer.interface.generic",+ ):super().__init__(ip_address, username, password, api_key, vm_name)self._ws = Noneself._reconnect_task = None@@ -38,7 +52,7 @@ class GenericComputerInterface(BaseComputerInterface):async def _handle_delay(self, delay: Optional[float] = None):"""Handle delay between commands using async sleep.-+Args:delay: Optional delay in seconds. If None, uses self.delay."""@@ -51,18 +65,18 @@ class GenericComputerInterface(BaseComputerInterface):@propertydef ws_uri(self) -> str:"""Get the WebSocket URI using the current IP address.-+Returns:WebSocket URI for the Computer API Server"""protocol = "wss" if self.api_key else "ws"port = "8443" if self.api_key else "8000"return f"{protocol}://{self.ip_address}:{port}/ws"-+@propertydef rest_uri(self) -> str:"""Get the REST URI using the current IP address.-+Returns:REST URI for the Computer API Server"""@@ -71,23 +85,41 @@ class GenericComputerInterface(BaseComputerInterface):return f"{protocol}://{self.ip_address}:{port}/cmd"# Mouse actions- async def mouse_down(self, x: Optional[int] = None, y: Optional[int] = None, button: str = "left", delay: Optional[float] = None) -> None:+ async def mouse_down(+ self,+ x: Optional[int] = None,+ y: Optional[int] = None,+ button: str = "left",+ delay: Optional[float] = None,+ ) -> None:await self._send_command("mouse_down", {"x": x, "y": y, "button": button})await self._handle_delay(delay)-- async def mouse_up(self, x: Optional[int] = None, y: Optional[int] = None, button: str = "left", delay: Optional[float] = None) -> None:++ async def mouse_up(+ self,+ x: Optional[int] = None,+ y: Optional[int] = None,+ button: str = "left",+ delay: Optional[float] = None,+ ) -> None:await self._send_command("mouse_up", {"x": x, "y": y, "button": button})await self._handle_delay(delay)-- async def left_click(self, x: Optional[int] = None, y: Optional[int] = None, delay: Optional[float] = None) -> None:++ async def left_click(+ self, x: Optional[int] = None, y: Optional[int] = None, delay: Optional[float] = None+ ) -> None:await self._send_command("left_click", {"x": x, "y": y})await self._handle_delay(delay)- async def right_click(self, x: Optional[int] = None, y: Optional[int] = None, delay: Optional[float] = None) -> None:+ async def right_click(+ self, x: Optional[int] = None, y: Optional[int] = None, delay: Optional[float] = None+ ) -> None:await self._send_command("right_click", {"x": x, "y": y})await self._handle_delay(delay)- async def double_click(self, x: Optional[int] = None, y: Optional[int] = None, delay: Optional[float] = None) -> None:+ async def double_click(+ self, x: Optional[int] = None, y: Optional[int] = None, delay: Optional[float] = None+ ) -> None:await self._send_command("double_click", {"x": x, "y": y})await self._handle_delay(delay)@@ -95,27 +127,38 @@ class GenericComputerInterface(BaseComputerInterface):await self._send_command("move_cursor", {"x": x, "y": y})await self._handle_delay(delay)- async def drag_to(self, x: int, y: int, button: "MouseButton" = "left", duration: float = 0.5, delay: Optional[float] = None) -> None:+ async def drag_to(+ self,+ x: int,+ y: int,+ button: "MouseButton" = "left",+ duration: float = 0.5,+ delay: Optional[float] = None,+ ) -> None:await self._send_command("drag_to", {"x": x, "y": y, "button": button, "duration": duration})await self._handle_delay(delay)- async def drag(self, path: List[Tuple[int, int]], button: "MouseButton" = "left", duration: float = 0.5, delay: Optional[float] = None) -> None:- await self._send_command(- "drag", {"path": path, "button": button, "duration": duration}- )+ async def drag(+ self,+ path: List[Tuple[int, int]],+ button: "MouseButton" = "left",+ duration: float = 0.5,+ delay: Optional[float] = None,+ ) -> None:+ await self._send_command("drag", {"path": path, "button": button, "duration": duration})await self._handle_delay(delay)# Keyboard Actionsasync def key_down(self, key: "KeyType", delay: Optional[float] = None) -> None:await self._send_command("key_down", {"key": key})await self._handle_delay(delay)-+async def key_up(self, key: "KeyType", delay: Optional[float] = None) -> None:await self._send_command("key_up", {"key": key})await self._handle_delay(delay)-+async def type_text(self, text: str, delay: Optional[float] = None) -> None:await self._send_command("type_text", {"text": text})await self._handle_delay(delay)@@ -195,10 +238,12 @@ class GenericComputerInterface(BaseComputerInterface):elif isinstance(key, str):# Try to convert to enum if it matches a known keykey_or_enum = Key.from_string(key)- actual_keys.append(key_or_enum.value if isinstance(key_or_enum, Key) else key_or_enum)+ actual_keys.append(+ key_or_enum.value if isinstance(key_or_enum, Key) else key_or_enum+ )else:raise ValueError(f"Invalid key type: {type(key)}. Must be Key enum or string.")-+await self._send_command("hotkey", {"keys": actual_keys})await self._handle_delay(delay)@@ -206,11 +251,11 @@ class GenericComputerInterface(BaseComputerInterface):async def scroll(self, x: int, y: int, delay: Optional[float] = None) -> None:await self._send_command("scroll", {"x": x, "y": y})await self._handle_delay(delay)-+async def scroll_down(self, clicks: int = 1, delay: Optional[float] = None) -> None:await self._send_command("scroll_down", {"clicks": clicks})await self._handle_delay(delay)-+async def scroll_up(self, clicks: int = 1, delay: Optional[float] = None) -> None:await self._send_command("scroll_up", {"clicks": clicks})await self._handle_delay(delay)@@ -294,27 +339,32 @@ class GenericComputerInterface(BaseComputerInterface):await self._send_command("set_clipboard", {"text": text})# File Operations- async def _write_bytes_chunked(self, path: str, content: bytes, append: bool = False, chunk_size: int = 1024 * 1024) -> None:+ async def _write_bytes_chunked(+ self, path: str, content: bytes, append: bool = False, chunk_size: int = 1024 * 1024+ ) -> None:"""Write large files in chunks to avoid memory issues."""total_size = len(content)current_offset = 0-+while current_offset < total_size:chunk_end = min(current_offset + chunk_size, total_size)chunk_data = content[current_offset:chunk_end]-+# First chunk uses the original append flag, subsequent chunks always appendchunk_append = append if current_offset == 0 else True-- result = await self._send_command("write_bytes", {- "path": path,- "content_b64": encode_base64_image(chunk_data),- "append": chunk_append- })-++ result = await self._send_command(+ "write_bytes",+ {+ "path": path,+ "content_b64": encode_base64_image(chunk_data),+ "append": chunk_append,+ },+ )+if not result.get("success", False):raise RuntimeError(result.get("error", "Failed to write file chunk"))-+current_offset = chunk_endasync def write_bytes(self, path: str, content: bytes, append: bool = False) -> None:@@ -322,36 +372,39 @@ class GenericComputerInterface(BaseComputerInterface):if len(content) > 5 * 1024 * 1024: # 5MB thresholdawait self._write_bytes_chunked(path, content, append)return-- result = await self._send_command("write_bytes", {"path": path, "content_b64": encode_base64_image(content), "append": append})++ result = await self._send_command(+ "write_bytes",+ {"path": path, "content_b64": encode_base64_image(content), "append": append},+ )if not result.get("success", False):raise RuntimeError(result.get("error", "Failed to write file"))- async def _read_bytes_chunked(self, path: str, offset: int, total_length: int, chunk_size: int = 1024 * 1024) -> bytes:+ async def _read_bytes_chunked(+ self, path: str, offset: int, total_length: int, chunk_size: int = 1024 * 1024+ ) -> bytes:"""Read large files in chunks to avoid memory issues."""chunks = []current_offset = offsetremaining = total_length-+while remaining > 0:read_size = min(chunk_size, remaining)- result = await self._send_command("read_bytes", {- "path": path,- "offset": current_offset,- "length": read_size- })-+ result = await self._send_command(+ "read_bytes", {"path": path, "offset": current_offset, "length": read_size}+ )+if not result.get("success", False):raise RuntimeError(result.get("error", "Failed to read file chunk"))-+content_b64 = result.get("content_b64", "")chunk_data = decode_base64_image(content_b64)chunks.append(chunk_data)-+current_offset += read_sizeremaining -= read_size-- return b''.join(chunks)++ return b"".join(chunks)async def read_bytes(self, path: str, offset: int = 0, length: Optional[int] = None) -> bytes:# For large files, use chunked reading@@ -360,34 +413,36 @@ class GenericComputerInterface(BaseComputerInterface):file_size = await self.get_file_size(path)# If file is larger than 5MB, read in chunksif file_size > 5 * 1024 * 1024: # 5MB threshold- return await self._read_bytes_chunked(path, offset, file_size - offset if offset > 0 else file_size)-- result = await self._send_command("read_bytes", {- "path": path,- "offset": offset,- "length": length- })+ return await self._read_bytes_chunked(+ path, offset, file_size - offset if offset > 0 else file_size+ )++ result = await self._send_command(+ "read_bytes", {"path": path, "offset": offset, "length": length}+ )if not result.get("success", False):raise RuntimeError(result.get("error", "Failed to read file"))content_b64 = result.get("content_b64", "")return decode_base64_image(content_b64)- async def read_text(self, path: str, encoding: str = 'utf-8') -> str:+ async def read_text(self, path: str, encoding: str = "utf-8") -> str:"""Read text from a file with specified encoding.-+Args:path: Path to the file to readencoding: Text encoding to use (default: 'utf-8')-+Returns:str: The decoded text content of the file"""content_bytes = await self.read_bytes(path)return content_bytes.decode(encoding)- async def write_text(self, path: str, content: str, encoding: str = 'utf-8', append: bool = False) -> None:+ async def write_text(+ self, path: str, content: str, encoding: str = "utf-8", append: bool = False+ ) -> None:"""Write text to a file with specified encoding.-+Args:path: Path to the file to writecontent: Text content to write@@ -440,7 +495,7 @@ class GenericComputerInterface(BaseComputerInterface):return CommandResult(stdout=result.get("stdout", ""),stderr=result.get("stderr", ""),- returncode=result.get("return_code", 0)+ returncode=result.get("return_code", 0),)# Accessibility Actions@@ -450,7 +505,7 @@ class GenericComputerInterface(BaseComputerInterface):if not result.get("success", False):raise RuntimeError(result.get("error", "Failed to get accessibility tree"))return result-+async def get_active_window_bounds(self) -> Dict[str, int]:"""Get the bounds of the currently active window."""result = await self._send_command("get_active_window_bounds")@@ -556,33 +611,30 @@ class GenericComputerInterface(BaseComputerInterface):timeout=120,)self.logger.info("WebSocket connection established")-+# If api_key and vm_name are provided, perform authentication handshakeif self.api_key and self.vm_name:self.logger.info("Performing authentication handshake...")auth_message = {"command": "authenticate",- "params": {- "api_key": self.api_key,- "container_name": self.vm_name- }+ "params": {"api_key": self.api_key, "container_name": self.vm_name},}await self._ws.send(json.dumps(auth_message))-+# Wait for authentication responseasync with self._recv_lock:auth_response = await asyncio.wait_for(self._ws.recv(), timeout=10)auth_result = json.loads(auth_response)-+if not auth_result.get("success"):error_msg = auth_result.get("error", "Authentication failed")self.logger.error(f"Authentication failed: {error_msg}")await self._ws.close()self._ws = Noneraise ConnectionError(f"Authentication failed: {error_msg}")-+self.logger.info("Authentication successful")-+self._reconnect_delay = 1 # Reset reconnect delay on successful connectionself._last_ping = time.time()retry_count = 0 # Reset retry count on successful connection@@ -592,7 +644,7 @@ class GenericComputerInterface(BaseComputerInterface):# Only log the first error at WARNING level, then every Nth attemptif retry_count == 1:self.logger.warning(- f"Computer API Server not ready yet. Will retry automatically."+ "Computer API Server not ready yet. Will retry automatically.")elif retry_count % log_interval == 0:self.logger.warning(@@ -640,7 +692,7 @@ class GenericComputerInterface(BaseComputerInterface):# Only log connection lost warnings at most once every min_warning_interval secondsif current_time - last_warning_time >= min_warning_interval:self.logger.warning(- f"Computer API Server connection lost. Will retry automatically."+ "Computer API Server connection lost. Will retry automatically.")last_warning_time = current_timeelse:@@ -653,7 +705,7 @@ class GenericComputerInterface(BaseComputerInterface):except:passself._ws = None-+async def _ensure_connection(self):"""Ensure WebSocket connection is established."""if self._reconnect_task is None or self._reconnect_task.done():@@ -722,32 +774,30 @@ class GenericComputerInterface(BaseComputerInterface):raise last_error if last_error else RuntimeError("Failed to send command")- async def _send_command_rest(self, command: str, params: Optional[Dict] = None) -> Dict[str, Any]:+ async def _send_command_rest(+ self, command: str, params: Optional[Dict] = None+ ) -> Dict[str, Any]:"""Send command through REST API without retries or connection management."""try:# Prepare the request payloadpayload = {"command": command, "params": params or {}}-+# Prepare headersheaders = {"Content-Type": "application/json"}if self.api_key:headers["X-API-Key"] = self.api_keyif self.vm_name:headers["X-Container-Name"] = self.vm_name-+# Send the requestasync with aiohttp.ClientSession() as session:- async with session.post(- self.rest_uri,- json=payload,- headers=headers- ) as response:+ async with session.post(self.rest_uri, json=payload, headers=headers) as response:# Get the response textresponse_text = await response.text()-+# Trim whitespaceresponse_text = response_text.strip()-+# Check if it starts with "data: "if response_text.startswith("data: "):# Extract everything after "data: "@@ -758,38 +808,39 @@ class GenericComputerInterface(BaseComputerInterface):return {"success": False,"error": "Server returned malformed response",- "message": response_text+ "message": response_text,}else:# Return error responsereturn {"success": False,"error": "Server returned malformed response",- "message": response_text+ "message": response_text,}-+except Exception as e:- return {- "success": False,- "error": "Request failed",- "message": str(e)- }+ return {"success": False, "error": "Request failed", "message": str(e)}async def _send_command(self, command: str, params: Optional[Dict] = None) -> Dict[str, Any]:"""Send command using REST API with WebSocket fallback."""# Try REST API firstresult = await self._send_command_rest(command, params)-+# If REST failed with "Request failed", try WebSocket as fallback- if not result.get("success", True) and (result.get("error") == "Request failed" or result.get("error") == "Server returned malformed response"):- self.logger.warning(f"REST API failed for command '{command}', trying WebSocket fallback")+ if not result.get("success", True) and (+ result.get("error") == "Request failed"+ or result.get("error") == "Server returned malformed response"+ ):+ self.logger.warning(+ f"REST API failed for command '{command}', trying WebSocket fallback"+ )try:return await self._send_command_ws(command, params)except Exception as e:self.logger.error(f"WebSocket fallback also failed: {e}")# Return the original REST errorreturn result-+return resultasync def wait_for_ready(self, timeout: int = 60, interval: float = 1.0):@@ -800,7 +851,9 @@ class GenericComputerInterface(BaseComputerInterface):result = await self._send_command_rest("version", {})assert result.get("success", True)except Exception as e:- self.logger.debug(f"REST API failed for command 'version', trying WebSocket fallback: {e}")+ self.logger.debug(+ f"REST API failed for command 'version', trying WebSocket fallback: {e}"+ )try:await self._wait_for_ready_ws(timeout, interval)return@@ -949,7 +1002,7 @@ class GenericComputerInterface(BaseComputerInterface):# if self._ws:# asyncio.create_task(self._ws.close())# self._ws = None-+def force_close(self):"""Force close the WebSocket connection.@@ -962,4 +1015,3 @@ class GenericComputerInterface(BaseComputerInterface):if self._ws:asyncio.create_task(self._ws.close())self._ws = None-diff --git a/libs/python/computer/computer/interface/linux.py b/libs/python/computer/computer/interface/linux.pyindex 174fe07a1e..9e5a3c9b4d 100644--- a/libs/python/computer/computer/interface/linux.py+++ b/libs/python/computer/computer/interface/linux.py@@ -1,8 +1,19 @@from typing import Optional+from .generic import GenericComputerInterface+class LinuxComputerInterface(GenericComputerInterface):"""Interface for Linux."""- def __init__(self, ip_address: str, username: str = "lume", password: str = "lume", api_key: Optional[str] = None, vm_name: Optional[str] = None):- super().__init__(ip_address, username, password, api_key, vm_name, "computer.interface.linux")+ def __init__(+ self,+ ip_address: str,+ username: str = "lume",+ password: str = "lume",+ api_key: Optional[str] = None,+ vm_name: Optional[str] = None,+ ):+ super().__init__(+ ip_address, username, password, api_key, vm_name, "computer.interface.linux"+ )diff --git a/libs/python/computer/computer/interface/macos.py b/libs/python/computer/computer/interface/macos.pyindex f4d03a524e..6dcf8a1b58 100644--- a/libs/python/computer/computer/interface/macos.py+++ b/libs/python/computer/computer/interface/macos.py@@ -1,12 +1,25 @@-from .generic import GenericComputerInterfacefrom typing import Optional+from .generic import GenericComputerInterface++class MacOSComputerInterface(GenericComputerInterface):"""Interface for macOS."""- def __init__(self, ip_address: str, username: str = "lume", password: str = "lume", api_key: Optional[str] = None, vm_name: Optional[str] = None):- super().__init__(ip_address, username, password, api_key, vm_name, "computer.interface.macos")+ def __init__(+ self,+ ip_address: str,+ username: str = "lume",+ password: str = "lume",+ api_key: Optional[str] = None,+ vm_name: Optional[str] = None,+ ):+ super().__init__(+ ip_address, username, password, api_key, vm_name, "computer.interface.macos"+ )async def diorama_cmd(self, action: str, arguments: Optional[dict] = None) -> dict:"""Send a diorama command to the server (macOS only)."""- return await self._send_command("diorama_cmd", {"action": action, "arguments": arguments or {}})\ No newline at end of file+ return await self._send_command(+ "diorama_cmd", {"action": action, "arguments": arguments or {}}+ )diff --git a/libs/python/computer/computer/interface/models.py b/libs/python/computer/computer/interface/models.pyindex 223ac32142..bbba789a00 100644--- a/libs/python/computer/computer/interface/models.py+++ b/libs/python/computer/computer/interface/models.py@@ -1,136 +1,145 @@-from enum import Enum-from typing import Dict, List, Any, TypedDict, Union, Literalfrom dataclasses import dataclass+from enum import Enum+from typing import Any, Dict, List, Literal, TypedDict, Union+@dataclassclass CommandResult:stdout: str- stderr: str+ stderr: strreturncode: int-+def __init__(self, stdout: str, stderr: str, returncode: int):self.stdout = stdoutself.stderr = stderrself.returncode = returncode+# Navigation key literals-NavigationKey = Literal['pagedown', 'pageup', 'home', 'end', 'left', 'right', 'up', 'down']+NavigationKey = Literal["pagedown", "pageup", "home", "end", "left", "right", "up", "down"]# Special key literals-SpecialKey = Literal['enter', 'esc', 'tab', 'space', 'backspace', 'del']+SpecialKey = Literal["enter", "esc", "tab", "space", "backspace", "del"]# Modifier key literals-ModifierKey = Literal['ctrl', 'alt', 'shift', 'win', 'command', 'option']+ModifierKey = Literal["ctrl", "alt", "shift", "win", "command", "option"]# Function key literals-FunctionKey = Literal['f1', 'f2', 'f3', 'f4', 'f5', 'f6', 'f7', 'f8', 'f9', 'f10', 'f11', 'f12']+FunctionKey = Literal["f1", "f2", "f3", "f4", "f5", "f6", "f7", "f8", "f9", "f10", "f11", "f12"]+class Key(Enum):"""Keyboard keys that can be used with press_key.-+These key names map to PyAutoGUI's expected key names."""+# Navigation- PAGE_DOWN = 'pagedown'- PAGE_UP = 'pageup'- HOME = 'home'- END = 'end'- LEFT = 'left'- RIGHT = 'right'- UP = 'up'- DOWN = 'down'-+ PAGE_DOWN = "pagedown"+ PAGE_UP = "pageup"+ HOME = "home"+ END = "end"+ LEFT = "left"+ RIGHT = "right"+ UP = "up"+ DOWN = "down"+# Special keys- RETURN = 'enter'- ENTER = 'enter'- ESCAPE = 'esc'- ESC = 'esc'- TAB = 'tab'- SPACE = 'space'- BACKSPACE = 'backspace'- DELETE = 'del'-+ RETURN = "enter"+ ENTER = "enter"+ ESCAPE = "esc"+ ESC = "esc"+ TAB = "tab"+ SPACE = "space"+ BACKSPACE = "backspace"+ DELETE = "del"+# Modifier keys- ALT = 'alt'- CTRL = 'ctrl'- SHIFT = 'shift'- WIN = 'win'- COMMAND = 'command'- OPTION = 'option'-+ ALT = "alt"+ CTRL = "ctrl"+ SHIFT = "shift"+ WIN = "win"+ COMMAND = "command"+ OPTION = "option"+# Function keys- F1 = 'f1'- F2 = 'f2'- F3 = 'f3'- F4 = 'f4'- F5 = 'f5'- F6 = 'f6'- F7 = 'f7'- F8 = 'f8'- F9 = 'f9'- F10 = 'f10'- F11 = 'f11'- F12 = 'f12'+ F1 = "f1"+ F2 = "f2"+ F3 = "f3"+ F4 = "f4"+ F5 = "f5"+ F6 = "f6"+ F7 = "f7"+ F8 = "f8"+ F9 = "f9"+ F10 = "f10"+ F11 = "f11"+ F12 = "f12"@classmethod- def from_string(cls, key: str) -> 'Key | str':+ def from_string(cls, key: str) -> "Key | str":"""Convert a string key name to a Key enum value.-+Args:key: String key name to convert-+Returns:Key enum value if the string matches a known key,otherwise returns the original string for single character keys"""# Map common alternative names to enum valueskey_mapping = {- 'page_down': cls.PAGE_DOWN,- 'page down': cls.PAGE_DOWN,- 'pagedown': cls.PAGE_DOWN,- 'page_up': cls.PAGE_UP,- 'page up': cls.PAGE_UP,- 'pageup': cls.PAGE_UP,- 'return': cls.RETURN,- 'enter': cls.ENTER,- 'escape': cls.ESCAPE,- 'esc': cls.ESC,- 'delete': cls.DELETE,- 'del': cls.DELETE,+ "page_down": cls.PAGE_DOWN,+ "page down": cls.PAGE_DOWN,+ "pagedown": cls.PAGE_DOWN,+ "page_up": cls.PAGE_UP,+ "page up": cls.PAGE_UP,+ "pageup": cls.PAGE_UP,+ "return": cls.RETURN,+ "enter": cls.ENTER,+ "escape": cls.ESCAPE,+ "esc": cls.ESC,+ "delete": cls.DELETE,+ "del": cls.DELETE,# Modifier key mappings- 'alt': cls.ALT,- 'ctrl': cls.CTRL,- 'control': cls.CTRL,- 'shift': cls.SHIFT,- 'win': cls.WIN,- 'windows': cls.WIN,- 'super': cls.WIN,- 'command': cls.COMMAND,- 'cmd': cls.COMMAND,- '⌘': cls.COMMAND,- 'option': cls.OPTION,- '⌥': cls.OPTION,+ "alt": cls.ALT,+ "ctrl": cls.CTRL,+ "control": cls.CTRL,+ "shift": cls.SHIFT,+ "win": cls.WIN,+ "windows": cls.WIN,+ "super": cls.WIN,+ "command": cls.COMMAND,+ "cmd": cls.COMMAND,+ "⌘": cls.COMMAND,+ "option": cls.OPTION,+ "⌥": cls.OPTION,}-+normalized = key.lower().strip()return key_mapping.get(normalized, key)+# Combined key typeKeyType = Union[Key, NavigationKey, SpecialKey, ModifierKey, FunctionKey, str]# Key type for mouse actions-MouseButton = Literal['left', 'right', 'middle']+MouseButton = Literal["left", "right", "middle"]+class AccessibilityWindow(TypedDict):"""Information about a window in the accessibility tree."""+app_name: strpid: intfrontmost: boolhas_windows: boolwindows: List[Dict[str, Any]]+class AccessibilityTree(TypedDict):"""Complete accessibility tree information."""+success: boolfrontmost_application: str- windows: List[AccessibilityWindow]\ No newline at end of file+ windows: List[AccessibilityWindow]diff --git a/libs/python/computer/computer/interface/windows.py b/libs/python/computer/computer/interface/windows.pyindex a874d35928..558ad749c2 100644--- a/libs/python/computer/computer/interface/windows.py+++ b/libs/python/computer/computer/interface/windows.py@@ -1,8 +1,19 @@from typing import Optional+from .generic import GenericComputerInterface+class WindowsComputerInterface(GenericComputerInterface):"""Interface for Windows."""- def __init__(self, ip_address: str, username: str = "lume", password: str = "lume", api_key: Optional[str] = None, vm_name: Optional[str] = None):- super().__init__(ip_address, username, password, api_key, vm_name, "computer.interface.windows")+ def __init__(+ self,+ ip_address: str,+ username: str = "lume",+ password: str = "lume",+ api_key: Optional[str] = None,+ vm_name: Optional[str] = None,+ ):+ super().__init__(+ ip_address, username, password, api_key, vm_name, "computer.interface.windows"+ )diff --git a/libs/python/computer/computer/models.py b/libs/python/computer/computer/models.pyindex 5ead143f66..beb0e65a68 100644--- a/libs/python/computer/computer/models.py+++ b/libs/python/computer/computer/models.py@@ -1,27 +1,33 @@"""Models for computer configuration."""from dataclasses import dataclass-from typing import Optional, Any, Dict+from typing import Any, Dict, Optional# Import base provider interfacefrom .providers.base import BaseVMProvider+@dataclassclass Display:"""Display configuration."""+width: intheight: int+@dataclassclass Image:"""VM image configuration."""+image: strtag: strname: str+@dataclassclass Computer:"""Computer configuration."""+image: strtag: strname: str@@ -29,13 +35,13 @@ class Computer:memory: strcpu: strvm_provider: Optional[BaseVMProvider] = None-+# @property # Remove the property decoratorasync def get_ip(self) -> Optional[str]:"""Get the IP address of the VM."""if not self.vm_provider:return None-+vm = await self.vm_provider.get_vm(self.name)# Handle both object attribute and dictionary access for ip_addressif vm:@@ -44,4 +50,4 @@ class Computer:else:# Access as attribute for object-based return valuesreturn getattr(vm, "ip_address", None)- return None\ No newline at end of file+ return Nonediff --git a/libs/python/computer/computer/providers/base.py b/libs/python/computer/computer/providers/base.pyindex 0c36c9137e..a32988bd42 100644--- a/libs/python/computer/computer/providers/base.py+++ b/libs/python/computer/computer/providers/base.py@@ -2,13 +2,14 @@import abcfrom enum import StrEnum-from typing import Dict, Optional, Any, AsyncContextManager+from typing import Any, AsyncContextManager, Dict, Optionalfrom .types import ListVMsResponseclass VMProviderType(StrEnum):"""Enum of supported VM provider types."""+LUME = "lume"LUMIER = "lumier"CLOUD = "cloud"@@ -19,30 +20,30 @@ class VMProviderType(StrEnum):class BaseVMProvider(AsyncContextManager):"""Base interface for VM providers.-+All VM provider implementations must implement this interface."""-+@property@abc.abstractmethoddef provider_type(self) -> VMProviderType:"""Get the provider type."""pass-+@abc.abstractmethodasync def get_vm(self, name: str, storage: Optional[str] = None) -> Dict[str, Any]:"""Get VM information by name.-+Args:name: Name of the VM to get information forstorage: Optional storage path override. If provided, this will be usedinstead of the provider's default storage path.-+Returns:Dictionary with VM information including status, IP address, etc."""pass-+@abc.abstractmethodasync def list_vms(self) -> ListVMsResponse:"""List all available VMs.@@ -52,76 +53,80 @@ class BaseVMProvider(AsyncContextManager):`computer.providers.types.MinimalVM`."""pass-+@abc.abstractmethod- async def run_vm(self, image: str, name: str, run_opts: Dict[str, Any], storage: Optional[str] = None) -> Dict[str, Any]:+ async def run_vm(+ self, image: str, name: str, run_opts: Dict[str, Any], storage: Optional[str] = None+ ) -> Dict[str, Any]:"""Run a VM by name with the given options.-+Args:image: Name/tag of the image to usename: Name of the VM to runrun_opts: Dictionary of run options (memory, cpu, etc.)storage: Optional storage path override. If provided, this will be usedinstead of the provider's default storage path.-+Returns:Dictionary with VM run status and information"""pass-+@abc.abstractmethodasync def stop_vm(self, name: str, storage: Optional[str] = None) -> Dict[str, Any]:"""Stop a VM by name.-+Args:name: Name of the VM to stopstorage: Optional storage path override. If provided, this will be usedinstead of the provider's default storage path.-+Returns:Dictionary with VM stop status and information"""pass-+@abc.abstractmethodasync def restart_vm(self, name: str, storage: Optional[str] = None) -> Dict[str, Any]:"""Restart a VM by name.-+Args:name: Name of the VM to restartstorage: Optional storage path override. If provided, this will be usedinstead of the provider's default storage path.-+Returns:Dictionary with VM restart status and information"""pass-+@abc.abstractmethod- async def update_vm(self, name: str, update_opts: Dict[str, Any], storage: Optional[str] = None) -> Dict[str, Any]:+ async def update_vm(+ self, name: str, update_opts: Dict[str, Any], storage: Optional[str] = None+ ) -> Dict[str, Any]:"""Update VM configuration.-+Args:name: Name of the VM to updateupdate_opts: Dictionary of update options (memory, cpu, etc.)storage: Optional storage path override. If provided, this will be usedinstead of the provider's default storage path.-+Returns:Dictionary with VM update status and information"""pass-+@abc.abstractmethodasync def get_ip(self, name: str, storage: Optional[str] = None, retry_delay: int = 2) -> str:"""Get the IP address of a VM, waiting indefinitely until it's available.-+Args:name: Name of the VM to get the IP forstorage: Optional storage path override. If provided, this will be usedinstead of the provider's default storage path.retry_delay: Delay between retries in seconds (default: 2)-+Returns:IP address of the VM when it becomes available"""diff --git a/libs/python/computer/computer/providers/cloud/provider.py b/libs/python/computer/computer/providers/cloud/provider.pyindex 5e4e7c511f..7d47968627 100644--- a/libs/python/computer/computer/providers/cloud/provider.py+++ b/libs/python/computer/computer/providers/cloud/provider.py@@ -9,7 +9,7 @@ Implements the following public API endpoints:"""import logging-from typing import Dict, List, Optional, Any+from typing import Any, Dict, List, Optionalfrom ..base import BaseVMProvider, VMProviderTypefrom ..types import ListVMsResponse, MinimalVM@@ -18,15 +18,17 @@ from ..types import ListVMsResponse, MinimalVMlogger = logging.getLogger(__name__)import asyncio-import aiohttp-from urllib.parse import urlparseimport os+from urllib.parse import urlparse+import aiohttpDEFAULT_API_BASE = os.getenv("CUA_API_BASE", "https://api.cua.ai")+class CloudProvider(BaseVMProvider):"""Cloud VM Provider implementation."""+def __init__(self,api_key: str,@@ -123,9 +125,9 @@ class CloudProvider(BaseVMProvider):vm["api_url"] = f"https://{host}:8443"# vnc_url: only when password availableif not vm.get("vnc_url") and isinstance(password, str) and password:- vm[- "vnc_url"- ] = f"https://{host}/vnc.html?autoconnect=true&password={password}"+ vm["vnc_url"] = (+ f"https://{host}/vnc.html?autoconnect=true&password={password}"+ )enriched.append(vm)return enriched # type: ignore[return-value]logger.warning("Unexpected response for list_vms; expected list")@@ -138,7 +140,13 @@ class CloudProvider(BaseVMProvider):logger.error(f"list_vms failed: HTTP {resp.status} - {text}")return []- async def run_vm(self, name: str, image: Optional[str] = None, run_opts: Optional[Dict[str, Any]] = None, storage: Optional[str] = None) -> Dict[str, Any]:+ async def run_vm(+ self,+ name: str,+ image: Optional[str] = None,+ run_opts: Optional[Dict[str, Any]] = None,+ storage: Optional[str] = None,+ ) -> Dict[str, Any]:"""Start a VM via public API. Returns a minimal status."""url = f"{self.api_base}/v1/vms/{name}/start"headers = {@@ -209,11 +217,19 @@ class CloudProvider(BaseVMProvider):text = await resp.text()return {"name": name, "status": "error", "message": text}- async def update_vm(self, name: str, update_opts: Dict[str, Any], storage: Optional[str] = None) -> Dict[str, Any]:+ async def update_vm(+ self, name: str, update_opts: Dict[str, Any], storage: Optional[str] = None+ ) -> Dict[str, Any]:logger.warning("CloudProvider.update_vm is not implemented via public API")- return {"name": name, "status": "unchanged", "message": "update_vm not supported by public API"}+ return {+ "name": name,+ "status": "unchanged",+ "message": "update_vm not supported by public API",+ }- async def get_ip(self, name: Optional[str] = None, storage: Optional[str] = None, retry_delay: int = 2) -> str:+ async def get_ip(+ self, name: Optional[str] = None, storage: Optional[str] = None, retry_delay: int = 2+ ) -> str:"""Return the VM's IP address as '{container_name}.containers.cloud.trycua.com'.Uses the provided 'name' argument (the VM name requested by the caller),diff --git a/libs/python/computer/computer/providers/docker/__init__.py b/libs/python/computer/computer/providers/docker/__init__.pyindex 048f526c46..64e42609cb 100644--- a/libs/python/computer/computer/providers/docker/__init__.py+++ b/libs/python/computer/computer/providers/docker/__init__.py@@ -5,6 +5,7 @@ from .provider import DockerProvider# Check if Docker is availabletry:import subprocess+subprocess.run(["docker", "--version"], capture_output=True, check=True)HAS_DOCKER = Trueexcept (subprocess.SubprocessError, FileNotFoundError):diff --git a/libs/python/computer/computer/providers/docker/provider.py b/libs/python/computer/computer/providers/docker/provider.pyindex 97622a2987..f133d771f3 100644--- a/libs/python/computer/computer/providers/docker/provider.py+++ b/libs/python/computer/computer/providers/docker/provider.py@@ -6,13 +6,13 @@ Linux VMs with computer-server. It handles VM lifecycle operations through Dockecommands and container management."""-import logging-import jsonimport asyncio-from typing import Dict, List, Optional, Any+import json+import logging+import reimport subprocessimport time-import re+from typing import Any, Dict, List, Optionalfrom ..base import BaseVMProvider, VMProviderType@@ -30,11 +30,11 @@ except (subprocess.SubprocessError, FileNotFoundError):class DockerProvider(BaseVMProvider):"""Docker VM Provider implementation using Docker containers.-+This provider uses Docker to run containers with the CUA Ubuntu imagethat includes computer-server for remote computer use."""-+def __init__(self,port: Optional[int] = 8000,@@ -80,7 +80,7 @@ class DockerProvider(BaseVMProvider):# Detect image type and configure user directory accordinglyself._detect_image_config()-+def _detect_image_config(self):"""Detect image type and configure paths accordingly."""# Detect if this is a docker-xfce image or Kasm image@@ -98,10 +98,10 @@ class DockerProvider(BaseVMProvider):def provider_type(self) -> VMProviderType:"""Return the provider type."""return VMProviderType.DOCKER-+def _parse_memory(self, memory_str: str) -> str:"""Parse memory string to Docker format.-+Examples:"8GB" -> "8g""1024MB" -> "1024m"@@ -109,31 +109,31 @@ class DockerProvider(BaseVMProvider):"""if isinstance(memory_str, int):return f"{memory_str}m"-+if isinstance(memory_str, str):# Extract number and unitmatch = re.match(r"(\d+)([A-Za-z]*)", memory_str)if match:value, unit = match.groups()unit = unit.upper()-+if unit == "GB" or unit == "G":return f"{value}g"elif unit == "MB" or unit == "M" or unit == "":return f"{value}m"-+# Default fallbacklogger.warning(f"Could not parse memory string '{memory_str}', using 4g default")return "4g" # Default to 4GB-+async def get_vm(self, name: str, storage: Optional[str] = None) -> Dict[str, Any]:"""Get VM information by name.-+Args:name: Name of the VM to get information forstorage: Optional storage path override. If provided, this will be usedinstead of the provider's default storage path.-+Returns:Dictionary with VM information including status, IP address, etc."""@@ -141,7 +141,7 @@ class DockerProvider(BaseVMProvider):# Check if container exists and get its statuscmd = ["docker", "inspect", name]result = subprocess.run(cmd, capture_output=True, text=True)-+if result.returncode != 0:# Container doesn't existreturn {@@ -150,14 +150,14 @@ class DockerProvider(BaseVMProvider):"ip_address": None,"ports": {},"image": self.image,- "provider": "docker"+ "provider": "docker",}-+# Parse container infocontainer_info = json.loads(result.stdout)[0]state = container_info["State"]network_settings = container_info["NetworkSettings"]-+# Determine statusif state["Running"]:status = "running"@@ -165,7 +165,7 @@ class DockerProvider(BaseVMProvider):status = "paused"else:status = "stopped"-+# Get IP addressip_address = network_settings.get("IPAddress", "")if not ip_address and "Networks" in network_settings:@@ -174,7 +174,7 @@ class DockerProvider(BaseVMProvider):if network_info.get("IPAddress"):ip_address = network_info["IPAddress"]break-+# Get port mappingsports = {}if "Ports" in network_settings and network_settings["Ports"]:@@ -187,7 +187,7 @@ class DockerProvider(BaseVMProvider):if mapping.get("HostPort"):ports[container_port] = mapping["HostPort"]break # Use the first valid mapping-+return {"name": name,"status": status,@@ -199,47 +199,46 @@ class DockerProvider(BaseVMProvider):"created": container_info["Created"],"started": state.get("StartedAt", ""),}-+except Exception as e:logger.error(f"Error getting VM info for {name}: {e}")import traceback+traceback.print_exc()- return {- "name": name,- "status": "error",- "error": str(e),- "provider": "docker"- }-+ return {"name": name, "status": "error", "error": str(e), "provider": "docker"}+async def list_vms(self) -> List[Dict[str, Any]]:"""List all Docker containers managed by this provider."""try:# List all containers (running and stopped) with the CUA imagecmd = ["docker", "ps", "-a", "--filter", f"ancestor={self.image}", "--format", "json"]result = subprocess.run(cmd, capture_output=True, text=True, check=True)-+containers = []if result.stdout.strip():- for line in result.stdout.strip().split('\n'):+ for line in result.stdout.strip().split("\n"):if line.strip():container_data = json.loads(line)vm_info = await self.get_vm(container_data["Names"])containers.append(vm_info)-+return containers-+except subprocess.CalledProcessError as e:logger.error(f"Error listing containers: {e.stderr}")return []except Exception as e:logger.error(f"Error listing VMs: {e}")import traceback+traceback.print_exc()return []-- async def run_vm(self, image: str, name: str, run_opts: Dict[str, Any], storage: Optional[str] = None) -> Dict[str, Any]:++ async def run_vm(+ self, image: str, name: str, run_opts: Dict[str, Any], storage: Optional[str] = None+ ) -> Dict[str, Any]:"""Run a VM with the given options.-+Args:image: Name/tag of the Docker image to usename: Name of the container to run@@ -248,7 +247,7 @@ class DockerProvider(BaseVMProvider):- cpu: CPU limit (e.g., 2 for 2 cores)- vnc_port: Specific port for VNC interface- api_port: Specific port for computer-server API-+Returns:Dictionary with VM status information"""@@ -263,36 +262,36 @@ class DockerProvider(BaseVMProvider):logger.info(f"Starting existing container {name}")start_cmd = ["docker", "start", name]result = subprocess.run(start_cmd, capture_output=True, text=True, check=True)-+# Wait for container to be readyawait self._wait_for_container_ready(name)return await self.get_vm(name, storage)-+# Use provided image or defaultdocker_image = image if image != "default" else self.image-+# Build docker run commandcmd = ["docker", "run", "-d", "--name", name]-+# Add memory limit if specifiedif "memory" in run_opts:memory_limit = self._parse_memory(run_opts["memory"])cmd.extend(["--memory", memory_limit])-+# Add CPU limit if specifiedif "cpu" in run_opts:cpu_count = str(run_opts["cpu"])cmd.extend(["--cpus", cpu_count])-+# Add port mappingsvnc_port = run_opts.get("vnc_port", self.vnc_port)api_port = run_opts.get("api_port", self.api_port)-+if vnc_port:cmd.extend(["-p", f"{vnc_port}:6901"]) # VNC portif api_port:cmd.extend(["-p", f"{api_port}:8000"]) # computer-server API port-+# Add volume mounts if storage is specifiedstorage_path = storage or self.storageif storage_path and storage_path != "ephemeral":@@ -303,66 +302,56 @@ class DockerProvider(BaseVMProvider):if self.shared_path:# Mount shared directory using detected home directorycmd.extend(["-v", f"{self.shared_path}:{self._home_dir}/shared"])-+# Add environment variablescmd.extend(["-e", "VNC_PW=password"]) # Set VNC passwordcmd.extend(["-e", "VNCOPTIONS=-disableBasicAuth"]) # Disable VNC basic auth-+# Add the imagecmd.append(docker_image)-+logger.info(f"Running Docker container with command: {' '.join(cmd)}")-+# Run the containerresult = subprocess.run(cmd, capture_output=True, text=True, check=True)container_id = result.stdout.strip()-+logger.info(f"Container {name} started with ID: {container_id[:12]}")-+# Store container infoself._container_id = container_idself._running_containers[name] = container_id-+# Wait for container to be readyawait self._wait_for_container_ready(name)-+# Return VM infovm_info = await self.get_vm(name, storage)vm_info["container_id"] = container_id[:12]-+return vm_info-+except subprocess.CalledProcessError as e:error_msg = f"Failed to run container {name}: {e.stderr}"logger.error(error_msg)- return {- "name": name,- "status": "error",- "error": error_msg,- "provider": "docker"- }+ return {"name": name, "status": "error", "error": error_msg, "provider": "docker"}except Exception as e:error_msg = f"Error running VM {name}: {e}"logger.error(error_msg)- return {- "name": name,- "status": "error",- "error": error_msg,- "provider": "docker"- }-+ return {"name": name, "status": "error", "error": error_msg, "provider": "docker"}+async def _wait_for_container_ready(self, container_name: str, timeout: int = 60) -> bool:"""Wait for the Docker container to be fully ready.-+Args:container_name: Name of the Docker container to checktimeout: Maximum time to wait in seconds (default: 60 seconds)-+Returns:True if the container is running and ready"""logger.info(f"Waiting for container {container_name} to be ready...")-+start_time = time.time()while time.time() - start_time < timeout:try:@@ -370,100 +359,94 @@ class DockerProvider(BaseVMProvider):vm_info = await self.get_vm(container_name)if vm_info["status"] == "running":logger.info(f"Container {container_name} is running")-+# Additional check: try to connect to computer-server API# This is optional - we'll just wait a bit more for services to startawait asyncio.sleep(5)return True-+except Exception as e:logger.debug(f"Container {container_name} not ready yet: {e}")-+await asyncio.sleep(2)-+logger.warning(f"Container {container_name} did not become ready within {timeout} seconds")return False-+async def stop_vm(self, name: str, storage: Optional[str] = None) -> Dict[str, Any]:"""Stop a running VM by stopping the Docker container."""try:logger.info(f"Stopping container {name}")-+# Stop the containercmd = ["docker", "stop", name]result = subprocess.run(cmd, capture_output=True, text=True, check=True)-+# Remove from running containers trackingif name in self._running_containers:del self._running_containers[name]-+logger.info(f"Container {name} stopped successfully")-+return {"name": name,"status": "stopped","message": "Container stopped successfully",- "provider": "docker"+ "provider": "docker",}-+except subprocess.CalledProcessError as e:error_msg = f"Failed to stop container {name}: {e.stderr}"logger.error(error_msg)- return {- "name": name,- "status": "error",- "error": error_msg,- "provider": "docker"- }+ return {"name": name, "status": "error", "error": error_msg, "provider": "docker"}except Exception as e:error_msg = f"Error stopping VM {name}: {e}"logger.error(error_msg)- return {- "name": name,- "status": "error",- "error": error_msg,- "provider": "docker"- }-+ return {"name": name, "status": "error", "error": error_msg, "provider": "docker"}+async def restart_vm(self, name: str, storage: Optional[str] = None) -> Dict[str, Any]:raise NotImplementedError("DockerProvider does not support restarting VMs.")- async def update_vm(self, name: str, update_opts: Dict[str, Any], storage: Optional[str] = None) -> Dict[str, Any]:+ async def update_vm(+ self, name: str, update_opts: Dict[str, Any], storage: Optional[str] = None+ ) -> Dict[str, Any]:"""Update VM configuration.-- Note: Docker containers cannot be updated while running.++ Note: Docker containers cannot be updated while running.This method will return an error suggesting to recreate the container."""return {"name": name,"status": "error","error": "Docker containers cannot be updated while running. Please stop and recreate the container with new options.",- "provider": "docker"+ "provider": "docker",}-+async def get_ip(self, name: str, storage: Optional[str] = None, retry_delay: int = 2) -> str:"""Get the IP address of a VM, waiting indefinitely until it's available.-+Args:name: Name of the VM to get the IP forstorage: Optional storage path overrideretry_delay: Delay between retries in seconds (default: 2)-+Returns:IP address of the VM when it becomes available"""logger.info(f"Getting IP address for container {name}")-+total_attempts = 0while True:total_attempts += 1-+try:vm_info = await self.get_vm(name, storage)-+if vm_info["status"] == "error":- raise Exception(f"VM is in error state: {vm_info.get('error', 'Unknown error')}")-+ raise Exception(+ f"VM is in error state: {vm_info.get('error', 'Unknown error')}"+ )+# TODO: for now, return localhost# it seems the docker container is not accessible from the host# on WSL2, unless you port forward? not sure@@ -476,40 +459,42 @@ class DockerProvider(BaseVMProvider):if ip and ip != "unknown" and not ip.startswith("0.0.0.0"):logger.info(f"Got valid container IP address: {ip}")return ip-+# For Docker containers, we can also use localhost if ports are mappedif vm_info["status"] == "running" and vm_info.get("ports"):- logger.info(f"Container is running with port mappings, using localhost")+ logger.info("Container is running with port mappings, using localhost")return "127.0.0.1"-+# Check the container statusstatus = vm_info.get("status", "unknown")-+if status == "stopped":logger.info(f"Container status is {status}, but still waiting for it to start")elif status != "running":logger.info(f"Container is not running yet (status: {status}). Waiting...")else:logger.info("Container is running but no valid IP address yet. Waiting...")-+except Exception as e:logger.warning(f"Error getting container {name} IP: {e}, continuing to wait...")-+# Wait before next retryawait asyncio.sleep(retry_delay)-+# Add progress log every 10 attemptsif total_attempts % 10 == 0:- logger.info(f"Still waiting for container {name} IP after {total_attempts} attempts...")-+ logger.info(+ f"Still waiting for container {name} IP after {total_attempts} attempts..."+ )+async def __aenter__(self):"""Async context manager entry."""logger.debug("Entering DockerProvider context")return self-+async def __aexit__(self, exc_type, exc_val, exc_tb):"""Async context manager exit.-+This method handles cleanup of running containers if needed."""logger.debug(f"Exiting DockerProvider context, handling exceptions: {exc_type}")diff --git a/libs/python/computer/computer/providers/factory.py b/libs/python/computer/computer/providers/factory.pyindex b95c2c6143..634b4293ef 100644--- a/libs/python/computer/computer/providers/factory.py+++ b/libs/python/computer/computer/providers/factory.py@@ -1,7 +1,7 @@"""Factory for creating VM providers."""import logging-from typing import Dict, Optional, Any, Type, Union+from typing import Any, Dict, Optional, Type, Unionfrom .base import BaseVMProvider, VMProviderType@@ -26,7 +26,7 @@ class VMProviderFactory:**kwargs,) -> BaseVMProvider:"""Create a VM provider of the specified type.-+Args:provider_type: Type of VM provider to createport: Port for the API server@@ -38,10 +38,10 @@ class VMProviderFactory:verbose: Enable verbose loggingephemeral: Use ephemeral (temporary) storagenoVNC_port: Specific port for noVNC interface (for Lumier provider)-+Returns:An instance of the requested VM provider-+Raises:ImportError: If the required dependencies for the provider are not installedValueError: If the provider type is not supported@@ -52,21 +52,18 @@ class VMProviderFactory:provider_type = VMProviderType(provider_type.lower())except ValueError:provider_type = VMProviderType.UNKNOWN-+if provider_type == VMProviderType.LUME:try:- from .lume import LumeProvider, HAS_LUME+ from .lume import HAS_LUME, LumeProvider+if not HAS_LUME:raise ImportError("The pylume package is required for LumeProvider. ""Please install it with 'pip install cua-computer[lume]'")return LumeProvider(- port=port,- host=host,- storage=storage,- verbose=verbose,- ephemeral=ephemeral+ port=port, host=host, storage=storage, verbose=verbose, ephemeral=ephemeral)except ImportError as e:logger.error(f"Failed to import LumeProvider: {e}")@@ -76,7 +73,8 @@ class VMProviderFactory:) from eelif provider_type == VMProviderType.LUMIER:try:- from .lumier import LumierProvider, HAS_LUMIER+ from .lumier import HAS_LUMIER, LumierProvider+if not HAS_LUMIER:raise ImportError("Docker is required for LumierProvider. "@@ -90,7 +88,7 @@ class VMProviderFactory:image=image or "macos-sequoia-cua:latest",verbose=verbose,ephemeral=ephemeral,- noVNC_port=noVNC_port+ noVNC_port=noVNC_port,)except ImportError as e:logger.error(f"Failed to import LumierProvider: {e}")@@ -102,6 +100,7 @@ class VMProviderFactory:elif provider_type == VMProviderType.CLOUD:try:from .cloud import CloudProvider+return CloudProvider(verbose=verbose,**kwargs,@@ -114,7 +113,8 @@ class VMProviderFactory:) from eelif provider_type == VMProviderType.WINSANDBOX:try:- from .winsandbox import WinSandboxProvider, HAS_WINSANDBOX+ from .winsandbox import HAS_WINSANDBOX, WinSandboxProvider+if not HAS_WINSANDBOX:raise ImportError("pywinsandbox is required for WinSandboxProvider. "@@ -126,7 +126,7 @@ class VMProviderFactory:storage=storage,verbose=verbose,ephemeral=ephemeral,- **kwargs+ **kwargs,)except ImportError as e:logger.error(f"Failed to import WinSandboxProvider: {e}")@@ -136,7 +136,8 @@ class VMProviderFactory:) from eelif provider_type == VMProviderType.DOCKER:try:- from .docker import DockerProvider, HAS_DOCKER+ from .docker import HAS_DOCKER, DockerProvider+if not HAS_DOCKER:raise ImportError("Docker is required for DockerProvider. "@@ -150,7 +151,7 @@ class VMProviderFactory:image=image or "trycua/cua-ubuntu:latest",verbose=verbose,ephemeral=ephemeral,- vnc_port=noVNC_port+ vnc_port=noVNC_port,)except ImportError as e:logger.error(f"Failed to import DockerProvider: {e}")diff --git a/libs/python/computer/computer/providers/lume/__init__.py b/libs/python/computer/computer/providers/lume/__init__.pyindex 8196c49bb7..70a48a4751 100644--- a/libs/python/computer/computer/providers/lume/__init__.py+++ b/libs/python/computer/computer/providers/lume/__init__.py@@ -2,6 +2,7 @@try:from .provider import LumeProvider+HAS_LUME = True__all__ = ["LumeProvider"]except ImportError:diff --git a/libs/python/computer/computer/providers/lume/provider.py b/libs/python/computer/computer/providers/lume/provider.pyindex d651d2eb5b..e9b953c914 100644--- a/libs/python/computer/computer/providers/lume/provider.py+++ b/libs/python/computer/computer/providers/lume/provider.py@@ -4,39 +4,40 @@ This provider uses direct curl commands to interact with the Lume API,removing the dependency on the pylume Python package."""-import os-import reimport asyncioimport jsonimport logging+import os+import reimport subprocessimport urllib.parse-from typing import Dict, Any, Optional, List, Tuple+from typing import Any, Dict, List, Optional, Tuple-from ..base import BaseVMProvider, VMProviderTypefrom ...logger import Logger, LogLevel+from ..base import BaseVMProvider, VMProviderTypefrom ..lume_api import (+ HAS_CURL,lume_api_get,+ lume_api_pull,lume_api_run,lume_api_stop,lume_api_update,- lume_api_pull,- HAS_CURL,- parse_memory+ parse_memory,)# Setup logginglogger = logging.getLogger(__name__)+class LumeProvider(BaseVMProvider):"""Lume VM provider implementation using direct curl commands.-+This provider uses curl to interact with the Lume API server,removing the dependency on the pylume Python package."""-+def __init__(- self,+ self,port: int = 7777,host: str = "localhost",storage: Optional[str] = None,@@ -44,7 +45,7 @@ class LumeProvider(BaseVMProvider):ephemeral: bool = False,):"""Initialize the Lume provider.-+Args:port: Port for the Lume API server (default: 7777)host: Host to use for API connections (default: localhost)@@ -56,42 +57,44 @@ class LumeProvider(BaseVMProvider):"curl is required for LumeProvider. ""Please ensure it is installed and in your PATH.")-+self.host = hostself.port = port # Default port for Lume APIself.storage = storageself.verbose = verboseself.ephemeral = ephemeral # If True, VMs will be deleted after stopping-+# Base API URL for Lume API callsself.api_base_url = f"http://{self.host}:{self.port}"-+self.logger = logging.getLogger(__name__)-+@propertydef provider_type(self) -> VMProviderType:"""Get the provider type."""return VMProviderType.LUME-+async def __aenter__(self):"""Enter async context manager."""# No initialization needed, just return selfreturn self-+async def __aexit__(self, exc_type, exc_val, exc_tb):"""Exit async context manager."""# No cleanup neededpass-- def _lume_api_get(self, vm_name: str = "", storage: Optional[str] = None, debug: bool = False) -> Dict[str, Any]:++ def _lume_api_get(+ self, vm_name: str = "", storage: Optional[str] = None, debug: bool = False+ ) -> Dict[str, Any]:"""Get VM information using shared lume_api function.-+Args:vm_name: Optional name of the VM to get info for.If empty, lists all VMs.storage: Optional storage path override. If provided, this will be used instead of self.storagedebug: Whether to show debug output-+Returns:Dictionary with VM status information parsed from JSON response"""@@ -102,105 +105,105 @@ class LumeProvider(BaseVMProvider):port=self.port,storage=storage if storage is not None else self.storage,debug=debug,- verbose=self.verbose+ verbose=self.verbose,)-- def _lume_api_run(self, vm_name: str, run_opts: Dict[str, Any], debug: bool = False) -> Dict[str, Any]:++ def _lume_api_run(+ self, vm_name: str, run_opts: Dict[str, Any], debug: bool = False+ ) -> Dict[str, Any]:"""Run a VM using shared lume_api function.-+Args:vm_name: Name of the VM to runrun_opts: Dictionary of run optionsdebug: Whether to show debug output-+Returns:Dictionary with API response or error information"""# Use the shared implementation from lume_api modulereturn lume_api_run(- vm_name=vm_name,+ vm_name=vm_name,host=self.host,port=self.port,run_opts=run_opts,storage=self.storage,debug=debug,- verbose=self.verbose+ verbose=self.verbose,)-+def _lume_api_stop(self, vm_name: str, debug: bool = False) -> Dict[str, Any]:"""Stop a VM using shared lume_api function.-+Args:vm_name: Name of the VM to stopdebug: Whether to show debug output-+Returns:Dictionary with API response or error information"""# Use the shared implementation from lume_api modulereturn lume_api_stop(- vm_name=vm_name,+ vm_name=vm_name,host=self.host,port=self.port,storage=self.storage,debug=debug,- verbose=self.verbose+ verbose=self.verbose,)-- def _lume_api_update(self, vm_name: str, update_opts: Dict[str, Any], debug: bool = False) -> Dict[str, Any]:++ def _lume_api_update(+ self, vm_name: str, update_opts: Dict[str, Any], debug: bool = False+ ) -> Dict[str, Any]:"""Update VM configuration using shared lume_api function.-+Args:vm_name: Name of the VM to updateupdate_opts: Dictionary of update optionsdebug: Whether to show debug output-+Returns:Dictionary with API response or error information"""# Use the shared implementation from lume_api modulereturn lume_api_update(- vm_name=vm_name,+ vm_name=vm_name,host=self.host,port=self.port,update_opts=update_opts,storage=self.storage,debug=debug,- verbose=self.verbose+ verbose=self.verbose,)-+async def get_vm(self, name: str, storage: Optional[str] = None) -> Dict[str, Any]:"""Get VM information by name.-+Args:name: Name of the VM to get information forstorage: Optional storage path override. If provided, this will be usedinstead of the provider's default storage path.-+Returns:Dictionary with VM information including status, IP address, etc.-+Note:If storage is not provided, the provider's default storage path will be used.The storage parameter allows overriding the storage location for this specific call."""if not HAS_CURL:logger.error("curl is not available. Cannot get VM status.")- return {- "name": name,- "status": "unavailable",- "error": "curl is not available"- }-+ return {"name": name, "status": "unavailable", "error": "curl is not available"}+# First try to get detailed VM info from the APItry:# Query the Lume API for VM status using the provider's storage_pathvm_info = self._lume_api_get(- vm_name=name,+ vm_name=name,storage=storage if storage is not None else self.storage,- debug=self.verbose+ debug=self.verbose,)-+# Check for API errorsif "error" in vm_info:logger.debug(f"API request error: {vm_info['error']}")@@ -209,12 +212,12 @@ class LumeProvider(BaseVMProvider):"name": name,"status": "starting", # VM is still starting - do not attempt to connect yet"api_status": "error",- "error": vm_info["error"]+ "error": vm_info["error"],}-+# Process the VM status informationvm_status = vm_info.get("status", "unknown")-+# Check if VM is stopped or not running - don't wait for IP in this caseif vm_status == "stopped":logger.info(f"VM {name} is in '{vm_status}' state - not waiting for IP address")@@ -222,10 +225,10 @@ class LumeProvider(BaseVMProvider):result = {"name": name,"status": vm_status,- **vm_info # Include all original fields from the API response+ **vm_info, # Include all original fields from the API response}return result-+# Handle field name differences between APIs# Some APIs use camelCase, others use snake_caseif "vncUrl" in vm_info:@@ -234,7 +237,7 @@ class LumeProvider(BaseVMProvider):vnc_url = vm_info["vnc_url"]else:vnc_url = ""-+if "ipAddress" in vm_info:ip_address = vm_info["ipAddress"]elif "ip_address" in vm_info:@@ -243,40 +246,42 @@ class LumeProvider(BaseVMProvider):# If no IP address is provided and VM is supposed to be running,# report it as still startingip_address = None- logger.info(f"VM {name} is in '{vm_status}' state but no IP address found - reporting as still starting")-+ logger.info(+ f"VM {name} is in '{vm_status}' state but no IP address found - reporting as still starting"+ )+logger.info(f"VM {name} status: {vm_status}")-+# Return the complete status informationresult = {"name": name,"status": vm_status if vm_status else "running","ip_address": ip_address,"vnc_url": vnc_url,- "api_status": "ok"+ "api_status": "ok",}-+# Include all original fields from the API responseif isinstance(vm_info, dict):for key, value in vm_info.items():if key not in result: # Don't override our carefully processed fieldsresult[key] = value-+return result-+except Exception as e:logger.error(f"Failed to get VM status: {e}")# Return a fallback status that indicates the VM is not ready yetreturn {"name": name,"status": "initializing", # VM is still initializing- "error": f"Failed to get VM status: {str(e)}"+ "error": f"Failed to get VM status: {str(e)}",}-+async def list_vms(self) -> List[Dict[str, Any]]:"""List all available VMs."""result = self._lume_api_get(debug=self.verbose)-+# Extract the VMs list from the responseif "vms" in result and isinstance(result["vms"], list):return result["vms"]@@ -285,48 +290,49 @@ class LumeProvider(BaseVMProvider):return []else:return []-- async def run_vm(self, image: str, name: str, run_opts: Dict[str, Any], storage: Optional[str] = None) -> Dict[str, Any]:++ async def run_vm(+ self, image: str, name: str, run_opts: Dict[str, Any], storage: Optional[str] = None+ ) -> Dict[str, Any]:"""Run a VM with the given options.-+If the VM does not exist in the storage location, this will attempt to pull itfrom the Lume registry first.-+Args:image: Image name to use when pulling the VM if it doesn't existname: Name of the VM to runrun_opts: Dictionary of run options (memory, cpu, etc.)storage: Optional storage path override. If provided, this will be usedinstead of the provider's default storage path.-+Returns:Dictionary with VM run status and information"""# First check if VM exists by trying to get its infovm_info = await self.get_vm(name, storage=storage)-+if "error" in vm_info:# VM doesn't exist, try to pull it- self.logger.info(f"VM {name} not found, attempting to pull image {image} from registry...")-- # Call pull_vm with the image parameter- pull_result = await self.pull_vm(- name=name,- image=image,- storage=storage+ self.logger.info(+ f"VM {name} not found, attempting to pull image {image} from registry...")-++ # Call pull_vm with the image parameter+ pull_result = await self.pull_vm(name=name, image=image, storage=storage)+# Check if pull was successfulif "error" in pull_result:self.logger.error(f"Failed to pull VM image: {pull_result['error']}")return pull_result # Return the error from pull-+self.logger.info(f"Successfully pulled VM image {image} as {name}")-+# Now run the VM with the given optionsself.logger.info(f"Running VM {name} with options: {run_opts}")-+from ..lume_api import lume_api_run+return lume_api_run(vm_name=name,host=self.host,@@ -334,52 +340,48 @@ class LumeProvider(BaseVMProvider):run_opts=run_opts,storage=storage if storage is not None else self.storage,debug=self.verbose,- verbose=self.verbose+ verbose=self.verbose,)-+async def stop_vm(self, name: str, storage: Optional[str] = None) -> Dict[str, Any]:"""Stop a running VM.-+If this provider was initialized with ephemeral=True, the VM will alsobe deleted after it is stopped.-+Args:name: Name of the VM to stopstorage: Optional storage path override-+Returns:Dictionary with stop status and information"""# Stop the VM firststop_result = self._lume_api_stop(name, debug=self.verbose)-+# Log ephemeral status for debuggingself.logger.info(f"Ephemeral mode status: {self.ephemeral}")-+# If ephemeral mode is enabled, delete the VM after stoppingif self.ephemeral and (stop_result.get("success", False) or "error" not in stop_result):self.logger.info(f"Ephemeral mode enabled - deleting VM {name} after stopping")try:delete_result = await self.delete_vm(name, storage=storage)-+# Return combined resultreturn {**stop_result, # Include all stop result info"deleted": True,- "delete_result": delete_result+ "delete_result": delete_result,}except Exception as e:self.logger.error(f"Failed to delete ephemeral VM {name}: {e}")# Include the error but still return stop result- return {- **stop_result,- "deleted": False,- "delete_error": str(e)- }-+ return {**stop_result, "deleted": False, "delete_error": str(e)}+# Just return the stop result if not ephemeralreturn stop_result-+async def pull_vm(self,name: str,@@ -390,7 +392,7 @@ class LumeProvider(BaseVMProvider):pull_opts: Optional[Dict[str, Any]] = None,) -> Dict[str, Any]:"""Pull a VM image from the registry.-+Args:name: Name for the VM after pullingimage: The image name to pull (e.g. 'macos-sequoia-cua:latest')@@ -398,31 +400,31 @@ class LumeProvider(BaseVMProvider):registry: Registry to pull from (default: ghcr.io)organization: Organization in registry (default: trycua)pull_opts: Additional options for pulling the VM (optional)-+Returns:Dictionary with information about the pulled VM-+Raises:RuntimeError: If pull operation fails or image is not provided"""# Validate image parameterif not image:raise ValueError("Image parameter is required for pull_vm")-+self.logger.info(f"Pulling VM image '{image}' as '{name}'")self.logger.info("You can check the pull progress using: lume logs -f")-+# Set default pull_opts if not providedif pull_opts is None:pull_opts = {}-+# Log information about the operationself.logger.debug(f"Pull storage location: {storage or 'default'}")-+try:# Call the lume_api_pull function from lume_api.pyfrom ..lume_api import lume_api_pull-+result = lume_api_pull(image=image,name=name,@@ -432,113 +434,115 @@ class LumeProvider(BaseVMProvider):registry=registry,organization=organization,debug=self.verbose,- verbose=self.verbose+ verbose=self.verbose,)-+# Check for errors in the resultif "error" in result:self.logger.error(f"Failed to pull VM image: {result['error']}")return result-+self.logger.info(f"Successfully pulled VM image '{image}' as '{name}'")return resultexcept Exception as e:self.logger.error(f"Failed to pull VM image '{image}': {e}")return {"error": f"Failed to pull VM: {str(e)}"}-+async def delete_vm(self, name: str, storage: Optional[str] = None) -> Dict[str, Any]:"""Delete a VM permanently.-+Args:name: Name of the VM to deletestorage: Optional storage path override-+Returns:Dictionary with delete status and information"""self.logger.info(f"Deleting VM {name}...")-+try:# Call the lume_api_delete function we createdfrom ..lume_api import lume_api_delete-+result = lume_api_delete(vm_name=name,host=self.host,port=self.port,storage=storage if storage is not None else self.storage,debug=self.verbose,- verbose=self.verbose+ verbose=self.verbose,)-+# Check for errors in the resultif "error" in result:self.logger.error(f"Failed to delete VM: {result['error']}")return result-+self.logger.info(f"Successfully deleted VM '{name}'")return resultexcept Exception as e:self.logger.error(f"Failed to delete VM '{name}': {e}")return {"error": f"Failed to delete VM: {str(e)}"}-- async def update_vm(self, name: str, update_opts: Dict[str, Any], storage: Optional[str] = None) -> Dict[str, Any]:++ async def update_vm(+ self, name: str, update_opts: Dict[str, Any], storage: Optional[str] = None+ ) -> Dict[str, Any]:"""Update VM configuration."""return self._lume_api_update(name, update_opts, debug=self.verbose)-+async def restart_vm(self, name: str, storage: Optional[str] = None) -> Dict[str, Any]:raise NotImplementedError("LumeProvider does not support restarting VMs.")-+async def get_ip(self, name: str, storage: Optional[str] = None, retry_delay: int = 2) -> str:"""Get the IP address of a VM, waiting indefinitely until it's available.-+Args:name: Name of the VM to get the IP forstorage: Optional storage path overrideretry_delay: Delay between retries in seconds (default: 2)-+Returns:IP address of the VM when it becomes available"""# Track total attempts for logging purposestotal_attempts = 0-+# Loop indefinitely until we get a valid IPwhile True:total_attempts += 1-+# Log retry message but not on first attemptif total_attempts > 1:self.logger.info(f"Waiting for VM {name} IP address (attempt {total_attempts})...")-+try:# Get VM informationvm_info = await self.get_vm(name, storage=storage)-+# Check if we got a valid IPip = vm_info.get("ip_address", None)if ip and ip != "unknown" and not ip.startswith("0.0.0.0"):self.logger.info(f"Got valid VM IP address: {ip}")return ip-+# Check the VM statusstatus = vm_info.get("status", "unknown")-+# If VM is not running yet, log and waitif status != "running":self.logger.info(f"VM is not running yet (status: {status}). Waiting...")# If VM is running but no IP yet, wait and retryelse:self.logger.info("VM is running but no valid IP address yet. Waiting...")-+except Exception as e:self.logger.warning(f"Error getting VM {name} IP: {e}, continuing to wait...")-+# Wait before next retryawait asyncio.sleep(retry_delay)-+# Add progress log every 10 attemptsif total_attempts % 10 == 0:- self.logger.info(f"Still waiting for VM {name} IP after {total_attempts} attempts...")--+ self.logger.info(+ f"Still waiting for VM {name} IP after {total_attempts} attempts..."+ )diff --git a/libs/python/computer/computer/providers/lume_api.py b/libs/python/computer/computer/providers/lume_api.pyindex 3cbe10972d..d034e1df6f 100644--- a/libs/python/computer/computer/providers/lume_api.py+++ b/libs/python/computer/computer/providers/lume_api.py@@ -4,11 +4,11 @@ This module contains shared functions for interacting with the Lume API,used by both the LumeProvider and LumierProvider classes."""-import loggingimport json+import loggingimport subprocessimport urllib.parse-from typing import Dict, List, Optional, Any+from typing import Any, Dict, List, Optional# Setup logginglogger = logging.getLogger(__name__)@@ -27,10 +27,10 @@ def lume_api_get(port: int,storage: Optional[str] = None,debug: bool = False,- verbose: bool = False+ verbose: bool = False,) -> Dict[str, Any]:"""Use curl to get VM information from Lume API.-+Args:vm_name: Name of the VM to get info forhost: API host@@ -38,46 +38,46 @@ def lume_api_get(storage: Storage path for the VMdebug: Whether to show debug outputverbose: Enable verbose logging-+Returns:Dictionary with VM status information parsed from JSON response"""# URL encode the storage parameter for the queryencoded_storage = ""storage_param = ""-+if storage:# First encode the storage path properly- encoded_storage = urllib.parse.quote(storage, safe='')+ encoded_storage = urllib.parse.quote(storage, safe="")storage_param = f"?storage={encoded_storage}"-+# Construct API URL with encoded storage parameter if neededapi_url = f"http://{host}:{port}/lume/vms/{vm_name}{storage_param}"-+# Construct the curl command with increased timeouts for more reliability# --connect-timeout: Time to establish connection (15 seconds)# --max-time: Maximum time for the whole operation (20 seconds)# -f: Fail silently (no output at all) on server errors# Add single quotes around URL to ensure special characters are handled correctlycmd = ["curl", "--connect-timeout", "15", "--max-time", "20", "-s", "-f", f"'{api_url}'"]-+# For logging and display, show the properly escaped URLdisplay_cmd = ["curl", "--connect-timeout", "15", "--max-time", "20", "-s", "-f", api_url]-+# Only print the curl command when debug is enabled- display_curl_string = ' '.join(display_cmd)+ display_curl_string = " ".join(display_cmd)logger.debug(f"Executing API request: {display_curl_string}")-+# Execute the command - for execution we need to use shell=True to handle URLs with special characterstry:# Use a single string with shell=True for proper URL handling- shell_cmd = ' '.join(cmd)+ shell_cmd = " ".join(cmd)result = subprocess.run(shell_cmd, shell=True, capture_output=True, text=True)-+# Handle curl exit codesif result.returncode != 0:curl_error = "Unknown error"-+# Map common curl error codes to helpful messagesif result.returncode == 7:curl_error = "Failed to connect to the API server - it might still be starting up"@@ -86,35 +86,42 @@ def lume_api_get(elif result.returncode == 28:curl_error = "Operation timeout - the API server is taking too long to respond"elif result.returncode == 52:- curl_error = "Empty reply from server - the API server is starting but not fully ready yet"+ curl_error = (+ "Empty reply from server - the API server is starting but not fully ready yet"+ )elif result.returncode == 56:curl_error = "Network problem during data transfer - check container networking"-+# Only log at debug level to reduce noise during retrieslogger.debug(f"API request failed with code {result.returncode}: {curl_error}")-+# Return a more useful error messagereturn {"error": f"API request failed: {curl_error}","curl_code": result.returncode,"vm_name": vm_name,- "status": "unknown" # We don't know the actual status due to API error+ "status": "unknown", # We don't know the actual status due to API error}-+# Try to parse the response as JSONif result.stdout and result.stdout.strip():try:vm_status = json.loads(result.stdout)if debug or verbose:- logger.info(f"Successfully parsed VM status: {vm_status.get('status', 'unknown')}")+ logger.info(+ f"Successfully parsed VM status: {vm_status.get('status', 'unknown')}"+ )return vm_statusexcept json.JSONDecodeError as e:# Return the raw response if it's not valid JSONlogger.warning(f"Invalid JSON response: {e}")if "Virtual machine not found" in result.stdout:return {"status": "not_found", "message": "VM not found in Lume API"}-- return {"error": f"Invalid JSON response: {result.stdout[:100]}...", "status": "unknown"}++ return {+ "error": f"Invalid JSON response: {result.stdout[:100]}...",+ "status": "unknown",+ }else:return {"error": "Empty response from API", "status": "unknown"}except subprocess.SubprocessError as e:@@ -129,10 +136,10 @@ def lume_api_run(run_opts: Dict[str, Any],storage: Optional[str] = None,debug: bool = False,- verbose: bool = False+ verbose: bool = False,) -> Dict[str, Any]:"""Run a VM using curl.-+Args:vm_name: Name of the VM to runhost: API host@@ -141,53 +148,62 @@ def lume_api_run(storage: Storage path for the VMdebug: Whether to show debug outputverbose: Enable verbose logging-+Returns:Dictionary with API response or error information"""# Construct API URLapi_url = f"http://{host}:{port}/lume/vms/{vm_name}/run"-+# Prepare JSON payload with required parameterspayload = {}-+# Add CPU cores if specifiedif "cpu" in run_opts:payload["cpu"] = run_opts["cpu"]-+# Add memory if specifiedif "memory" in run_opts:payload["memory"] = run_opts["memory"]-+# Add storage parameter if specifiedif storage:payload["storage"] = storageelif "storage" in run_opts:payload["storage"] = run_opts["storage"]-+# Add shared directories if specifiedif "shared_directories" in run_opts and run_opts["shared_directories"]:payload["sharedDirectories"] = run_opts["shared_directories"]-+# Log the payload for debugginglogger.debug(f"API payload: {json.dumps(payload, indent=2)}")-+# Construct the curl commandcmd = [- "curl", "--connect-timeout", "30", "--max-time", "30",- "-s", "-X", "POST", "-H", "Content-Type: application/json",- "-d", json.dumps(payload),- api_url+ "curl",+ "--connect-timeout",+ "30",+ "--max-time",+ "30",+ "-s",+ "-X",+ "POST",+ "-H",+ "Content-Type: application/json",+ "-d",+ json.dumps(payload),+ api_url,]-+# Execute the commandtry:result = subprocess.run(cmd, capture_output=True, text=True)-+if result.returncode != 0:logger.warning(f"API request failed with code {result.returncode}: {result.stderr}")return {"error": f"API request failed: {result.stderr}"}-+# Try to parse the response as JSONif result.stdout and result.stdout.strip():try:@@ -195,7 +211,11 @@ def lume_api_run(return responseexcept json.JSONDecodeError:# Return the raw response if it's not valid JSON- return {"success": True, "message": "VM started successfully", "raw_response": result.stdout}+ return {+ "success": True,+ "message": "VM started successfully",+ "raw_response": result.stdout,+ }else:return {"success": True, "message": "VM started successfully"}except subprocess.SubprocessError as e:@@ -209,10 +229,10 @@ def lume_api_stop(port: int,storage: Optional[str] = None,debug: bool = False,- verbose: bool = False+ verbose: bool = False,) -> Dict[str, Any]:"""Stop a VM using curl.-+Args:vm_name: Name of the VM to stophost: API host@@ -220,39 +240,48 @@ def lume_api_stop(storage: Storage path for the VMdebug: Whether to show debug outputverbose: Enable verbose logging-+Returns:Dictionary with API response or error information"""# Construct API URLapi_url = f"http://{host}:{port}/lume/vms/{vm_name}/stop"-+# Prepare JSON payload with required parameterspayload = {}-+# Add storage path if specifiedif storage:payload["storage"] = storage-+# Construct the curl commandcmd = [- "curl", "--connect-timeout", "15", "--max-time", "20",- "-s", "-X", "POST", "-H", "Content-Type: application/json",- "-d", json.dumps(payload),- api_url+ "curl",+ "--connect-timeout",+ "15",+ "--max-time",+ "20",+ "-s",+ "-X",+ "POST",+ "-H",+ "Content-Type: application/json",+ "-d",+ json.dumps(payload),+ api_url,]-+# Execute the commandtry:if debug or verbose:logger.info(f"Executing: {' '.join(cmd)}")-+result = subprocess.run(cmd, capture_output=True, text=True)-+if result.returncode != 0:logger.warning(f"API request failed with code {result.returncode}: {result.stderr}")return {"error": f"API request failed: {result.stderr}"}-+# Try to parse the response as JSONif result.stdout and result.stdout.strip():try:@@ -260,7 +289,11 @@ def lume_api_stop(return responseexcept json.JSONDecodeError:# Return the raw response if it's not valid JSON- return {"success": True, "message": "VM stopped successfully", "raw_response": result.stdout}+ return {+ "success": True,+ "message": "VM stopped successfully",+ "raw_response": result.stdout,+ }else:return {"success": True, "message": "VM stopped successfully"}except subprocess.SubprocessError as e:@@ -275,10 +308,10 @@ def lume_api_update(update_opts: Dict[str, Any],storage: Optional[str] = None,debug: bool = False,- verbose: bool = False+ verbose: bool = False,) -> Dict[str, Any]:"""Update VM settings using curl.-+Args:vm_name: Name of the VM to updatehost: API host@@ -287,47 +320,56 @@ def lume_api_update(storage: Storage path for the VMdebug: Whether to show debug outputverbose: Enable verbose logging-+Returns:Dictionary with API response or error information"""# Construct API URLapi_url = f"http://{host}:{port}/lume/vms/{vm_name}/update"-+# Prepare JSON payload with required parameterspayload = {}-+# Add CPU cores if specifiedif "cpu" in update_opts:payload["cpu"] = update_opts["cpu"]-+# Add memory if specifiedif "memory" in update_opts:payload["memory"] = update_opts["memory"]-+# Add storage path if specifiedif storage:payload["storage"] = storage-+# Construct the curl commandcmd = [- "curl", "--connect-timeout", "15", "--max-time", "20",- "-s", "-X", "POST", "-H", "Content-Type: application/json",- "-d", json.dumps(payload),- api_url+ "curl",+ "--connect-timeout",+ "15",+ "--max-time",+ "20",+ "-s",+ "-X",+ "POST",+ "-H",+ "Content-Type: application/json",+ "-d",+ json.dumps(payload),+ api_url,]-+# Execute the commandtry:if debug:logger.info(f"Executing: {' '.join(cmd)}")-+result = subprocess.run(cmd, capture_output=True, text=True)-+if result.returncode != 0:logger.warning(f"API request failed with code {result.returncode}: {result.stderr}")return {"error": f"API request failed: {result.stderr}"}-+# Try to parse the response as JSONif result.stdout and result.stdout.strip():try:@@ -335,7 +377,11 @@ def lume_api_update(return responseexcept json.JSONDecodeError:# Return the raw response if it's not valid JSON- return {"success": True, "message": "VM updated successfully", "raw_response": result.stdout}+ return {+ "success": True,+ "message": "VM updated successfully",+ "raw_response": result.stdout,+ }else:return {"success": True, "message": "VM updated successfully"}except subprocess.SubprocessError as e:@@ -352,10 +398,10 @@ def lume_api_pull(registry: str = "ghcr.io",organization: str = "trycua",debug: bool = False,- verbose: bool = False+ verbose: bool = False,) -> Dict[str, Any]:"""Pull a VM image from a registry using curl.-+Args:image: Name/tag of the image to pullname: Name to give the VM after pulling@@ -366,47 +412,50 @@ def lume_api_pull(organization: Organization in registry (default: trycua)debug: Whether to show debug outputverbose: Enable verbose logging-+Returns:Dictionary with pull status and information"""# Prepare pull request payloadpull_payload = {"image": image, # Use provided image name- "name": name, # Always use name as the target VM name+ "name": name, # Always use name as the target VM name"registry": registry,- "organization": organization+ "organization": organization,}-+if storage:pull_payload["storage"] = storage-+# Construct pull command with proper JSON payload- pull_cmd = [- "curl"- ]-+ pull_cmd = ["curl"]+if not verbose:pull_cmd.append("-s")-- pull_cmd.extend([- "-X", "POST",- "-H", "Content-Type: application/json",- "-d", json.dumps(pull_payload),- f"http://{host}:{port}/lume/pull"- ])-++ pull_cmd.extend(+ [+ "-X",+ "POST",+ "-H",+ "Content-Type: application/json",+ "-d",+ json.dumps(pull_payload),+ f"http://{host}:{port}/lume/pull",+ ]+ )+logger.debug(f"Executing API request: {' '.join(pull_cmd)}")-+try:# Execute pull commandresult = subprocess.run(pull_cmd, capture_output=True, text=True)-+if result.returncode != 0:error_msg = f"Failed to pull VM {name}: {result.stderr}"logger.error(error_msg)return {"error": error_msg}-+try:response = json.loads(result.stdout)logger.info(f"Successfully initiated pull for VM {name}")@@ -415,7 +464,7 @@ def lume_api_pull(if result.stdout:logger.info(f"Pull response: {result.stdout}")return {"success": True, "message": f"Successfully initiated pull for VM {name}"}-+except subprocess.SubprocessError as e:error_msg = f"Failed to execute pull command: {str(e)}"logger.error(error_msg)@@ -428,10 +477,10 @@ def lume_api_delete(port: int,storage: Optional[str] = None,debug: bool = False,- verbose: bool = False+ verbose: bool = False,) -> Dict[str, Any]:"""Delete a VM using curl.-+Args:vm_name: Name of the VM to deletehost: API host@@ -439,42 +488,62 @@ def lume_api_delete(storage: Storage path for the VMdebug: Whether to show debug outputverbose: Enable verbose logging-+Returns:Dictionary with API response or error information"""# URL encode the storage parameter for the queryencoded_storage = ""storage_param = ""-+if storage:# First encode the storage path properly- encoded_storage = urllib.parse.quote(storage, safe='')+ encoded_storage = urllib.parse.quote(storage, safe="")storage_param = f"?storage={encoded_storage}"-+# Construct API URL with encoded storage parameter if neededapi_url = f"http://{host}:{port}/lume/vms/{vm_name}{storage_param}"-+# Construct the curl command for DELETE operation - using much longer timeouts matching shell implementation- cmd = ["curl", "--connect-timeout", "6000", "--max-time", "5000", "-s", "-X", "DELETE", f"'{api_url}'"]-+ cmd = [+ "curl",+ "--connect-timeout",+ "6000",+ "--max-time",+ "5000",+ "-s",+ "-X",+ "DELETE",+ f"'{api_url}'",+ ]+# For logging and display, show the properly escaped URL- display_cmd = ["curl", "--connect-timeout", "6000", "--max-time", "5000", "-s", "-X", "DELETE", api_url]-+ display_cmd = [+ "curl",+ "--connect-timeout",+ "6000",+ "--max-time",+ "5000",+ "-s",+ "-X",+ "DELETE",+ api_url,+ ]+# Only print the curl command when debug is enabled- display_curl_string = ' '.join(display_cmd)+ display_curl_string = " ".join(display_cmd)logger.debug(f"Executing API request: {display_curl_string}")-+# Execute the command - for execution we need to use shell=True to handle URLs with special characterstry:# Use a single string with shell=True for proper URL handling- shell_cmd = ' '.join(cmd)+ shell_cmd = " ".join(cmd)result = subprocess.run(shell_cmd, shell=True, capture_output=True, text=True)-+# Handle curl exit codesif result.returncode != 0:curl_error = "Unknown error"-+# Map common curl error codes to helpful messagesif result.returncode == 7:curl_error = "Failed to connect to the API server - it might still be starting up"@@ -483,21 +552,23 @@ def lume_api_delete(elif result.returncode == 28:curl_error = "Operation timeout - the API server is taking too long to respond"elif result.returncode == 52:- curl_error = "Empty reply from server - the API server is starting but not fully ready yet"+ curl_error = (+ "Empty reply from server - the API server is starting but not fully ready yet"+ )elif result.returncode == 56:curl_error = "Network problem during data transfer - check container networking"-+# Only log at debug level to reduce noise during retrieslogger.debug(f"API request failed with code {result.returncode}: {curl_error}")-+# Return a more useful error messagereturn {"error": f"API request failed: {curl_error}","curl_code": result.returncode,"vm_name": vm_name,- "storage": storage+ "storage": storage,}-+# Try to parse the response as JSONif result.stdout and result.stdout.strip():try:@@ -505,7 +576,11 @@ def lume_api_delete(return responseexcept json.JSONDecodeError:# Return the raw response if it's not valid JSON- return {"success": True, "message": "VM deleted successfully", "raw_response": result.stdout}+ return {+ "success": True,+ "message": "VM deleted successfully",+ "raw_response": result.stdout,+ }else:return {"success": True, "message": "VM deleted successfully"}except subprocess.SubprocessError as e:@@ -515,32 +590,33 @@ def lume_api_delete(def parse_memory(memory_str: str) -> int:"""Parse memory string to MB integer.-+Examples:"8GB" -> 8192"1024MB" -> 1024"512" -> 512-+Returns:Memory value in MB"""if isinstance(memory_str, int):return memory_str-+if isinstance(memory_str, str):# Extract number and unitimport re+match = re.match(r"(\d+)([A-Za-z]*)", memory_str)if match:value, unit = match.groups()value = int(value)unit = unit.upper()-+if unit == "GB" or unit == "G":return value * 1024elif unit == "MB" or unit == "M" or unit == "":return value-+# Default fallbacklogger.warning(f"Could not parse memory string '{memory_str}', using 8GB default")return 8192 # Default to 8GBdiff --git a/libs/python/computer/computer/providers/lumier/__init__.py b/libs/python/computer/computer/providers/lumier/__init__.pyindex 32a3954bb0..7785007a17 100644--- a/libs/python/computer/computer/providers/lumier/__init__.py+++ b/libs/python/computer/computer/providers/lumier/__init__.py@@ -3,6 +3,7 @@try:# Use the same import approach as in the Lume providerfrom .provider import LumierProvider+HAS_LUMIER = Trueexcept ImportError:HAS_LUMIER = Falsediff --git a/libs/python/computer/computer/providers/lumier/provider.py b/libs/python/computer/computer/providers/lumier/provider.pyindex 9b3e8c4d37..d4c99bfea6 100644--- a/libs/python/computer/computer/providers/lumier/provider.py+++ b/libs/python/computer/computer/providers/lumier/provider.py@@ -6,22 +6,17 @@ macOS and Linux VMs. It handles VM lifecycle operations through Dockercommands and container management."""+import asyncio+import jsonimport loggingimport os-import json-import asyncio-from typing import Dict, List, Optional, Any+import reimport subprocessimport time-import re+from typing import Any, Dict, List, Optionalfrom ..base import BaseVMProvider, VMProviderType-from ..lume_api import (- lume_api_get,- lume_api_run,- lume_api_stop,- lume_api_update-)+from ..lume_api import lume_api_get, lume_api_run, lume_api_stop, lume_api_update# Setup logginglogger = logging.getLogger(__name__)@@ -37,13 +32,13 @@ except (subprocess.SubprocessError, FileNotFoundError):class LumierProvider(BaseVMProvider):"""Lumier VM Provider implementation using Docker containers.-+This provider uses Docker to run Lumier containers that can createmacOS and Linux VMs through containerization."""-+def __init__(- self,+ self,port: Optional[int] = 7777,host: str = "localhost",storage: Optional[str] = None, # Can be a path or 'ephemeral'@@ -54,7 +49,7 @@ class LumierProvider(BaseVMProvider):noVNC_port: Optional[int] = 8006,):"""Initialize the Lumier VM Provider.-+Args:port: Port for the API server (default: 7777)host: Hostname for the API server (default: localhost)@@ -70,28 +65,28 @@ class LumierProvider(BaseVMProvider):self.api_port = 7777 if port is None else portself.vnc_port = noVNC_port # User-specified noVNC port, will be set in run_vm if providedself.ephemeral = ephemeral-+# Handle ephemeral storage (temporary directory)if ephemeral:self.storage = "ephemeral"else:self.storage = storage-+self.shared_path = shared_pathself.image = image # Store the VM image name to use# The container_name will be set in run_vm using the VM nameself.verbose = verboseself._container_id = Noneself._api_url = None # Will be set after container starts-+@propertydef provider_type(self) -> VMProviderType:"""Return the provider type."""return VMProviderType.LUMIER-+def _parse_memory(self, memory_str: str) -> int:"""Parse memory string to MB integer.-+Examples:"8GB" -> 8192"1024MB" -> 1024@@ -99,7 +94,7 @@ class LumierProvider(BaseVMProvider):"""if isinstance(memory_str, int):return memory_str-+if isinstance(memory_str, str):# Extract number and unitmatch = re.match(r"(\d+)([A-Za-z]*)", memory_str)@@ -107,25 +102,25 @@ class LumierProvider(BaseVMProvider):value, unit = match.groups()value = int(value)unit = unit.upper()-+if unit == "GB" or unit == "G":return value * 1024elif unit == "MB" or unit == "M" or unit == "":return value-+# Default fallbacklogger.warning(f"Could not parse memory string '{memory_str}', using 8GB default")return 8192 # Default to 8GB-+# Helper methods for interacting with the Lumier API through curl# These methods handle the various VM operations via API calls-+def _get_curl_error_message(self, return_code: int) -> str:"""Get a descriptive error message for curl return codes.-+Args:return_code: The curl return code-+Returns:A descriptive error message"""@@ -143,57 +138,62 @@ class LumierProvider(BaseVMProvider):else:return f"Unknown curl error code: {return_code}"-async def get_vm(self, name: str, storage: Optional[str] = None) -> Dict[str, Any]:"""Get VM information by name.-+Args:name: Name of the VM to get information forstorage: Optional storage path override. If provided, this will be usedinstead of the provider's default storage path.-+Returns:Dictionary with VM information including status, IP address, etc."""if not HAS_LUMIER:logger.error("Docker is not available. Cannot get VM status.")- return {- "name": name,- "status": "unavailable",- "error": "Docker is not available"- }-+ return {"name": name, "status": "unavailable", "error": "Docker is not available"}+# Store the current name for API requestsself.container_name = name-+try:# Check if the container exists and is running- check_cmd = ["docker", "ps", "-a", "--filter", f"name={name}", "--format", "{{.Status}}"]+ check_cmd = [+ "docker",+ "ps",+ "-a",+ "--filter",+ f"name={name}",+ "--format",+ "{{.Status}}",+ ]check_result = subprocess.run(check_cmd, capture_output=True, text=True)container_status = check_result.stdout.strip()-+if not container_status:logger.info(f"Container {name} does not exist. Will create when run_vm is called.")return {"name": name,"status": "not_found",- "message": "Container doesn't exist yet"+ "message": "Container doesn't exist yet",}-+# Container exists, check if it's runningis_running = container_status.startswith("Up")-+if not is_running:- logger.info(f"Container {name} exists but is not running. Status: {container_status}")+ logger.info(+ f"Container {name} exists but is not running. Status: {container_status}"+ )return {"name": name,"status": "stopped","container_status": container_status,}-+# Container is running, get the IP address and API status from Lumier APIlogger.info(f"Container {name} is running. Getting VM status from API.")-+# Use the shared lume_api_get function directlyvm_info = lume_api_get(vm_name=name,@@ -201,9 +201,9 @@ class LumierProvider(BaseVMProvider):port=self.api_port,storage=storage if storage is not None else self.storage,debug=self.verbose,- verbose=self.verbose+ verbose=self.verbose,)-+# Check for API errorsif "error" in vm_info:# Use debug level instead of warning to reduce log noise during polling@@ -213,14 +213,14 @@ class LumierProvider(BaseVMProvider):"status": "running", # Container is running even if API is not responsive"api_status": "error","error": vm_info["error"],- "container_status": container_status+ "container_status": container_status,}-+# Process the VM status informationvm_status = vm_info.get("status", "unknown")vnc_url = vm_info.get("vncUrl", "")ip_address = vm_info.get("ipAddress", "")-+# IMPORTANT: Always ensure we have a valid IP address for connectivity# If the API doesn't return an IP address, default to localhost (127.0.0.1)# This makes the behavior consistent with LumeProvider@@ -228,9 +228,9 @@ class LumierProvider(BaseVMProvider):ip_address = "127.0.0.1"logger.info(f"No IP address returned from API, defaulting to {ip_address}")vm_info["ipAddress"] = ip_address-+logger.info(f"VM {name} status: {vm_status}")-+if ip_address and vnc_url:logger.info(f"VM {name} has IP: {ip_address} and VNC URL: {vnc_url}")elif not ip_address and not vnc_url and vm_status != "running":@@ -238,8 +238,10 @@ class LumierProvider(BaseVMProvider):logger.info(f"VM {name} is not running yet. Status: {vm_status}")else:# Missing IP or VNC but status is running - this is unusual but handled with default IP- logger.warning(f"VM {name} is running but missing expected fields. API response: {vm_info}")-+ logger.warning(+ f"VM {name} is running but missing expected fields. API response: {vm_info}"+ )+# Return the full status informationreturn {"name": name,@@ -248,19 +250,19 @@ class LumierProvider(BaseVMProvider):"vnc_url": vnc_url,"api_status": "ok","container_status": container_status,- **vm_info # Include all fields from the API response+ **vm_info, # Include all fields from the API response}except subprocess.SubprocessError as e:logger.error(f"Failed to check container status: {e}")return {"name": name,"status": "error",- "error": f"Failed to check container status: {str(e)}"+ "error": f"Failed to check container status: {str(e)}",}-+async def list_vms(self) -> List[Dict[str, Any]]:"""List all VMs managed by this provider.-+For Lumier provider, there is only one VM per container."""try:@@ -269,10 +271,12 @@ class LumierProvider(BaseVMProvider):except Exception as e:logger.error(f"Failed to list VMs: {e}")return []-- async def run_vm(self, image: str, name: str, run_opts: Dict[str, Any], storage: Optional[str] = None) -> Dict[str, Any]:++ async def run_vm(+ self, image: str, name: str, run_opts: Dict[str, Any], storage: Optional[str] = None+ ) -> Dict[str, Any]:"""Run a VM with the given options.-+Args:image: Name/tag of the image to usename: Name of the VM to run (used for the container name and Docker image tag)@@ -280,7 +284,7 @@ class LumierProvider(BaseVMProvider):- cpu: Number of CPU cores- memory: Amount of memory (e.g. "8GB")- noVNC_port: Specific port for noVNC interface-+Returns:Dictionary with VM status information"""@@ -289,10 +293,18 @@ class LumierProvider(BaseVMProvider):try:# First, check if container already exists and remove ittry:- check_cmd = ["docker", "ps", "-a", "--filter", f"name={self.container_name}", "--format", "{{.ID}}"]+ check_cmd = [+ "docker",+ "ps",+ "-a",+ "--filter",+ f"name={self.container_name}",+ "--format",+ "{{.ID}}",+ ]check_result = subprocess.run(check_cmd, capture_output=True, text=True)existing_container = check_result.stdout.strip()-+if existing_container:logger.info(f"Removing existing container: {self.container_name}")remove_cmd = ["docker", "rm", "-f", self.container_name]@@ -300,66 +312,68 @@ class LumierProvider(BaseVMProvider):except subprocess.CalledProcessError as e:logger.warning(f"Error removing existing container: {e}")# Continue anyway, next steps will fail if there's a real problem-+# Prepare the Docker run commandcmd = ["docker", "run", "-d", "--name", self.container_name]-+cmd.extend(["-p", f"{self.vnc_port}:8006"])logger.debug(f"Using specified noVNC_port: {self.vnc_port}")-+# Set API URL using the API portself._api_url = f"http://{self.host}:{self.api_port}"-+# Parse memory settingmemory_mb = self._parse_memory(run_opts.get("memory", "8GB"))-+# Add storage volume mount if storage is specified (for persistent VM storage)if self.storage and self.storage != "ephemeral":# Create storage directory if it doesn't existstorage_dir = os.path.abspath(os.path.expanduser(self.storage or ""))os.makedirs(storage_dir, exist_ok=True)-+# Add volume mount for storage- cmd.extend([- "-v", f"{storage_dir}:/storage",- "-e", f"HOST_STORAGE_PATH={storage_dir}"- ])+ cmd.extend(+ ["-v", f"{storage_dir}:/storage", "-e", f"HOST_STORAGE_PATH={storage_dir}"]+ )logger.debug(f"Using persistent storage at: {storage_dir}")-+# Add shared folder volume mount if shared_path is specifiedif self.shared_path:# Create shared directory if it doesn't existshared_dir = os.path.abspath(os.path.expanduser(self.shared_path or ""))os.makedirs(shared_dir, exist_ok=True)-+# Add volume mount for shared folder- cmd.extend([- "-v", f"{shared_dir}:/shared",- "-e", f"HOST_SHARED_PATH={shared_dir}"- ])+ cmd.extend(["-v", f"{shared_dir}:/shared", "-e", f"HOST_SHARED_PATH={shared_dir}"])logger.debug(f"Using shared folder at: {shared_dir}")-+# Add environment variables# Always use the container_name as the VM_NAME for consistency# Use the VM image passed from the Computer classlogger.debug(f"Using VM image: {self.image}")-+# If ghcr.io is in the image, use the full image nameif "ghcr.io" in self.image:vm_image = self.imageelse:vm_image = f"ghcr.io/trycua/{self.image}"- cmd.extend([- "-e", f"VM_NAME={self.container_name}",- "-e", f"VERSION={vm_image}",- "-e", f"CPU_CORES={run_opts.get('cpu', '4')}",- "-e", f"RAM_SIZE={memory_mb}",- ])-+ cmd.extend(+ [+ "-e",+ f"VM_NAME={self.container_name}",+ "-e",+ f"VERSION={vm_image}",+ "-e",+ f"CPU_CORES={run_opts.get('cpu', '4')}",+ "-e",+ f"RAM_SIZE={memory_mb}",+ ]+ )+# Specify the Lumier image with the full image namelumier_image = "trycua/lumier:latest"-+# First check if the image exists locallytry:logger.debug(f"Checking if Docker image {lumier_image} exists locally...")@@ -369,54 +383,73 @@ class LumierProvider(BaseVMProvider):except subprocess.CalledProcessError:# Image doesn't exist locallylogger.warning(f"\nWARNING: Docker image {lumier_image} not found locally.")- logger.warning("The system will attempt to pull it from Docker Hub, which may fail if you have network connectivity issues.")- logger.warning("If the Docker pull fails, you may need to manually pull the image first with:")+ logger.warning(+ "The system will attempt to pull it from Docker Hub, which may fail if you have network connectivity issues."+ )+ logger.warning(+ "If the Docker pull fails, you may need to manually pull the image first with:"+ )logger.warning(f" docker pull {lumier_image}\n")-+# Add the image to the commandcmd.append(lumier_image)-+# Print the Docker command for debugginglogger.debug(f"DOCKER COMMAND: {' '.join(cmd)}")-+# Run the container with improved error handlingtry:result = subprocess.run(cmd, capture_output=True, text=True, check=True)except subprocess.CalledProcessError as e:- if "no route to host" in str(e.stderr).lower() or "failed to resolve reference" in str(e.stderr).lower():- error_msg = (f"Network error while trying to pull Docker image '{lumier_image}'\n"- f"Error: {e.stderr}\n\n"- f"SOLUTION: Please try one of the following:\n"- f"1. Check your internet connection\n"- f"2. Pull the image manually with: docker pull {lumier_image}\n"- f"3. Check if Docker is running properly\n")+ if (+ "no route to host" in str(e.stderr).lower()+ or "failed to resolve reference" in str(e.stderr).lower()+ ):+ error_msg = (+ f"Network error while trying to pull Docker image '{lumier_image}'\n"+ f"Error: {e.stderr}\n\n"+ f"SOLUTION: Please try one of the following:\n"+ f"1. Check your internet connection\n"+ f"2. Pull the image manually with: docker pull {lumier_image}\n"+ f"3. Check if Docker is running properly\n"+ )logger.error(error_msg)raise RuntimeError(error_msg)raise-+# Container started, now check VM status with pollinglogger.debug("Container started, checking VM status...")- logger.debug("NOTE: This may take some time while the VM image is being pulled and initialized")-+ logger.debug(+ "NOTE: This may take some time while the VM image is being pulled and initialized"+ )+# Start a background thread to show container logs in real-timeimport threading-+def show_container_logs():# Give the container a moment to start generating logstime.sleep(1)logger.debug(f"\n---- CONTAINER LOGS FOR '{name}' (LIVE) ----")- logger.debug("Showing logs as they are generated. Press Ctrl+C to stop viewing logs...\n")-+ logger.debug(+ "Showing logs as they are generated. Press Ctrl+C to stop viewing logs...\n"+ )+try:# Use docker logs with follow optionlog_cmd = ["docker", "logs", "--tail", "30", "--follow", name]- process = subprocess.Popen(log_cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT,- text=True, bufsize=1, universal_newlines=True)-+ process = subprocess.Popen(+ log_cmd,+ stdout=subprocess.PIPE,+ stderr=subprocess.STDOUT,+ text=True,+ bufsize=1,+ universal_newlines=True,+ )+# Read and print logs line by linefor line in process.stdout:- logger.debug(line, end='')-+ logger.debug(line, end="")+# Break if process has exitedif process.poll() is not None:break@@ -427,20 +460,20 @@ class LumierProvider(BaseVMProvider):finally:logger.debug("\n---- LOG STREAMING ENDED ----")# Make sure process is terminated- if 'process' in locals() and process.poll() is None:+ if "process" in locals() and process.poll() is None:process.terminate()-+# Start log streaming in a background thread if verbose mode is enabledlog_thread = threading.Thread(target=show_container_logs)log_thread.daemon = True # Thread will exit when main program exitslog_thread.start()-+# Skip waiting for container readiness and just poll get_vm directly# Poll the get_vm method indefinitely until the VM is ready with an IP addressattempt = 0consecutive_errors = 0vm_running = False-+while True: # Wait indefinitelytry:# Use longer delays to give the system time to initialize@@ -449,117 +482,151 @@ class LumierProvider(BaseVMProvider):# But use shorter delays while we're getting API errorsif consecutive_errors > 0 and consecutive_errors < 5:wait_time = 3 # Use shorter delays when we're getting API errors- else:+ else:wait_time = min(30, 5 + (attempt * 2))-+logger.debug(f"Waiting {wait_time}s before retry #{attempt+1}...")await asyncio.sleep(wait_time)-+# Try to get VM statuslogger.debug(f"Checking VM status (attempt {attempt+1})...")vm_status = await self.get_vm(name)-+# Check for API errors- if 'error' in vm_status:+ if "error" in vm_status:consecutive_errors += 1- error_msg = vm_status.get('error', 'Unknown error')-+ error_msg = vm_status.get("error", "Unknown error")+# Only print a user-friendly status message, not the raw error# since _lume_api_get already logged the technical detailsif consecutive_errors == 1 or attempt % 5 == 0:- if 'Empty reply from server' in error_msg:- logger.info("API server is starting up - container is running, but API isn't fully initialized yet.")- logger.info("This is expected during the initial VM setup - will continue polling...")+ if "Empty reply from server" in error_msg:+ logger.info(+ "API server is starting up - container is running, but API isn't fully initialized yet."+ )+ logger.info(+ "This is expected during the initial VM setup - will continue polling..."+ )else:# Don't repeat the exact same error message each time- logger.warning(f"API request error (attempt {attempt+1}): {error_msg}")+ logger.warning(+ f"API request error (attempt {attempt+1}): {error_msg}"+ )# Just log that we're still working on itif attempt > 3:- logger.debug("Still waiting for the API server to become available...")-+ logger.debug(+ "Still waiting for the API server to become available..."+ )+# If we're getting errors but container is running, that's normal during startup- if vm_status.get('status') == 'running':+ if vm_status.get("status") == "running":if not vm_running:- logger.info("Container is running, waiting for the VM within it to become fully ready...")+ logger.info(+ "Container is running, waiting for the VM within it to become fully ready..."+ )logger.info("This might take a minute while the VM initializes...")vm_running = True-+# Increase counter and continueattempt += 1continue-+# Reset consecutive error counter when we get a successful responseconsecutive_errors = 0-+# If the VM is running, check if it has an IP address (which means it's fully ready)- if vm_status.get('status') == 'running':+ if vm_status.get("status") == "running":vm_running = True-+# Check if we have an IP address, which means the VM is fully ready- if 'ip_address' in vm_status and vm_status['ip_address']:- logger.info(f"VM is now fully running with IP: {vm_status.get('ip_address')}")- if 'vnc_url' in vm_status and vm_status['vnc_url']:+ if "ip_address" in vm_status and vm_status["ip_address"]:+ logger.info(+ f"VM is now fully running with IP: {vm_status.get('ip_address')}"+ )+ if "vnc_url" in vm_status and vm_status["vnc_url"]:logger.info(f"VNC URL: {vm_status.get('vnc_url')}")return vm_statuselse:- logger.debug("VM is running but still initializing network interfaces...")+ logger.debug(+ "VM is running but still initializing network interfaces..."+ )logger.debug("Waiting for IP address to be assigned...")else:# VM exists but might still be starting up- status = vm_status.get('status', 'unknown')+ status = vm_status.get("status", "unknown")logger.debug(f"VM found but status is: {status}. Continuing to poll...")-+# Increase counter for next iteration's delay calculationattempt += 1-+# If we reach a very large number of attempts, give a reassuring message but continueif attempt % 10 == 0:- logger.debug(f"Still waiting after {attempt} attempts. This might take several minutes for first-time setup.")+ logger.debug(+ f"Still waiting after {attempt} attempts. This might take several minutes for first-time setup."+ )if not vm_running and attempt >= 20:- logger.warning("\nNOTE: First-time VM initialization can be slow as images are downloaded.")- logger.warning("If this continues for more than 10 minutes, you may want to check:")+ logger.warning(+ "\nNOTE: First-time VM initialization can be slow as images are downloaded."+ )+ logger.warning(+ "If this continues for more than 10 minutes, you may want to check:"+ )logger.warning(" 1. Docker logs with: docker logs " + name)logger.warning(" 2. If your network can access container registries")logger.warning("Press Ctrl+C to abort if needed.\n")-+# After 150 attempts (likely over 30-40 minutes), return current statusif attempt >= 150:- logger.debug(f"Reached 150 polling attempts. VM status is: {vm_status.get('status', 'unknown')}")- logger.debug("Returning current VM status, but please check Docker logs if there are issues.")+ logger.debug(+ f"Reached 150 polling attempts. VM status is: {vm_status.get('status', 'unknown')}"+ )+ logger.debug(+ "Returning current VM status, but please check Docker logs if there are issues."+ )return vm_status-+except Exception as e:# Always continue retrying, but with increasing delays- logger.warning(f"Error checking VM status (attempt {attempt+1}): {e}. Will retry.")+ logger.warning(+ f"Error checking VM status (attempt {attempt+1}): {e}. Will retry."+ )consecutive_errors += 1-+# If we've had too many consecutive errors, might be a deeper problemif consecutive_errors >= 10:- logger.warning(f"\nWARNING: Encountered {consecutive_errors} consecutive errors while checking VM status.")- logger.warning("You may need to check the Docker container logs or restart the process.")+ logger.warning(+ f"\nWARNING: Encountered {consecutive_errors} consecutive errors while checking VM status."+ )+ logger.warning(+ "You may need to check the Docker container logs or restart the process."+ )logger.warning(f"Error details: {str(e)}\n")-+# Increase attempt counter for next iterationattempt += 1-+# After many consecutive errors, add a delay to avoid hammering the systemif attempt > 5:error_delay = min(30, 10 + attempt)- logger.warning(f"Multiple connection errors, waiting {error_delay}s before next attempt...")+ logger.warning(+ f"Multiple connection errors, waiting {error_delay}s before next attempt..."+ )await asyncio.sleep(error_delay)-+except subprocess.CalledProcessError as e:- error_msg = f"Failed to start Lumier container: {e.stderr if hasattr(e, 'stderr') else str(e)}"+ error_msg = (+ f"Failed to start Lumier container: {e.stderr if hasattr(e, 'stderr') else str(e)}"+ )logger.error(error_msg)raise RuntimeError(error_msg)-+async def _wait_for_container_ready(self, container_name: str, timeout: int = 90) -> bool:"""Wait for the Lumier container to be fully ready with a valid API response.-+Args:container_name: Name of the Docker container to checktimeout: Maximum time to wait in seconds (default: 90 seconds)-+Returns:True if the container is running, even if API is not fully ready.This allows operations to continue with appropriate fallbacks.@@ -567,21 +634,32 @@ class LumierProvider(BaseVMProvider):start_time = time.time()api_ready = Falsecontainer_running = False-+logger.debug(f"Waiting for container {container_name} to be ready (timeout: {timeout}s)...")-+while time.time() - start_time < timeout:# Check if container is runningtry:- check_cmd = ["docker", "ps", "--filter", f"name={container_name}", "--format", "{{.Status}}"]+ check_cmd = [+ "docker",+ "ps",+ "--filter",+ f"name={container_name}",+ "--format",+ "{{.Status}}",+ ]result = subprocess.run(check_cmd, capture_output=True, text=True, check=True)container_status = result.stdout.strip()-+if container_status and container_status.startswith("Up"):container_running = True- logger.info(f"Container {container_name} is running with status: {container_status}")+ logger.info(+ f"Container {container_name} is running with status: {container_status}"+ )else:- logger.warning(f"Container {container_name} not yet running, status: {container_status}")+ logger.warning(+ f"Container {container_name} not yet running, status: {container_status}"+ )# container is not running yet, wait and try againawait asyncio.sleep(2) # Longer sleep to give Docker timecontinue@@ -589,17 +667,17 @@ class LumierProvider(BaseVMProvider):logger.warning(f"Error checking container status: {e}")await asyncio.sleep(2)continue-+# Container is running, check if API is responsivetry:# First check the health endpointapi_url = f"http://{self.host}:{self.api_port}/health"logger.info(f"Checking API health at: {api_url}")-+# Use longer timeout for API health check since it may still be initializingcurl_cmd = ["curl", "-s", "--connect-timeout", "5", "--max-time", "10", api_url]result = subprocess.run(curl_cmd, capture_output=True, text=True)-+if result.returncode == 0 and "ok" in result.stdout.lower():api_ready = Truelogger.info(f"API is ready at {api_url}")@@ -610,12 +688,21 @@ class LumierProvider(BaseVMProvider):vm_api_url = f"http://{self.host}:{self.api_port}/lume/vms/{container_name}"if self.storage:import urllib.parse+encoded_storage = urllib.parse.quote_plus(self.storage)vm_api_url += f"?storage={encoded_storage}"-- curl_vm_cmd = ["curl", "-s", "--connect-timeout", "5", "--max-time", "10", vm_api_url]++ curl_vm_cmd = [+ "curl",+ "-s",+ "--connect-timeout",+ "5",+ "--max-time",+ "10",+ vm_api_url,+ ]vm_result = subprocess.run(curl_vm_cmd, capture_output=True, text=True)-+if vm_result.returncode == 0 and vm_result.stdout.strip():# VM API responded with something - consider the API readyapi_ready = True@@ -625,7 +712,7 @@ class LumierProvider(BaseVMProvider):curl_code = result.returncodeif curl_code == 0:curl_code = vm_result.returncode-+# Map common curl error codes to helpful messagesif curl_code == 7:curl_error = "Failed to connect - API server is starting up"@@ -639,29 +726,37 @@ class LumierProvider(BaseVMProvider):curl_error = "Network problem during data transfer"else:curl_error = f"Unknown curl error code: {curl_code}"-+logger.info(f"API not ready yet: {curl_error}")except subprocess.SubprocessError as e:logger.warning(f"Error checking API status: {e}")-+# If the container is running but API is not ready, that's OK - we'll just wait# a bit longer before checking again, as the container may still be initializingelapsed_seconds = time.time() - start_time- if int(elapsed_seconds) % 5 == 0: # Only print status every 5 seconds to reduce verbosity- logger.debug(f"Waiting for API to initialize... ({elapsed_seconds:.1f}s / {timeout}s)")-+ if (+ int(elapsed_seconds) % 5 == 0+ ): # Only print status every 5 seconds to reduce verbosity+ logger.debug(+ f"Waiting for API to initialize... ({elapsed_seconds:.1f}s / {timeout}s)"+ )+await asyncio.sleep(3) # Longer sleep between API checks-+# Handle timeout - if the container is running but API is not ready, that's not# necessarily an error - the API might just need more time to start upif not container_running:logger.warning(f"Timed out waiting for container {container_name} to start")return False-+if not api_ready:- logger.warning(f"Container {container_name} is running, but API is not fully ready yet.")- logger.warning(f"NOTE: You may see some 'API request failed' messages while the API initializes.")-+ logger.warning(+ f"Container {container_name} is running, but API is not fully ready yet."+ )+ logger.warning(+ "NOTE: You may see some 'API request failed' messages while the API initializes."+ )+# Return True if container is running, even if API isn't ready yet# This allows VM operations to proceed, with appropriate retries for API callsreturn container_running@@ -670,12 +765,12 @@ class LumierProvider(BaseVMProvider):"""Stop a running VM by stopping the Lumier container."""try:# Use Docker commands to stop the container directly- if hasattr(self, '_container_id') and self._container_id:+ if hasattr(self, "_container_id") and self._container_id:logger.info(f"Stopping Lumier container: {self.container_name}")cmd = ["docker", "stop", self.container_name]result = subprocess.run(cmd, capture_output=True, text=True, check=True)logger.info(f"Container stopped: {result.stdout.strip()}")-+# Return minimal status inforeturn {"name": name,@@ -684,16 +779,24 @@ class LumierProvider(BaseVMProvider):}else:# Try to find the container by name- check_cmd = ["docker", "ps", "-a", "--filter", f"name={self.container_name}", "--format", "{{.ID}}"]+ check_cmd = [+ "docker",+ "ps",+ "-a",+ "--filter",+ f"name={self.container_name}",+ "--format",+ "{{.ID}}",+ ]check_result = subprocess.run(check_cmd, capture_output=True, text=True)container_id = check_result.stdout.strip()-+if container_id:logger.info(f"Found container ID: {container_id}")cmd = ["docker", "stop", self.container_name]result = subprocess.run(cmd, capture_output=True, text=True, check=True)logger.info(f"Container stopped: {result.stdout.strip()}")-+return {"name": name,"status": "stopped",@@ -709,26 +812,30 @@ class LumierProvider(BaseVMProvider):error_msg = f"Failed to stop container: {e.stderr if hasattr(e, 'stderr') else str(e)}"logger.error(error_msg)raise RuntimeError(f"Failed to stop Lumier container: {error_msg}")-+# update_vm is not implemented as it's not needed for Lumier# The BaseVMProvider requires it, so we provide a minimal implementation- async def update_vm(self, name: str, update_opts: Dict[str, Any], storage: Optional[str] = None) -> Dict[str, Any]:+ async def update_vm(+ self, name: str, update_opts: Dict[str, Any], storage: Optional[str] = None+ ) -> Dict[str, Any]:"""Not implemented for Lumier provider."""logger.warning("update_vm is not implemented for Lumier provider")return {"name": name, "status": "unchanged"}-- async def get_logs(self, name: str, num_lines: int = 100, follow: bool = False, timeout: Optional[int] = None) -> str:++ async def get_logs(+ self, name: str, num_lines: int = 100, follow: bool = False, timeout: Optional[int] = None+ ) -> str:"""Get the logs from the Lumier container.-+Args:name: Name of the VM/container to get logs fornum_lines: Number of recent log lines to return (default: 100)follow: If True, follow the logs (stream new logs as they are generated)timeout: Optional timeout in seconds for follow mode (None means no timeout)-+Returns:Container logs as a string-+Note:If follow=True, this function will continuously stream logs until timeoutor until interrupted. The output will be printed to console in real-time.@@ -737,16 +844,16 @@ class LumierProvider(BaseVMProvider):error_msg = "Docker is not available. Cannot get container logs."logger.error(error_msg)return error_msg-+# Make sure we have a container namecontainer_name = name-+# Check if the container exists and is runningtry:# Check if the container existsinspect_cmd = ["docker", "container", "inspect", container_name]result = subprocess.run(inspect_cmd, capture_output=True, text=True)-+if result.returncode != 0:error_msg = f"Container '{container_name}' does not exist or is not accessible"logger.error(error_msg)@@ -755,39 +862,43 @@ class LumierProvider(BaseVMProvider):error_msg = f"Error checking container status: {str(e)}"logger.error(error_msg)return error_msg-+# Base docker logs commandlog_cmd = ["docker", "logs"]-+# Add tail parameter to limit the number of lineslog_cmd.extend(["--tail", str(num_lines)])-+# Handle follow mode with or without timeoutif follow:log_cmd.append("--follow")-+if timeout is not None:# For follow mode with timeout, we'll run the command and handle the timeoutlog_cmd.append(container_name)- logger.info(f"Following logs for container '{container_name}' with timeout {timeout}s")+ logger.info(+ f"Following logs for container '{container_name}' with timeout {timeout}s"+ )logger.info(f"\n---- CONTAINER LOGS FOR '{container_name}' (LIVE) ----")- logger.info(f"Press Ctrl+C to stop following logs\n")-+ logger.info("Press Ctrl+C to stop following logs\n")+try:# Run with timeoutprocess = subprocess.Popen(log_cmd, text=True)-+# Wait for the specified timeoutif timeout:try:process.wait(timeout=timeout)except subprocess.TimeoutExpired:process.terminate() # Stop after timeout- logger.info(f"\n---- LOG FOLLOWING STOPPED (timeout {timeout}s reached) ----")+ logger.info(+ f"\n---- LOG FOLLOWING STOPPED (timeout {timeout}s reached) ----"+ )else:# Without timeout, wait for user interruptionprocess.wait()-+return "Logs were displayed to console in follow mode"except KeyboardInterrupt:process.terminate()@@ -798,8 +909,8 @@ class LumierProvider(BaseVMProvider):log_cmd.append(container_name)logger.info(f"Following logs for container '{container_name}' indefinitely")logger.info(f"\n---- CONTAINER LOGS FOR '{container_name}' (LIVE) ----")- logger.info(f"Press Ctrl+C to stop following logs\n")-+ logger.info("Press Ctrl+C to stop following logs\n")+try:# Run the command and let it run until interruptedprocess = subprocess.Popen(log_cmd, text=True)@@ -813,19 +924,21 @@ class LumierProvider(BaseVMProvider):# For non-follow mode, capture and return the logs as a stringlog_cmd.append(container_name)logger.info(f"Getting {num_lines} log lines for container '{container_name}'")-+try:result = subprocess.run(log_cmd, capture_output=True, text=True, check=True)logs = result.stdout-+# Only print header and logs if there's contentif logs.strip():- logger.info(f"\n---- CONTAINER LOGS FOR '{container_name}' (LAST {num_lines} LINES) ----\n")+ logger.info(+ f"\n---- CONTAINER LOGS FOR '{container_name}' (LAST {num_lines} LINES) ----\n"+ )logger.info(logs)- logger.info(f"\n---- END OF LOGS ----")+ logger.info("\n---- END OF LOGS ----")else:logger.info(f"\nNo logs available for container '{container_name}'")-+return logsexcept subprocess.CalledProcessError as e:error_msg = f"Error getting logs: {e.stderr}"@@ -835,48 +948,48 @@ class LumierProvider(BaseVMProvider):error_msg = f"Unexpected error getting logs: {str(e)}"logger.error(error_msg)return error_msg-+async def restart_vm(self, name: str, storage: Optional[str] = None) -> Dict[str, Any]:raise NotImplementedError("LumierProvider does not support restarting VMs.")async def get_ip(self, name: str, storage: Optional[str] = None, retry_delay: int = 2) -> str:"""Get the IP address of a VM, waiting indefinitely until it's available.-+Args:name: Name of the VM to get the IP forstorage: Optional storage path overrideretry_delay: Delay between retries in seconds (default: 2)-+Returns:IP address of the VM when it becomes available"""# Use container_name = name for consistencyself.container_name = name-+# Track total attempts for logging purposestotal_attempts = 0-+# Loop indefinitely until we get a valid IPwhile True:total_attempts += 1-+# Log retry message but not on first attemptif total_attempts > 1:logger.info(f"Waiting for VM {name} IP address (attempt {total_attempts})...")-+try:# Get VM informationvm_info = await self.get_vm(name, storage=storage)-+# Check if we got a valid IPip = vm_info.get("ip_address", None)if ip and ip != "unknown" and not ip.startswith("0.0.0.0"):logger.info(f"Got valid VM IP address: {ip}")return ip-+# Check the VM statusstatus = vm_info.get("status", "unknown")-+# Special handling for Lumier: it may report "stopped" even when the VM is starting# If the VM information contains an IP but status is stopped, it might be a race conditionif status == "stopped" and "ip_address" in vm_info:@@ -891,43 +1004,43 @@ class LumierProvider(BaseVMProvider):# If VM is running but no IP yet, wait and retryelse:logger.info("VM is running but no valid IP address yet. Waiting...")-+except Exception as e:logger.warning(f"Error getting VM {name} IP: {e}, continuing to wait...")-+# Wait before next retryawait asyncio.sleep(retry_delay)-+# Add progress log every 10 attemptsif total_attempts % 10 == 0:logger.info(f"Still waiting for VM {name} IP after {total_attempts} attempts...")-+async def __aenter__(self):"""Async context manager entry.-+This method is called when entering an async context manager block.Returns self to be used in the context."""logger.debug("Entering LumierProvider context")-+# Initialize the API URL with the default value if not already set# This ensures get_vm can work before run_vm is called- if not hasattr(self, '_api_url') or not self._api_url:+ if not hasattr(self, "_api_url") or not self._api_url:self._api_url = f"http://{self.host}:{self.api_port}"logger.info(f"Initialized default Lumier API URL: {self._api_url}")-+return self-+async def __aexit__(self, exc_type, exc_val, exc_tb):"""Async context manager exit.-+This method is called when exiting an async context manager block.It handles proper cleanup of resources, including stopping any running containers."""logger.debug(f"Exiting LumierProvider context, handling exceptions: {exc_type}")try:# If we have a container ID, we should stop it to clean up resources- if hasattr(self, '_container_id') and self._container_id:+ if hasattr(self, "_container_id") and self._container_id:logger.info(f"Stopping Lumier container on context exit: {self.container_name}")try:cmd = ["docker", "stop", self.container_name]diff --git a/libs/python/computer/computer/providers/types.py b/libs/python/computer/computer/providers/types.pyindex 2db44230f2..da9e50c0af 100644--- a/libs/python/computer/computer/providers/types.py+++ b/libs/python/computer/computer/providers/types.py@@ -3,27 +3,30 @@These base types describe the common shape of objects returned by providermethods like `list_vms()`."""+from __future__ import annotations-from typing import Literal, TypedDict, NotRequired+from typing import Literal, NotRequired, TypedDict# Core status values per product docsVMStatus = Literal[- "pending", # VM deployment in progress- "running", # VM is active and accessible- "stopped", # VM is stopped but not terminated- "terminated", # VM has been permanently destroyed- "failed", # VM deployment or operation failed+ "pending", # VM deployment in progress+ "running", # VM is active and accessible+ "stopped", # VM is stopped but not terminated+ "terminated", # VM has been permanently destroyed+ "failed", # VM deployment or operation failed]OSType = Literal["macos", "linux", "windows"]+class MinimalVM(TypedDict):"""Minimal VM object shape returned by list calls.Providers may include additional fields. Optional fields below arecommon extensions some providers expose or that callers may compute."""+name: strstatus: VMStatus# Not always included by all providersdiff --git a/libs/python/computer/computer/providers/winsandbox/__init__.py b/libs/python/computer/computer/providers/winsandbox/__init__.pyindex 715ed7db06..0d08909286 100644--- a/libs/python/computer/computer/providers/winsandbox/__init__.py+++ b/libs/python/computer/computer/providers/winsandbox/__init__.py@@ -2,6 +2,7 @@try:import winsandbox+HAS_WINSANDBOX = Trueexcept ImportError:HAS_WINSANDBOX = Falsediff --git a/libs/python/computer/computer/providers/winsandbox/provider.py b/libs/python/computer/computer/providers/winsandbox/provider.pyindex 1c9aec3cb0..771ec2b46e 100644--- a/libs/python/computer/computer/providers/winsandbox/provider.py+++ b/libs/python/computer/computer/providers/winsandbox/provider.py@@ -1,11 +1,11 @@"""Windows Sandbox VM provider implementation using pywinsandbox."""-import osimport asyncioimport logging+import osimport time-from typing import Dict, Any, Optional, Listfrom pathlib import Path+from typing import Any, Dict, List, Optionalfrom ..base import BaseVMProvider, VMProviderType@@ -14,6 +14,7 @@ logger = logging.getLogger(__name__)try:import winsandbox+HAS_WINSANDBOX = Trueexcept ImportError:HAS_WINSANDBOX = False@@ -21,13 +22,13 @@ except ImportError:class WinSandboxProvider(BaseVMProvider):"""Windows Sandbox VM provider implementation using pywinsandbox.-+This provider uses Windows Sandbox to create isolated Windows environments.Storage is always ephemeral with Windows Sandbox."""-+def __init__(- self,+ self,port: int = 7777,host: str = "localhost",storage: Optional[str] = None,@@ -35,10 +36,10 @@ class WinSandboxProvider(BaseVMProvider):ephemeral: bool = True, # Windows Sandbox is always ephemeralmemory_mb: int = 4096,networking: bool = True,- **kwargs+ **kwargs,):"""Initialize the Windows Sandbox provider.-+Args:port: Port for the computer server (default: 7777)host: Host to use for connections (default: localhost)@@ -53,41 +54,43 @@ class WinSandboxProvider(BaseVMProvider):"pywinsandbox is required for WinSandboxProvider. ""Please install it with 'pip install pywinsandbox'")-+self.host = hostself.port = portself.verbose = verboseself.memory_mb = memory_mbself.networking = networking-+# Windows Sandbox is always ephemeralif not ephemeral:logger.warning("Windows Sandbox storage is always ephemeral. Ignoring ephemeral=False.")self.ephemeral = True-+# Storage is always ephemeral for Windows Sandboxif storage and storage != "ephemeral":- logger.warning("Windows Sandbox does not support persistent storage. Using ephemeral storage.")+ logger.warning(+ "Windows Sandbox does not support persistent storage. Using ephemeral storage."+ )self.storage = "ephemeral"-+self.logger = logging.getLogger(__name__)-+# Track active sandboxesself._active_sandboxes: Dict[str, Any] = {}-+@propertydef provider_type(self) -> VMProviderType:"""Get the provider type."""return VMProviderType.WINSANDBOX-+async def __aenter__(self):"""Enter async context manager."""# Verify Windows Sandbox is availableif not HAS_WINSANDBOX:raise ImportError("pywinsandbox is not available")-+return self-+async def __aexit__(self, exc_type, exc_val, exc_tb):"""Exit async context manager."""# Clean up any active sandboxes@@ -97,29 +100,24 @@ class WinSandboxProvider(BaseVMProvider):self.logger.info(f"Terminated sandbox: {name}")except Exception as e:self.logger.error(f"Error terminating sandbox {name}: {e}")-+self._active_sandboxes.clear()-+async def get_vm(self, name: str, storage: Optional[str] = None) -> Dict[str, Any]:"""Get VM information by name.-+Args:name: Name of the VM to get information forstorage: Ignored for Windows Sandbox (always ephemeral)-+Returns:Dictionary with VM information including status, IP address, etc."""if name not in self._active_sandboxes:- return {- "name": name,- "status": "stopped",- "ip_address": None,- "storage": "ephemeral"- }-+ return {"name": name, "status": "stopped", "ip_address": None, "storage": "ephemeral"}+sandbox = self._active_sandboxes[name]-+# Check if sandbox is still runningtry:# Try to ping the sandbox to see if it's responsive@@ -128,7 +126,7 @@ class WinSandboxProvider(BaseVMProvider):sandbox_responsive = Trueexcept Exception:sandbox_responsive = False-+if not sandbox_responsive:return {"name": name,@@ -136,33 +134,36 @@ class WinSandboxProvider(BaseVMProvider):"ip_address": None,"storage": "ephemeral","memory_mb": self.memory_mb,- "networking": self.networking+ "networking": self.networking,}-+# Check for computer server address file- server_address_file = r"C:\Users\WDAGUtilityAccount\Desktop\shared_windows_sandbox_dir\server_address"-+ server_address_file = (+ r"C:\Users\WDAGUtilityAccount\Desktop\shared_windows_sandbox_dir\server_address"+ )+try:# Check if the server address file existsfile_exists = sandbox.rpyc.modules.os.path.exists(server_address_file)-+if file_exists:# Read the server address file- with sandbox.rpyc.builtin.open(server_address_file, 'r') as f:+ with sandbox.rpyc.builtin.open(server_address_file, "r") as f:server_address = f.read().strip()-- if server_address and ':' in server_address:++ if server_address and ":" in server_address:# Parse IP:port from the file- ip_address, port = server_address.split(':', 1)-+ ip_address, port = server_address.split(":", 1)+# Verify the server is actually respondingtry:import socket+sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)sock.settimeout(3)result = sock.connect_ex((ip_address, int(port)))sock.close()-+if result == 0:# Server is respondingstatus = "running"@@ -183,26 +184,26 @@ class WinSandboxProvider(BaseVMProvider):# Server address file doesn't exist yetstatus = "starting"ip_address = None-+except Exception as e:self.logger.debug(f"Error checking server address file: {e}")status = "starting"ip_address = None-+except Exception as e:self.logger.error(f"Error checking sandbox status: {e}")status = "error"ip_address = None-+return {"name": name,"status": status,"ip_address": ip_address,"storage": "ephemeral","memory_mb": self.memory_mb,- "networking": self.networking+ "networking": self.networking,}-+async def list_vms(self) -> List[Dict[str, Any]]:"""List all available VMs."""vms = []@@ -210,25 +211,24 @@ class WinSandboxProvider(BaseVMProvider):vm_info = await self.get_vm(name)vms.append(vm_info)return vms-- async def run_vm(self, image: str, name: str, run_opts: Dict[str, Any], storage: Optional[str] = None) -> Dict[str, Any]:++ async def run_vm(+ self, image: str, name: str, run_opts: Dict[str, Any], storage: Optional[str] = None+ ) -> Dict[str, Any]:"""Run a VM with the given options.-+Args:image: Image name (ignored for Windows Sandbox - always uses host Windows)name: Name of the VM to runrun_opts: Dictionary of run options (memory, cpu, etc.)storage: Ignored for Windows Sandbox (always ephemeral)-+Returns:Dictionary with VM run status and information"""if name in self._active_sandboxes:- return {- "success": False,- "error": f"Sandbox {name} is already running"- }-+ return {"success": False, "error": f"Sandbox {name} is already running"}+try:# Extract options from run_optsmemory_mb = run_opts.get("memory_mb", self.memory_mb)@@ -240,9 +240,9 @@ class WinSandboxProvider(BaseVMProvider):memory_mb = int(memory_mb[:-2])else:memory_mb = self.memory_mb-+networking = run_opts.get("networking", self.networking)-+# Create folder mappers; always map a persistent venv directory on host for caching packagesfolder_mappers = []# Ensure host side persistent venv directory exists (Path.home()/wsb_venv)@@ -260,7 +260,7 @@ class WinSandboxProvider(BaseVMProvider):host_path = shared_direlse:continue-+if host_path and os.path.exists(host_path):folder_mappers.append(winsandbox.FolderMapper(host_path))@@ -272,182 +272,185 @@ class WinSandboxProvider(BaseVMProvider):)except Exception as e:self.logger.warning(f"Failed to map host winsandbox_venv: {e}")-+self.logger.info(f"Creating Windows Sandbox: {name}")self.logger.info(f"Memory: {memory_mb}MB, Networking: {networking}")if folder_mappers:self.logger.info(f"Shared directories: {len(folder_mappers)}")-+# Create the sandbox without logon scripttry:# Try with memory_mb parameter (newer pywinsandbox version)sandbox = winsandbox.new_sandbox(- memory_mb=str(memory_mb),- networking=networking,- folder_mappers=folder_mappers+ memory_mb=str(memory_mb), networking=networking, folder_mappers=folder_mappers)except TypeError as e:if "memory_mb" in str(e):# Fallback for older pywinsandbox version that doesn't support memory_mbself.logger.warning(- f"Your pywinsandbox version doesn't support memory_mb parameter. "- f"Using default memory settings. To use custom memory settings, "- f"please update pywinsandbox: pip install -U git+https://github.com/karkason/pywinsandbox.git"+ "Your pywinsandbox version doesn't support memory_mb parameter. "+ "Using default memory settings. To use custom memory settings, "+ "please update pywinsandbox: pip install -U git+https://github.com/karkason/pywinsandbox.git")sandbox = winsandbox.new_sandbox(- networking=networking,- folder_mappers=folder_mappers+ networking=networking, folder_mappers=folder_mappers)else:# Re-raise if it's a different TypeErrorraise-+# Store the sandboxself._active_sandboxes[name] = sandbox-+self.logger.info(f"Windows Sandbox {name} created successfully")-- venv_exists = (host_wsb_env / "venv" / "Lib" / "site-packages" / "computer_server").exists() if host_wsb_env else False++ venv_exists = (+ (host_wsb_env / "venv" / "Lib" / "site-packages" / "computer_server").exists()+ if host_wsb_env+ else False+ )# Setup the computer server in the sandboxawait self._setup_computer_server(sandbox, name, wait_for_venv=(not venv_exists))-+return {"success": True,"name": name,"status": "starting","memory_mb": memory_mb,"networking": networking,- "storage": "ephemeral"+ "storage": "ephemeral",}-+except Exception as e:self.logger.error(f"Failed to create Windows Sandbox {name}: {e}")# stack traceimport traceback+self.logger.error(f"Stack trace: {traceback.format_exc()}")- return {- "success": False,- "error": f"Failed to create sandbox: {str(e)}"- }-+ return {"success": False, "error": f"Failed to create sandbox: {str(e)}"}+async def stop_vm(self, name: str, storage: Optional[str] = None) -> Dict[str, Any]:"""Stop a running VM.-+Args:name: Name of the VM to stopstorage: Ignored for Windows Sandbox-+Returns:Dictionary with stop status and information"""if name not in self._active_sandboxes:- return {- "success": False,- "error": f"Sandbox {name} is not running"- }-+ return {"success": False, "error": f"Sandbox {name} is not running"}+try:sandbox = self._active_sandboxes[name]-+# Terminate the sandboxsandbox.shutdown()-+# Remove from active sandboxesdel self._active_sandboxes[name]-+self.logger.info(f"Windows Sandbox {name} stopped successfully")-- return {- "success": True,- "name": name,- "status": "stopped"- }-++ return {"success": True, "name": name, "status": "stopped"}+except Exception as e:self.logger.error(f"Failed to stop Windows Sandbox {name}: {e}")- return {- "success": False,- "error": f"Failed to stop sandbox: {str(e)}"- }-- async def update_vm(self, name: str, update_opts: Dict[str, Any], storage: Optional[str] = None) -> Dict[str, Any]:+ return {"success": False, "error": f"Failed to stop sandbox: {str(e)}"}++ async def update_vm(+ self, name: str, update_opts: Dict[str, Any], storage: Optional[str] = None+ ) -> Dict[str, Any]:"""Update VM configuration.-+Note: Windows Sandbox does not support runtime configuration updates.The sandbox must be stopped and restarted with new configuration.-+Args:name: Name of the VM to updateupdate_opts: Dictionary of update optionsstorage: Ignored for Windows Sandbox-+Returns:Dictionary with update status and information"""return {"success": False,"error": "Windows Sandbox does not support runtime configuration updates. "- "Please stop and restart the sandbox with new configuration."+ "Please stop and restart the sandbox with new configuration.",}async def restart_vm(self, name: str, storage: Optional[str] = None) -> Dict[str, Any]:raise NotImplementedError("WinSandboxProvider does not support restarting VMs.")-+async def get_ip(self, name: str, storage: Optional[str] = None, retry_delay: int = 2) -> str:"""Get the IP address of a VM, waiting indefinitely until it's available.-+Args:name: Name of the VM to get the IP forstorage: Ignored for Windows Sandboxretry_delay: Delay between retries in seconds (default: 2)-+Returns:IP address of the VM when it becomes available"""total_attempts = 0-+# Loop indefinitely until we get a valid IPwhile True:total_attempts += 1-+# Log retry message but not on first attemptif total_attempts > 1:- self.logger.info(f"Waiting for Windows Sandbox {name} IP address (attempt {total_attempts})...")-+ self.logger.info(+ f"Waiting for Windows Sandbox {name} IP address (attempt {total_attempts})..."+ )+try:# Get VM informationvm_info = await self.get_vm(name, storage=storage)-+# Check if we got a valid IPip = vm_info.get("ip_address", None)if ip and ip != "unknown" and not ip.startswith("0.0.0.0"):self.logger.info(f"Got valid Windows Sandbox IP address: {ip}")return ip-+# Check the VM statusstatus = vm_info.get("status", "unknown")-+# If VM is not running yet, log and waitif status != "running":- self.logger.info(f"Windows Sandbox is not running yet (status: {status}). Waiting...")+ self.logger.info(+ f"Windows Sandbox is not running yet (status: {status}). Waiting..."+ )# If VM is running but no IP yet, wait and retryelse:- self.logger.info("Windows Sandbox is running but no valid IP address yet. Waiting...")-+ self.logger.info(+ "Windows Sandbox is running but no valid IP address yet. Waiting..."+ )+except Exception as e:- self.logger.warning(f"Error getting Windows Sandbox {name} IP: {e}, continuing to wait...")-+ self.logger.warning(+ f"Error getting Windows Sandbox {name} IP: {e}, continuing to wait..."+ )+# Wait before next retryawait asyncio.sleep(retry_delay)-+# Add progress log every 10 attemptsif total_attempts % 10 == 0:- self.logger.info(f"Still waiting for Windows Sandbox {name} IP after {total_attempts} attempts...")-- async def _setup_computer_server(self, sandbox, name: str, visible: bool = False, wait_for_venv: bool = True):+ self.logger.info(+ f"Still waiting for Windows Sandbox {name} IP after {total_attempts} attempts..."+ )++ async def _setup_computer_server(+ self, sandbox, name: str, visible: bool = False, wait_for_venv: bool = True+ ):"""Setup the computer server in the Windows Sandbox using RPyC.-+Args:sandbox: The Windows Sandbox instancename: Name of the sandbox@@ -458,52 +461,58 @@ class WinSandboxProvider(BaseVMProvider):# Read the PowerShell setup scriptscript_path = os.path.join(os.path.dirname(__file__), "setup_script.ps1")- with open(script_path, 'r', encoding='utf-8') as f:+ with open(script_path, "r", encoding="utf-8") as f:setup_script_content = f.read()-+# Write the setup script to the sandbox using RPyCscript_dest_path = r"C:\Users\WDAGUtilityAccount\setup_cua.ps1"-+self.logger.info(f"Writing setup script to {script_dest_path}")- with sandbox.rpyc.builtin.open(script_dest_path, 'w') as f:+ with sandbox.rpyc.builtin.open(script_dest_path, "w") as f:f.write(setup_script_content)-+# Execute the PowerShell script in the backgroundself.logger.info("Executing setup script in sandbox...")-+# Use subprocess to run PowerShell scriptimport subprocess+powershell_cmd = [- "powershell.exe",- "-ExecutionPolicy", "Bypass",+ "powershell.exe",+ "-ExecutionPolicy",+ "Bypass","-NoExit", # Keep window open after script completes- "-File", script_dest_path+ "-File",+ script_dest_path,]-+# Set creation flags based on visibility preferenceif visible:# CREATE_NEW_CONSOLE - creates a new console window (visible)creation_flags = 0x00000010else:- creation_flags = 0x08000000 # CREATE_NO_WINDOW-+ creation_flags = 0x08000000 # CREATE_NO_WINDOW+# Start the process using RPyCprocess = sandbox.rpyc.modules.subprocess.Popen(- powershell_cmd,- creationflags=creation_flags,- shell=False+ powershell_cmd, creationflags=creation_flags, shell=False)if wait_for_venv:- print("Waiting for venv to be created for the first time setup of Windows Sandbox...")+ print(+ "Waiting for venv to be created for the first time setup of Windows Sandbox..."+ )print("This may take a minute...")await asyncio.sleep(120)-+ip = await self.get_ip(name)self.logger.info(f"Sandbox IP: {ip}")- self.logger.info(f"Setup script started in background in sandbox {name} with PID: {process.pid}")-+ self.logger.info(+ f"Setup script started in background in sandbox {name} with PID: {process.pid}"+ )+except Exception as e:self.logger.error(f"Failed to setup computer server in sandbox {name}: {e}")import traceback+self.logger.error(f"Stack trace: {traceback.format_exc()}")diff --git a/libs/python/computer/computer/ui/gradio/__init__.py b/libs/python/computer/computer/ui/gradio/__init__.pyindex 3645348ea7..62bbaf801a 100644--- a/libs/python/computer/computer/ui/gradio/__init__.py+++ b/libs/python/computer/computer/ui/gradio/__init__.py@@ -1,6 +1,7 @@"""Gradio UI for Computer UI."""-import gradio as grfrom typing import Optional+import gradio as gr+from .app import create_gradio_uidiff --git a/libs/python/computer/computer/ui/gradio/app.py b/libs/python/computer/computer/ui/gradio/app.pyindex d8c5c513e7..a297302c5d 100644--- a/libs/python/computer/computer/ui/gradio/app.py+++ b/libs/python/computer/computer/ui/gradio/app.py@@ -4,91 +4,171 @@ Advanced Gradio UI for Computer InterfaceThis is a Gradio interface for the Computer Interface"""-import gradio as grimport asyncio+import base64+import glob+import hashlibimport ioimport json-import uuid-import hashlibimport os-import globimport random-import base64+import random as rand+import uuidfrom datetime import datetime-from PIL import Image-from huggingface_hub import DatasetCard, DatasetCardData-from computer import Computer, VMProviderType-from gradio.components import ChatMessage++import datasets+import gradio as grimport pandas as pd+from computer import Computer, VMProviderTypefrom datasets import Dataset, Features, Sequence, concatenate_datasets-import datasets--import random as rand+from gradio.components import ChatMessage+from huggingface_hub import DatasetCard, DatasetCardData+from PIL import Image# Task examples as dictionaries with task string and setup functionTASK_EXAMPLES = [{"task": "Open the shopping list on my desktop and add all the items to a Doordash cart",- "setup": lambda computer: create_shopping_list_file(computer)- },+ "setup": lambda computer: create_shopping_list_file(computer),+ },{"task": "Do a random miniwob++ task, output the task name in <task> </task> tags and your reward in <reward> </reward> tags"- }+ },]+# Generate random shopping list and save to desktop using computer interfaceasync def create_shopping_list_file(computer):- items = ["Milk", "Eggs", "Bread", "Apples", "Bananas", "Chicken", "Rice",- "Cereal", "Coffee", "Cheese", "Pasta", "Tomatoes", "Potatoes",- "Onions", "Carrots", "Ice Cream", "Yogurt", "Cookies"]-+ items = [+ "Milk",+ "Eggs",+ "Bread",+ "Apples",+ "Bananas",+ "Chicken",+ "Rice",+ "Cereal",+ "Coffee",+ "Cheese",+ "Pasta",+ "Tomatoes",+ "Potatoes",+ "Onions",+ "Carrots",+ "Ice Cream",+ "Yogurt",+ "Cookies",+ ]+# Select 1-5 random itemsnum_items = rand.randint(1, 5)selected_items = rand.sample(items, num_items)-+# Create shopping list contentcontent = "SHOPPING LIST:\n\n"for item in selected_items:content += f"- {item}\n"-+# Create a temporary file with the contenttemp_file_path = "/tmp/shopping_list.txt"-+# Use run_command to create the file on the desktopdesktop_path = "~/Desktop"file_path = f"{desktop_path}/shopping_list.txt"-+# Create the file using echo commandcmd = f"echo '{content}' > {file_path}"stdout, stderr = await computer.interface.run_command(cmd)-+print(f"Created shopping list at {file_path} with {num_items} items")if stderr:print(f"Error: {stderr}")-+return file_path++import typing+# Load valid keys from the Key enum in models.pyfrom computer.interface.models import Key-import typing-VALID_KEYS = [key.value for key in Key] + [- 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm',- 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z',- '0', '1', '2', '3', '4', '5', '6', '7', '8', '9'++VALID_KEYS = [key.value for key in Key] + [+ "a",+ "b",+ "c",+ "d",+ "e",+ "f",+ "g",+ "h",+ "i",+ "j",+ "k",+ "l",+ "m",+ "n",+ "o",+ "p",+ "q",+ "r",+ "s",+ "t",+ "u",+ "v",+ "w",+ "x",+ "y",+ "z",+ "0",+ "1",+ "2",+ "3",+ "4",+ "5",+ "6",+ "7",+ "8",+ "9",]-VALID_KEYS = list(dict.fromkeys(VALID_KEYS)) # remove duplicates, preserve order+VALID_KEYS = list(dict.fromkeys(VALID_KEYS)) # remove duplicates, preserve order# List of random words for demo naming-RANDOM_WORDS = ["apple", "banana", "cherry", "dolphin", "elephant", "forest",- "giraffe", "harmony", "igloo", "jungle", "kangaroo", "lemon",- "mountain", "notebook", "ocean", "penguin", "quasar", "rainbow", "ohana",- "sunflower", "tiger", "umbrella", "volcano", "waterfall", "xylophone",- "yellow", "zebra"]+RANDOM_WORDS = [+ "apple",+ "banana",+ "cherry",+ "dolphin",+ "elephant",+ "forest",+ "giraffe",+ "harmony",+ "igloo",+ "jungle",+ "kangaroo",+ "lemon",+ "mountain",+ "notebook",+ "ocean",+ "penguin",+ "quasar",+ "rainbow",+ "ohana",+ "sunflower",+ "tiger",+ "umbrella",+ "volcano",+ "waterfall",+ "xylophone",+ "yellow",+ "zebra",+]+# Generate a random demo name with 3 wordsdef generate_random_demo_name():return " ".join(random.sample(RANDOM_WORDS, 3))+# Global session ID for tracking this runsession_id = str(uuid.uuid4())@@ -105,101 +185,108 @@ screenshot_images = [] # Array to store all screenshot imagesOUTPUT_DIR = "examples/output"SESSION_DIR = os.path.join(OUTPUT_DIR, "sessions")+def load_all_sessions(with_images=False):"""Load and concatenate all session datasets into a single Dataset"""try:# Get all session foldersif not os.path.exists(SESSION_DIR):return None-+session_folders = glob.glob(os.path.join(SESSION_DIR, "*"))if not session_folders:return None-+# Load each dataset and concatenateall_datasets = []for folder in session_folders:try:ds = Dataset.load_from_disk(folder)if not with_images:- ds = ds.remove_columns('images')-+ ds = ds.remove_columns("images")+# Add folder name to identify the sourcefolder_name = os.path.basename(folder)-+# Process the messages from tool_call_logsdef process_messages(example):messages_text = []current_role = None-+# Process the logs if they exist in the example- if 'tool_calls' in example:+ if "tool_calls" in example:# Use the existing get_chatbot_messages function with explicit logs parameter- formatted_msgs = get_chatbot_messages(logs=json.loads(example['tool_calls']))-+ formatted_msgs = get_chatbot_messages(+ logs=json.loads(example["tool_calls"])+ )+# Process each ChatMessage and extract either title or contentfor msg in formatted_msgs:# Check if role has changedif msg.role != current_role:# Add a line with the new role if it changedif current_role is not None: # Skip for the first message- messages_text.append("") # Add an empty line between role changes+ messages_text.append(+ ""+ ) # Add an empty line between role changesmessages_text.append(f"{msg.role}")current_role = msg.role-+# Add the message content- if msg.metadata and 'title' in msg.metadata:+ if msg.metadata and "title" in msg.metadata:# Use the title if available- messages_text.append(msg.metadata['title'])+ messages_text.append(msg.metadata["title"])else:# Use just the content without role prefix since we're adding role headersmessages_text.append(msg.content)-+# Join all messages with newlinesall_messages = "\n".join(messages_text)-+return {**example,"source_folder": folder_name,"messages": all_messages,}-+# Apply the processing to each exampleds = ds.map(process_messages)all_datasets.append(ds)except Exception as e:print(f"Error loading dataset from {folder}: {str(e)}")-+if not all_datasets:return None-+# Concatenate all datasetsreturn concatenate_datasets(all_datasets)except Exception as e:print(f"Error loading sessions: {str(e)}")return None+def get_existing_tags():"""Extract all existing tags from saved demonstrations"""all_sessions = load_all_sessions()if all_sessions is None:return [], []-+# Convert to pandas and extract tagsdf = all_sessions.to_pandas()-- if 'tags' not in df.columns:++ if "tags" not in df.columns:return []-+# Extract all tags and flatten the listall_tags = []- for tags in df['tags'].dropna():+ for tags in df["tags"].dropna():all_tags += list(tags)-+# Remove duplicates and sortunique_tags = sorted(list(set(all_tags)))return unique_tags, unique_tags+def get_sessions_data():"""Load all sessions dataset"""@@ -207,21 +294,22 @@ def get_sessions_data():if combined_ds:# Convert to pandas and select columnsdf = combined_ds.to_pandas()- columns = ['name', 'messages', 'source_folder']- if 'tags' in df.columns:- columns.append('tags')+ columns = ["name", "messages", "source_folder"]+ if "tags" in df.columns:+ columns.append("tags")return df[columns]else:return pd.DataFrame({"name": [""], "messages": [""], "source_folder": [""]})+def upload_to_huggingface(dataset_name, visibility, filter_tags=None):"""Upload sessions to HuggingFace Datasets Hub, optionally filtered by tags-+Args:dataset_name: Name of the dataset on HuggingFace (format: username/dataset-name)visibility: 'public' or 'private'filter_tags: List of tags to filter by (optional)-+Returns:Status message"""@@ -230,35 +318,35 @@ def upload_to_huggingface(dataset_name, visibility, filter_tags=None):hf_token = os.environ.get("HF_TOKEN")if not hf_token:return "Error: HF_TOKEN environment variable not found. Please set it before uploading."-+# Check if dataset name is in the correct formatif not dataset_name or "/" not in dataset_name:return "Dataset name must be in the format 'username/dataset-name'"-+# Load all sessionscombined_ds = load_all_sessions(with_images=True)if combined_ds is None or len(combined_ds) == 0:return "No sessions found to upload."-+# If tag filtering is provided, filter the datasetsif filter_tags:# Convert to pandas to filterdf = combined_ds.to_pandas()-- if 'tags' not in df.columns:++ if "tags" not in df.columns:return "No sessions with tags found to filter."-+# Get list of source folders for sessions that have any of the selected tagsmatching_folders = []for _, row in df.iterrows():- if not len(row.get('tags')):+ if not len(row.get("tags")):continue- if any(tag in list(row.get('tags', [])) for tag in filter_tags):- matching_folders.append(row['source_folder'])-+ if any(tag in list(row.get("tags", [])) for tag in filter_tags):+ matching_folders.append(row["source_folder"])+if not matching_folders:return "No sessions matched the selected tag filters."-+# Load only the matching datasetsfiltered_datasets = []for folder in matching_folders:@@ -269,10 +357,10 @@ def upload_to_huggingface(dataset_name, visibility, filter_tags=None):filtered_datasets.append(ds)except Exception as e:print(f"Error loading dataset from {folder}: {str(e)}")-+if not len(filtered_datasets):return "Error loading the filtered sessions."-+# Create a new combined dataset with just the filtered sessionsupload_ds = concatenate_datasets(filtered_datasets)session_count = len(upload_ds)@@ -280,57 +368,52 @@ def upload_to_huggingface(dataset_name, visibility, filter_tags=None):# Use all sessionsupload_ds = combined_dssession_count = len(upload_ds)-- tags = ['cua']++ tags = ["cua"]if isinstance(filter_tags, list):tags += filter_tags-+# Push to HuggingFaceupload_ds.push_to_hub(dataset_name,private=visibility == "private",token=hf_token,- commit_message="(Built with github.com/trycua/cua)"+ commit_message="(Built with github.com/trycua/cua)",)-+# Create dataset cardcard_data = DatasetCardData(- language='en',- license='mit',- task_categories=['visual-question-answering'],- tags=tags+ language="en", license="mit", task_categories=["visual-question-answering"], tags=tags)card = DatasetCard.from_template(card_data=card_data,- template_str="---\n{{ card_data }}\n---\n\n# Uploaded computer interface trajectories\n\nThese trajectories were generated and uploaded using [cua](https://github.com/trycua/cua)"+ template_str="---\n{{ card_data }}\n---\n\n# Uploaded computer interface trajectories\n\nThese trajectories were generated and uploaded using [cua](https://github.com/trycua/cua)",)- card.push_to_hub(- dataset_name,- commit_message="Cua dataset card"- )-+ card.push_to_hub(dataset_name, commit_message="Cua dataset card")+return f"Successfully uploaded {session_count} sessions to HuggingFace Datasets Hub at https://huggingface.co/datasets/{dataset_name}"-+except Exception as e:return f"Error uploading to HuggingFace: {str(e)}"+def save_demonstration(log_data, demo_name=None, demo_tags=None):"""Save the current tool call logs as a demonstration file using HuggingFace datasets"""global tool_call_logs, session_id-+if not tool_call_logs:return "No data to save", None-+# Create output directories if they don't existif not os.path.exists(OUTPUT_DIR):os.makedirs(OUTPUT_DIR)if not os.path.exists(SESSION_DIR):os.makedirs(SESSION_DIR)-+# Use default name if none providedif not demo_name or demo_name.strip() == "":demo_name = generate_random_demo_name()-+# Process tagstags = []if demo_tags:@@ -338,66 +421,69 @@ def save_demonstration(log_data, demo_name=None, demo_tags=None):tags = demo_tagselif isinstance(demo_tags, str):# Split by comma if it's a comma-separated string- tags = [tag.strip() for tag in demo_tags.split(',') if tag.strip()]-+ tags = [tag.strip() for tag in demo_tags.split(",") if tag.strip()]+log_time = datetime.now().isoformat()-+def msg_to_dict(msg: ChatMessage):- return {- "role": msg.role,- "content": str(msg.content),- "metadata": dict(msg.metadata)- }-+ return {"role": msg.role, "content": str(msg.content), "metadata": dict(msg.metadata)}+# Create dataset- demonstration_dataset = [{- "timestamp": str(log_time),- "session_id": str(session_id),- "name": str(demo_name),- "tool_calls": json.dumps(tool_call_logs),- "messages": json.dumps([msg_to_dict(msg) for msg in get_chatbot_messages(tool_call_logs)]),- "tags": list(tags),- "images": [Image.open(io.BytesIO(img)) for img in screenshot_images],- }]-+ demonstration_dataset = [+ {+ "timestamp": str(log_time),+ "session_id": str(session_id),+ "name": str(demo_name),+ "tool_calls": json.dumps(tool_call_logs),+ "messages": json.dumps(+ [msg_to_dict(msg) for msg in get_chatbot_messages(tool_call_logs)]+ ),+ "tags": list(tags),+ "images": [Image.open(io.BytesIO(img)) for img in screenshot_images],+ }+ ]+try:# Create a new HuggingFace dataset from the current sessionnew_session_ds = Dataset.from_list(demonstration_dataset,- features=Features({- 'timestamp': datasets.Value('string'),- 'session_id': datasets.Value('string'),- 'name': datasets.Value('string'),- 'tool_calls': datasets.Value('string'),- 'messages': datasets.Value('string'),- 'tags': Sequence(datasets.Value('string')),- 'images': Sequence(datasets.Image()),- })+ features=Features(+ {+ "timestamp": datasets.Value("string"),+ "session_id": datasets.Value("string"),+ "name": datasets.Value("string"),+ "tool_calls": datasets.Value("string"),+ "messages": datasets.Value("string"),+ "tags": Sequence(datasets.Value("string")),+ "images": Sequence(datasets.Image()),+ }+ ),)-+# Create a unique folder name with demonstration name, session ID and timestamptimestamp = datetime.now().strftime("%Y%m%d_%H%M%S")safe_name = demo_name.replace(" ", "_").replace("/", "_").replace("\\", "_")[:50]session_folder = os.path.join(SESSION_DIR, f"{safe_name}_{session_id}_{timestamp}")-+# Create the directory if it doesn't existif not os.path.exists(session_folder):os.makedirs(session_folder)-+# Save the dataset to the unique foldernew_session_ds.save_to_disk(session_folder)-+return f"Session saved to {session_folder}"except Exception as e:return f"Error saving demonstration: {str(e)}"+def log_tool_call(name, action, arguments, result=None):"""Log a tool call with unique IDs and results"""global tool_call_logs-+# Create arguments JSON that includes the actionargs = {"action": action, **arguments}-+# Process result for loggingprocessed_result = {}if result:@@ -417,37 +503,38 @@ def log_tool_call(name, action, arguments, result=None):processed_result[key] = f"<Binary data: MD5 {hash_value}>"else:processed_result[key] = value-+# Create the tool call log entrylog_entry = {"type": "function_call","name": name,"arguments": json.dumps(args),- "result": processed_result if result else None+ "result": processed_result if result else None,}-+# Add to logs and immediately flush by printingtool_call_logs.append(log_entry)print(f"Tool call logged: {json.dumps(log_entry)}")-+return log_entry+async def execute(name, action, arguments):"""Execute a tool call, log it, and return any results"""global computer, last_action, last_screenshot, last_screenshot_before-+last_screenshot_before = last_screenshot-+# Store last action for reasoning boxlast_action = {"name": name, "action": action, "arguments": arguments}-+results = {}-+# Execute the action based on name and actionif name == "computer":if computer is None:return {}-+# Get the method from the computer interfaceif action == "initialize":# Already initialized, just log@@ -505,7 +592,7 @@ async def execute(name, action, arguments):elif action == "done" or action == "fail":# Just a marker, doesn't do anythingpass-+# Add a screenshot to the results for every action (if not already there)if action != "shutdown" and "screenshot" not in results:results["screenshot"] = await computer.interface.screenshot()@@ -515,22 +602,25 @@ async def execute(name, action, arguments):# If requested, take a screenshot after messageif arguments.get("screenshot_after", False) and computer is not None:results["screenshot"] = await computer.interface.screenshot()-+# Log the tool call with resultslog_tool_call(name, action, arguments, results)-+if "screenshot" in results:# Convert bytes to PIL Imagescreenshot_img = Image.open(io.BytesIO(results["screenshot"]))results["screenshot"] = screenshot_img# Update last_screenshot with the new screenshotlast_screenshot = screenshot_img-+return results-async def handle_init_computer(os_choice: str, app_list=None, provider="lume", container_name=None, api_key=None):++async def handle_init_computer(+ os_choice: str, app_list=None, provider="lume", container_name=None, api_key=None+):"""Initialize the computer instance and tools for macOS or Ubuntu or Windows-+Args:os_choice: The OS to use ("macOS" or "Ubuntu" or "Windows")app_list: Optional list of apps to focus on using the app-use experiment@@ -539,14 +629,14 @@ async def handle_init_computer(os_choice: str, app_list=None, provider="lume", capi_key: The API key to use for cloud provider"""global computer, tool_call_logs, tools-+# Check if we should enable app-use experimentuse_app_experiment = app_list and len(app_list) > 0experiments = ["app-use"] if use_app_experiment else None-+# Determine if we should use host computer serveruse_host_computer_server = provider == "self"-+if os_choice == "Ubuntu":os_type_str = "linux"image_str = "ubuntu-noble-vanilla:latest"@@ -556,13 +646,11 @@ async def handle_init_computer(os_choice: str, app_list=None, provider="lume", celse:os_type_str = "macos"image_str = "macos-sequoia-cua:latest"-+# Create computer instance with appropriate configurationif use_host_computer_server:computer = Computer(- os_type=os_type_str,- use_host_computer_server=True,- experiments=experiments+ os_type=os_type_str, use_host_computer_server=True, experiments=experiments)elif provider == "cloud":# Use API key from environment variable or field input@@ -572,13 +660,11 @@ async def handle_init_computer(os_choice: str, app_list=None, provider="lume", cprovider_type=VMProviderType.CLOUD,name=container_name,api_key=cloud_api_key,- experiments=experiments+ experiments=experiments,)elif provider == "winsandbox":computer = Computer(- os_type="windows",- provider_type=VMProviderType.WINSANDBOX,- experiments=experiments+ os_type="windows", provider_type=VMProviderType.WINSANDBOX, experiments=experiments)else:computer = Computer(@@ -588,169 +674,174 @@ async def handle_init_computer(os_choice: str, app_list=None, provider="lume", cdisplay="1024x768",memory="8GB",cpu="4",- experiments=experiments+ experiments=experiments,)await computer.run()-+# If app list is provided, create desktop from appsif use_app_experiment:computer = computer.create_desktop_from_apps(app_list)# Log computer initialization as a tool call- init_params = {- "os": os_type_str,- "provider": provider- }-+ init_params = {"os": os_type_str, "provider": provider}+# Add VM-specific parameters if not using host computer serverif not use_host_computer_server:- init_params.update({- "image": image_str,- "display": "1024x768",- "memory": "8GB",- "cpu": "4"- })-+ init_params.update({"image": image_str, "display": "1024x768", "memory": "8GB", "cpu": "4"})+# Add app list to the log if providedif use_app_experiment:init_params["apps"] = app_listinit_params["experiments"] = ["app-use"]-+# Add container name to the log if using cloud providerif provider == "cloud":init_params["container_name"] = container_name-+result = await execute("computer", "initialize", init_params)return result["screenshot"], json.dumps(tool_call_logs, indent=2)+async def handle_screenshot():"""Take a screenshot and return it as a PIL Image"""global computerif computer is None:return None-+result = await execute("computer", "screenshot", {})return result["screenshot"]+async def handle_wait():"""Wait for 1 second and then take a screenshot"""global computerif computer is None:return None-+# Execute wait actionresult = await execute("computer", "wait", {})return result["screenshot"], json.dumps(tool_call_logs, indent=2)+async def handle_click(evt: gr.SelectData, img, click_type):"""Handle click events on the image based on click type"""global computerif computer is None:return img, json.dumps(tool_call_logs, indent=2)-+# Get the coordinates of the clickx, y = evt.index-+# Move cursor and perform clickresult = await execute("computer", click_type, {"x": x, "y": y})-+# Take a new screenshot to show the resultreturn result["screenshot"], json.dumps(tool_call_logs, indent=2)+async def handle_type(text, press_enter=False):"""Type text into the computer"""global computerif computer is None or not text:return await handle_screenshot(), json.dumps(tool_call_logs, indent=2)-+result = await execute("computer", "type_text", {"text": text, "press_enter": press_enter})-+return result["screenshot"], json.dumps(tool_call_logs, indent=2)+async def handle_copy():"""Copy selected content to clipboard and return it"""global computerif computer is None:return "Computer not initialized", json.dumps(tool_call_logs, indent=2)-+result = await execute("computer", "copy_to_clipboard", {})content = result.get("clipboard", "No content copied")-+return content, json.dumps(tool_call_logs, indent=2)+async def handle_set_clipboard(text):"""Set clipboard content"""global computerif computer is None:return "Computer not initialized", json.dumps(tool_call_logs, indent=2)-+await execute("computer", "set_clipboard", {"text": text})-+return f"Clipboard set to: {text}", json.dumps(tool_call_logs, indent=2)+async def handle_run_command(command):"""Run a shell command"""global computerif computer is None:return "Computer not initialized", json.dumps(tool_call_logs, indent=2)-+# Execute the run_command action and log itresult = await execute("computer", "run_command", {"command": command})-+# Get the result from the computer interfacestdout, stderr = result.get("stdout"), result.get("stderr")-+# Format the outputoutput = ""if stdout:output += f"STDOUT:\n{stdout}\n"if stderr:output += f"STDERR:\n{stderr}\n"-+if not output:output = "(No output)"-+return output, json.dumps(tool_call_logs, indent=2)+async def handle_shutdown():"""Shutdown the computer instance"""global computerif computer is None:return "Computer not initialized", json.dumps(tool_call_logs, indent=2)-+await execute("computer", "shutdown", {})-+computer = Nonereturn "Computer shut down", json.dumps(tool_call_logs, indent=2)+async def handle_memory(memory_text):"""Update the global memory"""global memory- await execute("memory", "update", { "memory_text": memory_text })+ await execute("memory", "update", {"memory_text": memory_text})memory = memory_textreturn "Memory updated"+async def update_reasoning(reasoning_text, is_erroneous=False):"""Update the reasoning for the last action"""global last_action, tool_call_logs-+if not last_action["name"]:return "No action to update reasoning for"-+# Find the last log entry that matches the last actionfor log_entry in reversed(tool_call_logs):- if (log_entry["name"] == last_action["name"] and- json.loads(log_entry["arguments"]).get("action") == last_action["action"]):+ if (+ log_entry["name"] == last_action["name"]+ and json.loads(log_entry["arguments"]).get("action") == last_action["action"]+ ):# Add reasoning to the log entrylog_entry["reasoning"] = reasoning_text# If marked as erroneous, set weight to 0log_entry["weight"] = 0 if is_erroneous else 1break-+return "Reasoning updated"+async def clear_log():"""Clear the tool call logs"""global tool_call_logs, screenshot_images@@ -758,67 +849,71 @@ async def clear_log():tool_call_logs = []return json.dumps(tool_call_logs, indent=2)+def get_last_action_display():"""Format the last action for display in the reasoning box"""global last_actionif not last_action["name"]:return "No actions performed yet"-+action_str = f"Tool: {last_action['name']}\nAction: {last_action['action']}"-+if last_action["arguments"]:args_str = "\nArguments:\n"for k, v in last_action["arguments"].items():args_str += f" {k}: {v}\n"action_str += args_str-+return action_str+def get_memory():"""Get the current memory"""global memoryreturn memory+def get_chatbot_messages(logs=None):"""Format chat messages for gr.Chatbot component-+Args:logs: Optional list of tool call logs. If None, uses global tool_call_logs.-+Returns:List of ChatMessage objects"""formatted_messages = []-+# Use provided logs if specified, otherwise use global tool_call_logslogs_to_process = logs if logs is not None else tool_call_logs-+for tool_call in logs_to_process:- if tool_call['type'] != "function_call":+ if tool_call["type"] != "function_call":continue-- name = tool_call['name']- arguments = json.loads(tool_call['arguments'])-- role = tool_call['role'] if 'role' in tool_call else arguments['role'] if 'role' in arguments else 'assistant'-++ name = tool_call["name"]+ arguments = json.loads(tool_call["arguments"])++ role = (+ tool_call["role"]+ if "role" in tool_call+ else arguments["role"] if "role" in arguments else "assistant"+ )+if "reasoning" in tool_call:- formatted_messages += [ChatMessage(- role=role,- content=tool_call['reasoning'],- metadata={"title": "🧠 Reasoning"}- )]-+ formatted_messages += [+ ChatMessage(+ role=role, content=tool_call["reasoning"], metadata={"title": "🧠 Reasoning"}+ )+ ]+# Format tool calls with titlesif name == "message":- formatted_messages += [ChatMessage(- role=role,- content=arguments['text']- )]+ formatted_messages += [ChatMessage(role=role, content=arguments["text"])]else:# Format tool calls with a title- action = arguments.get('action', '')-+ action = arguments.get("action", "")+# Define dictionary for title mappingstitle_mappings = {"wait": "⏳ Waiting...",@@ -837,9 +932,9 @@ def get_chatbot_messages(logs=None):"set_clipboard": "📋 Setting Clipboard","run_command": "🖥️ Running Shell Command","initialize": "🚀 Initializing Computer",- "shutdown": "🛑 Shutting Down"+ "shutdown": "🛑 Shutting Down",}-+# Look up title based on name.action or just actionkey = f"{name}.{action}"if key in title_mappings:@@ -848,84 +943,92 @@ def get_chatbot_messages(logs=None):title = title_mappings[action]else:title = f"🛠️ {name.capitalize()}: {action}"-+# Always set status to donestatus = "done"-+# Format the response contentcontent_parts = []-+# Add argumentsif arguments:content_parts.append("**Arguments:**")for k, v in arguments.items():if k != "action": # Skip action as it's in the titlecontent_parts.append(f"- {k}: {v}")-+# Add results if available- if tool_call.get('result'):+ if tool_call.get("result"):content_parts.append("\n**Results:**")content_parts.append(f"```json\n{json.dumps(tool_call['result'], indent=4)}\n```")# for k, v in tool_call['result'].items():# content_parts.append(f"- {k}: {v}")-+# Join all content partscontent = "\n".join(content_parts)-- formatted_messages += [ChatMessage(- role="assistant",- content=content,- metadata={"title": title, "status": status}- )]-++ formatted_messages += [+ ChatMessage(+ role="assistant", content=content, metadata={"title": title, "status": status}+ )+ ]+return formatted_messages+async def submit_message(message_text, role, screenshot_after=False):"""Submit a message with specified role (user or assistant)"""global last_screenshot-+# Log the message submission and get result (may include screenshot)- result = await execute("message", "submit", {- "role": role,- "text": message_text,- "screenshot_after": screenshot_after- })-+ result = await execute(+ "message",+ "submit",+ {"role": role, "text": message_text, "screenshot_after": screenshot_after},+ )+# Update return values based on whether a screenshot was takenif screenshot_after and "screenshot" in result:- return f"Message submitted as {role} with screenshot", get_chatbot_messages(), json.dumps(tool_call_logs, indent=2), result["screenshot"]+ return (+ f"Message submitted as {role} with screenshot",+ get_chatbot_messages(),+ json.dumps(tool_call_logs, indent=2),+ result["screenshot"],+ )else:# Return last screenshot if available- return f"Message submitted as {role}", get_chatbot_messages(), json.dumps(tool_call_logs, indent=2), last_screenshot+ return (+ f"Message submitted as {role}",+ get_chatbot_messages(),+ json.dumps(tool_call_logs, indent=2),+ last_screenshot,+ )+def create_gradio_ui():with gr.Blocks() as app:gr.Markdown("# Computer Interface Tool")-+with gr.Row():with gr.Column(scale=3):with gr.Group():# Main screenshot displayimg = gr.Image(- type="pil",- label="Current Screenshot",- show_label=False,- interactive=False+ type="pil", label="Current Screenshot", show_label=False, interactive=False)-+# Click type selectionclick_type = gr.Radio(- ["left_click", "right_click", "double_click", "move_cursor"],+ ["left_click", "right_click", "double_click", "move_cursor"],label="Click Type",- value="left_click"+ value="left_click",)-+with gr.Row():wait_btn = gr.Button("WAIT")done_btn = gr.Button("DONE")fail_btn = gr.Button("FAIL")--+# Tabbed logs: Tool logs, Conversational logs, and Demonstrationswith gr.Tabs() as logs_tabs:with gr.TabItem("Conversational Logs"):@@ -936,14 +1039,11 @@ def create_gradio_ui():height=400,type="messages",sanitize_html=True,- allow_tags=True+ allow_tags=True,)with gr.TabItem("Function Logs"):with gr.Group():- action_log = gr.JSON(- label="Function Logs",- every=0.2- )+ action_log = gr.JSON(label="Function Logs", every=0.2)clear_log_btn = gr.Button("Clear Log")with gr.TabItem("Save/Share Demonstrations"):with gr.Row():@@ -952,11 +1052,11 @@ def create_gradio_ui():dataset_viewer = gr.DataFrame(label="All Sessions",value=get_sessions_data,- show_search='filter',+ show_search="filter",max_height=300,- interactive=True # Make it interactive for selection+ interactive=True, # Make it interactive for selection)-+# HuggingFace Upload UIwith gr.Group(visible=True):gr.Markdown("Upload Sessions to HuggingFace")@@ -964,28 +1064,30 @@ def create_gradio_ui():hf_dataset_name = gr.Textbox(label="HuggingFace Dataset Name",placeholder="username/dataset-name",- info="Format: username/dataset-name"+ info="Format: username/dataset-name",)hf_visibility = gr.Radio(choices=["public", "private"],label="Dataset Visibility",- value="private"+ value="private",)-+# Tag filtering with a single multi-select dropdownfilter_tags = gr.Dropdown(label="Filter by tags (optional)",choices=get_existing_tags()[0],multiselect=True,allow_custom_value=True,- info="When tags are selected, only demonstrations with those tags will be uploaded. Leave empty to upload all sessions."+ info="When tags are selected, only demonstrations with those tags will be uploaded. Leave empty to upload all sessions.",)-+# Function to update button text based on selected tagsdef get_upload_button_text(selected_tags=None):if not selected_tags:# Count all sessions- session_folders = glob.glob(os.path.join(SESSION_DIR, "*"))+ session_folders = glob.glob(+ os.path.join(SESSION_DIR, "*")+ )count = len(session_folders) if session_folders else 0return f"Upload {count} Sessions to HuggingFace"else:@@ -993,98 +1095,96 @@ def create_gradio_ui():all_sessions = load_all_sessions()if all_sessions is None:return "Upload 0 Sessions to HuggingFace"-+df = all_sessions.to_pandas()- if 'tags' not in df.columns:+ if "tags" not in df.columns:return "Upload 0 Sessions to HuggingFace"-+# Filter by selected tags (sessions that have ANY of the selected tags)matching_count = 0for _, row in df.iterrows():- tags = row.get('tags', [])+ tags = row.get("tags", [])if not len(tags):continue# Check if any of the selected tags are in this session's tags- if any(tag in list(row['tags']) for tag in selected_tags):+ if any(+ tag in list(row["tags"])+ for tag in selected_tags+ ):matching_count += 1-- return f"Upload {matching_count} Sessions to HuggingFace"-++ return (+ f"Upload {matching_count} Sessions to HuggingFace"+ )+# Initial button text with all sessionshf_upload_btn = gr.Button(get_upload_button_text())-+# Update button text when filter changesdef update_button_text(selected_tags):return get_upload_button_text(selected_tags)-+# Connect filter changes to update button textfilter_tags.change(update_button_text,inputs=filter_tags,- outputs=hf_upload_btn+ outputs=hf_upload_btn,)-+hf_upload_status = gr.Textbox(label="Upload Status", value="")with gr.Column(scale=1):# Demo name with random name buttonwith gr.Group():demo_name = gr.Textbox(- label="Demonstration Name",+ label="Demonstration Name",value=generate_random_demo_name(),- placeholder="Enter a name for this demonstration"+ placeholder="Enter a name for this demonstration",)random_name_btn = gr.Button("🎲", scale=1)-+# Demo tags dropdowndemo_tags = gr.Dropdown(label="Demonstration Tags",choices=get_existing_tags()[0],multiselect=True,allow_custom_value=True,- info="Select existing tags or create new ones"+ info="Select existing tags or create new ones",)-+save_btn = gr.Button("Save Current Session")save_status = gr.Textbox(label="Save Status", value="")-+# Function to update the demo name with a new random namedef update_random_name():return generate_random_demo_name()-+# Connect random name button- random_name_btn.click(- update_random_name,- outputs=[demo_name]- )-+ random_name_btn.click(update_random_name, outputs=[demo_name])+with gr.Column(scale=1):with gr.Accordion("Memory / Scratchpad", open=False):with gr.Group():memory_display = gr.Textbox(- label="Current Memory",- value=get_memory(),- lines=5+ label="Current Memory", value=get_memory(), lines=5)with gr.Row():memory_submit_btn = gr.Button("Submit Memory")memory_refine_btn = gr.Button("Refine")memory_status = gr.Textbox(label="Status", value="")-+with gr.Accordion("Tasks", open=True):# Add current task display and controlswith gr.Group():current_task = gr.Textbox(- label="Current Task",- value=TASK_EXAMPLES[0]["task"],- interactive=True+ label="Current Task", value=TASK_EXAMPLES[0]["task"], interactive=True)with gr.Row():randomize_task_btn = gr.Button("🎲 Randomize Task")run_setup_btn = gr.Button("⚙️ Run Task Setup")# Setup status textboxsetup_status = gr.Textbox(label="Setup Status", value="")-+with gr.Group():with gr.Accordion("Computer Configuration", open=False):with gr.Row():@@ -1093,68 +1193,68 @@ def create_gradio_ui():choices=["macOS", "Ubuntu", "Windows"],value="macOS",)-+# Provider selection radioprovider_choice = gr.Radio(label="Provider",choices=["lume", "self", "cloud", "winsandbox"],value="lume",- info="'lume' uses a VM, 'self' uses the host computer server, 'cloud' uses a cloud container"+ info="'lume' uses a VM, 'self' uses the host computer server, 'cloud' uses a cloud container",)-+# Container name field for cloud provider (initially hidden)container_name = gr.Textbox(label="Container Name",placeholder="Enter your container name",visible=False,- info="Get your container from [trycua.com](https://trycua.com/)"+ info="Get your container from [trycua.com](https://trycua.com/)",)-+# Check if CUA_API_KEY is set in environmenthas_cua_key = os.environ.get("CUA_API_KEY") is not None-+# API key field for cloud provider (visible only if no env key and cloud selected)api_key_field = gr.Textbox(label="CUA API Key",placeholder="Enter your CUA API key",type="password",visible=False,- info="Required for cloud provider. Set CUA_API_KEY environment variable to hide this field."+ info="Required for cloud provider. Set CUA_API_KEY environment variable to hide this field.",)-+# App filtering dropdown for app-use experimentapp_filter = gr.Dropdown(label="Filter by apps (App-Use)",multiselect=True,allow_custom_value=True,- info="When apps are selected, the computer will focus on those apps using the app-use experiment"+ info="When apps are selected, the computer will focus on those apps using the app-use experiment",)-+# Function to show/hide container name and API key fields based on provider selectiondef update_cloud_fields_visibility(provider):show_container = provider == "cloud"show_api_key = provider == "cloud" and not has_cua_keyreturn (gr.update(visible=show_container),- gr.update(visible=show_api_key)+ gr.update(visible=show_api_key),)-+# Connect provider choice to field visibilityprovider_choice.change(update_cloud_fields_visibility,inputs=provider_choice,- outputs=[container_name, api_key_field]+ outputs=[container_name, api_key_field],)-+start_btn = gr.Button("Initialize Computer")-+with gr.Group():input_text = gr.Textbox(label="Type Text")with gr.Row():press_enter_checkbox = gr.Checkbox(label="Press Enter", value=False)submit_text_btn = gr.Button("Submit Text")text_refine_btn = gr.Button("Refine")-+with gr.Group():hotkey_keys = gr.Dropdown(choices=VALID_KEYS,@@ -1162,112 +1262,102 @@ def create_gradio_ui():multiselect=True,show_label=False,allow_custom_value=True,- info="Select one or more keys to send as a hotkey"+ info="Select one or more keys to send as a hotkey",)hotkey_btn = gr.Button("Send Hotkey(s)")-+with gr.Accordion("Scrolling", open=False):with gr.Group():- scroll_clicks = gr.Number(label="Number of Clicks", value=1, minimum=1, step=1)+ scroll_clicks = gr.Number(+ label="Number of Clicks", value=1, minimum=1, step=1+ )with gr.Row():scroll_up_btn = gr.Button("Scroll Up")scroll_down_btn = gr.Button("Scroll Down")-+with gr.Accordion("Reasoning for Last Action", open=False):with gr.Group():last_action_display = gr.Textbox(- label="Last Action",- value=get_last_action_display(),- interactive=False+ label="Last Action", value=get_last_action_display(), interactive=False)reasoning_text = gr.Textbox(label="What was your thought process behind this action?",placeholder="Enter your reasoning here...",- lines=3+ lines=3,)erroneous_checkbox = gr.Checkbox(- label="Mark this action as erroneous (sets weight to 0)",- value=False+ label="Mark this action as erroneous (sets weight to 0)", value=False)reasoning_submit_btn = gr.Button("Submit Reasoning")reasoning_refine_btn = gr.Button("Refine")reasoning_status = gr.Textbox(label="Status", value="")-+with gr.Accordion("Conversation Messages", open=False):message_role = gr.Radio(- ["user", "assistant"],- label="Message Role",- value="user"+ ["user", "assistant"], label="Message Role", value="user")message_text = gr.Textbox(- label="Message Content",- placeholder="Enter message here...",- lines=3+ label="Message Content", placeholder="Enter message here...", lines=3)screenshot_after_msg = gr.Checkbox(- label="Receive screenshot after message",- value=False+ label="Receive screenshot after message", value=False)message_submit_btn = gr.Button("Submit Message")message_status = gr.Textbox(label="Status")-+with gr.Accordion("Clipboard Operations", open=False):clipboard_content = gr.Textbox(label="Clipboard Content")get_clipboard_btn = gr.Button("Get Clipboard Content")set_clipboard_text = gr.Textbox(label="Set Clipboard Text")set_clipboard_btn = gr.Button("Set Clipboard")clipboard_status = gr.Textbox(label="Status")-+with gr.Accordion("Run Shell Commands", open=False):command_input = gr.Textbox(label="Command to run", placeholder="ls -la")run_command_btn = gr.Button("Run Command")command_output = gr.Textbox(label="Command Output", lines=5)-+shutdown_btn = gr.Button("Shutdown Computer")# Handle save buttonsave_btn.click(- save_demonstration,- inputs=[action_log, demo_name, demo_tags],- outputs=[save_status]+ save_demonstration, inputs=[action_log, demo_name, demo_tags], outputs=[save_status])-+# Function to refresh the dataset viewerdef refresh_dataset_viewer():return get_sessions_data()-+# Also update the dataset viewer when saving- save_btn.click(- refresh_dataset_viewer,- outputs=dataset_viewer- )-+ save_btn.click(refresh_dataset_viewer, outputs=dataset_viewer)+# Also update the tags dropdown when saving- save_btn.click(- get_existing_tags,- outputs=[demo_tags, filter_tags]- )-+ save_btn.click(get_existing_tags, outputs=[demo_tags, filter_tags])+# Handle HuggingFace upload buttonhf_upload_btn.click(upload_to_huggingface,inputs=[hf_dataset_name, hf_visibility, filter_tags],- outputs=[hf_upload_status]+ outputs=[hf_upload_status],)# Function to randomize taskdef randomize_task():task_dict = random.choice(TASK_EXAMPLES)return task_dict["task"]-+# Function to run task setupasync def run_task_setup(task_text):global computer-+# Check if computer is initializedif computer is None:- return "Computer not initialized. Please initialize the computer first.", img, action_log-+ return (+ "Computer not initialized. Please initialize the computer first.",+ img,+ action_log,+ )+# Find the task dict that matches the current task textfor task_dict in TASK_EXAMPLES:if task_dict["task"] == task_text:@@ -1276,60 +1366,54 @@ def create_gradio_ui():setup_func = task_dict["setup"]if setup_func:await setup_func(computer)-+# Send initial user message_, _, logs_json, screenshot = await submit_message(- task_text,- "user",- screenshot_after=True+ task_text, "user", screenshot_after=True)-+return f"Setup complete for: {task_text}", screenshot, logs_jsonexcept Exception as e:return f"Error during setup: {str(e)}", img, action_log-+return "Task not found in examples", img, action_log-+# Connect the randomize button to the function- randomize_task_btn.click(- randomize_task,- outputs=[current_task]- )-+ randomize_task_btn.click(randomize_task, outputs=[current_task])+# Connect the setup buttonrun_setup_btn.click(- run_task_setup,- inputs=[current_task],- outputs=[setup_status, img, action_log]+ run_task_setup, inputs=[current_task], outputs=[setup_status, img, action_log])-+# Event handlers- action_log.change(- get_chatbot_messages,- outputs=[chat_log]- )-+ action_log.change(get_chatbot_messages, outputs=[chat_log])+img.select(handle_click, inputs=[img, click_type], outputs=[img, action_log])- start_btn.click(handle_init_computer, inputs=[os_choice, app_filter, provider_choice, container_name, api_key_field], outputs=[img, action_log])+ start_btn.click(+ handle_init_computer,+ inputs=[os_choice, app_filter, provider_choice, container_name, api_key_field],+ outputs=[img, action_log],+ )wait_btn.click(handle_wait, outputs=[img, action_log])-+# DONE and FAIL buttons just do a placeholder actionasync def handle_done():output = await execute("computer", "done", {})return output["screenshot"], json.dumps(tool_call_logs, indent=2)-+async def handle_fail():output = await execute("computer", "fail", {})return output["screenshot"], json.dumps(tool_call_logs, indent=2)-+done_btn.click(handle_done, outputs=[img, action_log])fail_btn.click(handle_fail, outputs=[img, action_log])-+# Handle hotkey buttonasync def handle_hotkey(selected_keys):if not selected_keys or len(selected_keys) == 0:return await handle_screenshot(), json.dumps(tool_call_logs, indent=2)-+# When multiple keys are selected, the last one is the main key, the rest are modifiersif len(selected_keys) > 1:key = selected_keys[-1]@@ -1338,19 +1422,19 @@ def create_gradio_ui():# If only one key is selected, no modifierskey = selected_keys[0]modifiers = []-+output = await execute("computer", "send_hotkey", {"keys": selected_keys})return output["screenshot"], json.dumps(tool_call_logs, indent=2)-+hotkey_btn.click(handle_hotkey, inputs=[hotkey_keys], outputs=[img, action_log])-+# Define async handler for scrollingasync def handle_scroll(direction, num_clicks=1):"""Scroll the page up or down"""global computerif computer is None:return None, json.dumps(tool_call_logs, indent=2)-+# Convert num_clicks to integer with validationtry:num_clicks = int(num_clicks)@@ -1358,34 +1442,35 @@ def create_gradio_ui():num_clicks = 1except (ValueError, TypeError):num_clicks = 1-+# Execute the scroll actionaction = "scroll_up" if direction == "up" else "scroll_down"result = await execute("computer", action, {"clicks": num_clicks})-+return result["screenshot"], json.dumps(tool_call_logs, indent=2)-+# Connect scroll buttonsscroll_up_btn.click(- handle_scroll,- inputs=[gr.State("up"), scroll_clicks],- outputs=[img, action_log]+ handle_scroll, inputs=[gr.State("up"), scroll_clicks], outputs=[img, action_log])scroll_down_btn.click(- handle_scroll,- inputs=[gr.State("down"), scroll_clicks],- outputs=[img, action_log]+ handle_scroll, inputs=[gr.State("down"), scroll_clicks], outputs=[img, action_log]+ )++ submit_text_btn.click(+ handle_type, inputs=[input_text, press_enter_checkbox], outputs=[img, action_log])-- submit_text_btn.click(handle_type, inputs=[input_text, press_enter_checkbox], outputs=[img, action_log])get_clipboard_btn.click(handle_copy, outputs=[clipboard_content, action_log])- set_clipboard_btn.click(handle_set_clipboard, inputs=set_clipboard_text, outputs=[clipboard_status, action_log])- run_command_btn.click(handle_run_command, inputs=command_input, outputs=[command_output, action_log])+ set_clipboard_btn.click(+ handle_set_clipboard, inputs=set_clipboard_text, outputs=[clipboard_status, action_log]+ )+ run_command_btn.click(+ handle_run_command, inputs=command_input, outputs=[command_output, action_log]+ )shutdown_btn.click(handle_shutdown, outputs=[clipboard_status, action_log])clear_log_btn.click(clear_log, outputs=action_log)chat_log.clear(clear_log, outputs=action_log)-# Update last action display after each actionimg.select(lambda *args: get_last_action_display(), outputs=last_action_display)start_btn.click(lambda: get_last_action_display(), outputs=last_action_display)@@ -1395,31 +1480,33 @@ def create_gradio_ui():hotkey_btn.click(lambda: get_last_action_display(), outputs=last_action_display)submit_text_btn.click(lambda: get_last_action_display(), outputs=last_action_display)message_submit_btn.click(lambda: get_last_action_display(), outputs=last_action_display)-+# Handle reasoning submissionasync def handle_reasoning_update(reasoning, is_erroneous):status = await update_reasoning(reasoning, is_erroneous)return status, json.dumps(tool_call_logs, indent=2)-+reasoning_submit_btn.click(handle_reasoning_update,- inputs=[reasoning_text, erroneous_checkbox],- outputs=[reasoning_status, action_log]+ inputs=[reasoning_text, erroneous_checkbox],+ outputs=[reasoning_status, action_log],)-+# Helper function for text refinement - used for all refine buttons- async def handle_text_refinement(text_content, content_type="reasoning", task_text="", use_before = False):+ async def handle_text_refinement(+ text_content, content_type="reasoning", task_text="", use_before=False+ ):global last_screenshot, last_action, tool_call_logs, last_screenshot_before-+screenshot = last_screenshot_before if use_before else last_screenshot-+# Check if we have the necessary componentsif not text_content.strip():return f"No {content_type} text to refine", text_content-+if screenshot is None:return "No screenshot available for refinement", text_content-+try:# Convert the PIL image to base64 if availablescreenshot_base64 = None@@ -1427,39 +1514,45 @@ def create_gradio_ui():with io.BytesIO() as buffer:screenshot.save(buffer, format="PNG")screenshot_base64 = base64.b64encode(buffer.getvalue()).decode("utf-8")-+# Set up the OpenAI client for refinement# Try different API keys from environment in order of preferenceapi_key = os.getenv("OPENAI_API_KEY") or os.getenv("OMNI_OPENAI_API_KEY")-+if not api_key:return "OpenAI API key not found in environment", text_content-+from libs.agent.agent.providers.omni.clients.openai import OpenAIClient-+# Create a client - use gpt-4 if available, fall back to 3.5-turbomodel = "gpt-4.1-2025-04-14"-+client = OpenAIClient(api_key=api_key,model=model,max_tokens=1024,temperature=0.2, # Low temperature for more focused refinement)-+# Get the last 3 messages from the chat history- recent_messages = get_chatbot_messages(tool_call_logs)[-3:] if len(get_chatbot_messages(tool_call_logs)) >= 3 else get_chatbot_messages(tool_call_logs)-+ recent_messages = (+ get_chatbot_messages(tool_call_logs)[-3:]+ if len(get_chatbot_messages(tool_call_logs)) >= 3+ else get_chatbot_messages(tool_call_logs)+ )+# Format message history with titles when availableformatted_messages = []for msg in recent_messages:- if msg.metadata and 'title' in msg.metadata:- formatted_messages.append(f"{msg.role} ({msg.metadata['title']}): {msg.content}")+ if msg.metadata and "title" in msg.metadata:+ formatted_messages.append(+ f"{msg.role} ({msg.metadata['title']}): {msg.content}"+ )else:formatted_messages.append(f"{msg.role}: {msg.content}")-+formatted_messages = [f"<message>{msg}</message>" for msg in formatted_messages]-+# Create different prompts based on content typeif content_type == "reasoning":message_prompt = f"""You are helping refine an explanation about why a specific computer UI action is about to be taken.@@ -1482,7 +1575,7 @@ Make this into a concise reasoning / self-reflection trace, using "I should/needProvide ONLY the refined explanation text, with no additional commentary or markdown."""-+elif content_type == "memory":message_prompt = f"""You are helping refine memory/scratchpad content for an AI assistant.@@ -1503,7 +1596,7 @@ Refine this memory content to be more clear, organized, and useful for the assis- Make the format more readable with bullet points or other organizational elements if helpfulProvide ONLY the refined memory text, with no additional commentary or markdown."""-+elif content_type == "text":message_prompt = f"""You are helping refine text that will be typed into a computer interface.@@ -1524,7 +1617,7 @@ Refine this text to be more effective for the current context:- Optimize the text for the intended useProvide ONLY the refined text, with no additional commentary or markdown."""-+else:message_prompt = f"""You are helping refine text content.@@ -1539,50 +1632,48 @@ RECENT MESSAGES:Improve this text to be more clear, concise, and effective.Provide ONLY the refined text, with no additional commentary or markdown."""-+# Create messages with the screenshotmessages = []-+# Add message with image if availableif screenshot_base64:- messages.append({- "role": "user",- "content": [- {- "type": "text",- "text": message_prompt- },- {- "type": "image_url",- "image_url": {"url": f"data:image/png;base64,{screenshot_base64}"}- }- ]- })+ messages.append(+ {+ "role": "user",+ "content": [+ {"type": "text", "text": message_prompt},+ {+ "type": "image_url",+ "image_url": {+ "url": f"data:image/png;base64,{screenshot_base64}"+ },+ },+ ],+ }+ )else:# Fallback if screenshot isn't available- messages.append({- "role": "user",- "content": message_prompt- })-+ messages.append({"role": "user", "content": message_prompt})+print(message_prompt)-+# Make the API callresponse = await client.run_interleaved(messages=messages,system="You are a helpful AI assistant that improves and refines text.",)-+# Extract the refined text from the responseif "choices" in response and len(response["choices"]) > 0:refined_text = response["choices"][0]["message"]["content"]return f"{content_type.capitalize()} refined successfully", refined_textelse:return "Error: Unexpected API response format", text_content-+except Exception as e:return f"Error refining {content_type}: {str(e)}", text_content-+# Define async wrapper functions for each refine buttonasync def handle_reasoning_refinement(reasoning, task):return await handle_text_refinement(reasoning, "reasoning", task, use_before=True)@@ -1597,54 +1688,55 @@ Provide ONLY the refined text, with no additional commentary or markdown."""reasoning_refine_btn.click(handle_reasoning_refinement,inputs=[reasoning_text, current_task],- outputs=[reasoning_status, reasoning_text]+ outputs=[reasoning_status, reasoning_text],)-+# Connect memory refine buttonmemory_refine_btn.click(handle_memory_refinement,inputs=[memory_display, current_task],- outputs=[memory_status, memory_display]+ outputs=[memory_status, memory_display],)-+# Status element for type text sectionwith gr.Group():type_text_status = gr.Textbox(label="Text Status", value="", visible=False)-+# Connect text refine buttontext_refine_btn.click(handle_text_input_refinement,inputs=[input_text, current_task],- outputs=[type_text_status, input_text]+ outputs=[type_text_status, input_text],)-+# Handle memory submissionasync def handle_memory_update(memory_text):status = await handle_memory(memory_text)return status, json.dumps(tool_call_logs, indent=2)-+memory_submit_btn.click(- handle_memory_update,- inputs=memory_display,- outputs=[memory_status, action_log]+ handle_memory_update, inputs=memory_display, outputs=[memory_status, action_log])-+# Handle message submissionasync def handle_message_submit(message_content, role, screenshot_after):- status, chat_messages, logs_json, screenshot = await submit_message(message_content, role, screenshot_after)+ status, chat_messages, logs_json, screenshot = await submit_message(+ message_content, role, screenshot_after+ )if screenshot:return status, chat_messages, logs_json, screenshotelse:return status, chat_messages, logs_json, last_screenshot-+message_submit_btn.click(handle_message_submit,- inputs=[message_text, message_role, screenshot_after_msg],- outputs=[message_status, chat_log, action_log, img]+ inputs=[message_text, message_role, screenshot_after_msg],+ outputs=[message_status, chat_log, action_log, img],)return app+# Launch the appif __name__ == "__main__":app = create_gradio_ui()diff --git a/libs/python/computer/computer/utils.py b/libs/python/computer/computer/utils.pyindex 070f8ebc74..c2f04c4844 100644--- a/libs/python/computer/computer/utils.py+++ b/libs/python/computer/computer/utils.py@@ -1,40 +1,46 @@import base64-from typing import Tuple, Optional, Dict, Any-from PIL import Image, ImageDrawimport io+from typing import Any, Dict, Optional, Tuple++from PIL import Image, ImageDraw+def decode_base64_image(base64_str: str) -> bytes:"""Decode a base64 string into image bytes."""return base64.b64decode(base64_str)+def encode_base64_image(image_bytes: bytes) -> str:"""Encode image bytes to base64 string."""- return base64.b64encode(image_bytes).decode('utf-8')+ return base64.b64encode(image_bytes).decode("utf-8")+def bytes_to_image(image_bytes: bytes) -> Image.Image:"""Convert bytes to PIL Image.-+Args:image_bytes: Raw image bytes-+Returns:PIL.Image: The converted image"""return Image.open(io.BytesIO(image_bytes))-def image_to_bytes(image: Image.Image, format: str = 'PNG') -> bytes:++def image_to_bytes(image: Image.Image, format: str = "PNG") -> bytes:"""Convert PIL Image to bytes."""buf = io.BytesIO()image.save(buf, format=format)return buf.getvalue()+def resize_image(image_bytes: bytes, scale_factor: float) -> bytes:"""Resize an image by a scale factor.-+Args:image_bytes: The original image as bytesscale_factor: Factor to scale the image by (e.g., 0.5 for half size, 2.0 for double)-+Returns:bytes: The resized image as bytes"""@@ -44,6 +50,7 @@ def resize_image(image_bytes: bytes, scale_factor: float) -> bytes:image = image.resize(new_size, Image.Resampling.LANCZOS)return image_to_bytes(image)+def draw_box(image_bytes: bytes,x: int,@@ -51,10 +58,10 @@ def draw_box(width: int,height: int,color: str = "#FF0000",- thickness: int = 2+ thickness: int = 2,) -> bytes:"""Draw a box on an image.-+Args:image_bytes: The original image as bytesx: X coordinate of top-left corner@@ -63,39 +70,37 @@ def draw_box(height: Height of the boxcolor: Color of the box in hex formatthickness: Thickness of the box border in pixels-+Returns:bytes: The modified image as bytes"""# Convert bytes to PIL Imageimage = bytes_to_image(image_bytes)-+# Create drawing contextdraw = ImageDraw.Draw(image)-+# Draw rectangle- draw.rectangle(- [(x, y), (x + width, y + height)],- outline=color,- width=thickness- )-+ draw.rectangle([(x, y), (x + width, y + height)], outline=color, width=thickness)+# Convert back to bytesreturn image_to_bytes(image)+def get_image_size(image_bytes: bytes) -> Tuple[int, int]:"""Get the dimensions of an image.-+Args:image_bytes: The image as bytes-+Returns:Tuple[int, int]: Width and height of the image"""image = bytes_to_image(image_bytes)return image.size+def parse_vm_info(vm_info: Dict[str, Any]) -> Optional[Dict[str, Any]]:"""Parse VM info from pylume response."""if not vm_info:- return None\ No newline at end of file+ return Nonediff --git a/libs/python/core/README.md b/libs/python/core/README.mdindex 6c743a8bee..95d3fd2bef 100644--- a/libs/python/core/README.md+++ b/libs/python/core/README.md@@ -8,10 +8,11 @@</picture></div>- [](#)- [](#)- [](https://discord.com/invite/mVnXXpdE85)- [](https://pypi.org/project/cua-core/)+[](#)+[](#)+[](https://discord.com/invite/mVnXXpdE85)+[](https://pypi.org/project/cua-core/)+</h1></div>@@ -25,4 +26,4 @@```bashpip install cua-core-```\ No newline at end of file+```diff --git a/libs/python/core/core/telemetry/__init__.py b/libs/python/core/core/telemetry/__init__.pyindex b58467150c..4c84ace277 100644--- a/libs/python/core/core/telemetry/__init__.py+++ b/libs/python/core/core/telemetry/__init__.py@@ -4,12 +4,11 @@ It provides a low-overhead way to collect anonymous usage data."""from core.telemetry.posthog import (- record_event,- is_telemetry_enabled,destroy_telemetry_client,+ is_telemetry_enabled,+ record_event,)-__all__ = ["record_event","is_telemetry_enabled",diff --git a/libs/python/core/core/telemetry/posthog.py b/libs/python/core/core/telemetry/posthog.pyindex a6c361e5f6..5edd734316 100644--- a/libs/python/core/core/telemetry/posthog.py+++ b/libs/python/core/core/telemetry/posthog.py@@ -4,8 +4,8 @@ from __future__ import annotationsimport loggingimport os-import uuidimport sys+import uuidfrom pathlib import Pathfrom typing import Any, Dict, List, Optional@@ -20,6 +20,7 @@ logger = logging.getLogger("core.telemetry")PUBLIC_POSTHOG_API_KEY = "phc_eSkLnbLxsnYFaXksif1ksbrNzYlJShr35miFLDppF14"PUBLIC_POSTHOG_HOST = "https://eu.i.posthog.com"+class PostHogTelemetryClient:"""Collects and reports telemetry data via PostHog."""@@ -47,7 +48,8 @@ class PostHogTelemetryClient:# Legacy opt-out flagos.environ.get("CUA_TELEMETRY", "").lower() != "off"# Opt-in flag (defaults to enabled)- and os.environ.get("CUA_TELEMETRY_ENABLED", "true").lower() in { "1", "true", "yes", "on" }+ and os.environ.get("CUA_TELEMETRY_ENABLED", "true").lower()+ in {"1", "true", "yes", "on"})def _get_or_create_installation_id(self) -> str:@@ -150,14 +152,12 @@ class PostHogTelemetryClient:logger.debug(f"Setting up PostHog user properties for: {self.installation_id} with properties: {properties}")-+# In the Python SDK, we capture an identification event instead of calling identify()posthog.capture(- distinct_id=self.installation_id,- event="$identify",- properties={"$set": properties}+ distinct_id=self.installation_id, event="$identify", properties={"$set": properties})-+logger.info(f"Set up PostHog user properties for installation: {self.installation_id}")except Exception as e:logger.warning(f"Failed to set up PostHog user properties: {e}")@@ -224,13 +224,16 @@ class PostHogTelemetryClient:"""Destroy the global PostHogTelemetryClient instance."""cls._singleton = None+def destroy_telemetry_client() -> None:"""Destroy the global PostHogTelemetryClient instance (class-managed)."""PostHogTelemetryClient.destroy_client()+def is_telemetry_enabled() -> bool:return PostHogTelemetryClient.is_telemetry_enabled()+def record_event(event_name: str, properties: Optional[Dict[str, Any]] | None = None) -> None:"""Record an arbitrary PostHog event."""- PostHogTelemetryClient.get_client().record_event(event_name, properties or {})\ No newline at end of file+ PostHogTelemetryClient.get_client().record_event(event_name, properties or {})diff --git a/libs/python/mcp-server/CONCURRENT_SESSIONS.md b/libs/python/mcp-server/CONCURRENT_SESSIONS.mdindex 3a7028cb48..62e63dd2f1 100644--- a/libs/python/mcp-server/CONCURRENT_SESSIONS.md+++ b/libs/python/mcp-server/CONCURRENT_SESSIONS.md@@ -143,7 +143,7 @@ await cleanup_session(ctx, "session-to-cleanup")class SessionManager:def __init__(self, max_concurrent_sessions: int = 10):# Configurable maximum concurrent sessions-+class ComputerPool:def __init__(self, max_size: int = 5, idle_timeout: float = 300.0):# Configurable pool size and idle timeout@@ -152,6 +152,7 @@ class ComputerPool:## Performance Improvements### Before (Issues):+- ❌ Single global computer instance- ❌ Client interference and resource conflicts- ❌ Sequential task processing only@@ -159,6 +160,7 @@ class ComputerPool:- ❌ 30s timeout issues with long-running tasks### After (Benefits):+- ✅ Per-session computer instances with proper isolation- ✅ Computer instance pooling for efficient resource usage- ✅ Concurrent task execution supportdiff --git a/libs/python/mcp-server/README.md b/libs/python/mcp-server/README.mdindex 0ed794353a..7eddf4b725 100644--- a/libs/python/mcp-server/README.md+++ b/libs/python/mcp-server/README.md@@ -8,10 +8,11 @@</picture></div>- [](#)- [](#)- [](https://discord.com/invite/mVnXXpdE85)- [](https://pypi.org/project/cua-computer/)+[](#)+[](#)+[](https://discord.com/invite/mVnXXpdE85)+[](https://pypi.org/project/cua-computer/)+</h1></div>@@ -41,7 +42,8 @@ Add this to your MCP client configuration:"cua-agent": {"command": "/usr/bin/env","args": [- "bash", "-lc",+ "bash",+ "-lc","export CUA_MODEL_NAME='anthropic/claude-3-5-sonnet-20241022'; ~/.cua/start_mcp_server.sh"]}@@ -59,7 +61,8 @@ Use an absolute path to the repository root in the arguments below."cua-agent": {"command": "/usr/bin/env","args": [- "bash", "-lc",+ "bash",+ "-lc","export CUA_MODEL_NAME='huggingface-local/ByteDance-Seed/UI-TARS-1.5-7B'; /Users/your-username/Documents/GitHub/cua/libs/python/mcp-server/scripts/start_mcp_server.sh"]}@@ -68,6 +71,7 @@ Use an absolute path to the repository root in the arguments below.```Notes:+- Replace `/Users/your-username/Documents/GitHub/cua` with the absolute path to your clone.- The script sets `PYTHONPATH` for local libs and runs the server module.@@ -94,6 +98,7 @@ After configuring your MCP client, restart it and invoke one of these tools:```Expected results:+- Assistant messages streamed during execution- A final screenshot image@@ -109,6 +114,7 @@ Expected results:## TroubleshootingServer reports disconnected in MCP client:+- Use an absolute path in the `args` command.- Launch via `/usr/bin/env bash -lc` so the shell initializes and expands paths.- Run the script manually to verify:@@ -117,12 +123,14 @@ Server reports disconnected in MCP client:```pip not found in venv:+```bashpython3 -m ensurepip --upgradepython3 -m pip install -U pip setuptools wheel```Pydantic schema error related to Image:+```bashpython3 -m pip install -U "mcp>=1.2.0" "fastmcp>=0.4.7" "pydantic>=2.7,<2.12"```diff --git a/libs/python/mcp-server/mcp_server/__init__.py b/libs/python/mcp-server/mcp_server/__init__.pyindex a0a7407a99..f4b66e43da 100644--- a/libs/python/mcp-server/mcp_server/__init__.py+++ b/libs/python/mcp-server/mcp_server/__init__.py@@ -1,7 +1,7 @@"""MCP Server for Computer-Use Agent (CUA)."""-import sysimport os+import sys# Add detailed debugging at import timewith open("/tmp/mcp_server_debug.log", "w") as f:@@ -9,11 +9,11 @@ with open("/tmp/mcp_server_debug.log", "w") as f:f.write(f"Python version: {sys.version}\n")f.write(f"Working directory: {os.getcwd()}\n")f.write(f"Python path:\n{chr(10).join(sys.path)}\n")- f.write(f"Environment variables:\n")+ f.write("Environment variables:\n")for key, value in os.environ.items():f.write(f"{key}={value}\n")-from .server import server, main+from .server import main, server__version__ = "0.1.0"__all__ = ["server", "main"]diff --git a/libs/python/mcp-server/mcp_server/server.py b/libs/python/mcp-server/mcp_server/server.pyindex 67d2cbf2d9..7d47cfd119 100644--- a/libs/python/mcp-server/mcp_server/server.py+++ b/libs/python/mcp-server/mcp_server/server.py@@ -7,7 +7,7 @@ import signalimport sysimport tracebackimport uuid-from typing import Any, Dict, List, Optional, Union, Tuple+from typing import Any, Dict, List, Optional, Tuple, Unionimport anyio@@ -24,6 +24,7 @@ logger.debug("MCP Server module loading...")try:from mcp.server.fastmcp import Context, FastMCP+# Use the canonical Image typefrom mcp.server.fastmcp.utilities.types import Image@@ -34,8 +35,8 @@ except ImportError as e:sys.exit(1)try:- from computer import Computerfrom agent import ComputerAgent+ from computer import Computerlogger.debug("Successfully imported Computer and Agent modules")except ImportError as e:@@ -44,17 +45,24 @@ except ImportError as e:sys.exit(1)try:- from .session_manager import get_session_manager, initialize_session_manager, shutdown_session_manager+ from .session_manager import (+ get_session_manager,+ initialize_session_manager,+ shutdown_session_manager,+ )+logger.debug("Successfully imported session manager")except ImportError as e:logger.error(f"Failed to import session manager: {e}")traceback.print_exc(file=sys.stderr)sys.exit(1)+def get_env_bool(key: str, default: bool = False) -> bool:"""Get boolean value from environment variable."""return os.getenv(key, str(default)).lower() in ("true", "1", "yes")+async def _maybe_call_ctx_method(ctx: Context, method_name: str, *args, **kwargs) -> None:"""Call a context helper if it exists, awaiting the result when necessary."""method = getattr(ctx, method_name, None)@@ -64,6 +72,7 @@ async def _maybe_call_ctx_method(ctx: Context, method_name: str, *args, **kwargsif inspect.isawaitable(result):await result+def _normalise_message_content(content: Union[str, List[Dict[str, Any]]]) -> List[Dict[str, Any]]:"""Normalise message content to a list of structured parts."""if isinstance(content, list):@@ -72,6 +81,7 @@ def _normalise_message_content(content: Union[str, List[Dict[str, Any]]]) -> Lisreturn []return [{"type": "output_text", "text": str(content)}]+def _extract_text_from_content(content: Union[str, List[Dict[str, Any]]]) -> str:"""Extract textual content for inclusion in the aggregated result string."""if isinstance(content, str):@@ -84,6 +94,7 @@ def _extract_text_from_content(content: Union[str, List[Dict[str, Any]]]) -> strtexts.append(str(part["text"]))return "\n".join(texts)+def _serialise_tool_content(content: Any) -> str:"""Convert tool outputs into a string for aggregation."""if isinstance(content, str):@@ -91,7 +102,11 @@ def _serialise_tool_content(content: Any) -> str:if isinstance(content, list):texts: List[str] = []for part in content:- if isinstance(part, dict) and part.get("type") in {"output_text", "text"} and part.get("text"):+ if (+ isinstance(part, dict)+ and part.get("type") in {"output_text", "text"}+ and part.get("text")+ ):texts.append(str(part["text"]))if texts:return "\n".join(texts)@@ -99,6 +114,7 @@ def _serialise_tool_content(content: Any) -> str:return ""return str(content)+def serve() -> FastMCP:"""Create and configure the MCP server."""# NOTE: Do not pass model_config here; FastMCP 2.12.x doesn't support it.@@ -108,12 +124,12 @@ def serve() -> FastMCP:async def screenshot_cua(ctx: Context, session_id: Optional[str] = None) -> Any:"""Take a screenshot of the current MacOS VM screen and return the image.-+Args:session_id: Optional session ID for multi-client support. If not provided, a new session will be created."""session_manager = get_session_manager()-+async with session_manager.get_session(session_id) as session:screenshot = await session.computer.interface.screenshot()# Returning Image object is fine when structured_output=False@@ -123,21 +139,21 @@ def serve() -> FastMCP:async def run_cua_task(ctx: Context, task: str, session_id: Optional[str] = None) -> Any:"""Run a Computer-Use Agent (CUA) task in a MacOS VM and return (combined text, final screenshot).-+Args:task: The task description for the agent to executesession_id: Optional session ID for multi-client support. If not provided, a new session will be created."""session_manager = get_session_manager()task_id = str(uuid.uuid4())-+try:logger.info(f"Starting CUA task: {task} (task_id: {task_id})")async with session_manager.get_session(session_id) as session:# Register this task with the sessionawait session_manager.register_task(session.session_id, task_id)-+try:# Get model namemodel_name = os.getenv("CUA_MODEL_NAME", "anthropic/claude-3-5-sonnet-20241022")@@ -179,8 +195,14 @@ def serve() -> FastMCP:elif output_type in {"tool_use", "computer_call", "function_call"}:logger.debug("Streaming tool call: %s", output)call_id = output.get("id") or output.get("call_id")- tool_name = output.get("name") or output.get("action", {}).get("type")- tool_input = output.get("input") or output.get("arguments") or output.get("action")+ tool_name = output.get("name") or output.get("action", {}).get(+ "type"+ )+ tool_input = (+ output.get("input")+ or output.get("arguments")+ or output.get("action")+ )if call_id:await _maybe_call_ctx_method(ctx,@@ -190,7 +212,11 @@ def serve() -> FastMCP:input=tool_input,)- elif output_type in {"tool_result", "computer_call_output", "function_call_output"}:+ elif output_type in {+ "tool_result",+ "computer_call_output",+ "function_call_output",+ }:logger.debug("Streaming tool output: %s", output)call_id = output.get("call_id") or output.get("id")content = output.get("content") or output.get("output")@@ -203,7 +229,8 @@ def serve() -> FastMCP:"yield_tool_output",call_id=call_id,output=content,- is_error=output.get("status") == "failed" or output.get("is_error", False),+ is_error=output.get("status") == "failed"+ or output.get("is_error", False),)logger.info("CUA task completed successfully")@@ -215,10 +242,11 @@ def serve() -> FastMCP:)return (- "\n".join(aggregated_messages).strip() or "Task completed with no text output.",+ "\n".join(aggregated_messages).strip()+ or "Task completed with no text output.",screenshot_image,)-+finally:# Unregister the task from the sessionawait session_manager.unregister_task(session.session_id, task_id)@@ -227,7 +255,7 @@ def serve() -> FastMCP:error_msg = f"Error running CUA task: {str(e)}\n{traceback.format_exc()}"logger.error(error_msg)ctx.error(error_msg)-+# Try to get a screenshot from the session if availabletry:if session_id:@@ -239,7 +267,7 @@ def serve() -> FastMCP:)except Exception:pass-+# If we can't get a screenshot, return a placeholderreturn (f"Error during task execution: {str(e)}",@@ -247,10 +275,12 @@ def serve() -> FastMCP:)@server.tool(structured_output=False)- async def run_multi_cua_tasks(ctx: Context, tasks: List[str], session_id: Optional[str] = None, concurrent: bool = False) -> Any:+ async def run_multi_cua_tasks(+ ctx: Context, tasks: List[str], session_id: Optional[str] = None, concurrent: bool = False+ ) -> Any:"""Run multiple CUA tasks and return a list of (combined text, screenshot).-+Args:tasks: List of task descriptions to executesession_id: Optional session ID for multi-client support. If not provided, a new session will be created.@@ -262,25 +292,27 @@ def serve() -> FastMCP:return []session_manager = get_session_manager()-+if concurrent and total_tasks > 1:# Run tasks concurrentlylogger.info(f"Running {total_tasks} tasks concurrently")ctx.info(f"Running {total_tasks} tasks concurrently")-+# Create tasks with progress tracking- async def run_task_with_progress(task_index: int, task: str) -> Tuple[int, Tuple[str, Image]]:+ async def run_task_with_progress(+ task_index: int, task: str+ ) -> Tuple[int, Tuple[str, Image]]:ctx.report_progress(task_index / total_tasks)result = await run_cua_task(ctx, task, session_id)ctx.report_progress((task_index + 1) / total_tasks)return task_index, result-+# Create all task coroutinestask_coroutines = [run_task_with_progress(i, task) for i, task in enumerate(tasks)]-+# Wait for all tasks to completeresults_with_indices = await asyncio.gather(*task_coroutines, return_exceptions=True)-+# Sort results by original task order and handle exceptionsresults: List[Tuple[str, Image]] = []for result in results_with_indices:@@ -291,13 +323,13 @@ def serve() -> FastMCP:else:_, task_result = resultresults.append(task_result)-+return resultselse:# Run tasks sequentially (original behavior)logger.info(f"Running {total_tasks} tasks sequentially")ctx.info(f"Running {total_tasks} tasks sequentially")-+results: List[Tuple[str, Image]] = []for i, task in enumerate(tasks):logger.info(f"Running task {i+1}/{total_tasks}: {task}")@@ -322,7 +354,7 @@ def serve() -> FastMCP:async def cleanup_session(ctx: Context, session_id: str) -> str:"""Cleanup a specific session and release its resources.-+Args:session_id: The session ID to cleanup"""@@ -335,30 +367,31 @@ def serve() -> FastMCP:server = serve()+async def run_server():"""Run the MCP server with proper lifecycle management."""session_manager = Nonetry:logger.debug("Starting MCP server...")-+# Initialize session managersession_manager = await initialize_session_manager()logger.info("Session manager initialized")-+# Set up signal handlers for graceful shutdowndef signal_handler(signum, frame):logger.info(f"Received signal {signum}, initiating graceful shutdown...")# Create a task to shutdown gracefullyasyncio.create_task(graceful_shutdown())-+signal.signal(signal.SIGINT, signal_handler)signal.signal(signal.SIGTERM, signal_handler)-+# Start the serverlogger.info("Starting FastMCP server...")# Use run_stdio_async directly instead of server.run() to avoid nested event loopsawait server.run_stdio_async()-+except Exception as e:logger.error(f"Error starting server: {e}")traceback.print_exc(file=sys.stderr)@@ -369,6 +402,7 @@ async def run_server():logger.info("Shutting down session manager...")await shutdown_session_manager()+async def graceful_shutdown():"""Gracefully shutdown the server and all sessions."""logger.info("Initiating graceful shutdown...")@@ -380,8 +414,10 @@ async def graceful_shutdown():finally:# Exit the processimport os+os._exit(0)+def main():"""Run the MCP server with proper async lifecycle management."""try:@@ -394,5 +430,6 @@ def main():traceback.print_exc(file=sys.stderr)sys.exit(1)+if __name__ == "__main__":main()diff --git a/libs/python/mcp-server/mcp_server/session_manager.py b/libs/python/mcp-server/mcp_server/session_manager.pyindex 2691e6e5c2..dc8d480ba8 100644--- a/libs/python/mcp-server/mcp_server/session_manager.py+++ b/libs/python/mcp-server/mcp_server/session_manager.py@@ -12,16 +12,18 @@ import asyncioimport loggingimport timeimport uuid-from typing import Dict, Optional, Any, List, Set-from dataclasses import dataclass, field-from contextlib import asynccontextmanagerimport weakref+from contextlib import asynccontextmanager+from dataclasses import dataclass, field+from typing import Any, Dict, List, Optional, Setlogger = logging.getLogger("mcp-server.session_manager")+@dataclassclass SessionInfo:"""Information about an active session."""+session_id: strcomputer: Any # Computer instancecreated_at: float@@ -29,92 +31,95 @@ class SessionInfo:active_tasks: Set[str] = field(default_factory=set)is_shutting_down: bool = False+class ComputerPool:"""Pool of computer instances for efficient resource management."""-+def __init__(self, max_size: int = 5, idle_timeout: float = 300.0):self.max_size = max_sizeself.idle_timeout = idle_timeoutself._available: List[Any] = []self._in_use: Set[Any] = set()self._creation_lock = asyncio.Lock()-+async def acquire(self) -> Any:"""Acquire a computer instance from the pool."""# Try to get an available instanceif self._available:computer = self._available.pop()self._in_use.add(computer)- logger.debug(f"Reusing computer instance from pool")+ logger.debug("Reusing computer instance from pool")return computer-+# Check if we can create a new oneasync with self._creation_lock:if len(self._in_use) < self.max_size:logger.debug("Creating new computer instance")from computer import Computer+computer = Computer(verbosity=logging.INFO)await computer.run()self._in_use.add(computer)return computer-+# Wait for an instance to become availablelogger.debug("Waiting for computer instance to become available")while not self._available:await asyncio.sleep(0.1)-+computer = self._available.pop()self._in_use.add(computer)return computer-+async def release(self, computer: Any) -> None:"""Release a computer instance back to the pool."""if computer in self._in_use:self._in_use.remove(computer)self._available.append(computer)logger.debug("Released computer instance back to pool")-+async def cleanup_idle(self) -> None:"""Clean up idle computer instances."""current_time = time.time()idle_instances = []-+for computer in self._available[:]:# Check if computer has been idle too long# Note: We'd need to track last use time per instance for this# For now, we'll keep instances in the poolpass-+async def shutdown(self) -> None:"""Shutdown all computer instances in the pool."""logger.info("Shutting down computer pool")-+# Close all available instancesfor computer in self._available:try:- if hasattr(computer, 'close'):+ if hasattr(computer, "close"):await computer.close()- elif hasattr(computer, 'stop'):+ elif hasattr(computer, "stop"):await computer.stop()except Exception as e:logger.warning(f"Error closing computer instance: {e}")-+# Close all in-use instancesfor computer in self._in_use:try:- if hasattr(computer, 'close'):+ if hasattr(computer, "close"):await computer.close()- elif hasattr(computer, 'stop'):+ elif hasattr(computer, "stop"):await computer.stop()except Exception as e:logger.warning(f"Error closing computer instance: {e}")-+self._available.clear()self._in_use.clear()+class SessionManager:"""Manages concurrent client sessions with proper resource isolation."""-+def __init__(self, max_concurrent_sessions: int = 10):self.max_concurrent_sessions = max_concurrent_sessionsself._sessions: Dict[str, SessionInfo] = {}@@ -122,39 +127,39 @@ class SessionManager:self._session_lock = asyncio.Lock()self._cleanup_task: Optional[asyncio.Task] = Noneself._shutdown_event = asyncio.Event()-+async def start(self) -> None:"""Start the session manager and cleanup task."""logger.info("Starting session manager")self._cleanup_task = asyncio.create_task(self._cleanup_loop())-+async def stop(self) -> None:"""Stop the session manager and cleanup all resources."""logger.info("Stopping session manager")self._shutdown_event.set()-+if self._cleanup_task:self._cleanup_task.cancel()try:await self._cleanup_taskexcept asyncio.CancelledError:pass-+# Force cleanup all sessionsasync with self._session_lock:session_ids = list(self._sessions.keys())-+for session_id in session_ids:await self._force_cleanup_session(session_id)-+await self._computer_pool.shutdown()-+@asynccontextmanagerasync def get_session(self, session_id: Optional[str] = None) -> Any:"""Get or create a session with proper resource management."""if session_id is None:session_id = str(uuid.uuid4())-+# Check if session exists and is not shutting downasync with self._session_lock:if session_id in self._sessions:@@ -166,18 +171,20 @@ class SessionManager:else:# Create new sessionif len(self._sessions) >= self.max_concurrent_sessions:- raise RuntimeError(f"Maximum concurrent sessions ({self.max_concurrent_sessions}) reached")-+ raise RuntimeError(+ f"Maximum concurrent sessions ({self.max_concurrent_sessions}) reached"+ )+computer = await self._computer_pool.acquire()session = SessionInfo(session_id=session_id,computer=computer,created_at=time.time(),- last_activity=time.time()+ last_activity=time.time(),)self._sessions[session_id] = sessionlogger.info(f"Created new session: {session_id}")-+try:yield sessionfinally:@@ -185,81 +192,82 @@ class SessionManager:async with self._session_lock:if session_id in self._sessions:self._sessions[session_id].last_activity = time.time()-+async def register_task(self, session_id: str, task_id: str) -> None:"""Register a task for a session."""async with self._session_lock:if session_id in self._sessions:self._sessions[session_id].active_tasks.add(task_id)logger.debug(f"Registered task {task_id} for session {session_id}")-+async def unregister_task(self, session_id: str, task_id: str) -> None:"""Unregister a task from a session."""async with self._session_lock:if session_id in self._sessions:self._sessions[session_id].active_tasks.discard(task_id)logger.debug(f"Unregistered task {task_id} from session {session_id}")-+async def cleanup_session(self, session_id: str) -> None:"""Cleanup a specific session."""async with self._session_lock:if session_id not in self._sessions:return-+session = self._sessions[session_id]-+# Check if session has active tasksif session.active_tasks:logger.info(f"Session {session_id} has active tasks, marking for shutdown")session.is_shutting_down = Truereturn-+# Actually cleanup the sessionawait self._force_cleanup_session(session_id)-+async def _force_cleanup_session(self, session_id: str) -> None:"""Force cleanup a session regardless of active tasks."""async with self._session_lock:if session_id not in self._sessions:return-+session = self._sessions[session_id]logger.info(f"Cleaning up session: {session_id}")-+# Release computer back to poolawait self._computer_pool.release(session.computer)-+# Remove sessiondel self._sessions[session_id]-+async def _cleanup_loop(self) -> None:"""Background task to cleanup idle sessions."""while not self._shutdown_event.is_set():try:await asyncio.sleep(60) # Run cleanup every minute-+current_time = time.time()idle_timeout = 600.0 # 10 minutes-+async with self._session_lock:idle_sessions = []for session_id, session in self._sessions.items():if not session.is_shutting_down and not session.active_tasks:if current_time - session.last_activity > idle_timeout:idle_sessions.append(session_id)-+# Cleanup idle sessionsfor session_id in idle_sessions:await self._force_cleanup_session(session_id)logger.info(f"Cleaned up idle session: {session_id}")-+except asyncio.CancelledError:breakexcept Exception as e:logger.error(f"Error in cleanup loop: {e}")-+def get_session_stats(self) -> Dict[str, Any]:"""Get statistics about active sessions."""+async def _get_stats():async with self._session_lock:return {@@ -270,12 +278,12 @@ class SessionManager:"created_at": session.created_at,"last_activity": session.last_activity,"active_tasks": len(session.active_tasks),- "is_shutting_down": session.is_shutting_down+ "is_shutting_down": session.is_shutting_down,}for session_id, session in self._sessions.items()- }+ },}-+# Run in current event loop or create new onetry:loop = asyncio.get_running_loop()@@ -284,9 +292,11 @@ class SessionManager:# No event loop running, create a new onereturn asyncio.run(_get_stats())+# Global session manager instance_session_manager: Optional[SessionManager] = None+def get_session_manager() -> SessionManager:"""Get the global session manager instance."""global _session_manager@@ -294,6 +304,7 @@ def get_session_manager() -> SessionManager:_session_manager = SessionManager()return _session_manager+async def initialize_session_manager() -> None:"""Initialize the global session manager."""global _session_manager@@ -302,6 +313,7 @@ async def initialize_session_manager() -> None:await _session_manager.start()return _session_manager+async def shutdown_session_manager() -> None:"""Shutdown the global session manager."""global _session_managerdiff --git a/libs/python/pylume/README.md b/libs/python/pylume/README.mdindex 4502c9439c..459d1ce546 100644--- a/libs/python/pylume/README.md+++ b/libs/python/pylume/README.md@@ -8,14 +8,14 @@</picture></div>- [](#)- [](#)- [](https://discord.com/invite/mVnXXpdE85)- [](https://pypi.org/project/pylume/)+[](#)+[](#)+[](https://discord.com/invite/mVnXXpdE85)+[](https://pypi.org/project/pylume/)+</h1></div>-**pylume** is a lightweight Python library based on [lume](https://github.com/trycua/lume) to create, run and manage macOS and Linux virtual machines (VMs) natively on Apple Silicon.```bash@@ -28,7 +28,7 @@ Please refer to this [Notebook](./samples/nb.ipynb) for a quickstart. More detai## Prebuilt Images-Pre-built images are available on [ghcr.io/trycua](https://github.com/orgs/trycua/packages).+Pre-built images are available on [ghcr.io/trycua](https://github.com/orgs/trycua/packages).These images come pre-configured with an SSH server and auto-login enabled.## Contributingdiff --git a/libs/python/pylume/__init__.py b/libs/python/pylume/__init__.pyindex 65cacee11b..128ce1211e 100644--- a/libs/python/pylume/__init__.py+++ b/libs/python/pylume/__init__.py@@ -2,8 +2,8 @@PyLume Python SDK - A client library for managing macOS VMs with PyLume."""-from pylume.pylume import *-from pylume.models import *from pylume.exceptions import *+from pylume.models import *+from pylume.pylume import *__version__ = "0.1.0"diff --git a/libs/python/pylume/pylume/client.py b/libs/python/pylume/pylume/client.pyindex 607ddd0a54..101d5ee83d 100644--- a/libs/python/pylume/pylume/client.py+++ b/libs/python/pylume/pylume/client.py@@ -1,18 +1,19 @@-import jsonimport asyncio-import subprocess-from typing import Optional, Any, Dict+import jsonimport shlex+import subprocess+from typing import Any, Dict, Optionalfrom .exceptions import (+ LumeConfigError,+ LumeConnectionError,LumeError,+ LumeNotFoundError,LumeServerError,- LumeConnectionError,LumeTimeoutError,- LumeNotFoundError,- LumeConfigError,)+class LumeClient:def __init__(self, base_url: str, timeout: float = 60.0, debug: bool = False):self.base_url = base_url@@ -26,7 +27,13 @@ class LumeClient:if kwargs:print(json.dumps(kwargs, indent=2))- async def _run_curl(self, method: str, path: str, data: Optional[Dict[str, Any]] = None, params: Optional[Dict[str, Any]] = None) -> Any:+ async def _run_curl(+ self,+ method: str,+ path: str,+ data: Optional[Dict[str, Any]] = None,+ params: Optional[Dict[str, Any]] = None,+ ) -> Any:"""Execute a curl command and return the response."""url = f"{self.base_url}{path}"if params:@@ -34,30 +41,28 @@ class LumeClient:url = f"{url}?{param_str}"cmd = ["curl", "-X", method, "-s", "-w", "%{http_code}", "-m", str(self.timeout)]-+if data is not None:cmd.extend(["-H", "Content-Type: application/json", "-d", json.dumps(data)])-+cmd.append(url)-+self._log_debug(f"Running curl command: {' '.join(map(shlex.quote, cmd))}")-+try:process = await asyncio.create_subprocess_exec(- *cmd,- stdout=subprocess.PIPE,- stderr=subprocess.PIPE+ *cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)stdout, stderr = await process.communicate()-+if process.returncode != 0:raise LumeConnectionError(f"Curl command failed: {stderr.decode()}")-+# The last 3 characters are the status coderesponse = stdout.decode()status_code = int(response[-3:])response_body = response[:-3] # Remove status code from response-+if status_code >= 400:if status_code == 404:raise LumeNotFoundError(f"Resource not found: {path}")@@ -67,9 +72,9 @@ class LumeClient:raise LumeServerError(f"Server error: {response_body}")else:raise LumeError(f"Request failed with status {status_code}: {response_body}")-+return json.loads(response_body) if response_body.strip() else None-+except asyncio.TimeoutError:raise LumeTimeoutError(f"Request timed out after {self.timeout} seconds")@@ -77,7 +82,9 @@ class LumeClient:"""Make a GET request."""return await self._run_curl("GET", path, params=params)- async def post(self, path: str, data: Optional[Dict[str, Any]] = None, timeout: Optional[float] = None) -> Any:+ async def post(+ self, path: str, data: Optional[Dict[str, Any]] = None, timeout: Optional[float] = None+ ) -> Any:"""Make a POST request."""old_timeout = self.timeoutif timeout is not None:@@ -99,14 +106,14 @@ class LumeClient:"""Print equivalent curl command for debugging."""curl_cmd = f"""curl -X {method} \\'{self.base_url}{path}'"""-+if data:curl_cmd += f" \\\n -H 'Content-Type: application/json' \\\n -d '{json.dumps(data)}'"-+print("\nEquivalent curl command:")print(curl_cmd)print()async def close(self) -> None:"""Close the client resources."""- pass # No shared resources to clean up\ No newline at end of file+ pass # No shared resources to clean updiff --git a/libs/python/pylume/pylume/exceptions.py b/libs/python/pylume/pylume/exceptions.pyindex 420b5d4292..191718b0ea 100644--- a/libs/python/pylume/pylume/exceptions.py+++ b/libs/python/pylume/pylume/exceptions.py@@ -1,36 +1,54 @@from typing import Optional+class LumeError(Exception):"""Base exception for all PyLume errors."""+pass+class LumeServerError(LumeError):"""Raised when there's an error with the PyLume server."""- def __init__(self, message: str, status_code: Optional[int] = None, response_text: Optional[str] = None):++ def __init__(+ self, message: str, status_code: Optional[int] = None, response_text: Optional[str] = None+ ):self.status_code = status_codeself.response_text = response_textsuper().__init__(message)+class LumeConnectionError(LumeError):"""Raised when there's an error connecting to the PyLume server."""+pass+class LumeTimeoutError(LumeError):"""Raised when a request to the PyLume server times out."""+pass+class LumeNotFoundError(LumeError):"""Raised when a requested resource is not found."""+pass+class LumeConfigError(LumeError):"""Raised when there's an error with the configuration."""+pass+class LumeVMError(LumeError):"""Raised when there's an error with a VM operation."""+pass+class LumeImageError(LumeError):"""Raised when there's an error with an image operation."""- pass\ No newline at end of file++ passdiff --git a/libs/python/pylume/pylume/models.py b/libs/python/pylume/pylume/models.pyindex cd2ddb2ba7..021ea8aa15 100644--- a/libs/python/pylume/pylume/models.py+++ b/libs/python/pylume/pylume/models.py@@ -1,22 +1,26 @@-from typing import Optional, List, Literal, Dict, Anyimport re-from pydantic import BaseModel, Field, computed_field, validator, ConfigDict, RootModel+from typing import Any, Dict, List, Literal, Optional++from pydantic import BaseModel, ConfigDict, Field, RootModel, computed_field, validator+class DiskInfo(BaseModel):"""Information about disk storage allocation.-+Attributes:total: Total disk space in bytesallocated: Currently allocated disk space in bytes"""+total: intallocated: int+class VMConfig(BaseModel):"""Configuration for creating a new VM.-+Note: Memory and disk sizes should be specified with units (e.g., "4GB", "64GB")-+Attributes:name: Name of the virtual machineos: Operating system type, either "macOS" or "linux"@@ -26,6 +30,7 @@ class VMConfig(BaseModel):display: Display resolution in format "widthxheight"ipsw: IPSW path or 'latest' for macOS VMs, None for other OS types"""+name: stros: Literal["macOS", "linux"] = "macOS"cpu: int = Field(default=2, ge=1)@@ -37,46 +42,53 @@ class VMConfig(BaseModel):class Config:populate_by_alias = True+class SharedDirectory(BaseModel):"""Configuration for a shared directory.-+Attributes:host_path: Path to the directory on the host systemread_only: Whether the directory should be mounted as read-only"""+host_path: str = Field(..., alias="hostPath") # Allow host_path but serialize as hostPathread_only: bool = False-+class Config:populate_by_name = True # Allow both alias and original name- alias_generator = lambda s: ''.join(word.capitalize() if i else word for i, word in enumerate(s.split('_')))+ alias_generator = lambda s: "".join(+ word.capitalize() if i else word for i, word in enumerate(s.split("_"))+ )+class VMRunOpts(BaseModel):"""Configuration for running a VM.-+Args:no_display: Whether to not display the VNC clientshared_directories: List of directories to share with the VM"""+no_display: bool = Field(default=False, alias="noDisplay")shared_directories: Optional[list[SharedDirectory]] = Field(- default=None,- alias="sharedDirectories"+ default=None, alias="sharedDirectories")model_config = ConfigDict(populate_by_name=True,- alias_generator=lambda s: ''.join(word.capitalize() if i else word for i, word in enumerate(s.split('_')))+ alias_generator=lambda s: "".join(+ word.capitalize() if i else word for i, word in enumerate(s.split("_"))+ ),)def model_dump(self, **kwargs):"""Export model data with proper field name conversion.-+Converts shared directory fields to match API expectations when using aliases.-+Args:**kwargs: Keyword arguments passed to parent model_dump method-+Returns:dict: Model data with properly formatted field names"""@@ -84,19 +96,16 @@ class VMRunOpts(BaseModel):# Convert shared directory fields to match API expectationsif self.shared_directories and "by_alias" in kwargs and kwargs["by_alias"]:data["sharedDirectories"] = [- {- "hostPath": d.host_path,- "readOnly": d.read_only- }- for d in self.shared_directories+ {"hostPath": d.host_path, "readOnly": d.read_only} for d in self.shared_directories]# Remove the snake_case version if it existsdata.pop("shared_directories", None)return data+class VMStatus(BaseModel):"""Status information for a virtual machine.-+Attributes:name: Name of the virtual machinestatus: Current status of the VM@@ -107,6 +116,7 @@ class VMStatus(BaseModel):vnc_url: URL for VNC connection if availableip_address: IP address of the VM if available"""+name: strstatus: stros: Literal["macOS", "linux"]@@ -123,7 +133,7 @@ class VMStatus(BaseModel):@propertydef state(self) -> str:"""Get the current state of the VM.-+Returns:str: Current VM status"""@@ -133,7 +143,7 @@ class VMStatus(BaseModel):@propertydef cpu(self) -> int:"""Get the number of CPU cores.-+Returns:int: Number of CPU cores allocated to the VM"""@@ -143,7 +153,7 @@ class VMStatus(BaseModel):@propertydef memory(self) -> str:"""Get memory allocation in human-readable format.-+Returns:str: Memory size formatted as "{size}GB""""@@ -151,27 +161,31 @@ class VMStatus(BaseModel):gb = self.memory_size / (1024 * 1024 * 1024)return f"{int(gb)}GB"+class VMUpdateOpts(BaseModel):"""Options for updating VM configuration.-+Attributes:cpu: Number of CPU cores to update tomemory: Amount of memory to update to with unitsdisk_size: Size of disk to update to with units"""+cpu: Optional[int] = Nonememory: Optional[str] = Nonedisk_size: Optional[str] = None+class ImageRef(BaseModel):"""Reference to a VM image.-+Attributes:image: Name of the imagetag: Tag version of the imageregistry: Registry hostname where image is storedorganization: Organization or namespace in the registry"""+image: strtag: str = "latest"registry: Optional[str] = "ghcr.io"@@ -179,47 +193,53 @@ class ImageRef(BaseModel):def model_dump(self, **kwargs):"""Override model_dump to return just the image:tag format.-+Args:**kwargs: Keyword arguments (ignored)-+Returns:str: Image reference in "image:tag" format"""return f"{self.image}:{self.tag}"+class CloneSpec(BaseModel):"""Specification for cloning a VM.-+Attributes:name: Name of the source VM to clonenew_name: Name for the new cloned VM"""+name: strnew_name: str = Field(alias="newName")class Config:populate_by_alias = True+class ImageInfo(BaseModel):"""Model for individual image information.-+Attributes:imageId: Unique identifier for the image"""+imageId: str+class ImageList(RootModel):"""Response model for the images endpoint.-+A list-like container for ImageInfo objects that providesiteration and indexing capabilities."""+root: List[ImageInfo]def __iter__(self):"""Iterate over the image list.-+Returns:Iterator over ImageInfo objects"""@@ -227,10 +247,10 @@ class ImageList(RootModel):def __getitem__(self, item):"""Get an item from the image list by index.-+Args:item: Index or slice to retrieve-+Returns:ImageInfo or list of ImageInfo objects"""@@ -238,8 +258,8 @@ class ImageList(RootModel):def __len__(self):"""Get the number of images in the list.-+Returns:int: Number of images in the list"""- return len(self.root)\ No newline at end of file+ return len(self.root)diff --git a/libs/python/pylume/pylume/pylume.py b/libs/python/pylume/pylume/pylume.pyindex 2073b8834f..1bbe34b273 100644--- a/libs/python/pylume/pylume/pylume.py+++ b/libs/python/pylume/pylume/pylume.py@@ -1,36 +1,36 @@+import asyncio+import jsonimport os+import re+import signal+import subprocessimport sys-import jsonimport time-import asyncio-import subprocess-from typing import Optional, List, Union, Callable, TypeVar, Anyfrom functools import wraps-import re-import signal+from typing import Any, Callable, List, Optional, TypeVar, Union-from .server import LumeServerfrom .client import LumeClient-from .models import (- VMConfig,- VMStatus,- VMRunOpts,- VMUpdateOpts,- ImageRef,- CloneSpec,- SharedDirectory,- ImageList,-)from .exceptions import (+ LumeConfigError,+ LumeConnectionError,LumeError,+ LumeImageError,+ LumeNotFoundError,LumeServerError,- LumeConnectionError,LumeTimeoutError,- LumeNotFoundError,- LumeConfigError,LumeVMError,- LumeImageError,)+from .models import (+ CloneSpec,+ ImageList,+ ImageRef,+ SharedDirectory,+ VMConfig,+ VMRunOpts,+ VMStatus,+ VMUpdateOpts,+)+from .server import LumeServer# Type variable for the decoratorT = TypeVar("T")diff --git a/libs/python/pylume/pylume/server.py b/libs/python/pylume/pylume/server.pyindex 01c480849a..cab5f627f8 100644--- a/libs/python/pylume/pylume/server.py+++ b/libs/python/pylume/pylume/server.py@@ -1,18 +1,19 @@-import os-import timeimport asyncio-import subprocess-import tempfile+import jsonimport logging+import os+import random+import shlex+import signalimport socket-from typing import Optional+import subprocessimport sys-from .exceptions import LumeConnectionError-import signal-import json-import shlex-import random+import tempfile+import timefrom logging import getLogger+from typing import Optional++from .exceptions import LumeConnectionErrorclass LumeServer:diff --git a/libs/python/som/README.md b/libs/python/som/README.mdindex 02802bfcfb..ad7e906af0 100644--- a/libs/python/som/README.md+++ b/libs/python/som/README.md@@ -8,10 +8,11 @@</picture></div>- [](#)- [](#)- [](https://discord.com/invite/mVnXXpdE85)- [](https://pypi.org/project/cua-computer/)+[](#)+[](#)+[](https://discord.com/invite/mVnXXpdE85)+[](https://pypi.org/project/cua-computer/)+</h1></div>@@ -33,7 +34,6 @@- Uses Metal Performance Shaders (MPS)- Multi-scale detection enabled- ~0.4s average detection time-- **Supported**: Any Python 3.11+ environment- Falls back to CPU if no GPU available- Single-scale detection on CPU@@ -82,11 +82,13 @@ for elem in result.elements:## Development### Test Data+- Place test screenshots in `examples/test_data/`- Not tracked in git to keep repository size manageable- Default test image: `test_screen.png` (1920x1080)### Running Tests+```bash# Run benchmark with no OCRpython examples/omniparser_examples.py examples/test_data/test_screen.png --runs 5 --ocr nonediff --git a/libs/python/som/som/__init__.py b/libs/python/som/som/__init__.pyindex 906da597ba..48b0c7e823 100644--- a/libs/python/som/som/__init__.py+++ b/libs/python/som/som/__init__.py@@ -5,11 +5,11 @@ __version__ = "0.1.0"from .detect import OmniParserfrom .models import (BoundingBox,- UIElement,IconElement,- TextElement,+ ParseResult,ParserMetadata,- ParseResult+ TextElement,+ UIElement,)__all__ = [@@ -19,5 +19,5 @@ __all__ = ["IconElement","TextElement","ParserMetadata",- "ParseResult"-]\ No newline at end of file+ "ParseResult",+]diff --git a/libs/python/som/som/detect.py b/libs/python/som/som/detect.pyindex 79e648864f..8b27d52930 100644--- a/libs/python/som/som/detect.py+++ b/libs/python/som/som/detect.py@@ -1,28 +1,35 @@-from pathlib import Path-from typing import Union, List, Dict, Any, Tuple, Optional, cast-import logging-import torch-import torchvision.ops-import cv2-import numpy as np-import time-import torchvision.transforms as T-from PIL import Image-import io-import base64import argparse+import base64+import io+import loggingimport signal+import timefrom contextlib import contextmanager+from pathlib import Path+from typing import Any, Dict, List, Optional, Tuple, Union, cast-from ultralytics import YOLO-from huggingface_hub import hf_hub_download+import cv2+import numpy as npimport supervision as sv+import torch+import torchvision.ops+import torchvision.transforms as T+from huggingface_hub import hf_hub_download+from PIL import Imagefrom supervision.detection.core import Detections+from ultralytics import YOLOfrom .detection import DetectionProcessor+from .models import (+ BoundingBox,+ IconElement,+ ParseResult,+ ParserMetadata,+ TextElement,+ UIElement,+)from .ocr import OCRProcessorfrom .visualization import BoxAnnotator-from .models import BoundingBox, UIElement, IconElement, TextElement, ParserMetadata, ParseResultlogger = logging.getLogger(__name__)@@ -50,8 +57,9 @@ def timeout(seconds: int):def process_text_box(box, image):"""Process a single text box with OCR."""try:+ from typing import Any, List, Sequence, Tuple+import easyocr- from typing import List, Tuple, Any, Sequencex1 = int(min(point[0] for point in box))y1 = int(min(point[1] for point in box))@@ -100,6 +108,7 @@ def check_ocr_box(image_path: Union[str, Path]) -> Tuple[List[str], List[List[fl# Use EasyOCRimport ssl+import easyocr# Create unverified SSL context for development@@ -231,7 +240,7 @@ class OmniParser:for i, det in enumerate(text_detections)],)-+if elements and text_elements:# Filter out non-OCR elements that have OCR elements with center points colliding with themfiltered_elements = []@@ -241,17 +250,21 @@ class OmniParser:# Calculate center point of the text elementcenter_x = (text_elem.bbox.x1 + text_elem.bbox.x2) / 2center_y = (text_elem.bbox.y1 + text_elem.bbox.y2) / 2-+# Check if this center point is inside the non-OCR element- if (center_x >= elem.bbox.x1 and center_x <= elem.bbox.x2 and- center_y >= elem.bbox.y1 and center_y <= elem.bbox.y2):+ if (+ center_x >= elem.bbox.x1+ and center_x <= elem.bbox.x2+ and center_y >= elem.bbox.y1+ and center_y <= elem.bbox.y2+ ):should_keep = Falsebreak-+if should_keep:filtered_elements.append(elem)elements = filtered_elements-+# Merge detections using NMSall_elements = elements + text_elementsboxes = torch.tensor([elem.bbox.coordinates for elem in all_elements])diff --git a/libs/python/som/som/detection.py b/libs/python/som/som/detection.pyindex 3b585d9eaf..bc7454fd76 100644--- a/libs/python/som/som/detection.py+++ b/libs/python/som/som/detection.py@@ -1,12 +1,13 @@-from typing import List, Dict, Any, Tuple, Optionalimport logging+from pathlib import Path+from typing import Any, Dict, List, Optional, Tuple++import numpy as npimport torchimport torchvision+from huggingface_hub import hf_hub_downloadfrom PIL import Image-import numpy as npfrom ultralytics import YOLO-from huggingface_hub import hf_hub_download-from pathlib import Pathlogger = logging.getLogger(__name__)diff --git a/libs/python/som/som/models.py b/libs/python/som/som/models.pyindex aa11610668..fc1e350351 100644--- a/libs/python/som/som/models.py+++ b/libs/python/som/som/models.py@@ -1,4 +1,5 @@-from typing import List, Tuple, Optional, Literal, Dict, Any, Union+from typing import Any, Dict, List, Literal, Optional, Tuple, Union+from pydantic import BaseModel, Field, validatordiff --git a/libs/python/som/som/ocr.py b/libs/python/som/som/ocr.pyindex 32f15bd130..73f677b9ec 100644--- a/libs/python/som/som/ocr.py+++ b/libs/python/som/som/ocr.py@@ -1,12 +1,13 @@-from typing import List, Dict, Any, Tuple, Unionimport loggingimport signalfrom contextlib import contextmanagerfrom pathlib import Path+from typing import Any, Dict, List, Tuple, Union+import easyocr-from PIL import Imageimport numpy as npimport torch+from PIL import Imagelogger = logging.getLogger(__name__)@@ -18,9 +19,10 @@ class TimeoutException(Exception):@contextmanagerdef timeout(seconds: int):import threading-+# Check if we're in the main threadif threading.current_thread() is threading.main_thread():+def timeout_handler(signum, frame):raise TimeoutException("OCR process timed out")@@ -34,7 +36,9 @@ def timeout(seconds: int):signal.signal(signal.SIGALRM, original_handler)else:# In a non-main thread, we can't use signal- logger.warning("Timeout function called from non-main thread; signal-based timeout disabled")+ logger.warning(+ "Timeout function called from non-main thread; signal-based timeout disabled"+ )try:yieldfinally:@@ -80,7 +84,7 @@ class OCRProcessor:# Use GPU if availableuse_gpu = self.device in ["cuda", "mps"]self.reader = easyocr.Reader(["en"], gpu=use_gpu)-+# Verify reader initializationif self.reader is None:raise ValueError("Failed to initialize EasyOCR reader")diff --git a/libs/python/som/som/util/utils.py b/libs/python/som/som/util/utils.pyindex 4303b91d6b..e635adcdff 100644--- a/libs/python/som/som/util/utils.py+++ b/libs/python/som/som/util/utils.py@@ -1,13 +1,14 @@-import easyocr+import logging+import signal+import time+from contextlib import contextmanager+from typing import Any, List, Optional, Sequence, Tuple, Union, cast+import cv2+import easyocrimport matplotlib.pyplot as pltimport numpy as npfrom PIL import Image-from typing import Union, List, Tuple, Any, Optional, cast, Sequence-import time-import signal-from contextlib import contextmanager-import logginglogger = logging.getLogger(__name__)diff --git a/libs/python/som/som/visualization.py b/libs/python/som/som/visualization.pyindex 038af0f5ae..2668b23125 100644--- a/libs/python/som/som/visualization.py+++ b/libs/python/som/som/visualization.py@@ -1,10 +1,11 @@-from typing import List, Dict, Any, Tuple+import logging+import os+import platform+from typing import Any, Dict, List, Tuple+import numpy as np-from PIL import Image, ImageDraw, ImageFontimport supervision as sv-import platform-import os-import logging+from PIL import Image, ImageDraw, ImageFontlogger = logging.getLogger(__name__)@@ -184,7 +185,7 @@ class BoxAnnotator:new_box = (x, y, x + box_width, y + box_height)label_width = new_box[2] - new_box[0]label_height = new_box[3] - new_box[1]-+for used_box in used_areas:if not (new_box[2] < used_box[0] # new box is left of used box@@ -195,9 +196,11 @@ class BoxAnnotator:# Calculate dimensions of the used boxused_box_width = used_box[2] - used_box[0]used_box_height = used_box[3] - used_box[1]-+# Only consider as collision if used box is NOT more than 5x bigger in both dimensions- if not (used_box_width > 5 * label_width and used_box_height > 5 * label_height):+ if not (+ used_box_width > 5 * label_width and used_box_height > 5 * label_height+ ):return Truereturn Falsediff --git a/libs/typescript/agent/README.md b/libs/typescript/agent/README.mdindex 76db192e2a..27c152fb06 100644--- a/libs/typescript/agent/README.md+++ b/libs/typescript/agent/README.md@@ -17,28 +17,27 @@ yarn add @trycua/agent### Basic Usage```typescript-import AgentClient from "@trycua/agent";+import AgentClient from '@trycua/agent';// Connect to local HTTP server-const client = new AgentClient("https://localhost:8000");+const client = new AgentClient('https://localhost:8000');// Connect to a cloud container (port 8443 over HTTPS)-const cloud = new AgentClient(- "https://m-linux-96lcxd2c2k.containers.cloud.trycua.com:8443",- { apiKey: process.env.NEXT_PUBLIC_CUA_API_KEY || "" }-);+const cloud = new AgentClient('https://m-linux-96lcxd2c2k.containers.cloud.trycua.com:8443', {+ apiKey: process.env.NEXT_PUBLIC_CUA_API_KEY || '',+});// Connect to peer-const peerClient = new AgentClient("peer://my-agent-proxy");+const peerClient = new AgentClient('peer://my-agent-proxy');// Send a simple text requestconst response = await client.responses.create({- model: "anthropic/claude-3-5-sonnet-20241022",- input: "Write a one-sentence bedtime story about a unicorn.",+ model: 'anthropic/claude-3-5-sonnet-20241022',+ input: 'Write a one-sentence bedtime story about a unicorn.',// Optional per-request env overridesenv: {- OPENAI_API_KEY: "sk-..."- }+ OPENAI_API_KEY: 'sk-...',+ },});console.log(response.output);@@ -48,48 +47,48 @@ console.log(response.output);```typescriptconst response = await client.responses.create({- model: "anthropic/claude-3-5-sonnet-20241022",+ model: 'anthropic/claude-3-5-sonnet-20241022',input: [{- role: "user",+ role: 'user',content: [- { type: "input_text", text: "What is in this image?" },- {- type: "input_image",- image_url: "https://example.com/image.jpg"- }- ]- }+ { type: 'input_text', text: 'What is in this image?' },+ {+ type: 'input_image',+ image_url: 'https://example.com/image.jpg',+ },+ ],+ },],- env: { OPENROUTER_API_KEY: "sk-..." }+ env: { OPENROUTER_API_KEY: 'sk-...' },});```### Advanced Configuration```typescript-const client = new AgentClient("https://localhost:8000", {+const client = new AgentClient('https://localhost:8000', {timeout: 60000, // 60 second timeout- retries: 5, // 5 retry attempts- apiKey: "cua_...", // sent as X-API-Key header when using HTTP/HTTPS+ retries: 5, // 5 retry attempts+ apiKey: 'cua_...', // sent as X-API-Key header when using HTTP/HTTPS});const response = await client.responses.create({- model: "anthropic/claude-3-5-sonnet-20241022",- input: "Hello, world!",+ model: 'anthropic/claude-3-5-sonnet-20241022',+ input: 'Hello, world!',agent_kwargs: {save_trajectory: true,- verbosity: 20+ verbosity: 20,},computer_kwargs: {- os_type: "linux",- provider_type: "cloud"+ os_type: 'linux',+ provider_type: 'cloud',},// Per-request env overridesenv: {- ANTHROPIC_API_KEY: "sk-...",- OPENROUTER_API_KEY: "sk-..."- }+ ANTHROPIC_API_KEY: 'sk-...',+ OPENROUTER_API_KEY: 'sk-...',+ },});```@@ -174,6 +173,7 @@ interface Usage {```The `output` array contains the conversation history including:+- User messages- Agent reasoning/thinking- Computer actions and their results@@ -189,16 +189,16 @@ Connect to a CUA agent proxy server:```typescript// Local-const client = new AgentClient("https://my-agent-server.com:8000", { apiKey: "cua_..." });+const client = new AgentClient('https://my-agent-server.com:8000', { apiKey: 'cua_...' });// Cloud container (port 8443)-const cloud = new AgentClient(- "https://m-linux-96lcxd2c2k.containers.cloud.trycua.com:8443",- { apiKey: "cua_..." }-);+const cloud = new AgentClient('https://m-linux-96lcxd2c2k.containers.cloud.trycua.com:8443', {+ apiKey: 'cua_...',+});```Notes:+- The client sends the API key as `X-API-Key` for HTTP/HTTPS connections.- Cloud containers listen on `:8443` with HTTPS.@@ -207,7 +207,7 @@ Notes:Connect directly to another peer using WebRTC:```typescript-const client = new AgentClient("peer://agent-proxy-peer-id");+const client = new AgentClient('peer://agent-proxy-peer-id');```The client uses PeerJS with default configuration for peer connections.diff --git a/libs/typescript/agent/examples/README.md b/libs/typescript/agent/examples/README.mdindex 9893946649..d27eac5910 100644--- a/libs/typescript/agent/examples/README.md+++ b/libs/typescript/agent/examples/README.md@@ -9,6 +9,7 @@ This directory contains examples demonstrating how to use the `@trycua/agent` clA simple HTML page that demonstrates using the CUA Agent Client in a browser environment.**Features:**+- Connect to HTTP/HTTPS or P2P (peer://) agent proxies- Send text messages to any supported model- View responses in real-time@@ -18,19 +19,21 @@ A simple HTML page that demonstrates using the CUA Agent Client in a browser env**Usage:**1. **Build the library first:**+```bashcd ../pnpm build```2. **Start a local web server** (required for ES modules):+```bash# Option 1: Using Pythonpython -m http.server 8080-+# Option 2: Using Node.js (if you have http-server installed)npx http-server -p 8080-+# Option 3: Using any other local server```@@ -44,10 +47,12 @@ A simple HTML page that demonstrates using the CUA Agent Client in a browser env- View the response in the output textarea**Supported URLs:**+- **HTTP/HTTPS**: `https://localhost:8000`, `http://my-agent-server.com:8080`- **Peer-to-Peer**: `peer://computer-agent-proxy`, `peer://any-peer-id`**Example Models:**+- `anthropic/claude-3-5-sonnet-20241022`- `openai/gpt-4`- `huggingface-local/microsoft/UI-TARS-7B`diff --git a/libs/typescript/agent/src/client.ts b/libs/typescript/agent/src/client.tsindex d25e698b9d..2ae4da6628 100644--- a/libs/typescript/agent/src/client.ts+++ b/libs/typescript/agent/src/client.ts@@ -1,10 +1,5 @@-import {Peer} from "peerjs";-import type {- AgentRequest,- AgentResponse,- ConnectionType,- AgentClientOptions,-} from "./types";+import { Peer } from 'peerjs';+import type { AgentRequest, AgentResponse, ConnectionType, AgentClientOptions } from './types';export class AgentClient {private url: string;@@ -22,14 +17,12 @@ export class AgentClient {};// Determine connection type from URL- if (url.startsWith("http://") || url.startsWith("https://")) {- this.connectionType = url.startsWith("https://") ? "https" : "http";- } else if (url.startsWith("peer://")) {- this.connectionType = "peer";+ if (url.startsWith('http://') || url.startsWith('https://')) {+ this.connectionType = url.startsWith('https://') ? 'https' : 'http';+ } else if (url.startsWith('peer://')) {+ this.connectionType = 'peer';} else {- throw new Error(- "Invalid URL format. Must start with http://, https://, or peer://"- );+ throw new Error('Invalid URL format. Must start with http://, https://, or peer://');}}@@ -42,10 +35,10 @@ export class AgentClient {private async sendRequest(request: AgentRequest): Promise<AgentResponse> {switch (this.connectionType) {- case "http":- case "https":+ case 'http':+ case 'https':return this.sendHttpRequest(request);- case "peer":+ case 'peer':return this.sendPeerRequest(request);default:throw new Error(`Unsupported connection type: ${this.connectionType}`);@@ -54,21 +47,18 @@ export class AgentClient {private async sendHttpRequest(request: AgentRequest): Promise<AgentResponse> {const controller = new AbortController();- const timeoutId = setTimeout(- () => controller.abort(),- this.options.timeout- );+ const timeoutId = setTimeout(() => controller.abort(), this.options.timeout);try {const headers: Record<string, string> = {- "Content-Type": "application/json",+ 'Content-Type': 'application/json',};if (this.options.apiKey) {- headers["X-API-Key"] = this.options.apiKey;+ headers['X-API-Key'] = this.options.apiKey;}const response = await fetch(`${this.url}/responses`, {- method: "POST",+ method: 'POST',headers,body: JSON.stringify(request),signal: controller.signal,@@ -93,7 +83,7 @@ export class AgentClient {private async sendPeerRequest(request: AgentRequest): Promise<AgentResponse> {// Extract peer ID from peer:// URL- const peerId = this.url.replace("peer://", "");+ const peerId = this.url.replace('peer://', '');if (!this.peer) {// Initialize peer connection with default options as requested@@ -101,36 +91,35 @@ export class AgentClient {return new Promise<AgentResponse>((resolve, reject) => {const timeout = setTimeout(() => {- reject(new Error("Peer connection timeout"));+ reject(new Error('Peer connection timeout'));}, this.options.timeout);- this.peer!.on("open", () => {+ this.peer!.on('open', () => {// Connect to the target peerthis.connection = this.peer!.connect(peerId);- this.connection.on("open", () => {+ this.connection.on('open', () => {// Send the requestthis.connection!.send(JSON.stringify(request));});- this.connection.on("data", (data: any) => {+ this.connection.on('data', (data: any) => {clearTimeout(timeout);try {- const response =- typeof data === "string" ? JSON.parse(data) : data;+ const response = typeof data === 'string' ? JSON.parse(data) : data;resolve(response as AgentResponse);} catch (error) {- reject(new Error("Failed to parse peer response"));+ reject(new Error('Failed to parse peer response'));}});- this.connection.on("error", (error: any) => {+ this.connection.on('error', (error: any) => {clearTimeout(timeout);reject(new Error(`Peer connection error: ${error}`));});});- this.peer!.on("error", (error: any) => {+ this.peer!.on('error', (error: any) => {clearTimeout(timeout);reject(new Error(`Peer error: ${error}`));});@@ -139,7 +128,7 @@ export class AgentClient {// Reuse existing connectionreturn new Promise<AgentResponse>((resolve, reject) => {const timeout = setTimeout(() => {- reject(new Error("Peer request timeout"));+ reject(new Error('Peer request timeout'));}, this.options.timeout);if (this.connection && this.connection.open) {@@ -147,20 +136,19 @@ export class AgentClient {const handleData = (data: any) => {clearTimeout(timeout);- this.connection!.off("data", handleData);+ this.connection!.off('data', handleData);try {- const response =- typeof data === "string" ? JSON.parse(data) : data;+ const response = typeof data === 'string' ? JSON.parse(data) : data;resolve(response as AgentResponse);} catch (error) {- reject(new Error("Failed to parse peer response"));+ reject(new Error('Failed to parse peer response'));}};- this.connection.on("data", handleData);+ this.connection.on('data', handleData);} else {clearTimeout(timeout);- reject(new Error("Peer connection not available"));+ reject(new Error('Peer connection not available'));}});}@@ -168,18 +156,18 @@ export class AgentClient {// Health check methodasync health(): Promise<{ status: string }> {- if (this.connectionType === "peer") {- return { status: this.peer?.open ? "connected" : "disconnected" };+ if (this.connectionType === 'peer') {+ return { status: this.peer?.open ? 'connected' : 'disconnected' };}try {const response = await fetch(`${this.url}/health`);if (response.ok) {- return { status: "healthy" };+ return { status: 'healthy' };}- return { status: "unhealthy" };+ return { status: 'unhealthy' };} catch {- return { status: "unreachable" };+ return { status: 'unreachable' };}}diff --git a/libs/typescript/agent/src/types.ts b/libs/typescript/agent/src/types.tsindex 30e7340adb..eec5b1f815 100644--- a/libs/typescript/agent/src/types.ts+++ b/libs/typescript/agent/src/types.ts@@ -28,7 +28,6 @@ export interface AgentRequest {}// #endregion-// #region Response// Response typesexport interface AgentResponse {@@ -46,11 +45,9 @@ export interface Usage {}// #endregion--// #region Messages// Agent message types - can be one of several different message types-export type AgentMessage =+export type AgentMessage =| UserMessage| AssistantMessage| ReasoningMessage@@ -104,8 +101,6 @@ export interface FunctionCallOutputMessage {}// #endregion--// #region Message Contentexport interface InputContent {type: 'input_image' | 'input_text';@@ -126,14 +121,10 @@ export interface ComputerResultContent {}// #endregion--// #region Actions-export type ComputerAction =- | ComputerActionOpenAI- | ComputerActionAnthropic;+export type ComputerAction = ComputerActionOpenAI | ComputerActionAnthropic;// OpenAI Computer Actions-export type ComputerActionOpenAI =+export type ComputerActionOpenAI =| ClickAction| DoubleClickAction| DragAction@@ -187,9 +178,7 @@ export interface WaitAction {type: 'wait';}// Anthropic Computer Actions-export type ComputerActionAnthropic =- | LeftMouseDownAction- | LeftMouseUpAction;+export type ComputerActionAnthropic = LeftMouseDownAction | LeftMouseUpAction;export interface LeftMouseDownAction {type: 'left_mouse_down';x: number;@@ -200,4 +189,4 @@ export interface LeftMouseUpAction {x: number;y: number;}-// #endregion\ No newline at end of file+// #endregiondiff --git a/libs/typescript/agent/tsconfig.json b/libs/typescript/agent/tsconfig.jsonindex 8d56b691fb..cdcd74de6f 100644--- a/libs/typescript/agent/tsconfig.json+++ b/libs/typescript/agent/tsconfig.json@@ -1,28 +1,22 @@{- "compilerOptions": {- "target": "esnext",- "lib": [- "es2023"- ],- "moduleDetection": "force",- "module": "preserve",- "moduleResolution": "bundler",- "allowImportingTsExtensions": true,- "resolveJsonModule": true,- "types": [- "node"- ],- "allowSyntheticDefaultImports": true,- "strict": true,- "noUnusedLocals": true,- "declaration": true,- "emitDeclarationOnly": true,- "esModuleInterop": true,- "isolatedModules": true,- "verbatimModuleSyntax": true,- "skipLibCheck": true- },- "include": [- "src"- ]-}\ No newline at end of file+ "compilerOptions": {+ "target": "esnext",+ "lib": ["es2023"],+ "moduleDetection": "force",+ "module": "preserve",+ "moduleResolution": "bundler",+ "allowImportingTsExtensions": true,+ "resolveJsonModule": true,+ "types": ["node"],+ "allowSyntheticDefaultImports": true,+ "strict": true,+ "noUnusedLocals": true,+ "declaration": true,+ "emitDeclarationOnly": true,+ "esModuleInterop": true,+ "isolatedModules": true,+ "verbatimModuleSyntax": true,+ "skipLibCheck": true+ },+ "include": ["src"]+}diff --git a/libs/typescript/agent/tsdown.config.ts b/libs/typescript/agent/tsdown.config.tsindex b837b6ee98..efbd5ff2ef 100644--- a/libs/typescript/agent/tsdown.config.ts+++ b/libs/typescript/agent/tsdown.config.ts@@ -1,12 +1,12 @@-import { defineConfig } from "tsdown";+import { defineConfig } from 'tsdown';export default defineConfig({- entry: ["src/index.ts"],- format: ["module"],- platform: "browser",+ entry: ['src/index.ts'],+ format: ['module'],+ platform: 'browser',dts: true,clean: true,- // Remove if we don't need to support including the library via '<script/>' tags.+ // Remove if we don't need to support including the library via '<script/>' tags.// noExternal bundles this list of libraries within the final 'dist'- noExternal: ['peerjs']+ noExternal: ['peerjs'],});diff --git a/libs/typescript/agent/vitest.config.ts b/libs/typescript/agent/vitest.config.tsindex 56feb5b7e0..a9f5456ffd 100644--- a/libs/typescript/agent/vitest.config.ts+++ b/libs/typescript/agent/vitest.config.ts@@ -1,7 +1,7 @@-import { defineConfig } from 'vitest/config'+import { defineConfig } from 'vitest/config';export default defineConfig({test: {environment: 'happy-dom',},-})+});diff --git a/libs/typescript/computer/README.md b/libs/typescript/computer/README.mdindex 2505ee63b1..376734a003 100644--- a/libs/typescript/computer/README.md+++ b/libs/typescript/computer/README.md@@ -8,10 +8,11 @@</picture></div>- [](#)- [](#)- [](https://discord.com/invite/mVnXXpdE85)- [](https://www.npmjs.com/package/@trycua/computer)+[](#)+[](#)+[](https://discord.com/invite/mVnXXpdE85)+[](https://www.npmjs.com/package/@trycua/computer)+</h1></div>@@ -30,7 +31,7 @@ import { Computer, OSType } from '@trycua/computer';const computer = new Computer({osType: OSType.LINUX,name: 's-linux-vm_id',- apiKey: 'your-api-key'+ apiKey: 'your-api-key',});// Start the computerdiff --git a/libs/typescript/computer/src/computer/providers/base.ts b/libs/typescript/computer/src/computer/providers/base.tsindex ffd6da2de0..5e50b21176 100644--- a/libs/typescript/computer/src/computer/providers/base.ts+++ b/libs/typescript/computer/src/computer/providers/base.ts@@ -1,117 +1,115 @@-import os from "node:os";-import { Telemetry } from "@trycua/core";-import pino from "pino";-import type { OSType } from "../../types";-import type { BaseComputerConfig, Display, VMProviderType } from "../types";+import os from 'node:os';+import { Telemetry } from '@trycua/core';+import pino from 'pino';+import type { OSType } from '../../types';+import type { BaseComputerConfig, Display, VMProviderType } from '../types';-const logger = pino({ name: "computer.provider_base" });+const logger = pino({ name: 'computer.provider_base' });/*** Base Computer class with shared functionality*/export abstract class BaseComputer {- protected name: string;- protected osType: OSType;- protected vmProvider?: VMProviderType;- protected telemetry: Telemetry;+ protected name: string;+ protected osType: OSType;+ protected vmProvider?: VMProviderType;+ protected telemetry: Telemetry;- constructor(config: BaseComputerConfig) {- this.name = config.name;- this.osType = config.osType;- this.telemetry = new Telemetry();- this.telemetry.recordEvent("module_init", {- module: "computer",- version: process.env.npm_package_version,- node_version: process.version,- });+ constructor(config: BaseComputerConfig) {+ this.name = config.name;+ this.osType = config.osType;+ this.telemetry = new Telemetry();+ this.telemetry.recordEvent('module_init', {+ module: 'computer',+ version: process.env.npm_package_version,+ node_version: process.version,+ });- this.telemetry.recordEvent("computer_initialized", {- os: os.platform(),- os_version: os.version(),- node_version: process.version,- });- }+ this.telemetry.recordEvent('computer_initialized', {+ os: os.platform(),+ os_version: os.version(),+ node_version: process.version,+ });+ }- /**- * Get the name of the computer- */- getName(): string {- return this.name;- }+ /**+ * Get the name of the computer+ */+ getName(): string {+ return this.name;+ }- /**- * Get the OS type of the computer- */- getOSType(): OSType {- return this.osType;- }+ /**+ * Get the OS type of the computer+ */+ getOSType(): OSType {+ return this.osType;+ }- /**- * Get the VM provider type- */- getVMProviderType(): VMProviderType | undefined {- return this.vmProvider;- }+ /**+ * Get the VM provider type+ */+ getVMProviderType(): VMProviderType | undefined {+ return this.vmProvider;+ }- /**- * Shared method available to all computer types- */- async disconnect(): Promise<void> {- logger.info(`Disconnecting from ${this.name}`);- // Implementation would go here- }+ /**+ * Shared method available to all computer types+ */+ async disconnect(): Promise<void> {+ logger.info(`Disconnecting from ${this.name}`);+ // Implementation would go here+ }- /**- * Parse display string into Display object- * @param display Display string in format "WIDTHxHEIGHT"- * @returns Display object- */- public static parseDisplayString(display: string): Display {- const match = display.match(/^(\d+)x(\d+)$/);- if (!match) {- throw new Error(- `Invalid display format: ${display}. Expected format: WIDTHxHEIGHT`,- );- }+ /**+ * Parse display string into Display object+ * @param display Display string in format "WIDTHxHEIGHT"+ * @returns Display object+ */+ public static parseDisplayString(display: string): Display {+ const match = display.match(/^(\d+)x(\d+)$/);+ if (!match) {+ throw new Error(`Invalid display format: ${display}. Expected format: WIDTHxHEIGHT`);+ }- return {- width: Number.parseInt(match[1], 10),- height: Number.parseInt(match[2], 10),- };- }+ return {+ width: Number.parseInt(match[1], 10),+ height: Number.parseInt(match[2], 10),+ };+ }- /**- * Parse memory string to MB integer.- *- * Examples:- * "8GB" -> 8192- * "1024MB" -> 1024- * "512" -> 512- *- * @param memoryStr - Memory string to parse- * @returns Memory value in MB- */- public static parseMemoryString(memoryStr: string): number {- if (!memoryStr) {- return 0;- }+ /**+ * Parse memory string to MB integer.+ *+ * Examples:+ * "8GB" -> 8192+ * "1024MB" -> 1024+ * "512" -> 512+ *+ * @param memoryStr - Memory string to parse+ * @returns Memory value in MB+ */+ public static parseMemoryString(memoryStr: string): number {+ if (!memoryStr) {+ return 0;+ }- // Convert to uppercase for case-insensitive matching- const upperStr = memoryStr.toUpperCase().trim();+ // Convert to uppercase for case-insensitive matching+ const upperStr = memoryStr.toUpperCase().trim();- // Extract numeric value and unit- const match = upperStr.match(/^(\d+(?:\.\d+)?)\s*(GB|MB)?$/);- if (!match) {- throw new Error(`Invalid memory format: ${memoryStr}`);- }+ // Extract numeric value and unit+ const match = upperStr.match(/^(\d+(?:\.\d+)?)\s*(GB|MB)?$/);+ if (!match) {+ throw new Error(`Invalid memory format: ${memoryStr}`);+ }- const value = Number.parseFloat(match[1]);- const unit = match[2] || "MB"; // Default to MB if no unit specified+ const value = Number.parseFloat(match[1]);+ const unit = match[2] || 'MB'; // Default to MB if no unit specified- // Convert to MB- if (unit === "GB") {- return Math.round(value * 1024);- }- return Math.round(value);- }+ // Convert to MB+ if (unit === 'GB') {+ return Math.round(value * 1024);+ }+ return Math.round(value);+ }}diff --git a/libs/typescript/computer/src/computer/providers/cloud.ts b/libs/typescript/computer/src/computer/providers/cloud.tsindex 5614fb6461..4c79e68e2c 100644--- a/libs/typescript/computer/src/computer/providers/cloud.ts+++ b/libs/typescript/computer/src/computer/providers/cloud.ts@@ -1,8 +1,5 @@import pino from 'pino';-import {- type BaseComputerInterface,- InterfaceFactory,-} from '../../interface/index';+import { type BaseComputerInterface, InterfaceFactory } from '../../interface/index';import type { CloudComputerConfig, VMProviderType } from '../types';import { BaseComputer } from './base';diff --git a/libs/typescript/computer/src/interface/base.ts b/libs/typescript/computer/src/interface/base.tsindex 21b63389e7..4cd85f1879 100644--- a/libs/typescript/computer/src/interface/base.ts+++ b/libs/typescript/computer/src/interface/base.ts@@ -98,9 +98,7 @@ export abstract class BaseComputerInterface {} catch (error) {console.log(error);// Wait a bit before retrying- this.logger.error(- `Error connecting to websocket: ${JSON.stringify(error)}`- );+ this.logger.error(`Error connecting to websocket: ${JSON.stringify(error)}`);await new Promise((resolve) => setTimeout(resolve, 1000));}}@@ -158,17 +156,12 @@ export abstract class BaseComputerInterface {public async connect(): Promise<void> {// If the WebSocket is already open, check if we need to authenticateif (this.ws.readyState === WebSocket.OPEN) {- this.logger.info(- 'Websocket is open, ensuring authentication is complete.'- );+ this.logger.info('Websocket is open, ensuring authentication is complete.');return this.authenticate();}// If the WebSocket is closed or closing, reinitialize it- if (- this.ws.readyState === WebSocket.CLOSED ||- this.ws.readyState === WebSocket.CLOSING- ) {+ if (this.ws.readyState === WebSocket.CLOSED || this.ws.readyState === WebSocket.CLOSING) {this.logger.info('Websocket is closed. Reinitializing connection.');const headers: { [key: string]: string } = {};if (this.apiKey && this.vmName) {@@ -224,45 +217,39 @@ export abstract class BaseComputerInterface {params: { [key: string]: unknown } = {}): Promise<{ [key: string]: unknown }> {// Create a new promise for this specific command- const commandPromise = new Promise<{ [key: string]: unknown }>(- (resolve, reject) => {- // Chain it to the previous commands- const executeCommand = async (): Promise<{- [key: string]: unknown;- }> => {- if (!this.ws || this.ws.readyState !== WebSocket.OPEN) {- await this.connect();- }+ const commandPromise = new Promise<{ [key: string]: unknown }>((resolve, reject) => {+ // Chain it to the previous commands+ const executeCommand = async (): Promise<{+ [key: string]: unknown;+ }> => {+ if (!this.ws || this.ws.readyState !== WebSocket.OPEN) {+ await this.connect();+ }- return new Promise<{ [key: string]: unknown }>(- (innerResolve, innerReject) => {- const messageHandler = (data: WebSocket.RawData) => {- try {- const response = JSON.parse(data.toString());- if (response.error) {- innerReject(new Error(response.error));- } else {- innerResolve(response);- }- } catch (error) {- innerReject(error);- }- this.ws.off('message', messageHandler);- };-- this.ws.on('message', messageHandler);- const wsCommand = { command, params };- this.ws.send(JSON.stringify(wsCommand));+ return new Promise<{ [key: string]: unknown }>((innerResolve, innerReject) => {+ const messageHandler = (data: WebSocket.RawData) => {+ try {+ const response = JSON.parse(data.toString());+ if (response.error) {+ innerReject(new Error(response.error));+ } else {+ innerResolve(response);+ }+ } catch (error) {+ innerReject(error);}- );- };+ this.ws.off('message', messageHandler);+ };- // Add this command to the lock chain- this.commandLock = this.commandLock.then(() =>- executeCommand().then(resolve, reject)- );- }- );+ this.ws.on('message', messageHandler);+ const wsCommand = { command, params };+ this.ws.send(JSON.stringify(wsCommand));+ });+ };++ // Add this command to the lock chain+ this.commandLock = this.commandLock.then(() => executeCommand().then(resolve, reject));+ });return commandPromise;}@@ -297,22 +284,13 @@ export abstract class BaseComputerInterface {}// Mouse Actions- abstract mouseDown(- x?: number,- y?: number,- button?: MouseButton- ): Promise<void>;+ abstract mouseDown(x?: number, y?: number, button?: MouseButton): Promise<void>;abstract mouseUp(x?: number, y?: number, button?: MouseButton): Promise<void>;abstract leftClick(x?: number, y?: number): Promise<void>;abstract rightClick(x?: number, y?: number): Promise<void>;abstract doubleClick(x?: number, y?: number): Promise<void>;abstract moveCursor(x: number, y: number): Promise<void>;- abstract dragTo(- x: number,- y: number,- button?: MouseButton,- duration?: number- ): Promise<void>;+ abstract dragTo(x: number, y: number, button?: MouseButton, duration?: number): Promise<void>;abstract drag(path: Array<[number, number]>,button?: MouseButton,@@ -356,8 +334,5 @@ export abstract class BaseComputerInterface {// Accessibility Actionsabstract getAccessibilityTree(): Promise<AccessibilityNode>;abstract toScreenCoordinates(x: number, y: number): Promise<[number, number]>;- abstract toScreenshotCoordinates(- x: number,- y: number- ): Promise<[number, number]>;+ abstract toScreenshotCoordinates(x: number, y: number): Promise<[number, number]>;}diff --git a/libs/typescript/computer/src/interface/factory.ts b/libs/typescript/computer/src/interface/factory.tsindex 60864f0eaa..24dc72ad3b 100644--- a/libs/typescript/computer/src/interface/factory.ts+++ b/libs/typescript/computer/src/interface/factory.ts@@ -27,29 +27,11 @@ export const InterfaceFactory = {): BaseComputerInterface {switch (os) {case 'macos':- return new MacOSComputerInterface(- ipAddress,- 'lume',- 'lume',- apiKey,- vmName- );+ return new MacOSComputerInterface(ipAddress, 'lume', 'lume', apiKey, vmName);case 'linux':- return new LinuxComputerInterface(- ipAddress,- 'lume',- 'lume',- apiKey,- vmName- );+ return new LinuxComputerInterface(ipAddress, 'lume', 'lume', apiKey, vmName);case 'windows':- return new WindowsComputerInterface(- ipAddress,- 'lume',- 'lume',- apiKey,- vmName- );+ return new WindowsComputerInterface(ipAddress, 'lume', 'lume', apiKey, vmName);default:throw new Error(`Unsupported OS type: ${os}`);}diff --git a/libs/typescript/computer/src/interface/macos.ts b/libs/typescript/computer/src/interface/macos.tsindex 13310b2d1e..c1c05454a1 100644--- a/libs/typescript/computer/src/interface/macos.ts+++ b/libs/typescript/computer/src/interface/macos.ts@@ -15,11 +15,7 @@ export class MacOSComputerInterface extends BaseComputerInterface {* @param {MouseButton} [button='left'] - Mouse button to press down* @returns {Promise<void>}*/- async mouseDown(- x?: number,- y?: number,- button: MouseButton = 'left'- ): Promise<void> {+ async mouseDown(x?: number, y?: number, button: MouseButton = 'left'): Promise<void> {await this.sendCommand('mouse_down', { x, y, button });}@@ -30,11 +26,7 @@ export class MacOSComputerInterface extends BaseComputerInterface {* @param {MouseButton} [button='left'] - Mouse button to release* @returns {Promise<void>}*/- async mouseUp(- x?: number,- y?: number,- button: MouseButton = 'left'- ): Promise<void> {+ async mouseUp(x?: number, y?: number, button: MouseButton = 'left'): Promise<void> {await this.sendCommand('mouse_up', { x, y, button });}@@ -86,12 +78,7 @@ export class MacOSComputerInterface extends BaseComputerInterface {* @param {number} [duration=0.5] - Duration of the drag operation in seconds* @returns {Promise<void>}*/- async dragTo(- x: number,- y: number,- button: MouseButton = 'left',- duration = 0.5- ): Promise<void> {+ async dragTo(x: number, y: number, button: MouseButton = 'left', duration = 0.5): Promise<void> {await this.sendCommand('drag_to', { x, y, button, duration });}@@ -326,9 +313,7 @@ export class MacOSComputerInterface extends BaseComputerInterface {});if (!response.success) {- throw new Error(- (response.error as string) || 'Failed to read file chunk'- );+ throw new Error((response.error as string) || 'Failed to read file chunk');}const chunkData = Buffer.from(response.content_b64 as string, 'base64');@@ -374,9 +359,7 @@ export class MacOSComputerInterface extends BaseComputerInterface {});if (!response.success) {- throw new Error(- (response.error as string) || 'Failed to write file chunk'- );+ throw new Error((response.error as string) || 'Failed to write file chunk');}currentOffset = chunkEnd;@@ -491,9 +474,7 @@ export class MacOSComputerInterface extends BaseComputerInterface {async createDir(path: string): Promise<void> {const response = await this.sendCommand('create_dir', { path });if (!response.success) {- throw new Error(- (response.error as string) || 'Failed to create directory'- );+ throw new Error((response.error as string) || 'Failed to create directory');}}@@ -506,9 +487,7 @@ export class MacOSComputerInterface extends BaseComputerInterface {async deleteDir(path: string): Promise<void> {const response = await this.sendCommand('delete_dir', { path });if (!response.success) {- throw new Error(- (response.error as string) || 'Failed to delete directory'- );+ throw new Error((response.error as string) || 'Failed to delete directory');}}@@ -523,10 +502,7 @@ export class MacOSComputerInterface extends BaseComputerInterface {if (!response.success) {throw new Error((response.error as string) || 'Failed to run command');}- return [- (response.stdout as string) || '',- (response.stderr as string) || '',- ];+ return [(response.stdout as string) || '', (response.stderr as string) || ''];}// Accessibility Actions@@ -538,9 +514,7 @@ export class MacOSComputerInterface extends BaseComputerInterface {async getAccessibilityTree(): Promise<AccessibilityNode> {const response = await this.sendCommand('get_accessibility_tree');if (!response.success) {- throw new Error(- (response.error as string) || 'Failed to get accessibility tree'- );+ throw new Error((response.error as string) || 'Failed to get accessibility tree');}return response as unknown as AccessibilityNode;}@@ -567,10 +541,7 @@ export class MacOSComputerInterface extends BaseComputerInterface {* @returns {Promise<[number, number]>} Converted screenshot coordinates as [x, y]* @throws {Error} If coordinate conversion fails*/- async toScreenshotCoordinates(- x: number,- y: number- ): Promise<[number, number]> {+ async toScreenshotCoordinates(x: number, y: number): Promise<[number, number]> {const response = await this.sendCommand('to_screenshot_coordinates', {x,y,diff --git a/libs/typescript/computer/tests/interface/factory.test.ts b/libs/typescript/computer/tests/interface/factory.test.tsindex e5f3296a2e..247f43b04b 100644--- a/libs/typescript/computer/tests/interface/factory.test.ts+++ b/libs/typescript/computer/tests/interface/factory.test.ts@@ -60,10 +60,7 @@ describe('InterfaceFactory', () => {});it('should create interface without API key and VM name', () => {- const interface_ = InterfaceFactory.createInterfaceForOS(- OSType.MACOS,- testParams.ipAddress- );+ const interface_ = InterfaceFactory.createInterfaceForOS(OSType.MACOS, testParams.ipAddress);expect(interface_).toBeInstanceOf(MacOSComputerInterface);});diff --git a/libs/typescript/computer/tests/interface/index.test.ts b/libs/typescript/computer/tests/interface/index.test.tsindex 1a0cb8ef8d..8ddbad3279 100644--- a/libs/typescript/computer/tests/interface/index.test.ts+++ b/libs/typescript/computer/tests/interface/index.test.ts@@ -4,9 +4,7 @@ import * as InterfaceExports from '../../src/interface/index.ts';describe('Interface Module Exports', () => {it('should export InterfaceFactory', () => {expect(InterfaceExports.InterfaceFactory).toBeDefined();- expect(- InterfaceExports.InterfaceFactory.createInterfaceForOS- ).toBeDefined();+ expect(InterfaceExports.InterfaceFactory.createInterfaceForOS).toBeDefined();});it('should export BaseComputerInterface', () => {diff --git a/libs/typescript/computer/tests/interface/macos.test.ts b/libs/typescript/computer/tests/interface/macos.test.tsindex e655254f49..2a0fc57aec 100644--- a/libs/typescript/computer/tests/interface/macos.test.ts+++ b/libs/typescript/computer/tests/interface/macos.test.ts@@ -51,9 +51,7 @@ describe('MacOSComputerInterface', () => {case 'screenshot':ws.send(JSON.stringify({- image_data: Buffer.from('fake-screenshot-data').toString(- 'base64'- ),+ image_data: Buffer.from('fake-screenshot-data').toString('base64'),success: true,}));@@ -885,9 +883,7 @@ describe('MacOSComputerInterface', () => {await macosInterface.connect();// Command should throw error- await expect(macosInterface.leftClick(100, 100)).rejects.toThrow(- 'Command failed'- );+ await expect(macosInterface.leftClick(100, 100)).rejects.toThrow('Command failed');await macosInterface.disconnect();await new Promise<void>((resolve) => {diff --git a/libs/typescript/core/README.md b/libs/typescript/core/README.mdindex aecde720b8..d8e50a696c 100644--- a/libs/typescript/core/README.md+++ b/libs/typescript/core/README.md@@ -8,10 +8,11 @@</picture></div>- [](#)- [](#)- [](https://discord.com/invite/mVnXXpdE85)- [](https://www.npmjs.com/package/@trycua/core)+[](#)+[](#)+[](https://discord.com/invite/mVnXXpdE85)+[](https://www.npmjs.com/package/@trycua/core)+</h1></div>diff --git a/libs/typescript/core/src/telemetry/clients/posthog.ts b/libs/typescript/core/src/telemetry/clients/posthog.tsindex e42bc44903..7b14d162b9 100644--- a/libs/typescript/core/src/telemetry/clients/posthog.ts+++ b/libs/typescript/core/src/telemetry/clients/posthog.ts@@ -15,8 +15,7 @@ export const TELEMETRY_SAMPLE_RATE = 100; // 100% sampling rate// Public PostHog config for anonymous telemetry// These values are intentionally public and meant for anonymous telemetry only// https://posthog.com/docs/product-analytics/troubleshooting#is-it-ok-for-my-api-key-to-be-exposed-and-public-export const PUBLIC_POSTHOG_API_KEY =- 'phc_eSkLnbLxsnYFaXksif1ksbrNzYlJShr35miFLDppF14';+export const PUBLIC_POSTHOG_API_KEY = 'phc_eSkLnbLxsnYFaXksif1ksbrNzYlJShr35miFLDppF14';export const PUBLIC_POSTHOG_HOST = 'https://eu.i.posthog.com';export class PostHogTelemetryClient {@@ -50,9 +49,7 @@ export class PostHogTelemetryClient {// CUA_TELEMETRY_DISABLED=1 to disable telemetry (new, more explicit way)const telemetryDisabled =process.env.CUA_TELEMETRY?.toLowerCase() === 'off' ||- ['1', 'true', 'yes', 'on'].includes(- process.env.CUA_TELEMETRY_DISABLED?.toLowerCase() || ''- );+ ['1', 'true', 'yes', 'on'].includes(process.env.CUA_TELEMETRY_DISABLED?.toLowerCase() || '');this.config.enabled = !telemetryDisabled;this.config.sampleRate = Number.parseFloat(@@ -64,9 +61,7 @@ export class PostHogTelemetryClient {// Log telemetry status on startupif (this.config.enabled) {- this.logger.info(- `Telemetry enabled (sampling at ${this.config.sampleRate}%)`- );+ this.logger.info(`Telemetry enabled (sampling at ${this.config.sampleRate}%)`);// Initialize PostHog client if config is availablethis._initializePosthog();} else {@@ -150,10 +145,7 @@ export class PostHogTelemetryClient {/*** Capture an event with PostHog.*/- private _captureEvent(- eventName: string,- properties?: Record<string, unknown>- ): void {+ private _captureEvent(eventName: string, properties?: Record<string, unknown>): void {if (!this.posthogClient) {return;}diff --git a/libs/xfce/README.md b/libs/xfce/README.mdindex 347527ca6e..40170db7e9 100644--- a/libs/xfce/README.md+++ b/libs/xfce/README.md@@ -155,14 +155,14 @@ Both provide the same API and functionality - the provider automatically configu## Environment Variables-| Variable | Default | Description |-|----------|---------|-------------|-| `VNC_RESOLUTION` | `1024x768` | Screen resolution |-| `VNC_COL_DEPTH` | `24` | Color depth |-| `VNC_PORT` | `5901` | VNC server port |-| `NOVNC_PORT` | `6901` | noVNC web interface port |-| `API_PORT` | `8000` | Computer-server API port |-| `DISPLAY` | `:1` | X11 display number |+| Variable | Default | Description |+| ---------------- | ---------- | ------------------------ |+| `VNC_RESOLUTION` | `1024x768` | Screen resolution |+| `VNC_COL_DEPTH` | `24` | Color depth |+| `VNC_PORT` | `5901` | VNC server port |+| `NOVNC_PORT` | `6901` | noVNC web interface port |+| `API_PORT` | `8000` | Computer-server API port |+| `DISPLAY` | `:1` | X11 display number |## Exposed Ports@@ -185,11 +185,13 @@ Both provide the same API and functionality - the provider automatically configu## Creating Snapshots### Filesystem Snapshot+```bashdocker commit <container_id> cua-xfce-snapshot:latest```### Running from Snapshot+```bashdocker run --rm -it \--shm-size=512m \@@ -200,14 +202,14 @@ docker run --rm -it \## Comparison with Kasm Container-| Feature | Kasm Container | Docker XFCE Container |-|---------|---------------|----------------------|-| Base Image | KasmWeb Ubuntu | Vanilla Ubuntu |-| VNC Server | KasmVNC | TigerVNC |-| Dependencies | Higher | Lower |-| Configuration | Pre-configured | Minimal |-| Size | Larger | Smaller |-| Maintenance | Depends on Kasm | Independent |+| Feature | Kasm Container | Docker XFCE Container |+| ------------- | --------------- | --------------------- |+| Base Image | KasmWeb Ubuntu | Vanilla Ubuntu |+| VNC Server | KasmVNC | TigerVNC |+| Dependencies | Higher | Lower |+| Configuration | Pre-configured | Minimal |+| Size | Larger | Smaller |+| Maintenance | Depends on Kasm | Independent |## Process Management@@ -222,24 +224,31 @@ All processes are automatically restarted on failure.## Troubleshooting### VNC server won't start+Check if X11 lock files exist:+```bashdocker exec <container_id> rm -rf /tmp/.X1-lock /tmp/.X11-unix/X1```### noVNC shows black screen+Ensure VNC server is running:+```bashdocker exec <container_id> supervisorctl status vncserver```### Computer-server not responding+Check if X server is accessible:+```bashdocker exec <container_id> env DISPLAY=:1 xdpyinfo```### View logs+```bashdocker exec <container_id> tail -f /var/log/supervisor/supervisord.logdocker exec <container_id> supervisorctl status@@ -248,12 +257,14 @@ docker exec <container_id> supervisorctl status## Integration with CUA SystemThis container provides the same functionality as the Kasm container but with:+- **Reduced dependencies**: No reliance on KasmWeb infrastructure- **Smaller image size**: Minimal base configuration- **Full control**: Direct access to all components- **Easy customization**: Simple to modify and extendThe container integrates seamlessly with:+- CUA Computer library (via WebSocket API)- Docker provider for lifecycle management- Standard VNC clients for debuggingdiff --git a/notebooks/README.md b/notebooks/README.mdindex 2597841596..e0a18cd34d 100644--- a/notebooks/README.md+++ b/notebooks/README.md@@ -5,15 +5,18 @@ This folder contains Jupyter notebooks that demonstrate the core functionality o## Available Notebooks### Core Components+- **`computer_nb.ipynb`** - Demonstrates the Computer API for programmatically operating sandbox VMs using either Cua Cloud Sandbox or local Lume VMs on Apple Silicon macOS systems- **`agent_nb.ipynb`** - Shows how to use CUA's Agent to run automated workflows in virtual sandboxes with various AI models (OpenAI, Anthropic, local models)- **`pylume_nb.ipynb`** - Quickstart guide for the pylume Python library, which handles VM creation, management, and image operations- **`computer_server_nb.ipynb`** - Demonstrates how to host and configure the Computer server that powers the Computer API### Evaluation & Benchmarking+- **`eval_osworld.ipynb`** - Shows ComputerAgent integration with HUD for OSWorld benchmarking, supporting both Claude and OpenAI models### Tutorials+- **`blog/`** - Tutorial notebooks from blog posts:- `build-your-own-operator-on-macos-1.ipynb` - Part 1: Building a CUA operator using OpenAI's computer-use-preview model- `build-your-own-operator-on-macos-2.ipynb` - Part 2: Using the cua-agent package for more advanced automationdiff --git a/pyrightconfig.json b/pyrightconfig.jsonindex 3727e40da6..382f4b60e6 100644--- a/pyrightconfig.json+++ b/pyrightconfig.json@@ -1,13 +1,11 @@{- "include": [- "**/*.py"- ],+ "include": ["**/*.py"],"exclude": ["**/node_modules/**","**/__pycache__/**","**/.*/**","**/venv/**",- "**/.venv/**",+ "**/.venv/**","**/dist/**","**/build/**",".pdm-build/**",diff --git a/samples/community/global-online/README.md b/samples/community/global-online/README.mdindex 137cebe603..82ddd44e79 100644--- a/samples/community/global-online/README.md+++ b/samples/community/global-online/README.md@@ -1,3 +1,3 @@# Global Online Hackathon Submission-In construction 🏗 ️\ No newline at end of file+In construction 🏗 ️diff --git a/samples/community/hack-the-north/README.md b/samples/community/hack-the-north/README.mdindex b25f7a8de9..5d4fef0ca5 100644--- a/samples/community/hack-the-north/README.md+++ b/samples/community/hack-the-north/README.md@@ -1,3 +1,3 @@# Hack the North Hackathon Submission-In construction 🏗️\ No newline at end of file+In construction 🏗️diff --git a/tests/shell_cmd.py b/tests/shell_cmd.pyindex 6062e53e0a..f6712ca598 100644--- a/tests/shell_cmd.py+++ b/tests/shell_cmd.py@@ -6,12 +6,13 @@ Required environment variables:- CUA_CONTAINER_NAME: Name of the container to use"""-import osimport asyncio-import pytest-from pathlib import Path+import osimport sysimport traceback+from pathlib import Path++import pytest# Load environment variables from .env fileproject_root = Path(__file__).parent.parent@@ -30,6 +31,7 @@ for path in pythonpath.split(":"):from computer import Computer, VMProviderType+@pytest.fixture(scope="session")async def computer():"""Shared Computer instance for all test cases."""@@ -40,7 +42,7 @@ async def computer():name=str(os.getenv("CUA_CONTAINER_NAME")),provider_type=VMProviderType.CLOUD,)-+try:await computer.run()yield computer@@ -53,7 +55,7 @@ async def computer():async def test_cmd_echo_command(computer):"""Test basic echo command with cmd.exe."""result = await computer.interface.run_command("echo Hello World")-+assert result.stdout.strip() == "Hello World"assert result.stderr == ""assert result.returncode == 0@@ -63,7 +65,7 @@ async def test_cmd_echo_command(computer):async def test_cmd_dir_command(computer):"""Test dir command to list directory contents."""result = await computer.interface.run_command("dir C:\\")-+assert result.returncode == 0assert result.stderr == ""assert "Directory of C:\\" in result.stdout@@ -74,12 +76,14 @@ async def test_cmd_dir_command(computer):async def test_cmd_command_with_error(computer):"""Test command that produces an error."""result = await computer.interface.run_command("dir C:\\nonexistent_directory_12345")-+assert result.returncode != 0assert result.stdout == ""- assert ("File Not Found" in result.stderr or- "cannot find the path" in result.stderr or- "The system cannot find" in result.stderr)+ assert (+ "File Not Found" in result.stderr+ or "cannot find the path" in result.stderr+ or "The system cannot find" in result.stderr+ )if __name__ == "__main__":diff --git a/tests/test_files.py b/tests/test_files.pyindex b0ae9c60a7..4365531149 100644--- a/tests/test_files.py+++ b/tests/test_files.py@@ -6,12 +6,13 @@ Required environment variables:- CUA_CONTAINER_NAME: Name of the container to use"""-import osimport asyncio-import pytest-from pathlib import Path+import osimport sysimport traceback+from pathlib import Path++import pytest# Load environment variables from .env fileproject_root = Path(__file__).parent.parent@@ -30,6 +31,7 @@ for path in pythonpath.split(":"):from computer import Computer, VMProviderType+@pytest.fixture(scope="session")async def computer():"""Shared Computer instance for all test cases."""@@ -40,19 +42,20 @@ async def computer():name=str(os.getenv("CUA_CONTAINER_NAME")),provider_type=VMProviderType.CLOUD,)-+# Create a local macOS computer with Cua# computer = Computer()-+# Connect to host computer# computer = Computer(use_host_computer_server=True)-+try:await computer.run()yield computerfinally:await computer.disconnect()+@pytest.mark.asyncio(loop_scope="session")async def test_file_exists(computer):tmp_path = "test_file_exists.txt"@@ -142,14 +145,14 @@ async def test_read_bytes_basic(computer):"""Test basic read_bytes functionality."""tmp_path = "test_read_bytes.bin"test_data = b"Hello, World! This is binary data \x00\x01\x02\x03"-+# Write binary data using write_text (assuming it handles bytes)- await computer.interface.write_text(tmp_path, test_data.decode('latin-1'))-+ await computer.interface.write_text(tmp_path, test_data.decode("latin-1"))+# Read all bytesread_data = await computer.interface.read_bytes(tmp_path)assert read_data == test_data, "Binary data should match"-+await computer.interface.delete_file(tmp_path)@@ -158,25 +161,31 @@ async def test_read_bytes_with_offset_and_length(computer):"""Test read_bytes with offset and length parameters."""tmp_path = "test_read_bytes_offset.bin"test_data = b"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"-+# Write test data- await computer.interface.write_text(tmp_path, test_data.decode('latin-1'))-+ await computer.interface.write_text(tmp_path, test_data.decode("latin-1"))+# Test reading with offset onlyread_data = await computer.interface.read_bytes(tmp_path, offset=5)expected = test_data[5:]- assert read_data == expected, f"Data from offset 5 should match. Got: {read_data}, Expected: {expected}"-+ assert (+ read_data == expected+ ), f"Data from offset 5 should match. Got: {read_data}, Expected: {expected}"+# Test reading with offset and lengthread_data = await computer.interface.read_bytes(tmp_path, offset=10, length=5)expected = test_data[10:15]- assert read_data == expected, f"Data from offset 10, length 5 should match. Got: {read_data}, Expected: {expected}"-+ assert (+ read_data == expected+ ), f"Data from offset 10, length 5 should match. Got: {read_data}, Expected: {expected}"+# Test reading from beginning with lengthread_data = await computer.interface.read_bytes(tmp_path, offset=0, length=10)expected = test_data[:10]- assert read_data == expected, f"Data from beginning, length 10 should match. Got: {read_data}, Expected: {expected}"-+ assert (+ read_data == expected+ ), f"Data from beginning, length 10 should match. Got: {read_data}, Expected: {expected}"+await computer.interface.delete_file(tmp_path)@@ -185,12 +194,12 @@ async def test_get_file_size(computer):"""Test get_file_size functionality."""tmp_path = "test_file_size.txt"test_content = "A" * 1000 # 1000 bytes-+await computer.interface.write_text(tmp_path, test_content)-+file_size = await computer.interface.get_file_size(tmp_path)assert file_size == 1000, f"File size should be 1000 bytes, got {file_size}"-+await computer.interface.delete_file(tmp_path)@@ -198,200 +207,213 @@ async def test_get_file_size(computer):async def test_read_large_file(computer):"""Test reading a file larger than 10MB to verify chunked reading."""tmp_path = "test_large_file.bin"-+# Create a file larger than 10MB (10 * 1024 * 1024 = 10,485,760 bytes)total_size = 12 * 1024 * 1024 # 12MB-+print(f"Creating large file of {total_size} bytes ({total_size / (1024*1024):.1f}MB)...")-+# Create large file content (this will test the chunked writing functionality)large_content = b"X" * total_size-+# Write the large file using write_bytes (will automatically use chunked writing)await computer.interface.write_bytes(tmp_path, large_content)-+# Verify file sizefile_size = await computer.interface.get_file_size(tmp_path)assert file_size == total_size, f"Large file size should be {total_size} bytes, got {file_size}"-+print(f"Large file created successfully: {file_size} bytes")-+# Test reading the entire large file (should use chunked reading)print("Reading large file...")read_data = await computer.interface.read_bytes(tmp_path)- assert len(read_data) == total_size, f"Read data size should match file size. Got {len(read_data)}, expected {total_size}"-+ assert (+ len(read_data) == total_size+ ), f"Read data size should match file size. Got {len(read_data)}, expected {total_size}"+# Verify content (should be all 'X' characters)expected_data = b"X" * total_sizeassert read_data == expected_data, "Large file content should be all 'X' characters"-+print("Large file read successfully!")-+# Test reading with offset and length on large fileoffset = 5 * 1024 * 1024 # 5MB offsetlength = 2 * 1024 * 1024 # 2MB lengthread_data = await computer.interface.read_bytes(tmp_path, offset=offset, length=length)assert len(read_data) == length, f"Partial read size should be {length}, got {len(read_data)}"assert read_data == b"X" * length, "Partial read content should be all 'X' characters"-+print("Large file partial read successful!")-+# Clean upawait computer.interface.delete_file(tmp_path)print("Large file test completed successfully!")+@pytest.mark.asyncio(loop_scope="session")async def test_read_write_text_with_encoding(computer):"""Test reading and writing text files with different encodings."""print("Testing text file operations with different encodings...")-+tmp_path = "test_encoding.txt"-+# Test UTF-8 encoding (default)utf8_content = "Hello, 世界! 🌍 Ñoño café"- await computer.interface.write_text(tmp_path, utf8_content, encoding='utf-8')- read_utf8 = await computer.interface.read_text(tmp_path, encoding='utf-8')+ await computer.interface.write_text(tmp_path, utf8_content, encoding="utf-8")+ read_utf8 = await computer.interface.read_text(tmp_path, encoding="utf-8")assert read_utf8 == utf8_content, "UTF-8 content should match"-+# Test ASCII encodingascii_content = "Hello, World! Simple ASCII text."- await computer.interface.write_text(tmp_path, ascii_content, encoding='ascii')- read_ascii = await computer.interface.read_text(tmp_path, encoding='ascii')+ await computer.interface.write_text(tmp_path, ascii_content, encoding="ascii")+ read_ascii = await computer.interface.read_text(tmp_path, encoding="ascii")assert read_ascii == ascii_content, "ASCII content should match"-+# Test Latin-1 encodinglatin1_content = "Café, naïve, résumé"- await computer.interface.write_text(tmp_path, latin1_content, encoding='latin-1')- read_latin1 = await computer.interface.read_text(tmp_path, encoding='latin-1')+ await computer.interface.write_text(tmp_path, latin1_content, encoding="latin-1")+ read_latin1 = await computer.interface.read_text(tmp_path, encoding="latin-1")assert read_latin1 == latin1_content, "Latin-1 content should match"-+# Clean upawait computer.interface.delete_file(tmp_path)print("Text encoding test completed successfully!")+@pytest.mark.asyncio(loop_scope="session")async def test_write_text_append_mode(computer):"""Test appending text to files."""print("Testing text file append mode...")-+tmp_path = "test_append.txt"-+# Write initial contentinitial_content = "First line\n"await computer.interface.write_text(tmp_path, initial_content)-+# Append more contentappend_content = "Second line\n"await computer.interface.write_text(tmp_path, append_content, append=True)-+# Read and verifyfinal_content = await computer.interface.read_text(tmp_path)expected_content = initial_content + append_content- assert final_content == expected_content, f"Expected '{expected_content}', got '{final_content}'"-+ assert (+ final_content == expected_content+ ), f"Expected '{expected_content}', got '{final_content}'"+# Append one more linethird_content = "Third line\n"await computer.interface.write_text(tmp_path, third_content, append=True)-+# Read and verify final resultfinal_content = await computer.interface.read_text(tmp_path)expected_content = initial_content + append_content + third_content- assert final_content == expected_content, f"Expected '{expected_content}', got '{final_content}'"-+ assert (+ final_content == expected_content+ ), f"Expected '{expected_content}', got '{final_content}'"+# Clean upawait computer.interface.delete_file(tmp_path)print("Text append test completed successfully!")+@pytest.mark.asyncio(loop_scope="session")async def test_large_text_file(computer):"""Test reading and writing large text files (>5MB) to verify chunked operations."""print("Testing large text file operations...")-+tmp_path = "test_large_text.txt"-+# Create a large text content (approximately 6MB)# Each line is about 100 characters, so 60,000 lines ≈ 6MBline_template = "This is line {:06d} with some additional text to make it longer and reach about 100 chars.\n"large_content = ""num_lines = 60000-+print(f"Generating large text content with {num_lines} lines...")for i in range(num_lines):large_content += line_template.format(i)-- content_size_mb = len(large_content.encode('utf-8')) / (1024 * 1024)++ content_size_mb = len(large_content.encode("utf-8")) / (1024 * 1024)print(f"Generated text content size: {content_size_mb:.2f} MB")-+# Write the large text fileprint("Writing large text file...")await computer.interface.write_text(tmp_path, large_content)-+# Read the entire file backprint("Reading large text file...")read_content = await computer.interface.read_text(tmp_path)-+# Verify content matchesassert read_content == large_content, "Large text file content should match exactly"-+# Test partial reading by reading as bytes and decoding specific portionsprint("Testing partial text reading...")-+# Read first 1000 characters worth of bytesfirst_1000_chars = large_content[:1000]- first_1000_bytes = first_1000_chars.encode('utf-8')- read_bytes = await computer.interface.read_bytes(tmp_path, offset=0, length=len(first_1000_bytes))- decoded_partial = read_bytes.decode('utf-8')+ first_1000_bytes = first_1000_chars.encode("utf-8")+ read_bytes = await computer.interface.read_bytes(+ tmp_path, offset=0, length=len(first_1000_bytes)+ )+ decoded_partial = read_bytes.decode("utf-8")assert decoded_partial == first_1000_chars, "Partial text reading should match"-+# Test appending to large fileprint("Testing append to large text file...")append_text = "\n--- APPENDED CONTENT ---\nThis content was appended to the large file.\n"await computer.interface.write_text(tmp_path, append_text, append=True)-+# Read and verify appended contentfinal_content = await computer.interface.read_text(tmp_path)expected_final = large_content + append_textassert final_content == expected_final, "Appended large text file should match"-+# Clean upawait computer.interface.delete_file(tmp_path)print("Large text file test completed successfully!")+@pytest.mark.asyncio(loop_scope="session")async def test_text_file_edge_cases(computer):"""Test edge cases for text file operations."""print("Testing text file edge cases...")-+tmp_path = "test_edge_cases.txt"-+# Test empty fileempty_content = ""await computer.interface.write_text(tmp_path, empty_content)read_empty = await computer.interface.read_text(tmp_path)assert read_empty == empty_content, "Empty file should return empty string"-+# Test file with only whitespacewhitespace_content = " \n\t\r\n \n"await computer.interface.write_text(tmp_path, whitespace_content)read_whitespace = await computer.interface.read_text(tmp_path)assert read_whitespace == whitespace_content, "Whitespace content should be preserved"-+# Test file with special characters and newlinesspecial_content = "Line 1\nLine 2\r\nLine 3\tTabbed\nSpecial: !@#$%^&*()\n"await computer.interface.write_text(tmp_path, special_content)read_special = await computer.interface.read_text(tmp_path)assert read_special == special_content, "Special characters should be preserved"-+# Test very long single line (no newlines)long_line = "A" * 10000 # 10KB single lineawait computer.interface.write_text(tmp_path, long_line)read_long_line = await computer.interface.read_text(tmp_path)assert read_long_line == long_line, "Long single line should be preserved"-+# Clean upawait computer.interface.delete_file(tmp_path)print("Text file edge cases test completed successfully!")+if __name__ == "__main__":# Run tests directlypytest.main([__file__, "-v"])diff --git a/tests/test_mcp_server_session_management.py b/tests/test_mcp_server_session_management.pyindex febddd15d8..5a5c9fb37d 100644--- a/tests/test_mcp_server_session_management.py+++ b/tests/test_mcp_server_session_management.py@@ -7,14 +7,16 @@ This module tests the new concurrent session management and resource lifecycle fimport asyncioimport importlib.utilimport sys-import typesimport time+import typesfrom pathlib import Pathimport pytest-def _install_stub_module(name: str, module: types.ModuleType, registry: dict[str, types.ModuleType | None]) -> None:+def _install_stub_module(+ name: str, module: types.ModuleType, registry: dict[str, types.ModuleType | None]+) -> None:registry[name] = sys.modules.get(name)sys.modules[name] = module@@ -112,7 +114,7 @@ def server_module():{"type": "message","role": "assistant",- "content": [{"type": "output_text", "text": "Task completed"}]+ "content": [{"type": "output_text", "text": "Task completed"}],}]}@@ -142,7 +144,7 @@ def server_module():"""Context manager that returns a session."""if session_id is None:session_id = "test-session-123"-+async with self._session_lock:if session_id not in self._sessions:computer = _StubComputer()@@ -150,10 +152,10 @@ def server_module():session_id=session_id,computer=computer,created_at=time.time(),- last_activity=time.time()+ last_activity=time.time(),)self._sessions[session_id] = session-+return self._sessions[session_id]async def register_task(self, session_id: str, task_id: str):@@ -170,7 +172,7 @@ def server_module():return {"total_sessions": len(self._sessions),"max_concurrent": 10,- "sessions": {sid: {"active_tasks": 0} for sid in self._sessions}+ "sessions": {sid: {"active_tasks": 0} for sid in self._sessions},}_stub_session_manager = _StubSessionManager()@@ -216,7 +218,7 @@ def server_module():class FakeContext:"""Fake context for testing."""-+def __init__(self) -> None:self.events: list[tuple] = []self.progress_updates: list[float] = []@@ -245,10 +247,11 @@ class FakeContext:def test_screenshot_cua_with_session_id(server_module):"""Test that screenshot_cua works with session management."""+async def _run_test():ctx = FakeContext()result = await server_module.screenshot_cua(ctx, session_id="test-session")-+assert result.format == "png"assert result.data == b"test-screenshot-data"@@ -257,10 +260,11 @@ def test_screenshot_cua_with_session_id(server_module):def test_screenshot_cua_creates_new_session(server_module):"""Test that screenshot_cua creates a new session when none provided."""+async def _run_test():ctx = FakeContext()result = await server_module.screenshot_cua(ctx)-+assert result.format == "png"assert result.data == b"test-screenshot-data"@@ -269,13 +273,14 @@ def test_screenshot_cua_creates_new_session(server_module):def test_run_cua_task_with_session_management(server_module):"""Test that run_cua_task works with session management."""+async def _run_test():ctx = FakeContext()task = "Test task"session_id = "test-session-456"-+text_result, image = await server_module.run_cua_task(ctx, task, session_id)-+assert "Task completed" in text_resultassert image.format == "png"assert image.data == b"test-screenshot-data"@@ -285,12 +290,13 @@ def test_run_cua_task_with_session_management(server_module):def test_run_multi_cua_tasks_sequential(server_module):"""Test that run_multi_cua_tasks works sequentially."""+async def _run_test():ctx = FakeContext()tasks = ["Task 1", "Task 2", "Task 3"]-+results = await server_module.run_multi_cua_tasks(ctx, tasks, concurrent=False)-+assert len(results) == 3for i, (text, image) in enumerate(results):assert "Task completed" in text@@ -301,12 +307,13 @@ def test_run_multi_cua_tasks_sequential(server_module):def test_run_multi_cua_tasks_concurrent(server_module):"""Test that run_multi_cua_tasks works concurrently."""+async def _run_test():ctx = FakeContext()tasks = ["Task 1", "Task 2", "Task 3"]-+results = await server_module.run_multi_cua_tasks(ctx, tasks, concurrent=True)-+assert len(results) == 3for i, (text, image) in enumerate(results):assert "Task completed" in text@@ -317,10 +324,11 @@ def test_run_multi_cua_tasks_concurrent(server_module):def test_get_session_stats(server_module):"""Test that get_session_stats returns proper statistics."""+async def _run_test():ctx = FakeContext()stats = await server_module.get_session_stats()-+assert "total_sessions" in statsassert "max_concurrent" in statsassert "sessions" in stats@@ -330,12 +338,13 @@ def test_get_session_stats(server_module):def test_cleanup_session(server_module):"""Test that cleanup_session works properly."""+async def _run_test():ctx = FakeContext()session_id = "test-cleanup-session"-+result = await server_module.cleanup_session(ctx, session_id)-+assert f"Session {session_id} cleanup initiated" in resultasyncio.run(_run_test())@@ -343,9 +352,10 @@ def test_cleanup_session(server_module):def test_concurrent_sessions_isolation(server_module):"""Test that concurrent sessions are properly isolated."""+async def _run_test():ctx = FakeContext()-+# Run multiple tasks with different session IDs concurrentlytask1 = asyncio.create_task(server_module.run_cua_task(ctx, "Task for session 1", "session-1")@@ -353,9 +363,9 @@ def test_concurrent_sessions_isolation(server_module):task2 = asyncio.create_task(server_module.run_cua_task(ctx, "Task for session 2", "session-2"))-+results = await asyncio.gather(task1, task2)-+assert len(results) == 2for text, image in results:assert "Task completed" in text@@ -366,16 +376,17 @@ def test_concurrent_sessions_isolation(server_module):def test_session_reuse_with_same_id(server_module):"""Test that sessions are reused when the same session ID is provided."""+async def _run_test():ctx = FakeContext()session_id = "reuse-session"-+# First callresult1 = await server_module.screenshot_cua(ctx, session_id)-+# Second call with same session IDresult2 = await server_module.screenshot_cua(ctx, session_id)-+assert result1.format == result2.formatassert result1.data == result2.data@@ -384,6 +395,7 @@ def test_session_reuse_with_same_id(server_module):def test_error_handling_with_session_management(server_module):"""Test that errors are handled properly with session management."""+async def _run_test():# Mock an agent that raises an exceptionclass _FailingAgent:@@ -396,16 +408,16 @@ def test_error_handling_with_session_management(server_module):# Replace the ComputerAgent with our failing oneoriginal_agent = server_module.ComputerAgentserver_module.ComputerAgent = _FailingAgent-+try:ctx = FakeContext()task = "This will fail"-+text_result, image = await server_module.run_cua_task(ctx, task, "error-session")-+assert "Error during task execution" in text_resultassert image.format == "png"-+finally:# Restore original agentserver_module.ComputerAgent = original_agentdiff --git a/tests/test_mcp_server_streaming.py b/tests/test_mcp_server_streaming.pyindex ed84cbfed4..68aaa55586 100644--- a/tests/test_mcp_server_streaming.py+++ b/tests/test_mcp_server_streaming.py@@ -7,7 +7,9 @@ from pathlib import Pathimport pytest-def _install_stub_module(name: str, module: types.ModuleType, registry: dict[str, types.ModuleType | None]) -> None:+def _install_stub_module(+ name: str, module: types.ModuleType, registry: dict[str, types.ModuleType | None]+) -> None:registry[name] = sys.modules.get(name)sys.modules[name] = module@@ -182,9 +184,7 @@ def test_run_cua_task_streams_partial_results(server_module):{"type": "message","role": "assistant",- "content": [- {"type": "output_text", "text": "First chunk"}- ],+ "content": [{"type": "output_text", "text": "First chunk"}],}]},@@ -202,9 +202,7 @@ def test_run_cua_task_streams_partial_results(server_module):{"type": "computer_call_output","call_id": "call_1",- "output": [- {"type": "text", "text": "Tool completed"}- ],+ "output": [{"type": "text", "text": "Tool completed"}],},]},@@ -300,4 +298,4 @@ def test_run_multi_cua_tasks_reports_progress(server_module, monkeypatch):assert ctx.progress_updates[-1] == pytest.approx(1.0)assert len(ctx.progress_updates) == 6- asyncio.run(_run_test())\ No newline at end of file+ asyncio.run(_run_test())diff --git a/tests/test_shell_bash.py b/tests/test_shell_bash.pyindex ca7f8e1fc6..895d7da5fb 100644--- a/tests/test_shell_bash.py+++ b/tests/test_shell_bash.py@@ -6,12 +6,13 @@ Required environment variables:- CUA_CONTAINER_NAME: Name of the container to use"""-import osimport asyncio-import pytest-from pathlib import Path+import osimport sysimport traceback+from pathlib import Path++import pytest# Load environment variables from .env fileproject_root = Path(__file__).parent.parent@@ -30,6 +31,7 @@ for path in pythonpath.split(":"):from computer import Computer, VMProviderType+@pytest.fixture(scope="session")async def computer():"""Shared Computer instance for all test cases."""@@ -40,7 +42,7 @@ async def computer():name=str(os.getenv("CUA_CONTAINER_NAME")),provider_type=VMProviderType.CLOUD,)-+try:await computer.run()yield computer@@ -53,7 +55,7 @@ async def computer():async def test_bash_echo_command(computer):"""Test basic echo command with bash."""result = await computer.interface.run_command("echo 'Hello World'")-+assert result.stdout.strip() == "Hello World"assert result.stderr == ""assert result.returncode == 0@@ -63,19 +65,19 @@ async def test_bash_echo_command(computer):async def test_bash_ls_command(computer):"""Test ls command to list directory contents."""result = await computer.interface.run_command("ls -la /tmp")-+assert result.returncode == 0assert result.stderr == ""assert "total" in result.stdout # ls -la typically starts with "total"- assert "." in result.stdout # Current directory entry- assert ".." in result.stdout # Parent directory entry+ assert "." in result.stdout # Current directory entry+ assert ".." in result.stdout # Parent directory entry@pytest.mark.asyncio(loop_scope="session")async def test_bash_command_with_error(computer):"""Test command that produces an error."""result = await computer.interface.run_command("ls /nonexistent_directory_12345")-+assert result.returncode != 0assert result.stdout == ""assert "No such file or directory" in result.stderr or "cannot access" in result.stderrdiff --git a/tests/test_telemetry.py b/tests/test_telemetry.pyindex 80a7877932..4c7f9865c4 100644--- a/tests/test_telemetry.py+++ b/tests/test_telemetry.py@@ -4,9 +4,10 @@ Required environment variables:"""import os-import pytest-from pathlib import Pathimport sys+from pathlib import Path++import pytest# Load environment variables from .env fileproject_root = Path(__file__).parent.parent@@ -23,34 +24,35 @@ for path in pythonpath.split(":"):sys.path.insert(0, path) # Insert at beginning to prioritizeprint(f"Added to sys.path: {path}")-from core.telemetry import record_event, is_telemetry_enabled, destroy_telemetry_client+from core.telemetry import destroy_telemetry_client, is_telemetry_enabled, record_eventclass TestTelemetry:def setup_method(self):"""Reset environment variables before each test"""- os.environ.pop('CUA_TELEMETRY', None)- os.environ.pop('CUA_TELEMETRY_ENABLED', None)+ os.environ.pop("CUA_TELEMETRY", None)+ os.environ.pop("CUA_TELEMETRY_ENABLED", None)destroy_telemetry_client()-+def test_telemetry_disabled_when_cua_telemetry_is_off(self):"""Should return false when CUA_TELEMETRY is off"""- os.environ['CUA_TELEMETRY'] = 'off'+ os.environ["CUA_TELEMETRY"] = "off"assert is_telemetry_enabled() is False-+def test_telemetry_enabled_when_cua_telemetry_not_set(self):"""Should return true when CUA_TELEMETRY is not set"""assert is_telemetry_enabled() is True-+def test_telemetry_disabled_when_cua_telemetry_enabled_is_0(self):"""Should return false if CUA_TELEMETRY_ENABLED is 0"""- os.environ['CUA_TELEMETRY_ENABLED'] = '0'+ os.environ["CUA_TELEMETRY_ENABLED"] = "0"assert is_telemetry_enabled() is False-+def test_send_test_event_to_posthog(self):"""Should send a test event to PostHog"""# This should not raise an exception- record_event('test_telemetry', {'message': 'Hello, world!'})+ record_event("test_telemetry", {"message": "Hello, world!"})+if __name__ == "__main__":# Run tests directlydiff --git a/tests/test_venv.py b/tests/test_venv.pyindex 8479e28f69..abd7e70be2 100644--- a/tests/test_venv.py+++ b/tests/test_venv.py@@ -7,12 +7,13 @@ Required environment variables:- CUA_CONTAINER_NAME: Name of the container to use"""-import osimport asyncio-import pytest-from pathlib import Path+import osimport sysimport traceback+from pathlib import Path++import pytest# Load environment variables from .env fileproject_root = Path(__file__).parent.parent@@ -43,10 +44,10 @@ async def computer():name=str(os.getenv("CUA_CONTAINER_NAME")),provider_type=VMProviderType.CLOUD,)-+# # Create a local macOS computer with Cua# computer = Computer()-+try:await computer.run()yield computer@@ -60,137 +61,146 @@ async def test_venv_install(computer):"""Test virtual environment creation and package installation."""# Create a test virtual environment and install requestsstdout, _ = await computer.venv_install("test_env", ["requests"])-+# Check that installation was successful (no major errors)assert "Successfully installed" in stdout or "Requirement already satisfied" in stdout+@pytest.mark.asyncio(loop_scope="session")async def test_venv_cmd(computer):"""Test executing shell commands in virtual environment."""# Test Python version checkstdout, _ = await computer.venv_cmd("test_env", "python --version")-+assert "Python" in stdout+@pytest.mark.asyncio(loop_scope="session")async def test_venv_exec(computer):"""Test executing Python functions in virtual environment."""+def test_function(message="Hello World"):import sys+return f"Python {sys.version_info.major}.{sys.version_info.minor}: {message}"-+result = await computer.venv_exec("test_env", test_function, message="Test successful!")-+assert "Python" in resultassert "Test successful!" in result+@pytest.mark.asyncio(loop_scope="session")async def test_venv_exec_with_package(computer):"""Test executing Python functions that use installed packages."""+def test_requests():import requests+return f"requests version: {requests.__version__}"-+result = await computer.venv_exec("test_env", test_requests)-+assert "requests version:" in result+@pytest.mark.asyncio(loop_scope="session")async def test_venv_exec_error_handling(computer):"""Test error handling in venv_exec."""+def test_error():raise ValueError("This is a test error")-+with pytest.raises(ValueError, match="This is a test error"):await computer.venv_exec("test_env", test_error)+@pytest.mark.asyncio(loop_scope="session")async def test_venv_exec_with_args_kwargs(computer):"""Test executing Python functions with args and kwargs that return an object."""+def create_data_object(name, age, *hobbies, **metadata):return {"name": name,"age": age,"hobbies": list(hobbies),"metadata": metadata,- "status": "active"+ "status": "active",}-+args = ["Alice", 25, "reading", "coding"]kwargs = {"location": "New York", "department": "Engineering"}- result = await computer.venv_exec(- "test_env",- create_data_object,- *args,- **kwargs- )-+ result = await computer.venv_exec("test_env", create_data_object, *args, **kwargs)+assert result["name"] == "Alice"assert result["age"] == 25assert result["hobbies"] == ["reading", "coding"]assert result["metadata"]["location"] == "New York"assert result["status"] == "active"+@pytest.mark.asyncio(loop_scope="session")async def test_venv_exec_stdout_capture(computer, capfd):"""Test capturing stdout from Python functions executed in virtual environment."""+def hello_world_function():print("Hello World!")return "Function completed"-+# Execute the function in the virtual environmentresult = await computer.venv_exec("test_env", hello_world_function)-+# Capture stdout and stderrout, _ = capfd.readouterr()-+# Assert the stdout contains our expected outputassert out == "Hello World!\n\n"assert result == "Function completed"+@pytest.mark.asyncio(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 decoratorset_default_computer(computer)-+# Define a function with the remote decorator@sandboxed("test_env")def get_package_version():- import sysimport platform- return {- "python_version": sys.version,- "platform": platform.platform(),- "success": True- }-+ import sys++ return {"python_version": sys.version, "platform": platform.platform(), "success": True}+# Call the decorated functionresult = await get_package_version()-+# Verify the function executed in the virtual environmentassert "python_version" in resultassert "platform" in resultassert result["success"] == True+@pytest.mark.asyncio(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 osimport sys+return {"python_version": sys.version,"environment_vars": dict(os.environ),- "working_directory": os.getcwd()+ "working_directory": os.getcwd(),}-+# Call the decorated functionresult = await get_system_info()-+# Verify the function executed in the virtual environmentassert "python_version" in resultassert "environment_vars" in result@@ -199,6 +209,7 @@ async def test_remote_decorator_with_custom_computer(computer):# than the current test processassert result["working_directory"] != os.getcwd()+if __name__ == "__main__":# Run tests directlypytest.main([__file__, "-v"])diff --git a/tests/test_watchdog.py b/tests/test_watchdog.pyindex c5a014e623..c499c17009 100644--- a/tests/test_watchdog.py+++ b/tests/test_watchdog.py@@ -6,13 +6,14 @@ Required environment variables:- CUA_CONTAINER_NAME: Name of the container to use"""-import osimport asyncio-import pytest-from pathlib import Path+import osimport sys-import tracebackimport time+import traceback+from pathlib import Path++import pytest# Load environment variables from .env fileproject_root = Path(__file__).parent.parent@@ -31,6 +32,7 @@ for path in pythonpath.split(":"):from computer import Computer, VMProviderType+@pytest.fixture(scope="session")async def computer():"""Shared Computer instance for all test cases."""@@ -41,7 +43,7 @@ async def computer():name=str(os.getenv("CUA_CONTAINER_NAME")),provider_type=VMProviderType.CLOUD,)-+try:await computer.run()yield computer@@ -55,7 +57,7 @@ async def test_simple_server_ping(computer):Simple test to verify server connectivity before running watchdog tests."""print("Testing basic server connectivity...")-+try:result = await computer.interface.run_command("echo 'Server ping test'")print(f"Ping successful: {result}")@@ -70,15 +72,15 @@ async def test_simple_server_ping(computer):async def test_watchdog_recovery_after_hanging_command(computer):"""Test that the watchdog can recover the server after a hanging command.-+This test runs two concurrent tasks:1. A long-running command that hangs the server (sleep 300 = 5 minutes)2. Periodic ping commands every 30 seconds to test server responsiveness-+The watchdog should detect the unresponsive server and restart it."""print("Starting watchdog recovery test...")-+async def hanging_command():"""Execute a command that sleeps forever to hang the server."""try:@@ -90,65 +92,69 @@ async def test_watchdog_recovery_after_hanging_command(computer):except Exception as e:print(f"Hanging command interrupted (expected if watchdog restarts): {e}")return None # Expected result when watchdog kills the process-+async def ping_server():"""Ping the server every 30 seconds with echo commands."""ping_count = 0successful_pings = 0failed_pings = 0-+try:# Run pings for up to 4 minutes (8 pings at 30-second intervals)for i in range(8):try:ping_count += 1print(f"Ping #{ping_count}: Sending echo command...")-+start_time = time.time()result = await asyncio.wait_for(- computer.interface.run_command(f"echo 'Ping {ping_count} at {int(start_time)}'"),- timeout=10.0 # 10 second timeout for each ping+ computer.interface.run_command(+ f"echo 'Ping {ping_count} at {int(start_time)}'"+ ),+ timeout=10.0, # 10 second timeout for each ping)end_time = time.time()-- print(f"Ping #{ping_count} successful in {end_time - start_time:.2f}s: {result}")++ print(+ f"Ping #{ping_count} successful in {end_time - start_time:.2f}s: {result}"+ )successful_pings += 1-+except asyncio.TimeoutError:print(f"Ping #{ping_count} timed out (server may be unresponsive)")failed_pings += 1except Exception as e:print(f"Ping #{ping_count} failed with exception: {e}")failed_pings += 1-+# Wait 30 seconds before next pingif i < 7: # Don't wait after the last ping- print(f"Waiting 30 seconds before next ping...")+ print("Waiting 30 seconds before next ping...")await asyncio.sleep(30)-+print(f"Ping summary: {successful_pings} successful, {failed_pings} failed")return successful_pings, failed_pings-+except Exception as e:print(f"Ping server function failed with critical error: {e}")traceback.print_exc()return successful_pings, failed_pings-+# Run both tasks concurrentlyprint("Starting concurrent tasks: hanging command and ping monitoring...")-+try:# Use asyncio.gather to run both tasks concurrentlyhanging_task = asyncio.create_task(hanging_command())ping_task = asyncio.create_task(ping_server())-+# Wait for both tasks to complete or timeout after 5 minutesdone, pending = await asyncio.wait([hanging_task, ping_task],timeout=300, # 5 minute timeout- return_when=asyncio.ALL_COMPLETED+ return_when=asyncio.ALL_COMPLETED,)-+# Cancel any pending tasksfor task in pending:task.cancel()@@ -156,11 +162,11 @@ async def test_watchdog_recovery_after_hanging_command(computer):await taskexcept asyncio.CancelledError:pass-+# Get results from completed tasksping_result = Nonehanging_result = None-+if ping_task in done:try:ping_result = await ping_task@@ -168,7 +174,7 @@ async def test_watchdog_recovery_after_hanging_command(computer):except Exception as e:print(f"Error getting ping task result: {e}")traceback.print_exc()-+if hanging_task in done:try:hanging_result = await hanging_task@@ -176,33 +182,45 @@ async def test_watchdog_recovery_after_hanging_command(computer):except Exception as e:print(f"Error getting hanging task result: {e}")traceback.print_exc()-+# Analyze resultsif ping_result:successful_pings, failed_pings = ping_result-+# Test passes if we had some successful pings, indicating recovery- assert successful_pings > 0, f"No successful pings detected. Server may not have recovered."-+ assert (+ successful_pings > 0+ ), "No successful pings detected. Server may not have recovered."+# Check if hanging command was killed (indicating watchdog restart)if hanging_result is None:print("✅ SUCCESS: Hanging command was killed - watchdog restart detected")elif hanging_result is True:- print("⚠️ WARNING: Hanging command completed naturally - watchdog may not have restarted")-+ print(+ "⚠️ WARNING: Hanging command completed naturally - watchdog may not have restarted"+ )+# If we had failures followed by successes, that indicates watchdog recoveryif failed_pings > 0 and successful_pings > 0:- print("✅ SUCCESS: Watchdog recovery detected - server became unresponsive then recovered")+ print(+ "✅ SUCCESS: Watchdog recovery detected - server became unresponsive then recovered"+ )# Additional check: hanging command should be None if watchdog worked- assert hanging_result is None, "Expected hanging command to be killed by watchdog restart"+ assert (+ hanging_result is None+ ), "Expected hanging command to be killed by watchdog restart"elif successful_pings > 0 and failed_pings == 0:print("✅ SUCCESS: Server remained responsive throughout test")-- print(f"Test completed: {successful_pings} successful pings, {failed_pings} failed pings")- print(f"Hanging command result: {hanging_result} (None = killed by watchdog, True = completed naturally)")++ print(+ f"Test completed: {successful_pings} successful pings, {failed_pings} failed pings"+ )+ print(+ f"Hanging command result: {hanging_result} (None = killed by watchdog, True = completed naturally)"+ )else:pytest.fail("Ping task did not complete - unable to assess server recovery")-+except Exception as e:print(f"Test failed with exception: {e}")traceback.print_exc()