Files
Artemis-Eapil/artemis/tools/mobile/read_hierarchy.py
T
somew1nd 206a9ce921 feat: initial release of ARTEMIS Android Agent & Automation Platform
ARTEMIS is an autonomous multimodal Android agent and mobile UI automation
platform engineered for physical devices and emulators. It combines state-of-the-art
multimodal Vision-Language Models (VLMs) with hierarchical closed-loop planning,
resilient self-healing, and deep Android subsystem integration.

Key Features & Architectural Highlights:
- Dual-Engine Orchestration:
  * Pro Engine: Multi-agent closed-loop (Planner -> Operator -> Validator/Failure Analyzer -> Summarizer) powered by LangGraph.
  * Flash Engine: Ultra-fast reactive loop for deterministic, low-latency UI execution (<35 steps).
- Multimodal Perception & Grounding:
  * Hybrid visual screenshot grounding, real-time OCR extraction, and XML accessibility hierarchy parsing.
  * Dynamic-First, Coordinate-Fallback locating strategy for maximum resilience against UI drift.
- Autonomous Self-Healing & Diagnostics:
  * Failure analyzer and safety net for popup dismissal, crash recovery, and auto-retry.
  * Diagnostic sub-agents for log analysis, video recording inspection, and object detection.
- Unified CLI & Python SDK:
  * Rich CLI with commands: init, doctor, run, trace, batch, bench, server, and mcp.
  * Fluent Python SDK with Pydantic structured output models and package locking.
- Multi-Provider LLM Architecture:
  * Support for Google Gemini, OpenAI, Anthropic Claude, Vertex AI, OpenRouter, xAI Grok, and local endpoints (Ollama/vLLM).
  * Centralized configuration in config/artemis.jsonc.
- Native MCP & Observability:
  * Model Context Protocol (MCP) server endpoints for AI IDEs.
  * Full trace recording with before/after screenshots, action overlays, and execution replays.

Change-Id: I430b93ee2b76b54cc5a3c6eeccd15d2cf29830a1
2026-08-13 11:46:47 -07:00

107 lines
4.1 KiB
Python

# Copyright 2026 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import inspect
from typing import Any
from langchain_core.tools import BaseTool
from pydantic import BaseModel
from artemis.context import ArtemisContext
from artemis.data_engine.trace import trace_langchain_tool
from artemis.drivers.base import BaseDeviceDriver
from artemis.graph.state import State
from artemis.tools.base import ArtemisTool, ToolCategory, ToolRegistry
from artemis.tools.tool_wrapper import ToolWrapper
from artemis.tools.types import CyFunctionDetector
from artemis.utils.logger import get_logger
logger = get_logger(__name__)
class GetUiHierarchyArgs(BaseModel):
"""Arguments schema for getting UI hierarchy."""
model_config = {"ignored_types": (CyFunctionDetector,)}
GET_UI_HIERARCHY_DOCSTRING = (
"[DIAGNOSTIC] Retrieves the current screen UI hierarchy XML using a persistent"
" UI Automator client.\n\nUse this instead of running 'uiautomator dump'"
" command via adb shell, as it is much faster and more stable."
)
class GetUiHierarchyTool(ArtemisTool):
"""Universal tool for retrieving screen UI hierarchy XML."""
def __init__(self, category: ToolCategory = "diagnostic"):
super().__init__(
name="get_ui_hierarchy",
description=GET_UI_HIERARCHY_DOCSTRING,
args_schema=GetUiHierarchyArgs,
category=category,
)
# pylint: disable=too-many-arguments,too-many-positional-arguments
async def execute(
self,
driver: BaseDeviceDriver | None = None,
ctx: ArtemisContext | None = None,
tool_call_id: str | None = None, # pylint: disable=unused-argument
state: State | None = None, # pylint: disable=unused-argument
**kwargs: Any,
) -> str:
try:
logger.info("get_ui_hierarchy tool called.")
if ctx is not None and getattr(ctx, "ui_adb_client", None) is not None:
xml_hierarchy = ctx.ui_adb_client.get_hierarchy()
if inspect.iscoroutine(xml_hierarchy):
xml_hierarchy = await xml_hierarchy
return str(xml_hierarchy)
if driver is not None and hasattr(driver, "get_screen_data"):
screen_data = await driver.get_screen_data()
xml_hierarchy = getattr(screen_data, "ui_hierarchy_xml", None)
if xml_hierarchy:
return str(xml_hierarchy)
return "Error retrieving UI hierarchy: No UI hierarchy in screen data."
if driver is not None and hasattr(driver, "get_ui_hierarchy"):
xml_hierarchy = await driver.get_ui_hierarchy()
if inspect.iscoroutine(xml_hierarchy):
xml_hierarchy = await xml_hierarchy
return str(xml_hierarchy)
return "Error retrieving UI hierarchy: No UI Automator client or driver provided."
except Exception as e: # pylint: disable=broad-exception-caught
logger.error(f"Failed to get UI hierarchy: {e}")
return f"Error retrieving UI hierarchy: {e}"
# Universal tool instance & aliases
get_ui_hierarchy = GetUiHierarchyTool()
GetUiHierarchy = GetUiHierarchyTool
GetUIHierarchy = GetUiHierarchyTool
ToolRegistry.register(get_ui_hierarchy)
def get_ui_hierarchy_tool(ctx: ArtemisContext) -> BaseTool:
"""Exports get_ui_hierarchy as a LangChain BaseTool."""
return trace_langchain_tool(get_ui_hierarchy.to_langchain_tool(ctx), ctx)
ui_hierarchy_wrapper = ToolWrapper(
tool_fn_getter=get_ui_hierarchy_tool,
on_success_fn=lambda output: output,
on_failure_fn=lambda error: f"Failed to retrieve UI hierarchy: {error}",
)