cua-agent 0.1.17__py3-none-any.whl → 0.1.18__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.

Potentially problematic release.


This version of cua-agent might be problematic. Click here for more details.

@@ -0,0 +1,79 @@
1
+ """OpenAI-specific tool base classes."""
2
+
3
+ from abc import ABCMeta, abstractmethod
4
+ from dataclasses import dataclass, fields, replace
5
+ from typing import Any, Dict, List, Optional
6
+
7
+ from ....core.tools.base import BaseTool
8
+
9
+
10
+ class BaseOpenAITool(BaseTool, metaclass=ABCMeta):
11
+ """Abstract base class for OpenAI-defined tools."""
12
+
13
+ def __init__(self):
14
+ """Initialize the base OpenAI tool."""
15
+ # No specific initialization needed yet, but included for future extensibility
16
+ pass
17
+
18
+ @abstractmethod
19
+ async def __call__(self, **kwargs) -> Any:
20
+ """Executes the tool with the given arguments."""
21
+ ...
22
+
23
+ @abstractmethod
24
+ def to_params(self) -> Dict[str, Any]:
25
+ """Convert tool to OpenAI-specific API parameters.
26
+
27
+ Returns:
28
+ Dictionary with tool parameters for OpenAI API
29
+ """
30
+ raise NotImplementedError
31
+
32
+
33
+ @dataclass(kw_only=True, frozen=True)
34
+ class ToolResult:
35
+ """Represents the result of a tool execution."""
36
+
37
+ output: str | None = None
38
+ error: str | None = None
39
+ base64_image: str | None = None
40
+ system: str | None = None
41
+ content: list[dict] | None = None
42
+
43
+ def __bool__(self):
44
+ return any(getattr(self, field.name) for field in fields(self))
45
+
46
+ def __add__(self, other: "ToolResult"):
47
+ def combine_fields(field: str | None, other_field: str | None, concatenate: bool = True):
48
+ if field and other_field:
49
+ if concatenate:
50
+ return field + other_field
51
+ raise ValueError("Cannot combine tool results")
52
+ return field or other_field
53
+
54
+ return ToolResult(
55
+ output=combine_fields(self.output, other.output),
56
+ error=combine_fields(self.error, other.error),
57
+ base64_image=combine_fields(self.base64_image, other.base64_image, False),
58
+ system=combine_fields(self.system, other.system),
59
+ content=self.content or other.content, # Use first non-None content
60
+ )
61
+
62
+ def replace(self, **kwargs):
63
+ """Returns a new ToolResult with the given fields replaced."""
64
+ return replace(self, **kwargs)
65
+
66
+
67
+ class CLIResult(ToolResult):
68
+ """A ToolResult that can be rendered as a CLI output."""
69
+
70
+
71
+ class ToolFailure(ToolResult):
72
+ """A ToolResult that represents a failure."""
73
+
74
+
75
+ class ToolError(Exception):
76
+ """Raised when a tool encounters an error."""
77
+
78
+ def __init__(self, message):
79
+ self.message = message
@@ -0,0 +1,319 @@
1
+ """Computer tool for OpenAI."""
2
+
3
+ import asyncio
4
+ import base64
5
+ import logging
6
+ from typing import Literal, Any, Dict, Optional, List, Union
7
+
8
+ from computer.computer import Computer
9
+
10
+ from .base import BaseOpenAITool, ToolError, ToolResult
11
+ from ....core.tools.computer import BaseComputerTool
12
+
13
+ TYPING_DELAY_MS = 12
14
+ TYPING_GROUP_SIZE = 50
15
+
16
+ # Key mapping for special keys
17
+ KEY_MAPPING = {
18
+ "enter": "return",
19
+ "backspace": "delete",
20
+ "delete": "forwarddelete",
21
+ "escape": "esc",
22
+ "pageup": "page_up",
23
+ "pagedown": "page_down",
24
+ "arrowup": "up",
25
+ "arrowdown": "down",
26
+ "arrowleft": "left",
27
+ "arrowright": "right",
28
+ "home": "home",
29
+ "end": "end",
30
+ "tab": "tab",
31
+ "space": "space",
32
+ "shift": "shift",
33
+ "control": "control",
34
+ "alt": "alt",
35
+ "meta": "command",
36
+ }
37
+
38
+ Action = Literal[
39
+ "key",
40
+ "type",
41
+ "mouse_move",
42
+ "left_click",
43
+ "right_click",
44
+ "double_click",
45
+ "screenshot",
46
+ "scroll",
47
+ ]
48
+
49
+
50
+ class ComputerTool(BaseComputerTool, BaseOpenAITool):
51
+ """
52
+ A tool that allows the agent to interact with the screen, keyboard, and mouse of the current computer.
53
+ """
54
+
55
+ name: Literal["computer"] = "computer"
56
+ api_type: Literal["computer_use_preview"] = "computer_use_preview"
57
+ width: Optional[int] = None
58
+ height: Optional[int] = None
59
+ display_num: Optional[int] = None
60
+ computer: Computer # The CUA Computer instance
61
+ logger = logging.getLogger(__name__)
62
+
63
+ _screenshot_delay = 1.0 # macOS is generally faster than X11
64
+ _scaling_enabled = True
65
+
66
+ def __init__(self, computer: Computer):
67
+ """Initialize the computer tool.
68
+
69
+ Args:
70
+ computer: Computer instance
71
+ """
72
+ self.computer = computer
73
+ self.width = None
74
+ self.height = None
75
+ self.logger = logging.getLogger(__name__)
76
+
77
+ # Initialize the base computer tool first
78
+ BaseComputerTool.__init__(self, computer)
79
+ # Then initialize the OpenAI tool
80
+ BaseOpenAITool.__init__(self)
81
+
82
+ # Additional initialization
83
+ self.width = None # Will be initialized from computer interface
84
+ self.height = None # Will be initialized from computer interface
85
+ self.display_num = None
86
+
87
+ def to_params(self) -> Dict[str, Any]:
88
+ """Convert tool to API parameters.
89
+
90
+ Returns:
91
+ Dictionary with tool parameters
92
+ """
93
+ if self.width is None or self.height is None:
94
+ raise RuntimeError(
95
+ "Screen dimensions not initialized. Call initialize_dimensions() first."
96
+ )
97
+ return {
98
+ "type": self.api_type,
99
+ "display_width": self.width,
100
+ "display_height": self.height,
101
+ "display_number": self.display_num,
102
+ }
103
+
104
+ async def initialize_dimensions(self):
105
+ """Initialize screen dimensions from the computer interface."""
106
+ try:
107
+ display_size = await self.computer.interface.get_screen_size()
108
+ self.width = display_size["width"]
109
+ self.height = display_size["height"]
110
+ assert isinstance(self.width, int) and isinstance(self.height, int)
111
+ self.logger.info(f"Initialized screen dimensions to {self.width}x{self.height}")
112
+ except Exception as e:
113
+ # Fall back to defaults if we can't get accurate dimensions
114
+ self.width = 1024
115
+ self.height = 768
116
+ self.logger.warning(
117
+ f"Failed to get screen dimensions, using defaults: {self.width}x{self.height}. Error: {e}"
118
+ )
119
+
120
+ async def __call__(
121
+ self,
122
+ *,
123
+ type: str, # OpenAI uses 'type' instead of 'action'
124
+ text: Optional[str] = None,
125
+ **kwargs,
126
+ ):
127
+ try:
128
+ # Ensure dimensions are initialized
129
+ if self.width is None or self.height is None:
130
+ await self.initialize_dimensions()
131
+ if self.width is None or self.height is None:
132
+ raise ToolError("Failed to initialize screen dimensions")
133
+
134
+ if type == "type":
135
+ if text is None:
136
+ raise ToolError("text is required for type action")
137
+ return await self.handle_typing(text)
138
+ elif type == "click":
139
+ # Map button to correct action name
140
+ button = kwargs.get("button")
141
+ if button is None:
142
+ raise ToolError("button is required for click action")
143
+ return await self.handle_click(button, kwargs["x"], kwargs["y"])
144
+ elif type == "keypress":
145
+ # Check for keys in kwargs if text is None
146
+ if text is None:
147
+ if "keys" in kwargs and isinstance(kwargs["keys"], list):
148
+ # Pass the keys list directly instead of joining and then splitting
149
+ return await self.handle_key(kwargs["keys"])
150
+ else:
151
+ raise ToolError("Either 'text' or 'keys' is required for keypress action")
152
+ return await self.handle_key(text)
153
+ elif type == "mouse_move":
154
+ if "coordinates" not in kwargs:
155
+ raise ToolError("coordinates is required for mouse_move action")
156
+ return await self.handle_mouse_move(
157
+ kwargs["coordinates"][0], kwargs["coordinates"][1]
158
+ )
159
+ elif type == "scroll":
160
+ # Get x, y coordinates directly from kwargs
161
+ x = kwargs.get("x")
162
+ y = kwargs.get("y")
163
+ if x is None or y is None:
164
+ raise ToolError("x and y coordinates are required for scroll action")
165
+ scroll_x = kwargs.get("scroll_x", 0)
166
+ scroll_y = kwargs.get("scroll_y", 0)
167
+ return await self.handle_scroll(x, y, scroll_x, scroll_y)
168
+ elif type == "screenshot":
169
+ return await self.screenshot()
170
+ elif type == "wait":
171
+ duration = kwargs.get("duration", 1.0)
172
+ await asyncio.sleep(duration)
173
+ return await self.screenshot()
174
+ else:
175
+ raise ToolError(f"Unsupported action: {type}")
176
+
177
+ except Exception as e:
178
+ self.logger.error(f"Error in ComputerTool.__call__: {str(e)}")
179
+ raise ToolError(f"Failed to execute {type}: {str(e)}")
180
+
181
+ async def handle_click(self, button: str, x: int, y: int) -> ToolResult:
182
+ """Handle different click actions."""
183
+ try:
184
+ # Perform requested click action
185
+ if button == "left":
186
+ await self.computer.interface.left_click(x, y)
187
+ elif button == "right":
188
+ await self.computer.interface.right_click(x, y)
189
+ elif button == "double":
190
+ await self.computer.interface.double_click(x, y)
191
+
192
+ # Wait for UI to update
193
+ await asyncio.sleep(0.5)
194
+
195
+ # Take screenshot after action
196
+ screenshot = await self.computer.interface.screenshot()
197
+ base64_screenshot = base64.b64encode(screenshot).decode("utf-8")
198
+
199
+ return ToolResult(
200
+ output=f"Performed {button} click at ({x}, {y})",
201
+ base64_image=base64_screenshot,
202
+ )
203
+ except Exception as e:
204
+ self.logger.error(f"Error in handle_click: {str(e)}")
205
+ raise ToolError(f"Failed to perform {button} click at ({x}, {y}): {str(e)}")
206
+
207
+ async def handle_typing(self, text: str) -> ToolResult:
208
+ """Handle typing text with a small delay between characters."""
209
+ try:
210
+ # Type the text with a small delay
211
+ await self.computer.interface.type_text(text)
212
+
213
+ await asyncio.sleep(0.3)
214
+
215
+ # Take screenshot after typing
216
+ screenshot = await self.computer.interface.screenshot()
217
+ base64_screenshot = base64.b64encode(screenshot).decode("utf-8")
218
+
219
+ return ToolResult(output=f"Typed: {text}", base64_image=base64_screenshot)
220
+ except Exception as e:
221
+ self.logger.error(f"Error in handle_typing: {str(e)}")
222
+ raise ToolError(f"Failed to type '{text}': {str(e)}")
223
+
224
+ async def handle_key(self, key: Union[str, List[str]]) -> ToolResult:
225
+ """Handle key press, supporting both single keys and combinations.
226
+
227
+ Args:
228
+ key: Either a string (e.g. "ctrl+c") or a list of keys (e.g. ["ctrl", "c"])
229
+ """
230
+ try:
231
+ # Check if key is already a list
232
+ if isinstance(key, list):
233
+ keys = [k.strip().lower() for k in key]
234
+ else:
235
+ # Split key string into list if it's a combination (e.g. "ctrl+c")
236
+ keys = [k.strip().lower() for k in key.split("+")]
237
+
238
+ # Map each key
239
+ mapped_keys = [KEY_MAPPING.get(k, k) for k in keys]
240
+
241
+ if len(mapped_keys) > 1:
242
+ # For key combinations (like Ctrl+C)
243
+ for k in mapped_keys:
244
+ await self.computer.interface.press_key(k)
245
+ await asyncio.sleep(0.1)
246
+ for k in reversed(mapped_keys):
247
+ await self.computer.interface.press_key(k)
248
+ else:
249
+ # Single key press
250
+ await self.computer.interface.press_key(mapped_keys[0])
251
+
252
+ # Wait briefly
253
+ await asyncio.sleep(0.3)
254
+
255
+ # Take screenshot after action
256
+ screenshot = await self.computer.interface.screenshot()
257
+ base64_screenshot = base64.b64encode(screenshot).decode("utf-8")
258
+
259
+ return ToolResult(output=f"Pressed key: {key}", base64_image=base64_screenshot)
260
+ except Exception as e:
261
+ self.logger.error(f"Error in handle_key: {str(e)}")
262
+ raise ToolError(f"Failed to press key '{key}': {str(e)}")
263
+
264
+ async def handle_mouse_move(self, x: int, y: int) -> ToolResult:
265
+ """Handle mouse movement."""
266
+ try:
267
+ # Move cursor to position
268
+ await self.computer.interface.move_cursor(x, y)
269
+
270
+ # Wait briefly
271
+ await asyncio.sleep(0.2)
272
+
273
+ # Take screenshot after action
274
+ screenshot = await self.computer.interface.screenshot()
275
+ base64_screenshot = base64.b64encode(screenshot).decode("utf-8")
276
+
277
+ return ToolResult(output=f"Moved cursor to ({x}, {y})", base64_image=base64_screenshot)
278
+ except Exception as e:
279
+ self.logger.error(f"Error in handle_mouse_move: {str(e)}")
280
+ raise ToolError(f"Failed to move cursor to ({x}, {y}): {str(e)}")
281
+
282
+ async def handle_scroll(self, x: int, y: int, scroll_x: int, scroll_y: int) -> ToolResult:
283
+ """Handle scrolling."""
284
+ try:
285
+ # Move cursor to position first
286
+ await self.computer.interface.move_cursor(x, y)
287
+
288
+ # Scroll based on direction
289
+ if scroll_y > 0:
290
+ await self.computer.interface.scroll_down(abs(scroll_y))
291
+ elif scroll_y < 0:
292
+ await self.computer.interface.scroll_up(abs(scroll_y))
293
+
294
+ # Wait for UI to update
295
+ await asyncio.sleep(0.5)
296
+
297
+ # Take screenshot after action
298
+ screenshot = await self.computer.interface.screenshot()
299
+ base64_screenshot = base64.b64encode(screenshot).decode("utf-8")
300
+
301
+ return ToolResult(
302
+ output=f"Scrolled at ({x}, {y}) with delta ({scroll_x}, {scroll_y})",
303
+ base64_image=base64_screenshot,
304
+ )
305
+ except Exception as e:
306
+ self.logger.error(f"Error in handle_scroll: {str(e)}")
307
+ raise ToolError(f"Failed to scroll at ({x}, {y}): {str(e)}")
308
+
309
+ async def screenshot(self) -> ToolResult:
310
+ """Take a screenshot."""
311
+ try:
312
+ # Take screenshot
313
+ screenshot = await self.computer.interface.screenshot()
314
+ base64_screenshot = base64.b64encode(screenshot).decode("utf-8")
315
+
316
+ return ToolResult(output="Screenshot taken", base64_image=base64_screenshot)
317
+ except Exception as e:
318
+ self.logger.error(f"Error in screenshot: {str(e)}")
319
+ raise ToolError(f"Failed to take screenshot: {str(e)}")
@@ -0,0 +1,106 @@
1
+ """Tool manager for the OpenAI provider."""
2
+
3
+ import logging
4
+ from typing import Dict, Any, Optional, List, Callable, Awaitable, Union
5
+
6
+ from computer import Computer
7
+ from ..types import ComputerAction, ResponseItemType
8
+ from .computer import ComputerTool
9
+ from ....core.tools.base import ToolResult, ToolFailure
10
+ from ....core.tools.collection import ToolCollection
11
+
12
+ logger = logging.getLogger(__name__)
13
+
14
+
15
+ class ToolManager:
16
+ """Manager for computer tools in the OpenAI agent."""
17
+
18
+ def __init__(
19
+ self,
20
+ computer: Computer,
21
+ acknowledge_safety_check_callback: Optional[Callable[[str], Awaitable[bool]]] = None,
22
+ ):
23
+ """Initialize the tool manager.
24
+
25
+ Args:
26
+ computer: Computer instance
27
+ acknowledge_safety_check_callback: Optional callback for safety check acknowledgment
28
+ """
29
+ self.computer = computer
30
+ self.acknowledge_safety_check_callback = acknowledge_safety_check_callback
31
+ self._initialized = False
32
+ self.computer_tool = ComputerTool(computer)
33
+ self.tools = None
34
+ logger.info("Initialized OpenAI ToolManager")
35
+
36
+ async def initialize(self) -> None:
37
+ """Initialize the tool manager."""
38
+ if not self._initialized:
39
+ logger.info("Initializing OpenAI ToolManager")
40
+
41
+ # Initialize the computer tool
42
+ await self.computer_tool.initialize_dimensions()
43
+
44
+ # Initialize tool collection
45
+ self.tools = ToolCollection(self.computer_tool)
46
+
47
+ self._initialized = True
48
+ logger.info("OpenAI ToolManager initialized")
49
+
50
+ async def get_tools_definition(self) -> List[Dict[str, Any]]:
51
+ """Get the tools definition for the OpenAI agent.
52
+
53
+ Returns:
54
+ Tools definition for the OpenAI agent
55
+ """
56
+ if not self.tools:
57
+ raise RuntimeError("Tools not initialized. Call initialize() first.")
58
+
59
+ # For the OpenAI Agent Response API, we use a special "computer-preview" tool
60
+ # which provides the correct interface for computer control
61
+ display_width, display_height = await self._get_computer_dimensions()
62
+
63
+ # Get environment, using "mac" as default since we're on macOS
64
+ environment = getattr(self.computer, "environment", "mac")
65
+
66
+ # Ensure environment is one of the allowed values
67
+ if environment not in ["windows", "mac", "linux", "browser"]:
68
+ logger.warning(f"Invalid environment value: {environment}, using 'mac' instead")
69
+ environment = "mac"
70
+
71
+ return [
72
+ {
73
+ "type": "computer-preview",
74
+ "display_width": display_width,
75
+ "display_height": display_height,
76
+ "environment": environment,
77
+ }
78
+ ]
79
+
80
+ async def _get_computer_dimensions(self) -> tuple[int, int]:
81
+ """Get the dimensions of the computer display.
82
+
83
+ Returns:
84
+ Tuple of (width, height)
85
+ """
86
+ # If computer tool is initialized, use its dimensions
87
+ if self.computer_tool.width is not None and self.computer_tool.height is not None:
88
+ return (self.computer_tool.width, self.computer_tool.height)
89
+
90
+ # Try to get from computer.interface if available
91
+ screen_size = await self.computer.interface.get_screen_size()
92
+ return (int(screen_size["width"]), int(screen_size["height"]))
93
+
94
+ async def execute_tool(self, name: str, tool_input: Dict[str, Any]) -> ToolResult:
95
+ """Execute a tool with the given input.
96
+
97
+ Args:
98
+ name: Name of the tool to execute
99
+ tool_input: Input parameters for the tool
100
+
101
+ Returns:
102
+ Result of the tool execution
103
+ """
104
+ if not self.tools:
105
+ raise RuntimeError("Tools not initialized. Call initialize() first.")
106
+ return await self.tools.run(name=name, tool_input=tool_input)
@@ -0,0 +1,36 @@
1
+ """Type definitions for the OpenAI provider."""
2
+
3
+ from enum import StrEnum, auto
4
+ from typing import Dict, List, Optional, Union, Any
5
+ from dataclasses import dataclass
6
+
7
+
8
+ class LLMProvider(StrEnum):
9
+ """OpenAI LLM provider types."""
10
+
11
+ OPENAI = "openai"
12
+
13
+
14
+ class ResponseItemType(StrEnum):
15
+ """Types of items in OpenAI Agent Response output."""
16
+
17
+ MESSAGE = "message"
18
+ COMPUTER_CALL = "computer_call"
19
+ COMPUTER_CALL_OUTPUT = "computer_call_output"
20
+ REASONING = "reasoning"
21
+
22
+
23
+ @dataclass
24
+ class ComputerAction:
25
+ """Represents a computer action to be performed."""
26
+
27
+ type: str
28
+ x: Optional[int] = None
29
+ y: Optional[int] = None
30
+ text: Optional[str] = None
31
+ button: Optional[str] = None
32
+ keys: Optional[List[str]] = None
33
+ ms: Optional[int] = None
34
+ scroll_x: Optional[int] = None
35
+ scroll_y: Optional[int] = None
36
+ path: Optional[List[Dict[str, int]]] = None
@@ -0,0 +1,98 @@
1
+ """Utility functions for the OpenAI provider."""
2
+
3
+ import logging
4
+ import json
5
+ import base64
6
+ from typing import Any, Dict, List, Optional
7
+
8
+ from ...core.types import AgentResponse
9
+
10
+ logger = logging.getLogger(__name__)
11
+
12
+
13
+ def format_images_for_openai(images_base64: List[str]) -> List[Dict[str, Any]]:
14
+ """Format images for OpenAI Agent Response API.
15
+
16
+ Args:
17
+ images_base64: List of base64 encoded images
18
+
19
+ Returns:
20
+ List of formatted image items for Agent Response API
21
+ """
22
+ return [
23
+ {"type": "input_image", "image_url": f"data:image/png;base64,{image}"}
24
+ for image in images_base64
25
+ ]
26
+
27
+
28
+ def extract_message_content(message: Dict[str, Any]) -> str:
29
+ """Extract text content from a message.
30
+
31
+ Args:
32
+ message: Message to extract content from
33
+
34
+ Returns:
35
+ Text content from the message
36
+ """
37
+ if isinstance(message.get("content"), str):
38
+ return message["content"]
39
+
40
+ if isinstance(message.get("content"), list):
41
+ text = ""
42
+ role = message.get("role", "user")
43
+
44
+ for item in message["content"]:
45
+ if isinstance(item, dict):
46
+ # For user messages
47
+ if role == "user" and item.get("type") == "input_text":
48
+ text += item.get("text", "")
49
+ # For standard format
50
+ elif item.get("type") == "text":
51
+ text += item.get("text", "")
52
+ # For assistant messages in Agent Response API format
53
+ elif item.get("type") == "output_text":
54
+ text += item.get("text", "")
55
+ return text
56
+
57
+ return ""
58
+
59
+
60
+ def sanitize_message(msg: Dict[str, Any]) -> Dict[str, Any]:
61
+ """Sanitize a message for logging by removing large image data.
62
+
63
+ Args:
64
+ msg: Message to sanitize
65
+
66
+ Returns:
67
+ Sanitized message
68
+ """
69
+ if not isinstance(msg, dict):
70
+ return msg
71
+
72
+ sanitized = msg.copy()
73
+
74
+ # Handle message content
75
+ if isinstance(sanitized.get("content"), list):
76
+ sanitized_content = []
77
+ for item in sanitized["content"]:
78
+ if isinstance(item, dict):
79
+ # Handle various image types
80
+ if item.get("type") == "image_url" and "image_url" in item:
81
+ sanitized_content.append({"type": "image_url", "image_url": "[omitted]"})
82
+ elif item.get("type") == "input_image" and "image_url" in item:
83
+ sanitized_content.append({"type": "input_image", "image_url": "[omitted]"})
84
+ elif item.get("type") == "image" and "source" in item:
85
+ sanitized_content.append({"type": "image", "source": "[omitted]"})
86
+ else:
87
+ sanitized_content.append(item)
88
+ else:
89
+ sanitized_content.append(item)
90
+ sanitized["content"] = sanitized_content
91
+
92
+ # Handle computer_call_output
93
+ if sanitized.get("type") == "computer_call_output" and "output" in sanitized:
94
+ output = sanitized["output"]
95
+ if isinstance(output, dict) and "image_url" in output:
96
+ sanitized["output"] = {**output, "image_url": "[omitted]"}
97
+
98
+ return sanitized