### Quickstart: Create Session, Start App, List and Activate Window (Python) Source: https://github.com/agbcloud/agbcloud-sdk/blob/master/docs/computer/windows.md A minimal runnable example demonstrating how to create a session, start an application (notepad.exe), list the root windows, and activate the first window found. This requires the AGB SDK, a valid AGB_API_KEY, and a computer automation image ID. ```python import time from agb import AGB from agb.session_params import CreateSessionParams agb = AGB() create_result = agb.create(CreateSessionParams(image_id="agb-computer-use-ubuntu-2204")) if not create_result.success: raise SystemExit(create_result.error_message) session = create_result.session start_result = session.computer.app.start("notepad.exe") if not start_result.success: raise SystemExit(start_result.error_message) time.sleep(2) windows = session.computer.window.list_root_windows(timeout_ms=5000) if windows: window_id = windows[0].window_id result = session.computer.window.activate(window_id) if not result.success: raise SystemExit(result.error_message) agb.delete(session) ``` -------------------------------- ### Quickstart: Create, Use, and Delete Session - Python Source: https://github.com/agbcloud/agbcloud-sdk/blob/master/docs/session/overview.md A minimal runnable example demonstrating the creation of a session, execution of a single command within it, and subsequent deletion of the session. Requires AGB SDK installation and valid credentials. ```python from agb import AGB from agb.session_params import CreateSessionParams agb = AGB() create_result = agb.create(CreateSessionParams(image_id="agb-code-space-1")) if not create_result.success: raise SystemExit(f"Session creation failed: {create_result.error_message}") session = create_result.session # Do something in the session session.code.run("print('Hello from AGB')", "python") agb.delete(session) ``` -------------------------------- ### Install AGB Cloud SDK and Set API Key Source: https://github.com/agbcloud/agbcloud-sdk/blob/master/docs/quickstart.md Installs the AGB Cloud SDK using pip and sets the AGB_API_KEY environment variable for authentication. Ensure you replace 'your_key' with your actual API key. ```bash pip install agbcloud-sdk export AGB_API_KEY="your_key" ``` -------------------------------- ### Start an Application using Installed List (Python) Source: https://github.com/agbcloud/agbcloud-sdk/blob/master/docs/computer/applications.md Starts an application by finding its entry in the installed applications list and using its predefined start command. This method ensures that the correct command is used, especially for applications with complex startup procedures. ```python apps_result = session.computer.app.list_installed() if not apps_result.success: raise SystemExit(apps_result.error_message) apps = apps_result.data target_app = None for app in apps: if "google chrome" in app.name.lower(): target_app = app break if target_app: start_result = session.computer.app.start(target_app.start_cmd) if not start_result.success: raise SystemExit(start_result.error_message) ``` -------------------------------- ### Basic Navigation with Python Source: https://github.com/agbcloud/agbcloud-sdk/blob/master/docs/examples/browser/README.md Demonstrates starting a browser, navigating to a URL, and retrieving basic page information using Python. This is a foundational example for browser automation. ```python from agbcloud.sdk import AGBCloud async def basic_navigation(): session = AGBCloud() await session.browser.new_page() await session.browser.goto("https://example.com") title = await session.browser.title() print(f"Page title: {title}") await session.close() # To run this example: # import asyncio # asyncio.run(basic_navigation()) ``` -------------------------------- ### Quickstart: Start App, Wait for Window, Type Text, Close with Python Source: https://github.com/agbcloud/agbcloud-sdk/blob/master/docs/computer/workflows.md This Python snippet demonstrates a basic workflow: starting an application, waiting for a specific window to appear, typing text into it, and then closing the session. It requires the 'agb' library and a valid 'image_id'. ```python import time from agb import AGB from agb.session_params import CreateSessionParams agb = AGB() create_result = agb.create(CreateSessionParams(image_id="agb-computer-use-ubuntu-2204")) if not create_result.success: raise SystemExit(create_result.error_message) session = create_result.session start_result = session.computer.app.start("notepad.exe") if not start_result.success: raise SystemExit(start_result.error_message) time.sleep(2) type_result = session.computer.keyboard.type("Hello from an automated workflow!") if not type_result.success: raise SystemExit(type_result.error_message) agb.delete(session) ``` -------------------------------- ### Quickstart: Create and Get Context (Python) Source: https://github.com/agbcloud/agbcloud-sdk/blob/master/docs/context/basics.md Initializes the AGB client and retrieves or creates a project context. It checks for success and prints context details. Requires the AGB API key. ```python from agb import AGB agb = AGB() result = agb.context.get("my-project-context", create=True) if not result.success: raise SystemExit(result.error_message) context = result.context print("Context:", context.name, context.id) ``` -------------------------------- ### Quickstart: Automate Computer Session (Python) Source: https://github.com/agbcloud/agbcloud-sdk/blob/master/docs/computer/overview.md A minimal runnable example demonstrating how to create a computer session, perform mouse clicks, type text, capture a screenshot, and then clean up the session. It requires the AGB SDK and a valid image ID. ```python from agb import AGB from agb.session_params import CreateSessionParams from agb import MouseButton agb = AGB() create_result = agb.create(CreateSessionParams(image_id="agb-computer-use-ubuntu-2204")) if not create_result.success: raise SystemExit(f"Session creation failed: {create_result.error_message}") session = create_result.session session.computer.mouse.click(x=500, y=300, button=MouseButton.LEFT) session.computer.keyboard.type("Hello from AGB!") image_url = session.computer.screen.capture() print("Screenshot URL:", image_url) agb.delete(session) ``` -------------------------------- ### Basic File System Monitoring with Python Source: https://github.com/agbcloud/agbcloud-sdk/blob/master/docs/examples/directory_monitoring/README.md This example demonstrates basic directory monitoring using the `filesystem.watch` API in Python. It starts a background process to create files and detects these changes, reporting them. No external dependencies are required beyond the agbcloud-sdk. ```python from agbcloud.sdk.filesystem import watch import time import os def monitor_directory(session): """Monitors a directory for file changes.""" watch_path = "/tmp/watch_dir" os.makedirs(watch_path, exist_ok=True) def on_change(event): print(f"File {event.src_path} {event.event_type}") observer = watch(watch_path, on_change) observer.start() try: # Create some files to trigger events with open(os.path.join(watch_path, "file1.txt"), "w") as f: f.write("Hello") time.sleep(1) os.remove(os.path.join(watch_path, "file1.txt")) time.sleep(1) with open(os.path.join(watch_path, "file2.txt"), "w") as f: f.write("World") while True: time.sleep(1) except KeyboardInterrupt: observer.stop() observer.join() # Example usage (assuming 'session' is an active agbcloud session object) # monitor_directory(session) ``` -------------------------------- ### Install Packages with Shell Command Source: https://github.com/agbcloud/agbcloud-sdk/blob/master/docs/command/overview.md Shows how to install packages using a package manager like `apt-get` within a session. Includes updating package lists and installing `jq`, with an example of increasing the command timeout. ```python session.command.execute("apt-get update && apt-get install -y jq", timeout_ms=30000) ``` -------------------------------- ### Quickstart: Create Session and List Applications (Python) Source: https://github.com/agbcloud/agbcloud-sdk/blob/master/docs/computer/applications.md Initializes the AGB SDK, creates a computer session using a specified image ID, lists installed applications, and then cleans up the session. Requires 'AGB_API_KEY' and a valid 'image_id'. ```python from agb import AGB from agb.session_params import CreateSessionParams agb = AGB() create_result = agb.create(CreateSessionParams(image_id="agb-computer-use-ubuntu-2204")) if not create_result.success: raise SystemExit(create_result.error_message) session = create_result.session apps_result = session.computer.app.list_installed() if not apps_result.success: raise SystemExit(apps_result.error_message) apps = apps_result.data print("Installed apps:", len(apps)) agb.delete(session) ``` -------------------------------- ### Setup Development Environment for AGBcloud SDK Source: https://github.com/agbcloud/agbcloud-sdk/blob/master/README.md Provides instructions for setting up the development environment for the AGBcloud SDK. This includes cloning the repository, creating a virtual environment, and installing development dependencies. ```bash git clone https://github.com/agbcloud/agbcloud-sdk.git cd agbcloud-sdk python -m venv venv source venv/bin/activate # On Windows: venv\Scripts\activate pip install -e ."[dev,test]" ``` -------------------------------- ### Launch Browser with Command Arguments in Python Source: https://github.com/agbcloud/agbcloud-sdk/blob/master/docs/examples/browser/README.md Shows how to launch the browser with custom command-line arguments and a default navigation URL. This is useful for disabling specific Chrome features or starting the browser on a particular page. ```python from agbcloud.sdk import AGBCloud async def browser_command_args(): session = AGBCloud() # Example: Launch Chrome with --no-sandbox argument and navigate to a URL await session.browser.new_page( url="https://www.google.com", args=["--no-sandbox", "--disable-setuid-sandbox"] ) print("Browser launched with custom arguments.") # Perform actions await session.close() # To run this example: # import asyncio # asyncio.run(browser_command_args()) ``` -------------------------------- ### Basic Code Execution Example Source: https://github.com/agbcloud/agbcloud-sdk/blob/master/docs/examples/code_execution/README.md A comprehensive example demonstrating basic code execution across all supported languages (Python, JavaScript, Java, R) using the AGB SDK. This serves as a starting point for understanding the SDK's execution capabilities. ```python print("Hello from Python!") ``` ```javascript console.log("Hello from JavaScript!"); ``` ```java System.out.println("Hello from Java!"); ``` ```r print("Hello from R!") ``` -------------------------------- ### AGB Cloud SDK Fingerprint Persistence Example Orchestration Source: https://github.com/agbcloud/agbcloud-sdk/blob/master/docs/browser/fingerprint.md Orchestrates the fingerprint persistence example by first running the initial session setup and then running the second session that reuses the persisted fingerprint. This function ties together the two core operations for the demonstration. ```python def fingerprint_persistence_example(): """Test browser fingerprint persist across sessions with the same browser and fingerprint context.""" run_as_first_time() time.sleep(3) run_as_second_time() if __name__ == "__main__": fingerprint_persistence_example() ``` -------------------------------- ### Achieving Consistent Fingerprint with Persistence Source: https://github.com/agbcloud/agbcloud-sdk/blob/master/docs/browser/fingerprint.md Example demonstrating how to ensure a consistent fingerprint across sessions using `fingerprint_persistent=True` and the `fingerprint` parameter. ```python # ✅ Correct - Consistent fingerprint across sessions browser_option = BrowserOption( use_stealth=True, fingerprint_persistent=True, fingerprint=BrowserFingerprint(devices=["desktop"]) ) # Will use the same fingerprint in all sessions ``` -------------------------------- ### BrowserContext Initialization Examples (Python) Source: https://github.com/agbcloud/agbcloud-sdk/blob/master/docs/api-reference/reference/configurations.md Demonstrates how to initialize the BrowserContext class in Python. Examples show configurations with and without extensions, using ExtensionOption for managing browser extensions and their synchronization. ```python # With extensions using ExtensionOption from agb.extension import ExtensionOption ext_option = ExtensionOption( context_id="my_extensions", extension_ids=["ext1", "ext2"] ) browser_context = BrowserContext( context_id="browser_session", auto_upload=True, extension_option=ext_option ) # Without extensions (minimal configuration) browser_context = BrowserContext( context_id="browser_session", auto_upload=True ) # extension_context_syncs will be None ``` -------------------------------- ### Correct Device and OS Compatibility for Fingerprints Source: https://github.com/agbcloud/agbcloud-sdk/blob/master/docs/browser/fingerprint.md Provides examples of correctly configured `BrowserFingerprint` objects, ensuring that device types match the intended operating systems. ```python # ✅ Correct configurations desktop_fingerprint = BrowserFingerprint( devices=["desktop"], operating_systems=["windows", "macos", "linux"] ) mobile_fingerprint = BrowserFingerprint( devices=["mobile"], operating_systems=["android", "ios"] ) ``` -------------------------------- ### Start Application - Python Source: https://github.com/agbcloud/agbcloud-sdk/blob/master/docs/api-reference/capabilities/computer.md Starts a specified application with optional working directory and activity. It returns a ProcessListResult containing information about the started processes and any errors encountered. The start command can be an executable name or a full path. ```python class ApplicationManager(BaseService): def start(self, start_cmd: str, work_directory: str = "", activity: str = "") -> ProcessListResult: """Starts the specified application. Args: start_cmd (str): The command to start the application (executable name or full path, may include arguments). work_directory (str, optional): Working directory for the application. Defaults to "". activity (str, optional): Activity name to launch (for mobile apps). Defaults to "". Returns: ProcessListResult: Result object containing list of processes started and error message if any. """ pass ``` -------------------------------- ### Download File Example Source: https://github.com/agbcloud/agbcloud-sdk/blob/master/docs/api-reference/capabilities/file_system.md An example demonstrating the usage of the download method from the FileSystem class. It illustrates how to specify the remote and local paths for downloading a file. ```python remote_path = session.file.transfer_path() + "/file.txt" download_result = session.file.download(remote_path, "/local/file.txt") ``` -------------------------------- ### Complete Sync Policy Configuration in Python Source: https://github.com/agbcloud/agbcloud-sdk/blob/master/docs/context/sync-policies.md Provides a comprehensive example of configuring a SyncPolicy with detailed settings for upload, download, delete, extract, recycle, and black/white lists. This configuration is suitable for general use. ```python from agb.context_sync import ( SyncPolicy, UploadPolicy, DownloadPolicy, DeletePolicy, ExtractPolicy, RecyclePolicy, BWList, WhiteList, MappingPolicy, UploadStrategy, DownloadStrategy, UploadMode, Lifecycle ) # Create complete sync policy sync_policy = SyncPolicy( # Upload policy upload_policy=UploadPolicy( auto_upload=True, upload_strategy=UploadStrategy.UPLOAD_BEFORE_RESOURCE_RELEASE, upload_mode=UploadMode.FILE ), # Download policy download_policy=DownloadPolicy( auto_download=True, download_strategy=DownloadStrategy.DOWNLOAD_ASYNC ), # Delete policy delete_policy=DeletePolicy( sync_local_file=True ), # Extract policy extract_policy=ExtractPolicy( extract=True, delete_src_file=False, # Keep source file extract_current_folder=True ), # Recycle policy recycle_policy=RecyclePolicy( lifecycle=Lifecycle.LIFECYCLE_30DAYS, paths=[""] ), # Black/white list bw_list=BWList( white_lists=[ WhiteList( path="/home/project", exclude_paths=[ "/home/project/temp", "/home/project/logs", "/home/project/.git" ] ) ] ), # Mapping policy mapping_policy=MappingPolicy( path="/tmp/mapping" ) ) ``` -------------------------------- ### Comprehensive File Operations with Filesystem API Source: https://github.com/agbcloud/agbcloud-sdk/blob/master/docs/examples/file_system/README.md Demonstrates a wide range of file system operations including basic read/write, directory management, file info retrieval, editing, moving, deletion, searching, batch operations, and binary file handling. This example covers 19 operations with error handling and includes examples for large file operations. ```python from agbcloud.api import Filesystem from agbcloud.api.filesystem import FileInfo from agbcloud.api.filesystem.exceptions import FileNotFoundError, DirectoryNotEmptyError import os import time async def main(): fs = Filesystem() # --- Basic Operations --- print("\n--- Basic Operations ---") file_path = "example.txt" content_to_write = "Hello, AGBCloud!\n" # Write to file await fs.write(file_path, content_to_write) print(f"Wrote to {file_path}") # Read from file read_content = await fs.read(file_path) print(f"Read from {file_path}: {read_content.strip()}") # Append to file content_to_append = "Appending new line.\n" await fs.write(file_path, content_to_append, append=True) print(f"Appended to {file_path}") read_content_after_append = await fs.read(file_path) print(f"Read after append: {read_content_after_append.strip()}") # --- Directory Management --- print("\n--- Directory Management ---") dir_path = "my_directory" subdir_path = os.path.join(dir_path, "subdir") file_in_subdir = os.path.join(subdir_path, "nested_file.txt") # Create directory await fs.mkdir(dir_path) print(f"Created directory: {dir_path}") await fs.mkdir(subdir_path) print(f"Created directory: {subdir_path}") # List directory contents print(f"Listing contents of {dir_path}:") dir_contents = await fs.list(dir_path) for item in dir_contents: print(f"- {item}") # --- File Information --- print("\n--- File Information ---") # Write a file to get info info_file_path = "info_test.txt" await fs.write(info_file_path, "File for info.") file_info: FileInfo = await fs.info(info_file_path) print(f"Info for {info_file_path}:") print(f" Name: {file_info.name}") print(f" Path: {file_info.path}") print(f" Size: {file_info.size} bytes") print(f" Last Modified: {file_info.last_modified}") print(f" Is Directory: {file_info.is_directory}") # --- File Editing --- print("\n--- File Editing ---") edit_file_path = "edit_test.txt" await fs.write(edit_file_path, "Original line.\nAnother line.") print(f"Content before edit: {(await fs.read(edit_file_path)).strip()}") # Replace 'Original' with 'Modified' await fs.edit(edit_file_path, {"Original": "Modified"}) print(f"Content after edit: {(await fs.read(edit_file_path)).strip()}") # --- File Movement --- print("\n--- File Movement ---") move_source_path = "move_source.txt" move_dest_path = os.path.join(dir_path, "move_dest.txt") await fs.write(move_source_path, "Content to move.") print(f"Moved {move_source_path} to {move_dest_path}") await fs.move(move_source_path, move_dest_path) print(f"File exists at {move_dest_path}: {await fs.exists(move_dest_path)}") print(f"File exists at {move_source_path}: {await fs.exists(move_source_path)}") # --- File Deletion --- print("\n--- File Deletion ---") delete_file_path = "delete_me.txt" await fs.write(delete_file_path, "Delete this.") print(f"Deleting {delete_file_path}") await fs.remove(delete_file_path) print(f"File exists at {delete_file_path}: {await fs.exists(delete_file_path)}") # Delete directory (must be empty) print(f"Deleting empty directory: {subdir_path}") await fs.remove(subdir_path) print(f"Directory exists at {subdir_path}: {await fs.exists(subdir_path)}") try: print(f"Attempting to delete non-empty directory: {dir_path}") await fs.remove(dir_path) except DirectoryNotEmptyError as e: print(f"Caught expected error: {e}") # Clean up the directory after removing its contents await fs.remove(move_dest_path) # Remove the moved file first await fs.remove(dir_path) print(f"Directory exists at {dir_path}: {await fs.exists(dir_path)}") # --- File Search --- print("\n--- File Search ---") search_file_path = "search_test.txt" await fs.write(search_file_path, "This file contains the word search and another search.") search_results = await fs.search(search_file_path, "search") print(f"Search results for 'search' in {search_file_path}: {search_results}") # --- Batch Operations --- print("\n--- Batch Operations ---") batch_files = [f"batch_{i}.txt" for i in range(3)] for i, bf in enumerate(batch_files): await fs.write(bf, f"Content for batch file {i}") print(f"Reading batch files: {batch_files}") batch_content = await fs.read_batch(batch_files) for path, content in batch_content.items(): print(f" {path}: {content.strip()}") # Clean up batch files for bf in batch_files: await fs.remove(bf) # --- Binary File Handling --- print("\n--- Binary File Handling ---") binary_file_path = "binary_test.bin" binary_data = b'\x01\x02\x03\x04\x05' await fs.write(binary_file_path, binary_data, format="bytes") print(f"Wrote binary data to {binary_file_path}") read_binary_data: bytes = await fs.read(binary_file_path, format="bytes") print(f"Read binary data: {read_binary_data}") print(f"Data matches: {read_binary_data == binary_data}") # --- Large File Operations --- print("\n--- Large File Operations ---") large_file_path = "large_file.txt" large_content = "A" * (1024 * 1024) # 1MB of data start_time = time.time() await fs.write(large_file_path, large_content) write_time = time.time() - start_time print(f"Time to write large file ({len(large_content)} bytes): {write_time:.4f} seconds") start_time = time.time() read_large_content = await fs.read(large_file_path) read_time = time.time() - start_time print(f"Time to read large file ({len(read_large_content)} bytes): {read_time:.4f} seconds") # Clean up large file await fs.remove(large_file_path) # --- Cleanup --- print("\n--- Cleanup ---") await fs.remove(file_path) await fs.remove(info_file_path) await fs.remove(edit_file_path) await fs.remove(search_file_path) await fs.remove(binary_file_path) print("All example files and directories cleaned up.") if __name__ == "__main__": import asyncio asyncio.run(main()) ``` -------------------------------- ### Upload File Example Source: https://github.com/agbcloud/agbcloud-sdk/blob/master/docs/api-reference/capabilities/file_system.md An example demonstrating how to use the upload method of the FileSystem class. It shows retrieving the transfer path and then uploading a local file to a specified remote path. ```python remote_path = session.file.transfer_path() + "/file.txt" upload_result = session.file.upload("/local/file.txt", remote_path) ``` -------------------------------- ### Context Sync Demo: Bidirectional Sync with Python Source: https://github.com/agbcloud/agbcloud-sdk/blob/master/docs/examples/data_persistence/README.md Illustrates bidirectional file synchronization. This example shows how to upload local input files, process them within the AGB session, and then download the resulting output files back to the local machine using Python. ```python from agbcloud import AGB def main(): agb = AGB() # Upload local input files agb.upload_file("./input_data.csv", "/agb/data/") agb.upload_file("./config.json", "/agb/config/") # ... your AGB session logic that processes the files ... # For example, running a script that uses the uploaded files agb.run_script("process_data.py") # Download generated output files agb.download_file("/agb/output/results.json", "./local_results/") agb.download_file("/agb/output/summary.txt", "./local_summary/") if __name__ == "__main__": main() ``` -------------------------------- ### AGB SDK Advanced Usage: Session Creation and Batch Operations (Python) Source: https://github.com/agbcloud/agbcloud-sdk/blob/master/docs/quickstart.md Demonstrates advanced AGB SDK usage, including robust error handling during session creation and performing batch operations by creating and cleaning up multiple sessions. Requires the 'agbcloud-sdk' package. ```python # Session management params = CreateSessionParams( image_id="agb-code-space-1" ) # Error handling result = agb.create(params) if result.success: session = result.session # Use session... else: print(f"Creation failed: {result.error_message}") # Batch operations sessions = [] for i in range(3): params = CreateSessionParams(image_id="agb-code-space-1") result = agb.create(params) if result.success: sessions.append(result.session) # Clean up all sessions for session in sessions: agb.delete(session) ``` -------------------------------- ### Ensure Application Readiness with Start and Activation in Python Source: https://github.com/agbcloud/agbcloud-sdk/blob/master/docs/computer/best-practices.md A Python function that attempts to start an application and then repeatedly tries to activate its window until it's ready or a timeout is reached. It returns the activated window object if successful. ```python import time def ensure_application_ready(session, app_name: str, timeout_s: int = 30): try: start_result = session.computer.app.start(app_name) if not start_result.success or not start_result.data: return None except Exception as e: return None start_time = time.time() while time.time() - start_time < timeout_s: try: windows = session.computer.window.list_root_windows() for window in windows: if getattr(window, "window_id", None): session.computer.window.activate(window.window_id) return window except Exception: pass time.sleep(1) return None ``` -------------------------------- ### Basic Execution Example in Python Source: https://github.com/agbcloud/agbcloud-sdk/blob/master/docs/code-interpreting/supported-languages.md A comprehensive example demonstrating basic code execution in Python. This snippet shows how to interact with the AGBCloud environment using Python 3 and its standard libraries. ```python print("This is a placeholder for the actual Python execution code.") # The actual code from ./main.py would be inserted here. ``` -------------------------------- ### Configure AGB SDK for Production with Custom Endpoint (Python) Source: https://github.com/agbcloud/agbcloud-sdk/blob/master/docs/quickstart.md Shows how to configure the AGB SDK for production environments by setting a custom API endpoint and adjusting the request timeout. This allows connection to specific AGB cloud instances. Requires the 'agbcloud-sdk' package. ```python import os # Environment variable configuration agb = AGB() # Custom configuration from agb.config import Config config = Config( endpoint="your-custom-endpoint.com", timeout_ms=60000, ) agb = AGB(cfg=config) ``` -------------------------------- ### Start an Application with Working Directory (Python) Source: https://github.com/agbcloud/agbcloud-sdk/blob/master/docs/computer/applications.md Starts an application and specifies a working directory for it. This is useful for applications that need to access specific files or configurations relative to a particular directory. ```python result = session.computer.app.start("notepad.exe", work_directory="C:\\Users\\Public\\Documents") if not result.success: raise SystemExit(result.error_message) processes = result.data print(f"Started {len(processes)} processes") ``` -------------------------------- ### Start an Application by Name (Python) Source: https://github.com/agbcloud/agbcloud-sdk/blob/master/docs/computer/applications.md Starts an application using its executable name. This is a straightforward way to launch a program if its executable is in the system's PATH. It returns the PIDs of the started processes. ```python result = session.computer.app.start("notepad.exe") if not result.success: raise SystemExit(result.error_message) processes = result.data print(f"Started {len(processes)} processes") ``` -------------------------------- ### Client-Side Caching Example Source: https://github.com/agbcloud/agbcloud-sdk/blob/master/docs/examples/code_execution/README.md Demonstrates implementing client-side caching for deterministic code execution results with the AGB SDK. This approach helps save costs and reduce latency by reusing previous results. ```python # Example for caching results in Python # Assumes an SDK client is initialized and configured for caching. # result = sdk_client.execute(code='deterministic_function()', cache_key='my_cache_key') ``` -------------------------------- ### Window and Application Management with AGB Cloud SDK Source: https://context7.com/agbcloud/agbcloud-sdk/llms.txt Programmatically manages desktop windows and applications. This includes listing installed applications, starting and stopping applications, listing windows, and controlling window states (activate, maximize, restore, resize, minimize, fullscreen, close). ```python from agb import AGB from agb.session_params import CreateSessionParams import time agb = AGB(api_key="your-api-key") params = CreateSessionParams(image_id="agb-computer-use-ubuntu-2204") result = agb.create(params) session = result.session time.sleep(3) # List installed applications apps_result = session.computer.app.list_installed() if apps_result.success: for app in apps_result.data: print(f"App: {app.name}, Start: {app.start_cmd}") # Start an application start_result = session.computer.app.start("gnome-calculator") if start_result.success: processes = start_result.data print(f"Started {len(processes)} processes") time.sleep(2) # List all windows windows_result = session.computer.window.list_root_windows() if windows_result.success: for window in windows_result.windows: print(f"Window: {window.title} (ID: {window.window_id})") # Get active window active_result = session.computer.window.get_active_window() if active_result.success and active_result.window: window = active_result.window window_id = window.window_id # Window state management session.computer.window.activate(window_id) session.computer.window.maximize(window_id) time.sleep(1) session.computer.window.restore(window_id) session.computer.window.resize(window_id, 800, 600) session.computer.window.minimize(window_id) time.sleep(1) session.computer.window.fullscreen(window_id) time.sleep(1) # Close window session.computer.window.close(window_id) # Stop application by process name session.computer.app.stop_by_pname("gnome-calculator") agb.delete(session) ``` -------------------------------- ### Create and Execute Code in an AGB Session (Python) Source: https://github.com/agbcloud/agbcloud-sdk/blob/master/docs/quickstart.md Demonstrates how to create a code execution session using a specified image ID, run Python code within that session, and print the results. It also includes cleanup by deleting the session. Requires the 'agbcloud-sdk' package. ```python from agb import AGB from agb.session_params import CreateSessionParams # Create client agb = AGB() # Create code execution session params = CreateSessionParams(image_id="agb-code-space-1") result =agb .create(params) if not result.success: print(f"✅ Session created failed: {result.error_message}") exit(1) session = result.session # Execute code result = session.code.run("print('Hello AGB!')", "python") # Print execution results if result.success and result.results: for exec_result in result.results: if exec_result.text: print(exec_result.text) # Cleanup agb.delete(session) ``` -------------------------------- ### ApplicationManager - Start Application Source: https://github.com/agbcloud/agbcloud-sdk/blob/master/docs/api-reference/capabilities/computer.md Starts a specified application with given command, working directory, and activity. ```APIDOC ## POST /application/start ### Description Starts the specified application. ### Method POST ### Endpoint /application/start ### Parameters #### Query Parameters - **start_cmd** (str) - Required - The command to start the application (executable name or full path, may include arguments). - **work_directory** (str) - Optional - Working directory for the application. Defaults to "". - **activity** (str) - Optional - Activity name to launch (for mobile apps). Defaults to "". ### Request Example ```json { "start_cmd": "notepad.exe", "work_directory": "C:\\Users\\User\\Documents", "activity": "" } ``` ### Response #### Success Response (200) - **processes** (list) - List of processes started. - **error_message** (str) - Error message if any. #### Response Example ```json { "processes": [ { "pid": 1234, "name": "notepad.exe", "command_line": "C:\\Windows\\System32\\notepad.exe" } ], "error_message": "" } ``` ``` -------------------------------- ### Python Session: Call MCP Tool Examples Source: https://github.com/agbcloud/agbcloud-sdk/blob/master/docs/api-reference/session.md Provides example usage for the `call_mcp_tool` method, demonstrating how to invoke the 'tap' and 'get_ui_elements' MCP tools. ```python # Call mobile device tap tool result = session.call_mcp_tool("tap", {"x": 100, "y": 200}) # Call get UI elements tool result = session.call_mcp_tool("get_ui_elements", {}) ``` -------------------------------- ### ApplicationManager - List Installed Applications Source: https://github.com/agbcloud/agbcloud-sdk/blob/master/docs/api-reference/capabilities/computer.md Gets the list of installed applications, with options to include start menu and desktop applications, and to ignore system apps. ```APIDOC ## GET /application/list_installed ### Description Gets the list of installed applications. ### Method GET ### Endpoint /application/list_installed ### Parameters #### Query Parameters - **start_menu** (bool) - Optional - Whether to include start menu applications. Defaults to True. - **desktop** (bool) - Optional - Whether to include desktop applications. Defaults to False. - **ignore_system_apps** (bool) - Optional - Whether to ignore system applications. Defaults to True. ### Response #### Success Response (200) - **installed_apps** (list) - List of installed applications, each with name, start_cmd, and optionally work_directory. - **error_message** (str) - Error message if any. #### Response Example ```json { "installed_apps": [ { "name": "Notepad", "start_cmd": "notepad.exe", "work_directory": "" } ], "error_message": "" } ``` ``` -------------------------------- ### Persist Browser Fingerprint with Python Source: https://github.com/agbcloud/agbcloud-sdk/blob/master/docs/examples/browser/README.md An advanced example showing how to persist browser fingerprints across multiple sessions using `BrowserContext` and `BrowserFingerprintContext`. This is crucial for maintaining a consistent browser identity over time. ```python from agbcloud.sdk import AGBCloud from agbcloud.sdk.browser_fingerprint import BrowserFingerprintContext async def browser_fingerprint_persistence(): # Using BrowserFingerprintContext to manage persistence async with BrowserFingerprintContext() as fingerprint_context: session1 = AGBCloud(fingerprint_context=fingerprint_context) await session1.browser.new_page() await session1.browser.goto("https://example.com") user_agent1 = await session1.evaluate("navigator.userAgent") print(f"Session 1 User Agent: {user_agent1}") await session1.close() # Create a new session, it should inherit the fingerprint session2 = AGBCloud(fingerprint_context=fingerprint_context) await session2.browser.new_page() await session2.browser.goto("https://example.com") user_agent2 = await session2.evaluate("navigator.userAgent") print(f"Session 2 User Agent: {user_agent2}") await session2.close() # To run this example: # import asyncio # asyncio.run(browser_fingerprint_persistence()) ``` -------------------------------- ### CAPTCHA Solving with Python Source: https://github.com/agbcloud/agbcloud-sdk/blob/master/docs/examples/browser/README.md An advanced example demonstrating how the agent can handle complex interactions like CAPTCHA challenges on real-world websites. This typically involves specialized tools or services integrated within the agent. ```python from agbcloud.sdk import AGBCloud async def captcha_solving(): session = AGBCloud() await session.browser.new_page() # Navigate to a page with a CAPTCHA (replace with actual URL) await session.browser.goto("https://www.example-captcha-site.com") # The agent's capabilities would automatically attempt to solve CAPTCHAs # if configured and detected. This is a high-level example. print("Attempting to navigate and potentially solve CAPTCHA...") # Example: After CAPTCHA is solved (or if none present), perform an action try: # Replace with an action that would occur after CAPTCHA resolution await session.action("Click the submit button") print("Action after CAPTCHA (or on page without CAPTCHA) performed.") except Exception as e: print(f"Action failed, possibly due to CAPTCHA or other issue: {e}") await session.close() # To run this example: # import asyncio # asyncio.run(captcha_solving()) ``` -------------------------------- ### AGB Cloud SDK Session and File Operation Example in Python Source: https://github.com/agbcloud/agbcloud-sdk/blob/master/docs/file-system/advanced-usage/different-file-types.md This Python code demonstrates the usage of the AGB Cloud SDK to create a session, perform file operations (JSON and CSV), and then delete the session. It requires the 'agb' library. The example shows how to initialize the SDK, create a session with a specified image ID, and handle potential session creation failures. ```python from agb import AGB from agb.session_params import CreateSessionParams # Assuming handle_json_file and handle_csv_file are defined as above agb = AGB() params = CreateSessionParams(image_id="agb-code-space-1") result = agb.create(params) if result.success: session = result.session # JSON example json_data = {"name": "John", "age": 30, "city": "New York"} success, result = handle_json_file(session, "/tmp/data.json", json_data) if success: print("JSON data:", result) # CSV example csv_data = [ {"name": "Alice", "age": 25, "city": "Boston"}, {"name": "Bob", "age": 30, "city": "Chicago"} ] success, result = handle_csv_file(session, "/tmp/data.csv", csv_data) if success: print("CSV data:", result) agb.delete(session) else: print(f"Failed to create session: {result.error_message}") ``` -------------------------------- ### Discover Installed Applications (Python) Source: https://github.com/agbcloud/agbcloud-sdk/blob/master/docs/computer/applications.md Retrieves a list of all installed applications on the computer session. It iterates through the applications and prints their names, start commands, stop commands, and working directories. This function helps in identifying the correct commands for starting applications. ```python apps_result = session.computer.app.list_installed() if not apps_result.success: raise SystemExit(apps_result.error_message) apps = apps_result.data print(f"Found {len(apps)} installed applications") for app in apps[:5]: print(f"Name: {app.name}") print(f"Start Command: {app.start_cmd}") print(f"Stop Command: {app.stop_cmd if app.stop_cmd else 'N/A'}") print(f"Work Directory: {app.work_directory if app.work_directory else 'N/A'}") print("---") ``` -------------------------------- ### List Installed Applications - Python Source: https://github.com/agbcloud/agbcloud-sdk/blob/master/docs/api-reference/capabilities/computer.md Retrieves a list of installed applications, with options to include start menu and desktop applications, and to ignore system apps. It returns an InstalledAppListResult containing the app list and any errors. Each app entry includes name, start command, and optionally work directory. ```python class ApplicationManager(BaseService): def list_installed(self, start_menu: bool = True, desktop: bool = False, ignore_system_apps: bool = True) -> InstalledAppListResult: """Gets the list of installed applications. Args: start_menu (bool, optional): Whether to include start menu applications. Defaults to True. desktop (bool, optional): Whether to include desktop applications. Defaults to False. ignore_system_apps (bool, optional): Whether to ignore system applications. Defaults to True. Returns: InstalledAppListResult: Result object containing list of installed apps and error message if any. """ pass ``` -------------------------------- ### Quickstart: Type text and press keys with AGBCloud SDK (Python) Source: https://github.com/agbcloud/agbcloud-sdk/blob/master/docs/computer/keyboard.md This snippet demonstrates the basic usage of the AGBCloud SDK to create a session, type text, press key combinations, and then delete the session. It requires the AGB library and session parameters. ```python from agb import AGB from agb.session_params import CreateSessionParams agb = AGB() create_result = agb.create(CreateSessionParams(image_id="agb-computer-use-ubuntu-2204")) if not create_result.success: raise SystemExit(create_result.error_message) session = create_result.session session.computer.keyboard.type("Hello AGB!") session.computer.keyboard.press(["Ctrl", "a"]) agb.delete(session) ``` -------------------------------- ### Quick Start: AGB Python SDK Usage Source: https://github.com/agbcloud/agbcloud-sdk/blob/master/README.md Demonstrates the basic usage of the AGB Python SDK. It shows how to initialize the SDK, create a session, execute Python code and shell commands, and manage files within the session. It also includes error handling for session creation. ```python from agb import AGB from agb.session_params import CreateSessionParams # Initialize AGB with your API key agb = AGB(api_key="your-api-key") # Create a session params = CreateSessionParams( image_id="agb-code-space-1", ) result = agb.create(params) if result.success: session = result.session # Execute Python code code_result = session.code.run("print('Hello AGB!')", "python") print(code_result.result) # Execute shell command cmd_result = session.command.execute("ls -la") print(cmd_result.output) # Work with files session.file.write("/tmp/test.txt", "Hello World!") file_result = session.file.read("/tmp/test.txt") print(file_result.content) # Clean up agb.delete(session) else: print(f"Failed to create session: {result.error_message}") ``` -------------------------------- ### Quickstart: Perform Mouse Actions in AGB Cloud Session Source: https://github.com/agbcloud/agbcloud-sdk/blob/master/docs/computer/mouse.md This Python snippet demonstrates how to initialize the AGB SDK, create a computer session, and perform basic mouse actions including clicking, moving, and scrolling. It requires an AGB API key and a valid computer automation image ID. ```python from agb import AGB, MouseButton, ScrollDirection from agb.session_params import CreateSessionParams agb = AGB() create_result = agb.create(CreateSessionParams(image_id="agb-computer-use-ubuntu-2204")) if not create_result.success: raise SystemExit(create_result.error_message) session = create_result.session result = session.computer.mouse.click(x=500, y=300, button=MouseButton.LEFT) if not result.success: raise SystemExit(result.error_message) result = session.computer.mouse.move(x=600, y=400) if not result.success: raise SystemExit(result.error_message) result = session.computer.mouse.scroll(x=500, y=500, direction=ScrollDirection.DOWN, amount=3) if not result.success: raise SystemExit(result.error_message) agb.delete(session) ``` -------------------------------- ### Extract and Sync Local Chrome Fingerprint to Remote Session (Python) Source: https://github.com/agbcloud/agbcloud-sdk/blob/master/docs/browser/fingerprint.md This Python example demonstrates how to extract a fingerprint from a local Chrome browser installation and apply it to a remote browser session managed by the AGB Cloud SDK. It utilizes the `BrowserFingerprintGenerator` to capture local characteristics and `BrowserOption` to configure the remote session. Dependencies include the `agb` SDK and `playwright`. ```python import os import asyncio from agb import AGB from agb.session_params import CreateSessionParams from agb.modules.browser.browser import BrowserOption from agb.modules.browser.fingerprint import BrowserFingerprintGenerator from playwright.async_api import async_playwright async def local_sync_fingerprint_example(): """Main function demonstrating browser fingerprint local sync.""" # Get API key from environment variable api_key = os.getenv("AGB_API_KEY") if not api_key: print("Error: AGB_API_KEY environment variable not set") return # Initialize AGB client print("Initializing AGB client...") agb = AGB(api_key=api_key) # Create a session print("Creating a new session...") params = CreateSessionParams( image_id="agb-browser-use-1", ) session_result = agb.create(params) if session_result.success: session = session_result.session print(f"Session created with ID: {session.session_id}") # Generate fingerprint from local Chrome browser fingerprint_generator = BrowserFingerprintGenerator() fingerprint_format = await fingerprint_generator.generate_fingerprint() # Create browser option with fingerprint format. # Fingerprint format is dumped from local chrome browser by BrowserFingerprintGenerator # automatically, you can use it to sync to remote browser fingerprint. browser_option = BrowserOption( use_stealth=True, fingerprint_format=fingerprint_format ) if await session.browser.initialize_async(browser_option): endpoint_url = session.browser.get_endpoint_url() print("endpoint_url =", endpoint_url) async with async_playwright() as p: browser = await p.chromium.connect_over_cdp(endpoint_url) context = browser.contexts[0] page = await context.new_page() # Check user agent. print("\n--- Check User Agent ---") await page.goto("https://httpbin.org/user-agent", timeout=120000) response = await page.evaluate("() => JSON.parse(document.body.textContent)") user_agent = response.get("user-agent", "") print(f"User Agent: {user_agent}") print("Please check if User Agent is synced correctly by visiting https://httpbin.org/user-agent in local chrome browser.") await page.wait_for_timeout(3000) await browser.close() # Clean up session agb.delete(session) if __name__ == "__main__": asyncio.run(local_sync_fingerprint_example()) ``` -------------------------------- ### Forcing Fingerprint Update with Persistence Source: https://github.com/agbcloud/agbcloud-sdk/blob/master/docs/browser/fingerprint.md Example showing how to force an update to the persisted fingerprint data by using `fingerprint_persistent=True` along with `fingerprint_format`. ```python # ✅ Correct - Force update persisted fingerprint browser_option = BrowserOption( use_stealth=True, fingerprint_persistent=True, fingerprint_format=new_fingerprint_data ) # Will replace existing fingerprint with new data ``` -------------------------------- ### Natural Language Actions with Python Source: https://github.com/agbcloud/agbcloud-sdk/blob/master/docs/examples/browser/README.md Demonstrates using natural language instructions (e.g., 'Click the 'Sign Up' button') to interact with web pages. This simplifies automation logic by abstracting complex element selection. ```python from agbcloud.sdk import AGBCloud async def natural_language_actions(): session = AGBCloud() await session.browser.new_page() await session.browser.goto("https://example.com") # Replace with a page having interactive elements # Example: Click a button described in natural language try: await session.action("Click the 'More information...' link") print("Natural language action executed successfully.") except Exception as e: print(f"Natural language action failed: {e}") await session.close() # To run this example: # import asyncio # asyncio.run(natural_language_actions()) ``` -------------------------------- ### Incorrect Device and OS Compatibility for Fingerprints Source: https://github.com/agbcloud/agbcloud-sdk/blob/master/docs/browser/fingerprint.md Shows an example of an incorrectly configured `BrowserFingerprint` where mobile operating systems are paired with a desktop device type, which is not supported. ```python # ❌ Incorrect - mismatched device and OS wrong_fingerprint = BrowserFingerprint( devices=["desktop"], operating_systems=["android", "ios"] # Mobile OS with desktop device ) ```