feat: add agentic video analysis and clarify action results

Report device actions as dispatched and preserve full failure details. Route
Flash through McpActionExecutor and use ToolFailure across helper tools and
agent loops instead of inferring failure from response text.

Require model-provided descriptions for coordinate targets. Keep observed
element metadata separate from those descriptions in safety checks, visual
summaries, history, and frontend labels.

Add Gemini Interactions API video analysis with configurable processing mode,
chunk size, and timeouts. Centralize Google provider capabilities and token
usage normalization, and update google-genai to 2.22.0.

Preserve system instructions on follow-up interactions, replan pending chunks
when falling back to static processing, and reject unanswered native video
and audio segments instead of caching placeholder results. Keep helper-tool
failure status intact through history tools and committee calls.

Validation: 1,762 Python unit tests passed (3 skipped), 40 frontend formatter
tests passed, and the production UI build completed. Ruff lint, formatting,
the quality ratchet, and git diff checks passed.
This commit is contained in:
somew1nd committed 2026-09-08 17:05:54 -07:00
1 parent 611d1a0947
commit a45daf23f8
120 files changed
+6301 -1710

No files matched your search

+3 -1
View File
@@ -16,6 +16,8 @@
import httpx
from artemis.llm.google.provider import is_google_family_provider
from artemis.utils.logger import get_logger
logger = get_logger(__name__)
@@ -89,7 +91,7 @@ async def validate_api_key(
try:
async with httpx.AsyncClient(timeout=timeout) as client:
if clean_provider in ("google", "gemini", "vertexai", "vertex"):
if is_google_family_provider(clean_provider):
# Test Google Gemini via generativelanguage API
url = f"https://generativelanguage.googleapis.com/v1beta/models?key={clean_key}&pageSize=1"
resp = await client.get(url)
+5 -46
View File
@@ -12,35 +12,16 @@
# See the License for the specific language governing permissions and
# limitations under the License.
"""Record-time action semantics enrichment via element hit testing.
"""Element hit testing: which indexed element covers a pixel point.
An action addressed by bare coordinates carries no element semantics
("tap(632,1180)" says nothing about what was tapped). Before such an action is
persisted to the DataEngine, these helpers resolve the smallest indexed element
covering the tap point on the pre-action frame and attach best-effort
``target_text`` / ``target_class`` / ``target_resource_id`` fields, plus a
``target_label_source`` marker distinguishing model-named targets from
after-the-fact inference:
- ``"index"``: the model addressed the element by its perception index — the
semantics come straight from the indexed element (highest confidence).
- ``"hit_test"``: inferred by hit testing the coordinates against XML-derived
indexed elements on the pre-action frame.
- ``"ocr"``: inferred by hit testing against OCR-derived indexed elements
(used only when no XML-derived element covers the point).
- ``"none"``: no element covers the point (or no perception data was
available) — the action stays a bare-coordinate action.
Enrichment is strictly best-effort: missing/malformed element data degrades to
``"none"`` and never raises.
Used by the Explorer to deduplicate candidates against the screen index.
Recorded coordinate actions use the model's ``target_description``.
"""
from typing import Any
from artemis.utils.visualization import parse_bounds
_LABEL_SOURCE_KEY = "target_label_source"
def _element_bounds(element: dict[str, Any]) -> tuple[int, int, int, int] | None:
"""Returns (left, top, right, bottom) pixel bounds of an indexed element.
@@ -69,7 +50,8 @@ def find_element_at_point(
XML-derived elements are preferred over OCR-derived ones (OCR boxes carry
text but weaker structure); within each group the smallest covering area
wins. Returns ``(element, source)`` where source is ``"hit_test"``,
``"ocr"``, or ``"none"`` (with element None).
``"ocr"``, or ``"none"`` (with element None). Malformed element data is
skipped; the function never raises on it.
"""
best_xml: tuple[int, dict[str, Any]] | None = None
best_ocr: tuple[int, dict[str, Any]] | None = None
@@ -96,26 +78,3 @@ def find_element_at_point(
if best_ocr is not None:
return best_ocr[1], "ocr"
return None, "none"
def hit_test_semantics(elements: list[dict[str, Any]] | None, x: int, y: int) -> dict[str, Any]:
"""Best-effort semantic fields for a bare-coordinate action at pixel (x, y).
Always returns a dict containing ``target_label_source``; the
``target_text`` / ``target_class`` / ``target_resource_id`` fields are only
present when the covering element carries them.
"""
try:
element, source = find_element_at_point(elements, int(x), int(y))
except Exception:
return {_LABEL_SOURCE_KEY: "none"}
semantics: dict[str, Any] = {_LABEL_SOURCE_KEY: source}
if element is None:
return semantics
if element.get("text"):
semantics["target_text"] = element["text"]
if element.get("class"):
semantics["target_class"] = element["class"]
if element.get("resource_id"):
semantics["target_resource_id"] = element["resource_id"]
return semantics
+4 -3
View File
@@ -18,6 +18,7 @@ import os
from pathlib import Path
import re
from artemis.core.tool_failure import ToolFailure
from artemis.data_engine.engine import _CURRENT_DATA_ENGINE
from artemis.utils.logger import get_logger
from artemis.utils.plan_grammar import parse_plan
@@ -385,8 +386,8 @@ def format_read_note_success(
def format_read_note_failure(key: str, error: str) -> str:
"""Formats the failure message for reading a note."""
if "not found" in error.lower():
return f"Note '{key}' not found in scratchpad."
return f"Failed to read note '{key}': {error}"
return ToolFailure(f"Note '{key}' not found in scratchpad.")
return ToolFailure(f"Failed to read note '{key}': {error}")
def format_list_notes_success(notes_info: dict[str, int]) -> str:
@@ -399,7 +400,7 @@ def format_list_notes_success(notes_info: dict[str, int]) -> str:
def format_list_notes_failure(error: str) -> str:
"""Formats the failure message for listing notes."""
return f"Failed to list notes: {error}"
return ToolFailure(f"Failed to list notes: {error}")
def record_subgoal_hash_chain(
+58 -18
View File
@@ -23,6 +23,23 @@ from artemis.utils.plan_grammar import parse_plan
logger = logging.getLogger(__name__)
#: Suffix on a rendered target label whose text is the acting model's own
#: ``target_description`` (a coordinate target) rather than the element text
#: observed in the UI tree (an index target). Every later reader of the history
#: (Checker, Planner, Summarizer, incident block) sees which kind it is.
SELF_DESCRIBED_MARKER = "(self-described)"
def _target_label(action_obj: dict, *, fallback: str) -> str:
"""The quoted target label, provenance-marked, or ``fallback`` when unnamed."""
observed = action_obj.get("target_text")
if observed:
return f"'{observed}'"
described = action_obj.get("target_description")
if described:
return f"'{described}' {SELF_DESCRIBED_MARKER}"
return fallback
def format_action_clean(action_obj) -> str:
if not action_obj:
@@ -49,7 +66,6 @@ def format_action_clean(action_obj) -> str:
merged.setdefault("intent", raw_args.get("action"))
action_obj = merged
target_text = action_obj.get("target_text") or action_obj.get("text")
coords = action_obj.get("coordinates") or action_obj.get("target")
app_name = (
action_obj.get("app_name")
@@ -60,9 +76,13 @@ def format_action_clean(action_obj) -> str:
)
keycode = action_obj.get("keycode") or action_obj.get("key")
if act_type in ("tap", "click", "long_press"):
label = f"'{target_text}'" if target_text else "element"
if act_type == "long_press":
if act_type in ("tap", "click", "long_press", "long_press_on"):
# Legacy records carried the label under ``text``; the typed text of an
# input action never reaches this branch.
label = _target_label(action_obj, fallback="element")
if label == "element" and action_obj.get("text"):
label = f"'{action_obj['text']}'"
if act_type in ("long_press", "long_press_on"):
duration = action_obj.get("duration") or action_obj.get("duration_ms")
duration_str = f" for {duration}ms" if duration else ""
return f"Long pressed {label} at {coords}{duration_str}"
@@ -82,10 +102,9 @@ def format_action_clean(action_obj) -> str:
else:
return f"Tapped {label} at {coords}"
elif act_type in ("input_text", "focus_and_input_text"):
# The field label is the resolved target's text only — the typed text
# is not the field's name.
field_text = action_obj.get("target_text")
label = f"'{field_text}'" if field_text else "field"
# The field label is the resolved target's text (or the model's own
# description of the field) only — the typed text is not the field's name.
label = _target_label(action_obj, fallback="field")
text_val = action_obj.get("text")
clear_exist = action_obj.get("clear_exist") or action_obj.get("clear_before_input")
clear_str = " (without clearing)" if clear_exist is False else ""
@@ -110,7 +129,9 @@ def format_action_clean(action_obj) -> str:
if isinstance(coords_list, list) and len(coords_list) == 4:
start_coords = coords_list[:2]
end_coords = coords_list[2:]
return f"Swiped from {start_coords} to {end_coords}{duration_str}"
dragged = _target_label(action_obj, fallback="")
dragged_str = f" {dragged}" if dragged else ""
return f"Swiped{dragged_str} from {start_coords} to {end_coords}{duration_str}"
elif act_type == "press_key":
return f"Pressed key '{keycode}'"
elif act_type == "launch_app":
@@ -142,7 +163,18 @@ def format_action_clean(action_obj) -> str:
)
return f"Waited for {delay_val}"
elif act_type in ("click_sequence", "tap_sequence"):
seq = action_obj.get("target") or action_obj.get("sequence") or []
seq = (
action_obj.get("target")
or action_obj.get("sequence")
or action_obj.get("coordinates")
or []
)
descriptions = action_obj.get("target_descriptions")
if isinstance(descriptions, (list, tuple)) and len(descriptions) == len(seq) and seq:
labelled = ", ".join(
f"'{d}' {SELF_DESCRIBED_MARKER} at {p}" for d, p in zip(descriptions, seq)
)
return f"Tapped sequence of targets: {labelled}"
return f"Tapped sequence of targets: {seq}"
else:
return f"Action: {act_type} with args: {json.dumps(action_obj, ensure_ascii=False)}"
@@ -164,7 +196,7 @@ def _is_terminal_attempt_failure(attempts) -> bool:
if not attempts:
return False
last = str(attempts[-1])
return last != "Success" and not last.startswith("Skipped")
return last != "Dispatched" and not last.startswith("Skipped")
def failed_execution_error(result_obj) -> str | None:
@@ -217,13 +249,19 @@ def format_result_clean(result_obj) -> str | None:
status = result_obj.get("status")
error = failed_execution_error(result_obj)
if status in ("failed", "error"):
return f"Error: {error}" if error else "Error"
if error:
return f"Error: {error}"
return _error_line(error)
if status in ("failed", "error"):
return "Error"
return None
def _error_line(error: str) -> str:
"""One ``Error: ...`` line; executor messages already start with "Error"."""
text = str(error).strip()
return text if text.lower().startswith("error") else f"Error: {text}"
def safe_parse_validation_result(result: Any) -> list:
if isinstance(result, (list, tuple)):
return list(result)
@@ -315,6 +353,8 @@ def format_tool_call_clean(
"target_text": (
args.get("text") or args.get("target_text") or args.get("target_text_or_desc")
),
"target_description": args.get("target_description"),
"target_descriptions": args.get("target_descriptions"),
"text": args.get("text"),
"clear_exist": (args.get("clear_exist") or args.get("clear_before_input")),
"clear_before_input": args.get("clear_before_input"),
@@ -492,13 +532,13 @@ def _burst_member_status(result: Any, index: int) -> str:
return ""
exec_list = result.get("execution") or []
if index >= len(exec_list) or not isinstance(exec_list[index], dict):
return " (not executed)"
return " (not dispatched)"
attempts = exec_list[index].get("attempts") or []
if not attempts:
return " (executed)"
return " (dispatched)"
last = str(attempts[-1])
if last == "Success":
return " (executed)"
if last == "Dispatched":
return " (dispatched)"
if last.startswith("Skipped"):
return " (skipped)"
return f" (FAILED: {last.strip()})"