import os import sys import glob import json import argparse import re from typing import List from google import genai from google.genai import types def run_validate(category: str, check_name: str, passed: bool, message: str = ""): check_file = "/logs/verifier/validate_results.txt" os.makedirs(os.path.dirname(check_file), exist_ok=True) val = "pass" if passed else "fail" with open(check_file, "a") as f: f.write(f"{category}#{check_name}: {val}\n") if passed: print(f"✅ PASS: [{category}#{check_name}]") else: print(f"❌ FAILED: [{category}#{check_name}] {message}") def execute_commands(command: str) -> str: """Execute an Android CLI or ADB command and return its output.""" cmd = command.strip() if not ( cmd.startswith("adb") or cmd.startswith("android") or cmd.startswith("sleep") or cmd.startswith("ls") ): return "ERROR: You are only allowed to run 'adb', 'android', 'ls', or 'sleep' commands. Do not write python scripts to analyze images. You have built-in vision—just capture the screenshot and look at it!" import subprocess try: res = subprocess.run( command, shell=True, capture_output=True, text=True, timeout=30 ) return res.stdout + "\n" + res.stderr except Exception as e: return str(e) def main(): parser = argparse.ArgumentParser(description="Run journey tests evaluation.") parser.add_argument( "--journey-dir", type=str, required=True, help="Directory containing .journey.xml files", ) parser.add_argument( "--model", type=str, default=os.environ.get("MODEL_NAME", "gemini-3.6-flash"), help="Model to use for evaluation", ) parser.add_argument( "--fallback-model", type=str, default=os.environ.get("FALLBACK_MODEL_NAME", "gemini-3.5-flash"), help="Fallback model to use for evaluation in case of 503/429/529 errors", ) parser.add_argument( "--category", type=str, default="functional", help="Test category to record in validation results", ) args = parser.parse_args() print("--------------------------------------------------") print("🚀 Starting Journey Test Evaluation...") print("--------------------------------------------------") print("Setting up Android CLI...") import subprocess subprocess.run("apt-get update && apt-get install -y curl", shell=True, check=True) subprocess.run( "wget -qO- https://dl.google.com/android/cli/latest/linux_x86_64/install_root.sh | bash", shell=True, check=True, ) subprocess.run("android init", shell=True, check=True) # Find journey test XML files journey_files = glob.glob(f"{args.journey_dir}/*.journey.xml") api_key = os.environ.get("GEMINI_API_KEY") if not api_key: print("ERROR: GEMINI_API_KEY environment variable not set.") if journey_files: for journey_file in journey_files: journey_name = os.path.basename(journey_file) check_key = f"journey_{journey_name.replace('.journey.xml', '')}" run_validate( args.category, check_key, False, message="GEMINI_API_KEY environment variable not set.", ) sys.exit(1) model = args.model fallback_model = args.fallback_model client = genai.Client(api_key=api_key) if not journey_files: print(f"ERROR: No journey XML files found under {args.journey_dir}/") sys.exit(1) all_passed = True for journey_file in journey_files: current_model = model journey_name = os.path.basename(journey_file) print(f"Evaluating journey test: {journey_name}...") try: with open(journey_file, "r", encoding="utf-8") as f: journey_xml = f.read() except Exception as e: print(f"Error reading journey file {journey_file}: {e}") continue skill_md, interact_md, journeys_md = "", "", "" try: import subprocess res = subprocess.run( "find /root /home -path '*/skills/android-cli/SKILL.md' 2>/dev/null | head -n 1", shell=True, capture_output=True, text=True, ) skill_md_path = res.stdout.strip() if skill_md_path and os.path.exists(skill_md_path): skill_dir = os.path.dirname(skill_md_path) with open(os.path.join(skill_dir, "SKILL.md"), "r") as f: skill_md = f.read() with open( os.path.join(skill_dir, "references", "interact.md"), "r" ) as f: interact_md = f.read() with open( os.path.join(skill_dir, "references", "journeys.md"), "r" ) as f: journeys_md = f.read() else: print("Warning: Could not locate android-cli SKILL.md dynamically") except Exception as e: print(f"Warning: Could not read skill files: {e}") prompt = f""" You are evaluating an Android journey test using the Android CLI and its journey testing skills. Here is the Android CLI skill documentation: {skill_md} {interact_md} {journeys_md} Here is the Journey Test XML specification: ```xml {journey_xml} ``` Evaluate the journey test according to the journey instructions in the Android CLI skills. RULES: 1. Be really clear and critical about EVERY single word in EVERY ``. 2. An action must be 100% achievable and flawless to be marked as "PASSED". 3. The Android CLI allows you to see the screenshot, so you can use images if you'd like to see them using this skill. 4. DO NOT write python or shell scripts to analyze images. You have native multimodal vision capabilities. When you run a screenshot command, the image will be directly shown to your vision system. Just look at it! 5. ALWAYS save your screenshots to the `/tmp/screenshots/` directory (e.g., `android screen capture -o /tmp/screenshots/screen.png`). For each `` you evaluated, output should be as per the documentation. OUTPUT FORMAT: When done evaluating, output your final result as a raw JSON string. """ pass_count = 0 fail_count = 0 last_message = "" free_retry_used = False for attempt_idx in range(4): attempt = attempt_idx + 1 try: chat = client.chats.create( model=current_model, config=types.GenerateContentConfig( tools=[execute_commands], temperature=0.0, automatic_function_calling=types.AutomaticFunctionCallingConfig( disable=True ), ), ) response = chat.send_message(prompt) while response.function_calls: if response.text: print(f"🤔 LLM Thought: {response.text.strip()}") parts = [] all_valid_screenshots = [] for call in response.function_calls: cmd = call.args.get("command", "") print(f"🤖 LLM running command: {cmd}") os.makedirs("/tmp/screenshots", exist_ok=True) expected_paths = re.findall(r"-o\s+([^\s]+\.png)", cmd) pngs_to_check = ( glob.glob("/tmp/screenshots/*.png") + expected_paths ) for f in set(pngs_to_check): try: os.remove(f) except: pass out = execute_commands(cmd) parts.append( types.Part.from_function_response( name=call.name, response={"output": out} ) ) screenshots = ( glob.glob("/tmp/screenshots/*.png") + expected_paths ) valid_screenshots = [ f for f in set(screenshots) if os.path.exists(f) ] if valid_screenshots: all_valid_screenshots.extend(valid_screenshots) response = chat.send_message(parts) if all_valid_screenshots: print( f"📸 Attaching {len(set(all_valid_screenshots))} screenshot(s) to LLM context..." ) image_parts = [ "Here are the newly captured screenshots from the commands:" ] for f in set(all_valid_screenshots): with open(f, "rb") as img: image_parts.append( types.Part.from_bytes( data=img.read(), mime_type="image/png" ) ) response = chat.send_message(image_parts) if response.text: print(f"🤔 LLM Thought: {response.text.strip()}") text = response.text.strip() if response.text else "" match = re.search(r"```(?:json)?\s*(.*?)\s*```", text, re.DOTALL) if match: text = match.group(1).strip() else: match = re.search(r"(\{.*\})", text, re.DOTALL) if match: text = match.group(1).strip() eval_result = json.loads(text) results = eval_result.get("results", []) passed = bool(results) and all( r.get("status") == "PASSED" for r in results ) check_key = f"journey_{journey_name.replace('.journey.xml', '')}" error_messages = [ r.get("comment", "") for r in results if r.get("status") != "PASSED" ] message = ( " | ".join(error_messages) if error_messages else "All actions passed" ) last_message = message if passed: pass_count += 1 else: fail_count += 1 if pass_count >= 2: run_validate( args.category, check_key, True, message="Passed 2 out of 3. Msg:" + last_message, ) break elif fail_count >= 2: run_validate( args.category, check_key, False, message="Failed 2 out of 3. Msg:" + last_message, ) all_passed = False break else: print( f"Attempt {attempt}: {'PASS' if passed else 'FAIL'} ({pass_count}P/{fail_count}F). Retrying..." ) except Exception as e: print(f"Error calling LLM for {journey_name}: {e}") err_str = str(e) if "503" in err_str or "429" in err_str or "529" in err_str: if not free_retry_used: print( f"API error 503/429/529. Fallback model: {fallback_model} (free retry)" ) current_model = fallback_model free_retry_used = True last_message = str(e) continue else: print( f"API error 503/429/529. Fallback model: {fallback_model} (counted fail)" ) current_model = fallback_model last_message = str(e) fail_count += 1 if fail_count >= 2: check_key = f"journey_{journey_name.replace('.journey.xml', '')}" run_validate( args.category, check_key, False, message="Failed 2 out of 3 with API errors. Msg: " + last_message, ) all_passed = False break else: print( f"Attempt {attempt}: ERROR ({pass_count}P/{fail_count}F). Retrying..." ) if not all_passed: sys.exit(1) if __name__ == "__main__": main()